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> getRequests() + abstract ListProperty getJvmArguments() abstract Property getPort() diff --git a/grails-gradle/plugins/src/main/groovy/org/apache/grails/gradle/plugin/aot/TraceNativeMetadataTask.groovy b/grails-gradle/plugins/src/main/groovy/org/apache/grails/gradle/plugin/aot/TraceNativeMetadataTask.groovy index c9395dd82e5..439aa9ca0a7 100644 --- a/grails-gradle/plugins/src/main/groovy/org/apache/grails/gradle/plugin/aot/TraceNativeMetadataTask.groovy +++ b/grails-gradle/plugins/src/main/groovy/org/apache/grails/gradle/plugin/aot/TraceNativeMetadataTask.groovy @@ -85,6 +85,19 @@ import org.gradle.work.DisableCachingByDefault * -- the one declaring the most fields is submitted, and which it was is reported. A page whose * wanted form is not the fullest names it: {@code '/book/create#bookForm'}.

* + *

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:

+ * + *
+ * grails {
+ *     nativeMetadata {
+ *         requests = [[method: 'QUERY', path: '/book/search', contentType: 'application/json',
+ *                      body: '{"title": "Grails"}', accept: 'application/json']]
+ *     }
+ * }
+ * 
+ * *

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> getRequests() + @Input abstract Property getPort() @@ -196,6 +220,7 @@ abstract class TraceNativeMetadataTask extends DefaultTask { // the login form, and what the agent records is the login page under the name of the // page that was wanted. The session the form establishes is carried by this client. forms.get().each { String path -> answered << submit(path) } + requests.get().each { Map request -> answered << send(request) } paths.get().each { String path -> answered << ask(path) } } finally { @@ -220,8 +245,8 @@ abstract class TraceNativeMetadataTask extends DefaultTask { 'traced, so what was recorded is not what was asked for:\n ' + "${failed*.line.join('\n ')}\nWhat it printed is in ${output}") } - logger.lifecycle('Traced {} forms and {} paths into {}', - forms.get().size(), paths.get().size(), metadata) + logger.lifecycle('Traced {} forms, {} requests and {} paths into {}', + forms.get().size(), requests.get().size(), paths.get().size(), metadata) } /** What one request recorded, and whether it recorded the thing it was asked for. */ @@ -277,6 +302,36 @@ abstract class TraceNativeMetadataTask extends DefaultTask { response.statusCode() < 400, elsewhere) } + /** + * Makes a request as it is declared, with the Accept header {@link #requestTo} gives one that names none, and + * reports where it was answered from as {@link #ask} does: a request that needs a login and has not got one is + * sent on to the login page, which records that page under the name of this one. + */ + private Answer send(Map request) { + Map declared = request + Collection unknown = declared.keySet() - REQUEST_KEYS + String method = declared.method?.toString()?.toUpperCase(Locale.ROOT) + String path = declared.path?.toString() + if (unknown || !method || !path) { + return new Answer("REQUEST ${declared} -> a request names its method and path, and may name " + + "${REQUEST_KEYS - ['method', 'path']}".toString(), false) + } + HttpRequest.Builder builder = requestTo(path) + if (declared.accept) { + builder.setHeader('Accept', declared.accept.toString()) + } + if (declared.contentType) { + builder.header('Content-Type', declared.contentType.toString()) + } + builder.method(method, declared.body == null ? HttpRequest.BodyPublishers.noBody() : + HttpRequest.BodyPublishers.ofString(declared.body.toString())) + HttpResponse response = client.send(builder.build(), HttpResponse.BodyHandlers.ofString()) + String landed = response.uri().path + boolean elsewhere = landed != uriOf(path).path + String where = elsewhere ? " (landed on ${landed})" : '' + new Answer("${method} ${path} -> ${response.statusCode()}${where}".toString(), response.statusCode() < 400, elsewhere) + } + /** * Fills in the form on a page and submits it to wherever the form says. * 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 bf2d17fe649..3a5208318f4 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 @@ -1234,6 +1234,7 @@ ${importStatements} .extensions.create('nativeMetadata', NativeMetadataExtension) extension.paths.convention(['/']) extension.forms.convention([]) + extension.requests.convention([]) extension.jvmArguments.convention(['-Dgrails.env=production']) extension.port.convention(TRACING_PORT) extension.startTimeoutSeconds.convention(TRAINING_START_TIMEOUT_SECONDS) @@ -1259,6 +1260,7 @@ ${importStatements} task.jvmArguments.set(extension.jvmArguments) task.paths.set(extension.paths) task.forms.set(extension.forms) + task.requests.set(extension.requests) task.port.set(extension.port) task.startTimeoutSeconds.set(extension.startTimeoutSeconds) task.outputDirectory.set(extension.outputDirectory) diff --git a/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/TraceNativeMetadataTaskSpec.groovy b/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/TraceNativeMetadataTaskSpec.groovy index 1c27fb1687d..04f54406fdb 100644 --- a/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/TraceNativeMetadataTaskSpec.groovy +++ b/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/TraceNativeMetadataTaskSpec.groovy @@ -289,6 +289,79 @@ exec '${new File(System.getProperty('java.home'), 'bin/java').absolutePath}' \\ e.message.contains('did not answer with the page') } + void 'a request is made with the method, type, body and accept it names'() { + given: + TraceNativeMetadataTask task = task([], []) + task.requests.set([[method: 'query', path: '/book/search', contentType: 'application/json', + body: '{"title":"Grails"}', accept: 'application/json']]) + + when: + task.trace() + + then: 'an action restricted to QUERY answers nothing else, so nothing else records what it reaches' + requested.contains('QUERY /book/search {"title":"Grails"}') + requested.contains('HEADERS application/json application/json') + } + + void 'a request that names only its method and path sends no body, and accepts what a path does'() { + given: + TraceNativeMetadataTask task = task([], []) + task.requests.set([[method: 'DELETE', path: '/book/1']]) + + when: + task.trace() + + then: + requested.contains('DELETE /book/1') + requested.contains('HEADERS null text/html,*/*') + } + + void 'requests are made after the forms, whose session they are in'() { + given: 'a request of a signed-in client is only worth making once the login form has been submitted' + TraceNativeMetadataTask task = task(['/after'], ['/login']) + task.requests.set([[method: 'QUERY', path: '/protected']]) + + when: + task.trace() + + then: + requested.findIndexOf { it.startsWith('POST /authenticate') } < requested.indexOf('QUERY /protected') + requested.indexOf('QUERY /protected') < requested.indexOf('GET /after') + + and: 'and it was not sent on to the login page' + requested.count('GET /login') == 1 + } + + void 'a request that answers with an error fails the trace'() { + given: + TraceNativeMetadataTask task = task([], []) + task.requests.set([[method: 'QUERY', path: '/broken']]) + + when: + task.trace() + + then: + GradleException e = thrown() + e.message.contains('QUERY /broken -> 500') + } + + void 'a request that does not say what to send, or misspells it, fails the trace rather than sending something else'() { + given: + TraceNativeMetadataTask task = task([], []) + task.requests.set([request]) + + when: + task.trace() + + then: + GradleException e = thrown() + e.message.contains('a request names its method and path') + !requested.any { it.contains('/book/search') } + + where: + request << [[path: '/book/search'], [method: 'QUERY'], [method: 'QUERY', path: '/book/search', bodyy: '{}']] + } + void 'the cookie handler the build had is put back after a trace'() { given: 'a daemon outlives the build, so what this sets is handed to every task after it' CookieHandler inherited = new CookieManager() diff --git a/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/TracedRunFixture.groovy b/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/TracedRunFixture.groovy index 7785db385bb..c567f41696e 100644 --- a/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/TracedRunFixture.groovy +++ b/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/TracedRunFixture.groovy @@ -70,8 +70,11 @@ class TracedRunFixture { server.createContext('/') { HttpExchange exchange -> String path = exchange.requestURI.path String method = exchange.requestMethod - String body = method == 'POST' ? exchange.requestBody.getText('UTF-8') : '' + String body = exchange.requestBody.getText('UTF-8') requested << "${method} ${path}${body ? ' ' + body : ''}\n" + if (!(method in ['GET', 'POST'])) { + requested << "HEADERS ${exchange.requestHeaders.getFirst('Content-Type')} ${exchange.requestHeaders.getFirst('Accept')}\n" + } boolean signedIn = exchange.requestHeaders.getFirst('Cookie')?.contains('session=in') int status = 200 From c551b18af68dc3d55dfcef9c611cfa02f277c231 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Thu, 5 Nov 2026 17:41:19 -0800 Subject: [PATCH 23/78] Wait for an application that holds requests until it has started The Spring Security plugin answers every request with 503 until the application has started, and a run's log and its open port both come before that. traceNativeMetadata recorded the refusal, and failed on it, and trainAotCache trained on it. Both now ask with a HEAD request whether what answers is ready. Only a 503 says to wait, and only until the start timeout, so an application whose home page answers 503 for reasons of its own is still traced and trained as it was. --- .../grails/gradle/plugin/aot/RunPort.groovy | 28 ++++++++++++++ .../plugin/aot/TraceNativeMetadataTask.groovy | 11 ++++-- .../plugin/aot/TrainAotCacheTask.groovy | 14 +++++-- .../gradle/plugin/aot/RunPortSpec.groovy | 38 ++++++++++++++++++- .../aot/TraceNativeMetadataTaskSpec.groovy | 25 ++++++++++++ .../gradle/plugin/aot/TracedRunFixture.groovy | 9 +++++ .../plugin/aot/TrainAotCacheTaskSpec.groovy | 29 +++++++++++++- .../plugin/aot/TrainingRunFixture.groovy | 11 +++++- 8 files changed, 153 insertions(+), 12 deletions(-) diff --git a/grails-gradle/plugins/src/main/groovy/org/apache/grails/gradle/plugin/aot/RunPort.groovy b/grails-gradle/plugins/src/main/groovy/org/apache/grails/gradle/plugin/aot/RunPort.groovy index 6d8d015ddc5..2c7588ad8f9 100644 --- a/grails-gradle/plugins/src/main/groovy/org/apache/grails/gradle/plugin/aot/RunPort.groovy +++ b/grails-gradle/plugins/src/main/groovy/org/apache/grails/gradle/plugin/aot/RunPort.groovy @@ -41,6 +41,34 @@ final class RunPort { private RunPort() { } + /** + * Whether what listens on the port says it is not ready yet. A connection and the log saying the application + * started both come before its {@code ApplicationStartedEvent}, and a filter that holds requests until then, such + * as the Spring Security plugin's, answers them with 503, which a run would record in place of the page. + * + * @param port the port the run is reached on + * @return whether it answers with 503, and not where nothing answers at all + * @since 9.1 + */ + static boolean answersNotReady(int port) { + try { + HttpURLConnection connection = (HttpURLConnection) new URI("http://localhost:${port}/").toURL().openConnection() + connection.requestMethod = 'HEAD' + connection.instanceFollowRedirects = false + connection.connectTimeout = 500 + connection.readTimeout = 2000 + try { + return connection.responseCode == HttpURLConnection.HTTP_UNAVAILABLE + } + finally { + connection.disconnect() + } + } + catch (IOException ignored) { + return false + } + } + /** * Refuses where something is already listening on the port. * diff --git a/grails-gradle/plugins/src/main/groovy/org/apache/grails/gradle/plugin/aot/TraceNativeMetadataTask.groovy b/grails-gradle/plugins/src/main/groovy/org/apache/grails/gradle/plugin/aot/TraceNativeMetadataTask.groovy index 439aa9ca0a7..a896fe12824 100644 --- a/grails-gradle/plugins/src/main/groovy/org/apache/grails/gradle/plugin/aot/TraceNativeMetadataTask.groovy +++ b/grails-gradle/plugins/src/main/groovy/org/apache/grails/gradle/plugin/aot/TraceNativeMetadataTask.groovy @@ -504,19 +504,22 @@ abstract class TraceNativeMetadataTask extends DefaultTask { private void awaitStarted(Process process, File output) { long deadline = System.currentTimeMillis() + Duration.ofSeconds(startTimeoutSeconds.get()).toMillis() StartupLog log = new StartupLog(output) + boolean started = false while (System.currentTimeMillis() < deadline) { if (!process.isAlive()) { throw new GradleException('The application ended before it started serving. ' + "What it printed is in ${output}") } - if (log.saysItStarted()) { - return - } - if (serving()) { + started = log.saysItStarted() || serving() + if (started && !RunPort.answersNotReady(port.get())) { return } Thread.sleep(250L) } + if (started) { + // Its home page is what answers 503, as it may for reasons of its own, so the requests are its to answer. + return + } throw new GradleException("The application did not start within ${startTimeoutSeconds.get()}s. " + "What it printed is in ${output}") } diff --git a/grails-gradle/plugins/src/main/groovy/org/apache/grails/gradle/plugin/aot/TrainAotCacheTask.groovy b/grails-gradle/plugins/src/main/groovy/org/apache/grails/gradle/plugin/aot/TrainAotCacheTask.groovy index 2ad118d7ea3..1a92e31c51d 100644 --- a/grails-gradle/plugins/src/main/groovy/org/apache/grails/gradle/plugin/aot/TrainAotCacheTask.groovy +++ b/grails-gradle/plugins/src/main/groovy/org/apache/grails/gradle/plugin/aot/TrainAotCacheTask.groovy @@ -272,23 +272,29 @@ abstract class TrainAotCacheTask extends DefaultTask { * the earlier and clearer of the two, but it is an INFO log an application is free to turn off * or reword; a port that accepts a connection is the application's own doing and cannot be * configured away while it is still an application worth training.

+ * + *

Both come before its {@code ApplicationStartedEvent}, so a filter that holds requests until then is waited + * for, up to the timeout.

*/ private void awaitStarted(Process process, File output) { long deadline = System.currentTimeMillis() + Duration.ofSeconds(startTimeoutSeconds.get()).toMillis() StartupLog log = new StartupLog(output) + boolean started = false while (System.currentTimeMillis() < deadline) { if (!process.isAlive()) { throw new GradleException('The training run ended before it started serving.' + whyItEnded(output) + " What it printed is in ${output}") } - if (log.saysItStarted()) { - return - } - if (serving()) { + started = log.saysItStarted() || serving() + if (started && !RunPort.answersNotReady(port.get())) { return } Thread.sleep(250L) } + if (started) { + // Its home page is what answers 503, as it may for reasons of its own, so the requests are its to answer. + return + } throw new GradleException("The training run did not start within ${startTimeoutSeconds.get()}s. " + "What it printed is in ${output}") } diff --git a/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/RunPortSpec.groovy b/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/RunPortSpec.groovy index 941573d27f3..8786bd92da3 100644 --- a/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/RunPortSpec.groovy +++ b/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/RunPortSpec.groovy @@ -18,14 +18,50 @@ */ package org.apache.grails.gradle.plugin.aot +import com.sun.net.httpserver.HttpExchange +import com.sun.net.httpserver.HttpServer import org.gradle.api.GradleException import spock.lang.Specification +import spock.lang.Unroll /** - * Covers refusing a port something else is already answering on. + * Covers refusing a port something else is already answering on, and asking whether what answers on one is ready. */ class RunPortSpec extends Specification { + @Unroll + void 'an application answering #status is #description'() { + given: + HttpServer server = HttpServer.create(new InetSocketAddress('localhost', 0), 0) + server.createContext('/') { HttpExchange exchange -> + exchange.sendResponseHeaders(status, -1) + exchange.close() + } + server.start() + + expect: + RunPort.answersNotReady(server.address.port) == notReady + + cleanup: + server?.stop(0) + + where: + status | notReady | description + 503 | true | 'not ready' + 200 | false | 'ready' + 302 | false | 'ready, wherever it sends the request' + 404 | false | 'ready, whatever it has at its home page' + 500 | false | 'ready, since only 503 says to come back' + } + + void 'a port nothing answers on is not said to be not ready'() { + given: + int free = new ServerSocket(0).withCloseable { ServerSocket socket -> socket.localPort } + + expect: 'whether anything listens is what the wait for the port itself is for' + !RunPort.answersNotReady(free) + } + void 'a free port is not refused'() { given: 'a port nothing is listening on, found by letting the system choose one and closing it' int free = new ServerSocket(0).withCloseable { ServerSocket socket -> socket.localPort } diff --git a/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/TraceNativeMetadataTaskSpec.groovy b/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/TraceNativeMetadataTaskSpec.groovy index 04f54406fdb..c49deb44f0d 100644 --- a/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/TraceNativeMetadataTaskSpec.groovy +++ b/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/TraceNativeMetadataTaskSpec.groovy @@ -264,6 +264,31 @@ exec '${new File(System.getProperty('java.home'), 'bin/java').absolutePath}' \\ e.message.contains('no form on the page') } + void 'a path is not asked for while the application still answers that it is not ready'() { + given: 'the Spring Security plugin answers every request with 503 until the application has started' + TraceNativeMetadataTask task = task(['/'], [], 'gated') + + when: + task.trace() + + then: 'where it would otherwise record the refusal and fail' + notThrown(GradleException) + requested.contains('GET /') + } + + void 'an application whose home page always answers that it is not ready is still traced'() { + given: 'waited for no longer than the timeout, since nothing says that answer will change' + TraceNativeMetadataTask task = task(['/page'], [], 'homePageDown') + task.startTimeoutSeconds.set(2) + + when: + task.trace() + + then: + notThrown(GradleException) + requested.contains('GET /page') + } + void 'a path that answers with an error fails the trace'() { given: 'because what would be recorded is the error page rather than the page' TraceNativeMetadataTask task = task(['/broken'], []) diff --git a/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/TracedRunFixture.groovy b/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/TracedRunFixture.groovy index c567f41696e..4ae696d1047 100644 --- a/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/TracedRunFixture.groovy +++ b/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/TracedRunFixture.groovy @@ -66,10 +66,19 @@ class TracedRunFixture { File requested = new File(args[1]) String behaviour = args.length > 2 ? args[2] : 'ok' + long openAt = System.currentTimeMillis() + 1500 + HttpServer server = HttpServer.create(new InetSocketAddress('localhost', port), 0) server.createContext('/') { HttpExchange exchange -> String path = exchange.requestURI.path String method = exchange.requestMethod + boolean holding = behaviour == 'gated' && System.currentTimeMillis() < openAt + boolean homePageDown = behaviour == 'homePageDown' && path == '/' + if (holding || homePageDown) { + exchange.sendResponseHeaders(503, -1) + exchange.close() + return + } String body = exchange.requestBody.getText('UTF-8') requested << "${method} ${path}${body ? ' ' + body : ''}\n" if (!(method in ['GET', 'POST'])) { diff --git a/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/TrainAotCacheTaskSpec.groovy b/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/TrainAotCacheTaskSpec.groovy index 6e91a595a76..ad1f1c943ec 100644 --- a/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/TrainAotCacheTaskSpec.groovy +++ b/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/TrainAotCacheTaskSpec.groovy @@ -62,7 +62,7 @@ class TrainAotCacheTaskSpec extends Specification { * {@code -XX:AOTCacheOutput}, which a JDK before 25 refuses outright, and a test of this task * should not also be a test of which JDK the build is running on.

*/ - private TrainAotCacheTask servingTask(List paths, boolean announcesItself = true) { + private TrainAotCacheTask servingTask(List paths, boolean announcesItself = true, String behaviour = 'ok') { File application = new File(temporaryFolder, 'serving') application.mkdirs() new File(application, 'served.jar').text = 'stands in for the archive, and is what is digested' @@ -81,7 +81,7 @@ for arg in "\$@"; do done exec '${new File(System.getProperty('java.home'), 'bin/java').absolutePath}' \\ -cp '${System.getProperty('java.class.path')}' \\ - ${TrainingRunFixture.name} "\$cache" "\$port" '${requestedFile.absolutePath}' ${announcesItself ? 'loud' : 'quiet'} + ${TrainingRunFixture.name} "\$cache" "\$port" '${requestedFile.absolutePath}' ${announcesItself ? 'loud' : 'quiet'} ${behaviour} """ script.setExecutable(true) @@ -309,6 +309,31 @@ exit 1 requested == ['/'] } + void 'a path is not asked for while the run still answers that it is not ready'() { + given: 'the Spring Security plugin answers every request with 503 until the application has started' + TrainAotCacheTask task = servingTask(['/'], true, 'gated') + + when: + task.train() + + then: 'where it would otherwise train on the refusal' + noExceptionThrown() + requested == ['/'] + } + + void 'a run whose home page always answers that it is not ready is still exercised'() { + given: 'waited for no longer than the timeout, since nothing says that answer will change' + TrainAotCacheTask task = servingTask(['/page'], true, 'homePageDown') + task.startTimeoutSeconds.set(2) + + when: + task.train() + + then: + noExceptionThrown() + requested == ['/page'] + } + void 'a run that says nothing is found by its port'() { given: 'an application that has turned off the log line Spring Boot starts with' TrainAotCacheTask task = servingTask(['/'], false) diff --git a/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/TrainingRunFixture.groovy b/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/TrainingRunFixture.groovy index 90559bb3810..c1774784c9a 100644 --- a/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/TrainingRunFixture.groovy +++ b/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/TrainingRunFixture.groovy @@ -43,8 +43,17 @@ class TrainingRunFixture { File requested = new File(args[2]) HttpServer server = HttpServer.create(new InetSocketAddress('localhost', port), 0) + long openAt = args.length > 4 && args[4] == 'gated' ? System.currentTimeMillis() + 1500 : 0 + boolean homePageDown = args.length > 4 && args[4] == 'homePageDown' server.createContext('/') { HttpExchange exchange -> - requested << "${exchange.requestURI.path}\n" + if (System.currentTimeMillis() < openAt || (homePageDown && exchange.requestURI.path == '/')) { + exchange.sendResponseHeaders(503, -1) + exchange.close() + return + } + if (exchange.requestMethod != 'HEAD') { + requested << "${exchange.requestURI.path}\n" + } byte[] body = 'served'.bytes int status = exchange.requestURI.path == '/missing' ? 404 : 200 exchange.sendResponseHeaders(status, body.length) From bf0406ee5558a3d2dd5dce03a2d649e31c6e0ce3 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Thu, 5 Nov 2026 17:41:20 -0800 Subject: [PATCH 24/78] Let the Spring Security plugin build a native image processAot failed on the plugin, and an image could not load its defaults. Found by running the request cache change in an image. - The password encoders, the session listener and the after-invocation provider were live objects in their bean definitions, which ahead-of-time processing cannot write out. They are now beans. - passwordEncoder, authenticationManager and springSecurityFilterChainProxy have overlapping constructors it cannot choose between, so the default classes are created by a static factory method. A class set in their place is still created by its constructor. - grailsApplication was read while the beans were declared, not referenced. - DefaultSecurityConfig was compiled from its script at every startup. It is now compiled with the plugin, and a runtime hint keeps the constructor ConfigSlurper calls, which the trace does not see. PluginBeansAotSpec runs Spring's generator over what the plugin declares for each security config type and the optional filters. PluginBeansSpec covers what the beans are once created. --- .../en/guide/deployment/deploymentAot.adoc | 14 ++ grails-spring-security/plugin/build.gradle | 4 + .../SpringSecurityCoreGrailsPlugin.groovy | 95 +++++++-- .../aot/SpringSecurityRuntimeHints.groovy | 43 ++++ .../resources/META-INF/spring/aot.factories | 2 + .../springsecurity/PluginBeansSpec.groovy | 186 ++++++++++++++++++ .../aot/PluginBeansAotSpec.groovy | 137 +++++++++++++ .../aot/SpringSecurityRuntimeHintsSpec.groovy | 52 +++++ 8 files changed, 518 insertions(+), 15 deletions(-) create mode 100644 grails-spring-security/plugin/src/main/groovy/grails/plugin/springsecurity/aot/SpringSecurityRuntimeHints.groovy create mode 100644 grails-spring-security/plugin/src/main/resources/META-INF/spring/aot.factories create mode 100644 grails-spring-security/plugin/src/test/groovy/grails/plugin/springsecurity/PluginBeansSpec.groovy create mode 100644 grails-spring-security/plugin/src/test/groovy/grails/plugin/springsecurity/aot/PluginBeansAotSpec.groovy create mode 100644 grails-spring-security/plugin/src/test/groovy/grails/plugin/springsecurity/aot/SpringSecurityRuntimeHintsSpec.groovy diff --git a/grails-doc/src/en/guide/deployment/deploymentAot.adoc b/grails-doc/src/en/guide/deployment/deploymentAot.adoc index 2fcfc298733..551b999b34c 100644 --- a/grails-doc/src/en/guide/deployment/deploymentAot.adoc +++ b/grails-doc/src/en/guide/deployment/deploymentAot.adoc @@ -181,6 +181,20 @@ grails { A form may be told what to put in it with a query string, as `/login` is above. Only fields the form actually declares are set from it; a value naming a field that is not there is reported rather than posted, because it was meant for a form that has since changed. +An application using the Spring Security plugin traces its login the same way, naming the page the plugin renders: + +[source,groovy] +---- +grails { + nativeMetadata { + forms = ['/login/auth?username=admin&password=secret'] + paths = ['/', '/book'] + } +} +---- + +The plugin answers every request with a 503 until the application has started, so the trace and an AOT cache training run wait for that answer to change before they make their first request, for no longer than `startTimeoutSeconds`. What the plugin declares and the default configuration it loads are ready for an image. Its companion plugins (REST, LDAP, ACL, CAS, OAuth2 and UI) are not yet: each compiles a default configuration script as it starts, which an image cannot do. + ==== Choosing which form A page often carries more than one form — a layout's search box or sign-out button ahead of the page's own. The form declaring the most fields is the one submitted, and the trace output says which it was: diff --git a/grails-spring-security/plugin/build.gradle b/grails-spring-security/plugin/build.gradle index d0718b9ad24..f986419c45d 100644 --- a/grails-spring-security/plugin/build.gradle +++ b/grails-spring-security/plugin/build.gradle @@ -130,6 +130,10 @@ apply { from rootProject.layout.projectDirectory.file('gradle/spring-security-test-config.gradle') } +// DefaultSecurityConfig is compiled, so that loading it finds the class rather than compiling the script at every +// startup, which a native image cannot do. +sourceSets.main.groovy.srcDir('grails-app/conf') + tasks.named('generateConfigurationMetadata') { dslConfigurationFiles.from(file('grails-app/conf/DefaultSecurityConfig.groovy')) dslRootPrefixes.put('security', 'grails.plugin.springsecurity') 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 317581b75ee..29b9333aeda 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 @@ -79,6 +79,7 @@ import org.springframework.security.access.intercept.NullRunAsManager import org.springframework.security.access.vote.AuthenticatedVoter import org.springframework.security.access.vote.RoleHierarchyVoter import org.springframework.security.authentication.AccountStatusUserDetailsChecker +import org.springframework.security.authentication.AuthenticationProvider import org.springframework.security.authentication.AuthenticationTrustResolverImpl import org.springframework.security.authentication.DefaultAuthenticationEventPublisher import org.springframework.security.authentication.ProviderManager @@ -103,6 +104,7 @@ import org.springframework.security.crypto.scrypt.SCryptPasswordEncoder import org.springframework.security.web.FilterChainProxy import org.springframework.security.web.PortMapperImpl import org.springframework.security.web.PortResolverImpl +import org.springframework.security.web.SecurityFilterChain import org.springframework.security.web.access.AccessDeniedHandlerImpl import org.springframework.security.web.access.channel.ChannelDecisionManagerImpl import org.springframework.security.web.access.channel.ChannelProcessingFilter @@ -253,7 +255,9 @@ class SpringSecurityCoreGrailsPlugin extends Plugin { if (conf.useHttpSessionEventPublisher) { log.trace 'Configuring HttpSessionEventPublisher' - httpSessionEventPublisher(classFor('httpSessionEventPublisher', ServletListenerRegistrationBean), new HttpSessionEventPublisher()) + httpSessionEventPublisher(classFor('httpSessionEventPublisher', ServletListenerRegistrationBean)) { + listener = { HttpSessionEventPublisher publisher -> } + } } createRefList.delegate = delegate @@ -404,8 +408,9 @@ class SpringSecurityCoreGrailsPlugin extends Plugin { // TODO doc new if (conf.afterInvocationManagerProviderNames) { log.trace 'Configuring AfterInvocationProviderManager' + nullAfterInvocationProvider(NullAfterInvocationProvider) afterInvocationManager(classFor('afterInvocationManager', AfterInvocationProviderManager)) { - providers = [new NullAfterInvocationProvider()] // will be replaced in doWithApplicationContext + providers = [ref('nullAfterInvocationProvider')] // will be replaced in doWithApplicationContext } } else { @@ -447,7 +452,7 @@ class SpringSecurityCoreGrailsPlugin extends Plugin { if (securityConfigType == 'Annotation') { objectDefinitionSource(classFor('objectDefinitionSource', AnnotationFilterInvocationDefinition)) { - application = grailsApplication + application = ref('grailsApplication') grailsUrlConverter = ref('grailsUrlConverter') httpServletResponseExtension = ref('httpServletResponseExtension') if (conf.rejectIfNoRule instanceof Boolean) { @@ -503,11 +508,21 @@ class SpringSecurityCoreGrailsPlugin extends Plugin { String algorithm = conf.password.algorithm log.trace 'Using {} algorithm', algorithm - passwordEncoder(classFor('passwordEncoder', DelegatingPasswordEncoder), algorithm, idToPasswordEncoder(conf)) + passwordEncoders(SpringSecurityCoreGrailsPlugin, conf.password.encodeHashAsBase64, + conf.password.hash.iterations, conf.password.bcrypt.logrounds) { bean -> + bean.factoryMethod = 'passwordEncoders' + } + Class passwordEncoderClass = classFor('passwordEncoder', DelegatingPasswordEncoder) + boolean defaultEncoder = passwordEncoderClass == DelegatingPasswordEncoder + passwordEncoder(defaultEncoder ? SpringSecurityCoreGrailsPlugin : passwordEncoderClass, algorithm, ref('passwordEncoders')) { bean -> + if (defaultEncoder) { + bean.factoryMethod = 'delegatingPasswordEncoder' + } + } /** userDetailsService */ userDetailsService(classFor('userDetailsService', GormUserDetailsService)) { - grailsApplication = grailsApplication + grailsApplication = ref('grailsApplication') } /** authenticationUserDetailsService */ @@ -973,7 +988,12 @@ class SpringSecurityCoreGrailsPlugin extends Plugin { def providerRefs = createRefList(SpringSecurityUtils.providerNames) /** authenticationManager */ - authenticationManager(classFor('authenticationManager', ProviderManager), providerRefs) { + Class authenticationManagerClass = classFor('authenticationManager', ProviderManager) + boolean defaultManager = authenticationManagerClass == ProviderManager + authenticationManager(defaultManager ? SpringSecurityCoreGrailsPlugin : authenticationManagerClass, providerRefs) { bean -> + if (defaultManager) { + bean.factoryMethod = 'providerManager' + } authenticationEventPublisher = ref('authenticationEventPublisher') eraseCredentialsAfterAuthentication = conf.providerManager.eraseCredentialsAfterAuthentication // true } @@ -987,7 +1007,12 @@ class SpringSecurityCoreGrailsPlugin extends Plugin { securityFilterChains(classFor('securityFilterChains', ArrayList)) - springSecurityFilterChainProxy(classFor('springSecurityFilterChainProxy', FilterChainProxy), ref('securityFilterChains')) { + Class filterChainProxyClass = classFor('springSecurityFilterChainProxy', FilterChainProxy) + boolean defaultProxy = filterChainProxyClass == FilterChainProxy + springSecurityFilterChainProxy(defaultProxy ? SpringSecurityCoreGrailsPlugin : filterChainProxyClass, ref('securityFilterChains')) { bean -> + if (defaultProxy) { + bean.factoryMethod = 'filterChainProxy' + } filterChainValidator = ref('filterChainValidator') firewall = ref('httpFirewall') } @@ -1173,22 +1198,62 @@ class SpringSecurityCoreGrailsPlugin extends Plugin { beanTypeResolver.resolveType beanName, defaultType } + /** + * The default {@code passwordEncoder}. Its constructors overlap, so ahead-of-time processing cannot choose one for + * the reference a bean definition holds, and an application cannot build a native image. + * + * @since 9.1 + */ + static DelegatingPasswordEncoder delegatingPasswordEncoder(String algorithm, Map encoders) { + new DelegatingPasswordEncoder(algorithm, encoders) + } + + /** + * The default {@code authenticationManager}. Its constructors overlap, so ahead-of-time processing cannot choose one + * for the list of references a bean definition holds, and an application cannot build a native image. + * + * @since 9.1 + */ + static ProviderManager providerManager(List providers) { + new ProviderManager(providers) + } + + /** + * The default {@code springSecurityFilterChainProxy}, whose constructors overlap as {@code ProviderManager}'s do. + * + * @since 9.1 + */ + static FilterChainProxy filterChainProxy(List filterChains) { + new FilterChainProxy(filterChains) + } + static Map idToPasswordEncoder(ConfigObject conf) { + passwordEncoders((boolean) conf.password.encodeHashAsBase64, (int) conf.password.hash.iterations, + (int) conf.password.bcrypt.logrounds) + } + + /** + * The encoders {@code passwordEncoder} chooses between by id, as a bean created from plain values. Ahead-of-time + * processing cannot write out a bean definition that holds the encoders themselves, so an application with them in + * one cannot build a native image. + * + * @since 9.1 + */ + static Map passwordEncoders(boolean encodeHashAsBase64, int iterations, int bcryptLogRounds) { MessageDigestPasswordEncoder messageDigestPasswordEncoderMD5 = new MessageDigestPasswordEncoder(ENCODING_ID_MD5) - messageDigestPasswordEncoderMD5.encodeHashAsBase64 = conf.password.encodeHashAsBase64 // false - messageDigestPasswordEncoderMD5.iterations = conf.password.hash.iterations // 10000 + messageDigestPasswordEncoderMD5.encodeHashAsBase64 = encodeHashAsBase64 + messageDigestPasswordEncoderMD5.iterations = iterations MessageDigestPasswordEncoder messageDigestPasswordEncoderSHA1 = new MessageDigestPasswordEncoder(ENCODING_ID_SHA1) - messageDigestPasswordEncoderSHA1.encodeHashAsBase64 = conf.password.encodeHashAsBase64 // false - messageDigestPasswordEncoderSHA1.iterations = conf.password.hash.iterations // 10000 + messageDigestPasswordEncoderSHA1.encodeHashAsBase64 = encodeHashAsBase64 + messageDigestPasswordEncoderSHA1.iterations = iterations MessageDigestPasswordEncoder messageDigestPasswordEncoderSHA256 = new MessageDigestPasswordEncoder(ENCODING_IDSHA256) - messageDigestPasswordEncoderSHA256.encodeHashAsBase64 = conf.password.encodeHashAsBase64 // false - messageDigestPasswordEncoderSHA256.iterations = conf.password.hash.iterations // 10000 + messageDigestPasswordEncoderSHA256.encodeHashAsBase64 = encodeHashAsBase64 + messageDigestPasswordEncoderSHA256.iterations = iterations - int strength = conf.password.bcrypt.logrounds - [(ENCODING_ID_BCRYPT): new BCryptPasswordEncoder(strength), + [(ENCODING_ID_BCRYPT): new BCryptPasswordEncoder(bcryptLogRounds), (ENCODING_ID_LDAP): new LdapShaPasswordEncoder(), (ENCODING_ID_MD4): new Md4PasswordEncoder(), (ENCODING_ID_MD5): messageDigestPasswordEncoderMD5, diff --git a/grails-spring-security/plugin/src/main/groovy/grails/plugin/springsecurity/aot/SpringSecurityRuntimeHints.groovy b/grails-spring-security/plugin/src/main/groovy/grails/plugin/springsecurity/aot/SpringSecurityRuntimeHints.groovy new file mode 100644 index 00000000000..e2af7147da5 --- /dev/null +++ b/grails-spring-security/plugin/src/main/groovy/grails/plugin/springsecurity/aot/SpringSecurityRuntimeHints.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 grails.plugin.springsecurity.aot + +import groovy.transform.CompileStatic + +import org.springframework.aot.hint.MemberCategory +import org.springframework.aot.hint.RuntimeHints +import org.springframework.aot.hint.RuntimeHintsRegistrar + +/** + * Registers what the plugin reaches reflectively before any bean exists. + * + *

{@code ConfigSlurper} creates the plugin's default configuration through Groovy's cached constructors, which + * {@code traceNativeMetadata} does not see, though it records everything the script goes on to call.

+ * + * @since 9.1 + */ +@CompileStatic +class SpringSecurityRuntimeHints implements RuntimeHintsRegistrar { + + @Override + void registerHints(RuntimeHints hints, ClassLoader classLoader) { + hints.reflection().registerTypeIfPresent(classLoader, 'DefaultSecurityConfig', + MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS) + } +} diff --git a/grails-spring-security/plugin/src/main/resources/META-INF/spring/aot.factories b/grails-spring-security/plugin/src/main/resources/META-INF/spring/aot.factories new file mode 100644 index 00000000000..369a0ae4882 --- /dev/null +++ b/grails-spring-security/plugin/src/main/resources/META-INF/spring/aot.factories @@ -0,0 +1,2 @@ +org.springframework.aot.hint.RuntimeHintsRegistrar=\ +grails.plugin.springsecurity.aot.SpringSecurityRuntimeHints diff --git a/grails-spring-security/plugin/src/test/groovy/grails/plugin/springsecurity/PluginBeansSpec.groovy b/grails-spring-security/plugin/src/test/groovy/grails/plugin/springsecurity/PluginBeansSpec.groovy new file mode 100644 index 00000000000..281fe4f43a3 --- /dev/null +++ b/grails-spring-security/plugin/src/test/groovy/grails/plugin/springsecurity/PluginBeansSpec.groovy @@ -0,0 +1,186 @@ +/* + * 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.boot.web.servlet.ServletListenerRegistrationBean +import org.springframework.security.authentication.AuthenticationProvider +import org.springframework.security.authentication.ProviderManager +import org.springframework.security.crypto.password.DelegatingPasswordEncoder +import org.springframework.security.crypto.password.MessageDigestPasswordEncoder +import org.springframework.security.crypto.password.PasswordEncoder +import org.springframework.security.web.DefaultSecurityFilterChain +import org.springframework.security.web.FilterChainProxy +import org.springframework.security.web.SecurityFilterChain +import org.springframework.security.web.session.HttpSessionEventPublisher +import org.springframework.security.web.util.matcher.AnyRequestMatcher +import spock.lang.Specification + +import grails.plugin.springsecurity.access.NullAfterInvocationProvider +import grails.testing.web.GrailsWebUnitTest +import grails.web.CamelCaseUrlConverter + +/** + * What the beans the plugin declares are once created, however they are declared. + */ +abstract class AbstractPluginBeansSpec 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 + } +} + +class DefaultPluginBeansSpec extends AbstractPluginBeansSpec { + + protected void configure(Object securityConfig) { + securityConfig.password = [algorithm: 'SHA-256', encodeHashAsBase64: true, hash: [iterations: 2]] + securityConfig.providerManager = [eraseCredentialsAfterAuthentication: false] + securityConfig.useHttpSessionEventPublisher = true + securityConfig.afterInvocationManagerProviderNames = ['nullAfterInvocationProvider'] + } + + void 'the password encoder encodes as the application configured it'() { + given: 'what the digest encoder makes of the values, which it only accepts if they all arrived' + def digest = new MessageDigestPasswordEncoder('SHA-256') + digest.encodeHashAsBase64 = true + digest.iterations = 2 + + when: + String encoded = applicationContext.getBean('passwordEncoder', PasswordEncoder).encode('secret') + + then: + applicationContext.getBean('passwordEncoder') instanceof DelegatingPasswordEncoder + encoded.startsWith('{SHA-256}') + digest.matches('secret', encoded - '{SHA-256}') + } + + void 'the authentication manager is told what the application configured'() { + given: + ProviderManager manager = applicationContext.getBean('authenticationManager', ProviderManager) + + expect: + !manager.eraseCredentialsAfterAuthentication + } + + void 'the filter chain proxy reads the list the plugin goes on to fill'() { + given: + List chains = applicationContext.getBean('securityFilterChains', List) + FilterChainProxy proxy = applicationContext.getBean('springSecurityFilterChainProxy', FilterChainProxy) + def chain = new DefaultSecurityFilterChain(AnyRequestMatcher.INSTANCE) + + when: + chains << chain + + then: + proxy.filterChains.contains(chain) + } + + void 'the session event publisher is registered as a listener'() { + expect: + applicationContext.getBean('httpSessionEventPublisher', ServletListenerRegistrationBean) + .listener instanceof HttpSessionEventPublisher + } + + void 'the after-invocation manager starts with a provider'() { + expect: + applicationContext.getBean('afterInvocationManager').providers*.getClass() == [NullAfterInvocationProvider] + } +} + +class BcryptPluginBeansSpec extends AbstractPluginBeansSpec { + + protected void configure(Object securityConfig) { + securityConfig.password = [algorithm: 'bcrypt', bcrypt: [logrounds: 5]] + } + + void 'the password encoder uses the rounds the application configured'() { + expect: + applicationContext.getBean('passwordEncoder', PasswordEncoder).encode('secret').startsWith('{bcrypt}$2a$05$') + } +} + +class CustomClassesPluginBeansSpec extends AbstractPluginBeansSpec { + + protected void configure(Object securityConfig) { + securityConfig.password = [algorithm: 'bcrypt'] + securityConfig.passwordEncoderBeanClass = CustomPasswordEncoder + securityConfig.authenticationManagerBeanClass = CustomProviderManager + securityConfig.springSecurityFilterChainProxyBeanClass = CustomFilterChainProxy + } + + void 'a class configured in place of a default one is created with what the default is given'() { + given: + CustomPasswordEncoder encoder = applicationContext.getBean('passwordEncoder', CustomPasswordEncoder) + + expect: + encoder.algorithm == 'bcrypt' + encoder.encoders.bcrypt + applicationContext.getBean('authenticationManager') instanceof CustomProviderManager + applicationContext.getBean('springSecurityFilterChainProxy') instanceof CustomFilterChainProxy + } + + static class CustomPasswordEncoder extends DelegatingPasswordEncoder { + + final String algorithm + final Map encoders + + CustomPasswordEncoder(String algorithm, Map encoders) { + super(algorithm, encoders) + this.algorithm = algorithm + this.encoders = encoders + } + } + + static class CustomProviderManager extends ProviderManager { + + /** The plugin sets the providers on whatever class is configured, and this one's are private to its parent. */ + List providers + + CustomProviderManager(List providers) { + super(providers) + } + } + + static class CustomFilterChainProxy extends FilterChainProxy { + + CustomFilterChainProxy(List chains) { + super(chains) + } + } +} diff --git a/grails-spring-security/plugin/src/test/groovy/grails/plugin/springsecurity/aot/PluginBeansAotSpec.groovy b/grails-spring-security/plugin/src/test/groovy/grails/plugin/springsecurity/aot/PluginBeansAotSpec.groovy new file mode 100644 index 00000000000..978d40abbd5 --- /dev/null +++ b/grails-spring-security/plugin/src/test/groovy/grails/plugin/springsecurity/aot/PluginBeansAotSpec.groovy @@ -0,0 +1,137 @@ +/* + * 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.aot + +import org.springframework.aot.generate.DefaultGenerationContext +import org.springframework.aot.generate.InMemoryGeneratedFiles +import org.springframework.aot.generate.NameGenerator +import org.springframework.context.aot.ApplicationContextAotGenerator +import org.springframework.context.support.GenericApplicationContext +import org.springframework.javapoet.ClassName +import spock.lang.Specification + +import grails.plugin.springsecurity.CustomClassesPluginBeansSpec +import grails.plugin.springsecurity.ReflectionUtils +import grails.plugin.springsecurity.SpringSecurityCoreGrailsPlugin +import grails.plugin.springsecurity.SpringSecurityUtils +import grails.spring.BeanBuilder +import grails.testing.web.GrailsWebUnitTest + +/** + * Runs Spring's own ahead-of-time generator over the beans the plugin declares, which an application's + * {@code processAot} does with them, and which fails where a bean holds a value it cannot write out or + * has constructors it cannot choose between. + */ +abstract class AbstractPluginBeansAotSpec extends Specification implements GrailsWebUnitTest { + + Set getIncludePlugins() { + ['core'] as Set + } + + Closure doWithConfig() { + { config -> + configure(config.grails.plugin.springsecurity) + } + } + + protected abstract void configure(Object securityConfig) + + void cleanupSpec() { + SpringSecurityUtils.resetSecurityConfig() + ReflectionUtils.application = null + SpringSecurityUtils.application = null + } + + void 'what the plugin declares can be written out ahead of time'() { + given: + def plugin = new SpringSecurityCoreGrailsPlugin(grailsApplication: grailsApplication) + def builder = new BeanBuilder(null, getClass().classLoader) + builder.beans(plugin.doWithSpring()) + def context = new GenericApplicationContext() + builder.registerBeans(context) + def generationContext = new DefaultGenerationContext( + new NameGenerator(ClassName.get('generated', 'Application')), new InMemoryGeneratedFiles()) + + when: + new ApplicationContextAotGenerator().processAheadOfTime(context, generationContext) + + then: + noExceptionThrown() + context.getBeanDefinition('passwordEncoder') + context.getBeanDefinition('authenticationManager') + context.getBeanDefinition('springSecurityFilterChainProxy') + } +} + +class AnnotationConfigPluginBeansAotSpec extends AbstractPluginBeansAotSpec { + + protected void configure(Object securityConfig) { + securityConfig.securityConfigType = 'Annotation' + } +} + +class RequestmapPluginBeansAotSpec extends AbstractPluginBeansAotSpec { + + protected void configure(Object securityConfig) { + securityConfig.securityConfigType = 'Requestmap' + } +} + +class InterceptUrlMapPluginBeansAotSpec extends AbstractPluginBeansAotSpec { + + protected void configure(Object securityConfig) { + securityConfig.securityConfigType = 'InterceptUrlMap' + } +} + +class OptionalFiltersPluginBeansAotSpec extends AbstractPluginBeansAotSpec { + + protected void configure(Object securityConfig) { + securityConfig.securityConfigType = 'InterceptUrlMap' + securityConfig.useBasicAuth = true + securityConfig.useSwitchUserFilter = true + securityConfig.useX509 = true + securityConfig.useSecurityEventListener = true + securityConfig.useHttpSessionEventPublisher = true + securityConfig.registerLoggerListener = true + securityConfig.debug = [useFilter: true] + securityConfig.cacheUsers = true + securityConfig.secureChannel = [definition: [[pattern: '/secure/**', access: 'REQUIRES_SECURE_CHANNEL']]] + securityConfig.ipRestrictions = [[pattern: '/admin/**', access: ['127.0.0.1']]] + securityConfig.afterInvocationManagerProviderNames = ['afterInvocationProvider'] + } +} + +class PersistentRememberMePluginBeansAotSpec extends AbstractPluginBeansAotSpec { + + protected void configure(Object securityConfig) { + securityConfig.securityConfigType = 'InterceptUrlMap' + securityConfig.rememberMe = [persistent: true, persistentToken: [domainClassName: 'test.PersistentLogin']] + } +} + +class CustomClassesPluginBeansAotSpec extends AbstractPluginBeansAotSpec { + + protected void configure(Object securityConfig) { + securityConfig.securityConfigType = 'InterceptUrlMap' + securityConfig.passwordEncoderBeanClass = CustomClassesPluginBeansSpec.CustomPasswordEncoder + securityConfig.authenticationManagerBeanClass = CustomClassesPluginBeansSpec.CustomProviderManager + securityConfig.springSecurityFilterChainProxyBeanClass = CustomClassesPluginBeansSpec.CustomFilterChainProxy + } +} diff --git a/grails-spring-security/plugin/src/test/groovy/grails/plugin/springsecurity/aot/SpringSecurityRuntimeHintsSpec.groovy b/grails-spring-security/plugin/src/test/groovy/grails/plugin/springsecurity/aot/SpringSecurityRuntimeHintsSpec.groovy new file mode 100644 index 00000000000..c4e9f1b2452 --- /dev/null +++ b/grails-spring-security/plugin/src/test/groovy/grails/plugin/springsecurity/aot/SpringSecurityRuntimeHintsSpec.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.aot + +import org.springframework.aot.hint.MemberCategory +import org.springframework.aot.hint.RuntimeHints +import org.springframework.aot.hint.RuntimeHintsRegistrar +import org.springframework.aot.hint.TypeReference +import org.springframework.aot.hint.predicate.RuntimeHintsPredicates +import org.springframework.core.io.support.SpringFactoriesLoader +import spock.lang.Specification + +class SpringSecurityRuntimeHintsSpec extends Specification { + + void 'the default configuration can be created in an image'() { + given: + RuntimeHints hints = new RuntimeHints() + + when: + new SpringSecurityRuntimeHints().registerHints(hints, getClass().classLoader) + + then: 'the script the plugin loads its defaults from is compiled, and so found by name' + getClass().classLoader.loadClass('DefaultSecurityConfig').getConstructor() + RuntimeHintsPredicates.reflection() + .onType(TypeReference.of('DefaultSecurityConfig')) + .withMemberCategory(MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS) + .test(hints) + } + + void 'ahead-of-time processing finds the hints'() { + expect: + SpringFactoriesLoader.forResourceLocation('META-INF/spring/aot.factories') + .load(RuntimeHintsRegistrar)*.getClass() + .contains(SpringSecurityRuntimeHints) + } +} From e149adac14587b4abffb881e8d5b6abc021ce8f8 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Thu, 5 Nov 2026 17:46:03 -0800 Subject: [PATCH 25/78] Let digest authentication start and sign users in useDigestAuth with its default of hashed passwords failed at startup: the plugin named DigestAuthPasswordEncoder, a class that no longer exists, and could not be brought back, since PasswordEncoder is no longer given the username the hash needs. The guide still described it, along with an encodePassword(password, username) that no longer exists. With digest.useCleartextPasswords it started but signed nobody in. The DelegatingPasswordEncoder it used stored {noop}secret, and the filter hashes what is stored as a browser hashes the password. Now what a user has stored by default is the hash a browser computes, which the application computes and the guide shows, and passwordEncoder stays as configured. With cleartext passwords it is a NoOpPasswordEncoder, so what is stored is what was typed and a form signs in as well. Found by running Spring's ahead-of-time generator over the plugin's beans with each option on. DigestAuthenticationSpec makes the handshake a browser makes against the plugin's real entry point and filter. --- .../authentication/basicAndDigestAuth.adoc | 27 ++- .../src/en/guide/upgrading/upgrading90x.adoc | 6 + .../SpringSecurityCoreGrailsPlugin.groovy | 23 ++- .../DigestAuthenticationSpec.groovy | 166 ++++++++++++++++++ .../aot/PluginBeansAotSpec.groovy | 17 ++ 5 files changed, 211 insertions(+), 28 deletions(-) create mode 100644 grails-spring-security/plugin/src/test/groovy/grails/plugin/springsecurity/DigestAuthenticationSpec.groovy diff --git a/grails-doc/src/en/guide/security/securityPlugins/springSecurity/core/authentication/basicAndDigestAuth.adoc b/grails-doc/src/en/guide/security/securityPlugins/springSecurity/core/authentication/basicAndDigestAuth.adoc index 4c0e7e3911a..bd01cf7ce8a 100644 --- a/grails-doc/src/en/guide/security/securityPlugins/springSecurity/core/authentication/basicAndDigestAuth.adoc +++ b/grails-doc/src/en/guide/security/securityPlugins/springSecurity/core/authentication/basicAndDigestAuth.adoc @@ -89,7 +89,7 @@ https://en.wikipedia.org/wiki/Digest_access_authentication[Digest Authentication |digest.passwordAlreadyEncoded |`false` -|Whether you are managing the password hashing yourself +|Whether what is stored is already the hash a browser computes. Set for you unless `digest.useCleartextPasswords` is `true` |digest.createAuthenticatedToken |`false` @@ -97,12 +97,19 @@ https://en.wikipedia.org/wiki/Digest_access_authentication[Digest Authentication |digest.useCleartextPasswords |`false` -|If `true`, a cleartext password encoder is used (not recommended). If `false`, passwords hashed by `DigestAuthPasswordEncoder` are stored in the database +|If `true`, passwords are stored as they were typed (not recommended). If `false`, the hash a browser computes from the username, realm name and password is stored |==================== Digest authentication has a problem in that by default you store cleartext passwords in your database. This is because the browser hashes your password along with the username and Realm name, and this is compared to the password hashed using the same algorithm during authentication. The browser does not know about your `MessageDigest` algorithm or salt source, so to hash them the same way you need to load a cleartext password from the database. -The plugin does provide an alternative, although it has no configuration options (in particular the digest algorithm cannot be changed). If `digest.useCleartextPasswords` is `false` (the default), then the `passwordEncoder` bean is replaced with an instance of `grails.plugin.springsecurity.authentication.encoding.DigestAuthPasswordEncoder`. This encoder uses the same approach as the browser, that is, it combines your password along with your username and Realm name essentially as a salt, and hashes with MD5. MD5 is not recommended in general, but given the typical size of the salt it is reasonably safe to use. +The alternative is to store what the browser computes instead of the password. That is the default: with `digest.useCleartextPasswords` set to `false`, what a user has stored must be the MD5 hash of `username:realm:password`, which is what the filter needs and no more. MD5 is not recommended in general, but the username and realm name act as a salt. Changing the realm name makes every stored hash stop matching. + +The `passwordEncoder` bean cannot compute this hash, because an encoder is not given the username, so your application computes it wherever it saves a password: + +[source,groovy] +---- +password = "${username}:${realmName}:${password}".md5() +---- The only required attribute is `useDigestAuth`, which you must set to `true`, but you probably also want to change the realm name: @@ -116,17 +123,5 @@ Digest authentication cannot be applied to a subset of URLs like Basic authentic [NOTE] ==== -Note that since the Digest authentication password encoder is different from the typical encoders you must pass the username as the "`salt`" value. The code in the generated User class assumes you're not using a salt value, so you'll need to change the code in `encodePassword()` from - -[source,groovy] ----- -password = springSecurityService.encodePassword(password) ----- - -to - -[source,groovy] ----- -password = springSecurityService.encodePassword(password, username) ----- +What `s2-quickstart` generates hashes a password with `springSecurityService.encodePassword(password)`, in the user class or in its password encoder listener, which gives the wrong value for Digest authentication. Replace that call with the hash above, or set `digest.useCleartextPasswords` to `true`. With that set, `passwordEncoder` stores passwords as they were typed, so a form can sign a user in as well. Otherwise a form cannot sign in a user who has a Digest hash stored, because it authenticates against `passwordEncoder`, which stays as you configured it and does not recognize the hash. ==== diff --git a/grails-doc/src/en/guide/upgrading/upgrading90x.adoc b/grails-doc/src/en/guide/upgrading/upgrading90x.adoc index 000f1aad023..4acf7f1d83b 100644 --- a/grails-doc/src/en/guide/upgrading/upgrading90x.adoc +++ b/grails-doc/src/en/guide/upgrading/upgrading90x.adoc @@ -119,6 +119,12 @@ A denied request for `/apple-touch-icon.png`, `/manifest.json` or the `/.well-kn 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. +* *Digest authentication in the Spring Security plugin starts and signs users in.* +`useDigestAuth` with its default of hashed passwords used to fail at startup, naming an encoder that no longer exists. +What a user has stored is now the hash a browser computes, which the application computes, as the link:security.html#core-basicAndDigestAuth[guide] shows. +With `digest.useCleartextPasswords`, nobody could sign in with Digest authentication, because the password encoder stored `{noop}secret`. +It now stores what was typed, so an application that signed in through a form with stored values such as `{noop}secret` removes the `{noop}` prefix from them. + [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/src/main/groovy/grails/plugin/springsecurity/SpringSecurityCoreGrailsPlugin.groovy b/grails-spring-security/plugin/src/main/groovy/grails/plugin/springsecurity/SpringSecurityCoreGrailsPlugin.groovy index 29b9333aeda..1343535eb1d 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 @@ -748,13 +748,6 @@ class SpringSecurityCoreGrailsPlugin extends Plugin { applicationContext.registerAlias 'securityDebugFilter', 'springSecurityFilterChain' } - if (conf.useDigestAuth) { - def passwordEncoder = applicationContext.passwordEncoder -// TODO if (passwordEncoder instanceof DigestAuthPasswordEncoder) { -// passwordEncoder.resetInitializing() -// } - } - if (conf.rejectRequestsDuringStartup) { // the startup gate opens once this has run and the application has started applicationContext.springSecurityStartupGateFilter.markInitialized() @@ -911,14 +904,20 @@ class SpringSecurityCoreGrailsPlugin extends Plugin { private configureDigestAuth = { conf -> if (conf.digest.useCleartextPasswords) { - passwordEncoder(classFor('passwordEncoder', DelegatingPasswordEncoder), ENCODING_ID_NOOP, idToPasswordEncoder(conf)) + // the filter hashes what is stored as a browser hashes the password, so an encoder adding its id to it would + // leave nothing a browser could match + Class passwordEncoderClass = classFor('passwordEncoder', NoOpPasswordEncoder) + boolean defaultEncoder = passwordEncoderClass == NoOpPasswordEncoder + passwordEncoder(passwordEncoderClass) { bean -> + if (defaultEncoder) { + bean.factoryMethod = 'getInstance' + } + } } else { + // what is stored is the hash a browser computes, which no PasswordEncoder can make since it is not given the + // username, so the application makes it, and passwordEncoder stays as it was for what else it is used for conf.digest.passwordAlreadyEncoded = true - conf.dao.reflectionSaltSourceProperty = conf.userLookup.usernamePropertyName - passwordEncoder(classFor('passwordEncoder', DigestAuthPasswordEncoder)) { - realm = conf.digest.realmName - } } digestAuthenticationEntryPoint(classFor('digestAuthenticationEntryPoint', DigestAuthenticationEntryPoint)) { diff --git a/grails-spring-security/plugin/src/test/groovy/grails/plugin/springsecurity/DigestAuthenticationSpec.groovy b/grails-spring-security/plugin/src/test/groovy/grails/plugin/springsecurity/DigestAuthenticationSpec.groovy new file mode 100644 index 00000000000..ee7916075dc --- /dev/null +++ b/grails-spring-security/plugin/src/test/groovy/grails/plugin/springsecurity/DigestAuthenticationSpec.groovy @@ -0,0 +1,166 @@ +/* + * 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.MockFilterChain +import org.springframework.mock.web.MockHttpServletRequest +import org.springframework.mock.web.MockHttpServletResponse +import org.springframework.security.authentication.BadCredentialsException +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken +import org.springframework.security.core.Authentication +import org.springframework.security.core.authority.SimpleGrantedAuthority +import org.springframework.security.core.context.SecurityContextHolder +import org.springframework.security.core.userdetails.User +import org.springframework.security.core.userdetails.UserDetails +import org.springframework.security.core.userdetails.UserDetailsService +import org.springframework.security.crypto.password.PasswordEncoder +import spock.lang.Specification + +import grails.core.GrailsApplication +import grails.testing.web.GrailsWebUnitTest +import grails.web.CamelCaseUrlConverter + +/** + * The handshake a browser makes, against what the plugin creates with {@code useDigestAuth}: the challenge from its + * entry point, and the response its filter checks against what a user has stored. + */ +abstract class AbstractDigestAuthenticationSpec extends Specification implements GrailsWebUnitTest { + + protected static final String REALM = 'Test Realm' + + Set getIncludePlugins() { + ['core', 'springSecurityCore'] as Set + } + + Closure doWithSpring() { + { -> + grailsUrlConverter(CamelCaseUrlConverter) + } + } + + Closure doWithConfig() { + { config -> + config.grails.plugin.springsecurity.securityConfigType = 'InterceptUrlMap' + config.grails.plugin.springsecurity.useDigestAuth = true + config.grails.plugin.springsecurity.userDetailsServiceBeanClass = StoredPasswordUserDetailsService + config.grails.plugin.springsecurity.digest = digestConfig() + } + } + + protected abstract Map digestConfig() + + void cleanup() { + SecurityContextHolder.clearContext() + } + + void cleanupSpec() { + SpringSecurityUtils.resetSecurityConfig() + ReflectionUtils.application = null + SpringSecurityUtils.application = null + } + + protected void store(String password) { + applicationContext.getBean('userDetailsService', StoredPasswordUserDetailsService).password = password + } + + /** Who a browser sending this password is signed in as, if anyone. */ + protected String signedInWith(String password) { + def challenge = new MockHttpServletResponse() + applicationContext.getBean('digestAuthenticationEntryPoint') + .commence(new MockHttpServletRequest(), challenge, new BadCredentialsException('no credentials yet')) + String header = challenge.getHeader('WWW-Authenticate') + String realm = (header =~ /realm="([^"]*)"/)[0][1] + String nonce = (header =~ /nonce="([^"]*)"/)[0][1] + + String ha1 = "user:${realm}:${password}".md5() + String ha2 = 'GET:/secure'.md5() + String response = "${ha1}:${nonce}:00000001:cnonce:auth:${ha2}".md5() + + def request = new MockHttpServletRequest('GET', '/secure') + request.addHeader('Authorization', "Digest username=\"user\", realm=\"${realm}\", nonce=\"${nonce}\", " + + "uri=\"/secure\", qop=auth, nc=00000001, cnonce=\"cnonce\", response=\"${response}\"") + SecurityContextHolder.clearContext() + applicationContext.getBean('digestAuthenticationFilter') + .doFilter(request, new MockHttpServletResponse(), new MockFilterChain()) + SecurityContextHolder.context.authentication?.name + } + + static class StoredPasswordUserDetailsService implements UserDetailsService { + + GrailsApplication grailsApplication + String password + + @Override + UserDetails loadUserByUsername(String username) { + new User(username, password, [new SimpleGrantedAuthority('ROLE_USER')]) + } + } +} + +class EncodedDigestAuthenticationSpec extends AbstractDigestAuthenticationSpec { + + protected Map digestConfig() { + [realmName: REALM] + } + + void 'by default what is stored is the hash a browser computes, and not the password'() { + given: + store("user:${REALM}:secret".md5()) + + expect: + signedInWith('secret') == 'user' + signedInWith('wrong') == null + } + + void 'a password stored as it was typed does not sign anyone in'() { + given: + store('secret') + + expect: + signedInWith('secret') == null + } +} + +class CleartextDigestAuthenticationSpec extends AbstractDigestAuthenticationSpec { + + protected Map digestConfig() { + [realmName: REALM, useCleartextPasswords: true] + } + + void 'with cleartext passwords what the password encoder stores is what the filter hashes'() { + given: + store(applicationContext.getBean('passwordEncoder', PasswordEncoder).encode('secret')) + + expect: + signedInWith('secret') == 'user' + signedInWith('wrong') == null + } + + void 'with cleartext passwords a form still signs a user in'() { + given: + store(applicationContext.getBean('passwordEncoder', PasswordEncoder).encode('secret')) + + when: + Authentication signedIn = applicationContext.getBean('daoAuthenticationProvider') + .authenticate(UsernamePasswordAuthenticationToken.unauthenticated('user', 'secret')) + + then: + signedIn.authenticated + } +} diff --git a/grails-spring-security/plugin/src/test/groovy/grails/plugin/springsecurity/aot/PluginBeansAotSpec.groovy b/grails-spring-security/plugin/src/test/groovy/grails/plugin/springsecurity/aot/PluginBeansAotSpec.groovy index 978d40abbd5..86b989b932b 100644 --- a/grails-spring-security/plugin/src/test/groovy/grails/plugin/springsecurity/aot/PluginBeansAotSpec.groovy +++ b/grails-spring-security/plugin/src/test/groovy/grails/plugin/springsecurity/aot/PluginBeansAotSpec.groovy @@ -135,3 +135,20 @@ class CustomClassesPluginBeansAotSpec extends AbstractPluginBeansAotSpec { securityConfig.springSecurityFilterChainProxyBeanClass = CustomClassesPluginBeansSpec.CustomFilterChainProxy } } + +class CleartextDigestPluginBeansAotSpec extends AbstractPluginBeansAotSpec { + + protected void configure(Object securityConfig) { + securityConfig.securityConfigType = 'InterceptUrlMap' + securityConfig.useDigestAuth = true + securityConfig.digest = [useCleartextPasswords: true] + } +} + +class EncodedDigestPluginBeansAotSpec extends AbstractPluginBeansAotSpec { + + protected void configure(Object securityConfig) { + securityConfig.securityConfigType = 'InterceptUrlMap' + securityConfig.useDigestAuth = true + } +} From 0e5ca6d5a1c7d15fc8e2dfa08db447707ad05ca8 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Thu, 5 Nov 2026 18:06:51 -0800 Subject: [PATCH 26/78] Authenticate what a filter leaves unauthenticated before deciding access The previous commit's handshake spec called DigestAuthenticationFilter on its own, and passed, but over HTTP a right password was answered with 403. The filter leaves an unauthenticated token so that the account checks of the authentication manager run. The compat FilterSecurityInterceptor went straight to the access decision, where isAuthenticated() is false. It now authenticates it first, as Spring Security's own interceptor did before Spring Security 7 removed it, and honours fii.alwaysReauthenticate, which did nothing. The authentication manager is handed what is stored as the credentials, to be compared with itself, so passwordEncoder is a NoOpPasswordEncoder with hashed passwords too, unless a class is configured. A disabled account is refused. DigestAuthenticationSpec now sends the response through the whole filter chain. It fails without this, and curl --digest against a running application gets 200 and 401 for a right and a wrong password in both modes. --- .../authentication/basicAndDigestAuth.adoc | 2 +- .../src/en/guide/upgrading/upgrading90x.adoc | 3 + .../FilterSecurityInterceptor.groovy | 22 +++++- .../SpringSecurityCoreGrailsPlugin.groovy | 20 +++--- .../DigestAuthenticationSpec.groovy | 45 +++++++++--- .../FilterSecurityInterceptorSpec.groovy | 72 +++++++++++++++++++ 6 files changed, 140 insertions(+), 24 deletions(-) diff --git a/grails-doc/src/en/guide/security/securityPlugins/springSecurity/core/authentication/basicAndDigestAuth.adoc b/grails-doc/src/en/guide/security/securityPlugins/springSecurity/core/authentication/basicAndDigestAuth.adoc index bd01cf7ce8a..6a5af9cf84b 100644 --- a/grails-doc/src/en/guide/security/securityPlugins/springSecurity/core/authentication/basicAndDigestAuth.adoc +++ b/grails-doc/src/en/guide/security/securityPlugins/springSecurity/core/authentication/basicAndDigestAuth.adoc @@ -123,5 +123,5 @@ Digest authentication cannot be applied to a subset of URLs like Basic authentic [NOTE] ==== -What `s2-quickstart` generates hashes a password with `springSecurityService.encodePassword(password)`, in the user class or in its password encoder listener, which gives the wrong value for Digest authentication. Replace that call with the hash above, or set `digest.useCleartextPasswords` to `true`. With that set, `passwordEncoder` stores passwords as they were typed, so a form can sign a user in as well. Otherwise a form cannot sign in a user who has a Digest hash stored, because it authenticates against `passwordEncoder`, which stays as you configured it and does not recognize the hash. +What `s2-quickstart` generates hashes a password with `springSecurityService.encodePassword(password)`, in the user class or in its password encoder listener, which gives the wrong value for Digest authentication. Replace that call with the hash above, or set `digest.useCleartextPasswords` to `true`. With Digest authentication `passwordEncoder` compares a password as it is with what is stored, because the filter hands it what is stored as the credentials. So a form can sign a user in with cleartext passwords stored, and cannot with the hash stored. ==== diff --git a/grails-doc/src/en/guide/upgrading/upgrading90x.adoc b/grails-doc/src/en/guide/upgrading/upgrading90x.adoc index 4acf7f1d83b..f9b4f401502 100644 --- a/grails-doc/src/en/guide/upgrading/upgrading90x.adoc +++ b/grails-doc/src/en/guide/upgrading/upgrading90x.adoc @@ -125,6 +125,9 @@ What a user has stored is now the hash a browser computes, which the application With `digest.useCleartextPasswords`, nobody could sign in with Digest authentication, because the password encoder stored `{noop}secret`. It now stores what was typed, so an application that signed in through a form with stored values such as `{noop}secret` removes the `{noop}` prefix from them. +* *`fii.alwaysReauthenticate` in the Spring Security plugin takes effect.* +The setting did nothing, because the plugin's security interceptor went straight to the access decision. An application that sets it now has every request authenticated again, as the setting describes. + [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/compat/src/main/groovy/org/springframework/security/web/access/intercept/FilterSecurityInterceptor.groovy b/grails-spring-security/compat/src/main/groovy/org/springframework/security/web/access/intercept/FilterSecurityInterceptor.groovy index ac716a25670..0a97429c460 100644 --- a/grails-spring-security/compat/src/main/groovy/org/springframework/security/web/access/intercept/FilterSecurityInterceptor.groovy +++ b/grails-spring-security/compat/src/main/groovy/org/springframework/security/web/access/intercept/FilterSecurityInterceptor.groovy @@ -29,6 +29,8 @@ import jakarta.servlet.ServletResponse import org.springframework.security.access.intercept.AbstractSecurityInterceptor import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException +import org.springframework.security.core.Authentication +import org.springframework.security.core.context.SecurityContext import org.springframework.security.core.context.SecurityContextHolder import org.springframework.security.web.FilterInvocation @@ -65,16 +67,32 @@ class FilterSecurityInterceptor extends AbstractSecurityInterceptor implements F return } - def authentication = SecurityContextHolder.context?.authentication + Authentication authentication = SecurityContextHolder.context?.authentication if (authentication == null) { throw new AuthenticationCredentialsNotFoundException('An Authentication object was not found in the SecurityContext') } - accessDecisionManager?.decide(authentication, invocation, attributes) + accessDecisionManager?.decide(authenticateIfRequired(authentication), invocation, attributes) if (!invocation.response.committed) { chain.doFilter(request, response) } } + /** + * Authenticates what a filter left in the context without doing so, as {@code DigestAuthenticationFilter} does so + * that the account checks of the authentication manager still run, or everything if {@code alwaysReauthenticate} + * is set. Spring Security's own {@code AbstractSecurityInterceptor} did this before Spring Security 7 removed it. + */ + private Authentication authenticateIfRequired(Authentication authentication) { + if (authentication.authenticated && !alwaysReauthenticate) { + return authentication + } + Authentication authenticated = authenticationManager.authenticate(authentication) + SecurityContext context = SecurityContextHolder.createEmptyContext() + context.authentication = authenticated + SecurityContextHolder.context = context + authenticated + } + @Override void destroy() { } 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 1343535eb1d..019e8eab638 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 @@ -903,20 +903,16 @@ class SpringSecurityCoreGrailsPlugin extends Plugin { private configureDigestAuth = { conf -> - if (conf.digest.useCleartextPasswords) { - // the filter hashes what is stored as a browser hashes the password, so an encoder adding its id to it would - // leave nothing a browser could match - Class passwordEncoderClass = classFor('passwordEncoder', NoOpPasswordEncoder) - boolean defaultEncoder = passwordEncoderClass == NoOpPasswordEncoder - passwordEncoder(passwordEncoderClass) { bean -> - if (defaultEncoder) { - bean.factoryMethod = 'getInstance' - } + // the filter hands what is stored to the authentication manager as the credentials, to be compared with itself + if (classFor('passwordEncoder', NoOpPasswordEncoder) == NoOpPasswordEncoder) { + passwordEncoder(NoOpPasswordEncoder) { bean -> + bean.factoryMethod = 'getInstance' } } - else { - // what is stored is the hash a browser computes, which no PasswordEncoder can make since it is not given the - // username, so the application makes it, and passwordEncoder stays as it was for what else it is used for + + // what is stored is the hash a browser computes, which no PasswordEncoder can make since it is not given the + // username, so the application makes it + if (!conf.digest.useCleartextPasswords) { conf.digest.passwordAlreadyEncoded = true } diff --git a/grails-spring-security/plugin/src/test/groovy/grails/plugin/springsecurity/DigestAuthenticationSpec.groovy b/grails-spring-security/plugin/src/test/groovy/grails/plugin/springsecurity/DigestAuthenticationSpec.groovy index ee7916075dc..7b5b9222e93 100644 --- a/grails-spring-security/plugin/src/test/groovy/grails/plugin/springsecurity/DigestAuthenticationSpec.groovy +++ b/grails-spring-security/plugin/src/test/groovy/grails/plugin/springsecurity/DigestAuthenticationSpec.groovy @@ -18,7 +18,8 @@ */ package grails.plugin.springsecurity -import org.springframework.mock.web.MockFilterChain +import jakarta.servlet.FilterChain + import org.springframework.mock.web.MockHttpServletRequest import org.springframework.mock.web.MockHttpServletResponse import org.springframework.security.authentication.BadCredentialsException @@ -38,7 +39,7 @@ import grails.web.CamelCaseUrlConverter /** * The handshake a browser makes, against what the plugin creates with {@code useDigestAuth}: the challenge from its - * entry point, and the response its filter checks against what a user has stored. + * entry point, and the response sent through its whole filter chain, which is what grants the request. */ abstract class AbstractDigestAuthenticationSpec extends Specification implements GrailsWebUnitTest { @@ -57,6 +58,7 @@ abstract class AbstractDigestAuthenticationSpec extends Specification implements Closure doWithConfig() { { config -> config.grails.plugin.springsecurity.securityConfigType = 'InterceptUrlMap' + config.grails.plugin.springsecurity.interceptUrlMap = [[pattern: '/secure', access: ['isAuthenticated()']]] config.grails.plugin.springsecurity.useDigestAuth = true config.grails.plugin.springsecurity.userDetailsServiceBeanClass = StoredPasswordUserDetailsService config.grails.plugin.springsecurity.digest = digestConfig() @@ -75,11 +77,13 @@ abstract class AbstractDigestAuthenticationSpec extends Specification implements SpringSecurityUtils.application = null } - protected void store(String password) { - applicationContext.getBean('userDetailsService', StoredPasswordUserDetailsService).password = password + protected void store(String password, boolean enabled = true) { + def users = applicationContext.getBean('userDetailsService', StoredPasswordUserDetailsService) + users.password = password + users.enabled = enabled } - /** Who a browser sending this password is signed in as, if anyone. */ + /** Who a browser sending this password reaches the application as, if it reaches it. */ protected String signedInWith(String password) { def challenge = new MockHttpServletResponse() applicationContext.getBean('digestAuthenticationEntryPoint') @@ -93,22 +97,25 @@ abstract class AbstractDigestAuthenticationSpec extends Specification implements String response = "${ha1}:${nonce}:00000001:cnonce:auth:${ha2}".md5() def request = new MockHttpServletRequest('GET', '/secure') + request.servletPath = '/secure' request.addHeader('Authorization', "Digest username=\"user\", realm=\"${realm}\", nonce=\"${nonce}\", " + "uri=\"/secure\", qop=auth, nc=00000001, cnonce=\"cnonce\", response=\"${response}\"") + String reached = null + FilterChain application = { req, res -> reached = SecurityContextHolder.context.authentication.name } as FilterChain SecurityContextHolder.clearContext() - applicationContext.getBean('digestAuthenticationFilter') - .doFilter(request, new MockHttpServletResponse(), new MockFilterChain()) - SecurityContextHolder.context.authentication?.name + applicationContext.getBean('springSecurityFilterChainProxy').doFilter(request, new MockHttpServletResponse(), application) + reached } static class StoredPasswordUserDetailsService implements UserDetailsService { GrailsApplication grailsApplication String password + boolean enabled = true @Override UserDetails loadUserByUsername(String username) { - new User(username, password, [new SimpleGrantedAuthority('ROLE_USER')]) + new User(username, password, enabled, true, true, true, [new SimpleGrantedAuthority('ROLE_USER')]) } } } @@ -135,6 +142,26 @@ class EncodedDigestAuthenticationSpec extends AbstractDigestAuthenticationSpec { expect: signedInWith('secret') == null } + + void 'an account that is disabled is refused, however right the password'() { + given: + store("user:${REALM}:secret".md5(), false) + + expect: + signedInWith('secret') == null + } + + void 'a form cannot sign in a user with the hash stored'() { + given: + store("user:${REALM}:secret".md5()) + + when: + applicationContext.getBean('daoAuthenticationProvider') + .authenticate(UsernamePasswordAuthenticationToken.unauthenticated('user', 'secret')) + + then: + thrown(BadCredentialsException) + } } class CleartextDigestAuthenticationSpec extends AbstractDigestAuthenticationSpec { diff --git a/grails-spring-security/plugin/src/test/groovy/grails/plugin/springsecurity/web/access/intercept/FilterSecurityInterceptorSpec.groovy b/grails-spring-security/plugin/src/test/groovy/grails/plugin/springsecurity/web/access/intercept/FilterSecurityInterceptorSpec.groovy index 36d8bd48f38..b6a774ba181 100644 --- a/grails-spring-security/plugin/src/test/groovy/grails/plugin/springsecurity/web/access/intercept/FilterSecurityInterceptorSpec.groovy +++ b/grails-spring-security/plugin/src/test/groovy/grails/plugin/springsecurity/web/access/intercept/FilterSecurityInterceptorSpec.groovy @@ -28,6 +28,8 @@ import org.springframework.security.access.AccessDeniedException import org.springframework.security.access.SecurityConfig import org.springframework.security.access.vote.RoleVoter import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException +import org.springframework.security.authentication.AuthenticationManager +import org.springframework.security.authentication.BadCredentialsException import org.springframework.security.authentication.UsernamePasswordAuthenticationToken import org.springframework.security.core.authority.AuthorityUtils import org.springframework.security.core.context.SecurityContextHolder @@ -105,6 +107,76 @@ class FilterSecurityInterceptorSpec extends AbstractUnitSpec { 0 * chain._ } + void 'what a filter left unauthenticated is authenticated before the access decision'() { + given: + def left = UsernamePasswordAuthenticationToken.unauthenticated('user', 'stored') + def authenticated = UsernamePasswordAuthenticationToken.authenticated( + 'user', 'stored', AuthorityUtils.createAuthorityList('ROLE_USER')) + SecurityContextHolder.context.authentication = left + def interceptor = interceptorFor(Mock(AuthenticationManager), Mock(AccessDecisionManager)) + FilterChain chain = Mock() + + when: + interceptor.doFilter(request, response, chain) + + then: + 1 * interceptor.authenticationManager.authenticate(left) >> authenticated + + then: + 1 * interceptor.accessDecisionManager.decide(authenticated, _ as FilterInvocation, _) + + then: + 1 * chain.doFilter(request, response) + SecurityContextHolder.context.authentication.is(authenticated) + } + + void 'what the authentication manager refuses never reaches the access decision'() { + given: + SecurityContextHolder.context.authentication = UsernamePasswordAuthenticationToken.unauthenticated('user', 'stored') + def interceptor = interceptorFor( + Stub(AuthenticationManager) { authenticate(_) >> { throw new BadCredentialsException('refused') } }, + Mock(AccessDecisionManager)) + FilterChain chain = Mock() + + when: + interceptor.doFilter(request, response, chain) + + then: + thrown(BadCredentialsException) + 0 * interceptor.accessDecisionManager._ + 0 * chain._ + } + + void 'what is authenticated already is left alone unless alwaysReauthenticate is set'() { + given: + def authentication = UsernamePasswordAuthenticationToken.authenticated( + 'user', 'password', AuthorityUtils.createAuthorityList('ROLE_USER')) + SecurityContextHolder.context.authentication = authentication + def interceptor = interceptorFor(Mock(AuthenticationManager), Mock(AccessDecisionManager)) + interceptor.alwaysReauthenticate = always + + when: + interceptor.doFilter(request, response, Stub(FilterChain)) + + then: + times * interceptor.authenticationManager.authenticate(authentication) >> authentication + + where: + always | times + false | 0 + true | 1 + } + + private FilterSecurityInterceptor interceptorFor(AuthenticationManager manager, AccessDecisionManager decisions) { + new FilterSecurityInterceptor( + authenticationManager: manager, + accessDecisionManager: decisions, + securityMetadataSource: Stub(FilterInvocationSecurityMetadataSource) { + getAttributes(_ as FilterInvocation) >> [new SecurityConfig('ROLE_USER')] + } + ) + } + void 'secured filter chain responds with #status for #scenario'() { given: if (role != null) { From 285fa77e412dc6ef7cec6bc36fad820a2c44b8d1 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Thu, 5 Nov 2026 18:52:43 -0800 Subject: [PATCH 27/78] Load what the embedded MongoDB's event loops need as it starts With Spring Boot 4.2.0-RC2's Netty 4.2.20, an application with the in-memory backend run from its executable jar hung when it was stopped, every time, and so did traceNativeMetadata, which then recorded nothing. With Netty 4.2.19 it stopped in a second. Spring Boot's ClearCachesApplicationListener closes the jars of its class loader when the context has refreshed, and a class being loaded at that moment fails with IllegalStateException: Zip file closed. The driver connects just before it, and reading its first bytes allocates the event loop's first buffer. Netty logs the failure, Logback fails the same way to load a class to log it, and that ends the event loop's thread. The driver gets no answer, and stopping the server waits forever for its connection on that thread to close. The server now answers one isMaster as it starts, so the event loop has loaded what the first client needs long before that moment. The race is Spring Boot's, and remains for anything else loading a class right then. ClearedJarsServerApplication fails class loading for a moment as a client sends its first bytes. The spec fails without this. --- .../embedded/InMemoryMongoBackend.java | 61 ++++++++++ .../EmbeddedMongoLifecycleSpec.groovy | 28 ++++- .../ClearedJarsServerApplication.java | 113 ++++++++++++++++++ 3 files changed, 198 insertions(+), 4 deletions(-) create mode 100644 grails-data-mongodb/embedded/src/test/java/org/grails/datastore/gorm/mongodb/embedded/ClearedJarsServerApplication.java diff --git a/grails-data-mongodb/embedded/src/main/java/org/grails/datastore/gorm/mongodb/embedded/InMemoryMongoBackend.java b/grails-data-mongodb/embedded/src/main/java/org/grails/datastore/gorm/mongodb/embedded/InMemoryMongoBackend.java index 6c79126db94..f943b514aef 100644 --- a/grails-data-mongodb/embedded/src/main/java/org/grails/datastore/gorm/mongodb/embedded/InMemoryMongoBackend.java +++ b/grails-data-mongodb/embedded/src/main/java/org/grails/datastore/gorm/mongodb/embedded/InMemoryMongoBackend.java @@ -18,6 +18,13 @@ */ package org.grails.datastore.gorm.mongodb.embedded; +import java.io.IOException; +import java.io.InputStream; +import java.net.Socket; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.charset.StandardCharsets; + import de.bwaldvogel.mongo.MongoServer; import de.bwaldvogel.mongo.backend.memory.MemoryBackend; @@ -41,6 +48,14 @@ public class InMemoryMongoBackend implements EmbeddedMongoBackend { private static final String SERVER_CLASS = "de.bwaldvogel.mongo.MongoServer"; + private static final int SERVE_ONE_REQUEST_TIMEOUT_MILLIS = 5000; + + private static final int OP_MSG = 2013; + + private static final byte BSON_STRING = 0x02; + + private static final byte BSON_INT32 = 0x10; + @Override public String getName() { return NAME; @@ -70,9 +85,55 @@ public RunningEmbeddedMongo start(EmbeddedMongoSettings settings) { MemoryBackend backend = new RetainingMemoryBackend(); MongoServer server = new MongoServer(backend); server.bind("localhost", settings.getPort()); + serveOneRequest(settings.getPort()); return new RunningInMemoryMongo(backend, server); } + /** + * Has the server answer one request, so that what its event loops need is loaded while the + * application is starting rather than when its first client connects. + * + *

That client is the MongoDB driver, which connects as the application context finishes + * refreshing, the moment Spring Boot closes the jars of an executable jar to clear its class + * loader's caches. A class loaded right then fails with {@code IllegalStateException}. Reading + * the driver's first bytes allocates the event loop's first buffer, and an event loop that fails + * to load the class of it ends its thread. The driver's connections on it then never answer, and + * stopping the server waits forever for them to close. + * + *

Whatever goes wrong here goes wrong again for the first real client, where it says more, so + * it is not reported. + */ + private static void serveOneRequest(int port) { + try (Socket client = new Socket("localhost", port)) { + client.setSoTimeout(SERVE_ONE_REQUEST_TIMEOUT_MILLIS); + client.getOutputStream().write(isMaster()); + // the whole reply, since closing with some of it unread resets the connection, which the server logs as an error + InputStream reply = client.getInputStream(); + int length = ByteBuffer.wrap(reply.readNBytes(4)).order(ByteOrder.LITTLE_ENDIAN).getInt(); + reply.readNBytes(length - 4); + } + catch (IOException ignored) { + return; + } + } + + /** The {@code isMaster} command the driver starts with, in the wire protocol's {@code OP_MSG}. */ + private static byte[] isMaster() { + byte[] command = "isMaster".getBytes(StandardCharsets.UTF_8); + byte[] databaseField = "$db".getBytes(StandardCharsets.UTF_8); + byte[] database = "admin".getBytes(StandardCharsets.UTF_8); + int documentLength = 4 + 1 + command.length + 1 + 4 + 1 + databaseField.length + 1 + 4 + database.length + 1 + 1; + int messageLength = 16 + 4 + 1 + documentLength; + ByteBuffer message = ByteBuffer.allocate(messageLength).order(ByteOrder.LITTLE_ENDIAN); + message.putInt(messageLength).putInt(1).putInt(0).putInt(OP_MSG); + message.putInt(0).put((byte) 0); + message.putInt(documentLength); + message.put(BSON_INT32).put(command).put((byte) 0).putInt(1); + message.put(BSON_STRING).put(databaseField).put((byte) 0).putInt(database.length + 1).put(database).put((byte) 0); + message.put((byte) 0); + return message.array(); + } + /** * A backend that keeps its collections when the server it is attached to shuts down. * diff --git a/grails-data-mongodb/embedded/src/test/groovy/org/grails/datastore/gorm/mongodb/embedded/EmbeddedMongoLifecycleSpec.groovy b/grails-data-mongodb/embedded/src/test/groovy/org/grails/datastore/gorm/mongodb/embedded/EmbeddedMongoLifecycleSpec.groovy index 02adee21cdf..f1279b12c56 100644 --- a/grails-data-mongodb/embedded/src/test/groovy/org/grails/datastore/gorm/mongodb/embedded/EmbeddedMongoLifecycleSpec.groovy +++ b/grails-data-mongodb/embedded/src/test/groovy/org/grails/datastore/gorm/mongodb/embedded/EmbeddedMongoLifecycleSpec.groovy @@ -313,6 +313,27 @@ class EmbeddedMongoLifecycleSpec extends Specification { application?.destroyForcibly() } + void 'a client sending its first bytes needs no class loaded by the event loop reading them'() { + given: + File log = temp.resolve('application.log').toFile() + + when: 'they arrive at the moment Spring Boot has the jars of an executable jar closed' + Process application = startApplication(27970, log, ClearedJarsServerApplication.name) + boolean exited = application.waitFor(30, TimeUnit.SECONDS) + + then: 'the event loop has no reason to end its thread, and stopping the server finds it there' + assert exited : "still running 30 seconds after its main method returned:\n${log.text}" + assert application.exitValue() == 0 : log.text + assert !log.text.contains('Zip file closed') : log.text + + and: 'having the server answer a request on the way there did not trouble it' + assert !log.text.contains('failed to handle') : log.text + assert !log.text.contains('Connection reset') : log.text + + cleanup: + application?.destroyForcibly() + } + private static void write(String url, String title) { try (MongoClient client = MongoClients.create(url)) { client.getDatabase('bookstore').getCollection('books').insertOne(new Document('title', title)) @@ -347,16 +368,15 @@ class EmbeddedMongoLifecycleSpec extends Specification { } /** - * {@link ContextStoppedServerApplication} in a JVM of its own, because whether that JVM exits is - * the question. The command is written to an argument file, since a test class path is longer + * An application in a JVM of its own, because whether that JVM exits is the question. The command is written to an argument file, since a test class path is longer * than some platforms allow a command line to be. */ - private Process startApplication(int port, File log) { + private Process startApplication(int port, File log, String mainClass = ContextStoppedServerApplication.name) { File arguments = temp.resolve('application.args').toFile() arguments.text = [ '-cp', System.getProperty('java.class.path'), - ContextStoppedServerApplication.name, + mainClass, String.valueOf(port), ].collect { String argument -> quoted(argument) }.join('\n') Process application = new ProcessBuilder( diff --git a/grails-data-mongodb/embedded/src/test/java/org/grails/datastore/gorm/mongodb/embedded/ClearedJarsServerApplication.java b/grails-data-mongodb/embedded/src/test/java/org/grails/datastore/gorm/mongodb/embedded/ClearedJarsServerApplication.java new file mode 100644 index 00000000000..7e427790565 --- /dev/null +++ b/grails-data-mongodb/embedded/src/test/java/org/grails/datastore/gorm/mongodb/embedded/ClearedJarsServerApplication.java @@ -0,0 +1,113 @@ +/* + * 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.datastore.gorm.mongodb.embedded; + +import java.io.File; +import java.net.MalformedURLException; +import java.net.Socket; +import java.net.URL; +import java.net.URLClassLoader; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.springframework.context.support.GenericApplicationContext; +import org.springframework.core.env.MapPropertySource; + +/** + * An application whose classes stop loading for a moment after the server has started, as they do + * in an executable jar: Spring Boot closes the jars of its class loader when the context has + * refreshed, and a class being loaded at that moment fails with {@code IllegalStateException}. + * A client sends its first bytes during that moment, as the MongoDB driver does on the way to that + * event, and stays connected. + * + *

{@code EmbeddedMongoLifecycleSpec} runs it in a JVM of its own and reads what it printed. Reading + * those bytes allocates the event loop's first buffer, which fails if the class of it is not loaded + * yet. Netty then logs that, which in an application fails as well, since Logback loads a class of its + * own to log an exception. That ends the event loop's thread, which leaves the client's connection on + * it open for good, and stopping the server then waits forever. The logger of this JVM cannot fail + * that way, so what the spec looks for is the first failure. + */ +public final class ClearedJarsServerApplication { + + private ClearedJarsServerApplication() { + } + + public static void main(String[] args) throws Exception { + int port = Integer.parseInt(args[0]); + ClearedJarsClassLoader loader = new ClearedJarsClassLoader(); + Thread.currentThread().setContextClassLoader(loader); + Runnable stop = (Runnable) loader.loadClass(Server.class.getName()) + .getMethod("start", int.class).invoke(null, port); + + try (Socket client = new Socket("localhost", port)) { + Thread.sleep(1000L); + loader.cleared = true; + client.getOutputStream().write(1); + client.getOutputStream().flush(); + Thread.sleep(1000L); + loader.cleared = false; + + stop.run(); + } + } + + /** Created by the class loader above, so that what it loads is loaded through it. */ + public static final class Server { + + private Server() { + } + + public static Runnable start(int port) { + GenericApplicationContext context = new GenericApplicationContext(); + context.getEnvironment().getPropertySources().addFirst(new MapPropertySource("application", Map.of( + EmbeddedMongoInitializer.BACKEND, InMemoryMongoBackend.NAME, + "grails.mongodb.url", "mongodb://embedded:" + port + "/bookstore"))); + new EmbeddedMongoInitializer().initialize(context); + EmbeddedMongoLifecycle lifecycle = context.getBeanFactory() + .getBean(EmbeddedMongoLifecycle.BEAN_NAME, EmbeddedMongoLifecycle.class); + return lifecycle::stop; + } + } + + private static final class ClearedJarsClassLoader extends URLClassLoader { + + private volatile boolean cleared; + + private ClearedJarsClassLoader() throws MalformedURLException { + super(classPath(), ClassLoader.getPlatformClassLoader()); + } + + @Override + protected Class findClass(String name) throws ClassNotFoundException { + if (this.cleared) { + throw new IllegalStateException("Zip file closed"); + } + return super.findClass(name); + } + + private static URL[] classPath() throws MalformedURLException { + List urls = new ArrayList<>(); + for (String entry : System.getProperty("java.class.path").split(File.pathSeparator)) { + urls.add(new File(entry).toURI().toURL()); + } + return urls.toArray(new URL[0]); + } + } +} From e51768544aa451d9ca5e4c567a3f17fa3e0ad4f5 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Thu, 5 Nov 2026 18:52:43 -0800 Subject: [PATCH 28/78] Register the response a refused method is answered through An action with allowedMethods answered a method it does not allow with a 500 in a native image, not a 405: the check the compiler adds calls response.sendError dynamically, and a trace cannot record that, since it fails on a request that answers with an error. --- .../grails/controllers/aot/ControllerRuntimeHints.java | 7 ++++++- .../controllers/aot/ControllerRuntimeHintsSpec.groovy | 7 +++++++ 2 files changed, 13 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 e22e67250a5..4417cb2eebc 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 @@ -20,6 +20,8 @@ import java.security.Principal; +import jakarta.servlet.http.HttpServletResponse; + import org.jspecify.annotations.Nullable; import org.springframework.aot.hint.MemberCategory; @@ -73,7 +75,10 @@ public class ControllerRuntimeHints implements RuntimeHintsRegistrar { 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 + HttpMethod.class, + // the method check below refuses a method through the response, which a trace cannot record, since it fails on + // a request that answers with an error + HttpServletResponse.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 d1678f35b9b..eafbb5f9db1 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 @@ -18,6 +18,8 @@ */ package org.apache.grails.controllers.aot +import jakarta.servlet.http.HttpServletResponse + import grails.artefact.controller.support.AllowedMethodsHelper import org.springframework.aot.hint.MemberCategory @@ -53,6 +55,11 @@ class ControllerRuntimeHintsSpec extends Specification { registered(AllowedMethodsHelper) } + void 'the response the method check refuses a method through is registered'() { + expect: 'a trace fails on a request that answers with an error, so it cannot record this' + registered(HttpServletResponse) + } + 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) From 01fe15b656313ba8b34e221154caeb1147c23bc5 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Thu, 5 Nov 2026 19:03:33 -0800 Subject: [PATCH 29/78] Give the training run of a spec time to start on a loaded machine Two seconds was less than the fixture's JVM took to start on CI, so 'a run whose home page always answers that it is not ready' failed with 'did not start'. The wait for a home page to stop answering 503 is what the timeout bounds, so the feature takes as long as the timeout, and ten seconds is enough for the JVM to start. --- .../grails/gradle/plugin/aot/TrainAotCacheTaskSpec.groovy | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/TrainAotCacheTaskSpec.groovy b/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/TrainAotCacheTaskSpec.groovy index ad1f1c943ec..3e5f5b8f7f9 100644 --- a/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/TrainAotCacheTaskSpec.groovy +++ b/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/TrainAotCacheTaskSpec.groovy @@ -324,7 +324,7 @@ exit 1 void 'a run whose home page always answers that it is not ready is still exercised'() { given: 'waited for no longer than the timeout, since nothing says that answer will change' TrainAotCacheTask task = servingTask(['/page'], true, 'homePageDown') - task.startTimeoutSeconds.set(2) + task.startTimeoutSeconds.set(10) when: task.train() From 5ef273a187151b219dccb7bef3024c3c29791154 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Thu, 5 Nov 2026 19:03:33 -0800 Subject: [PATCH 30/78] Fill in a form's empty fields when tracing A scaffolded create page renders its fields with value="", which the trace took for a value and sent. Blank fields failed validation, the page answered with the form again, and the trace reported success having recorded nothing of what a save does when it succeeds. In the image, the first real save then stored the row and answered with a 500. A field rendered empty is now filled in as one with no value is. A hidden field is the page's own and is still sent as it is. --- .../plugin/aot/TraceNativeMetadataTask.groovy | 8 ++++++-- .../aot/TraceNativeMetadataTaskSpec.groovy | 20 ++++++++++++++++++- .../gradle/plugin/aot/TracedRunFixture.groovy | 13 ++++++++++++ 3 files changed, 38 insertions(+), 3 deletions(-) diff --git a/grails-gradle/plugins/src/main/groovy/org/apache/grails/gradle/plugin/aot/TraceNativeMetadataTask.groovy b/grails-gradle/plugins/src/main/groovy/org/apache/grails/gradle/plugin/aot/TraceNativeMetadataTask.groovy index a896fe12824..2e2e80ca17b 100644 --- a/grails-gradle/plugins/src/main/groovy/org/apache/grails/gradle/plugin/aot/TraceNativeMetadataTask.groovy +++ b/grails-gradle/plugins/src/main/groovy/org/apache/grails/gradle/plugin/aot/TraceNativeMetadataTask.groovy @@ -466,7 +466,10 @@ abstract class TraceNativeMetadataTask extends DefaultTask { /** * What the form would send. A field that carries a value sends it, which is how the token a * security filter demands is carried; a checkbox sends what a ticked one sends; anything else - * sends something recognisable, so a row in a database says where it came from. + * sends something recognisable, so a row in a database says where it came from. That includes a + * field rendered with an empty value, as the fields plugin renders them for a new instance: + * sent blank it fails validation, the page answers with the form again, and what a save does + * when it succeeds is never recorded. A hidden field is the page's own, so it is sent as it is. */ private static Map fieldsOf(String markup) { Map fields = [:] @@ -483,7 +486,8 @@ abstract class TraceNativeMetadataTask extends DefaultTask { if (kind in ['submit', 'button', 'reset', 'image', 'file']) { continue } - fields[name.group(1)] = value.find() ? value.group(1) + String carried = value.find() ? value.group(1) : null + fields[name.group(1)] = carried || (carried != null && kind == 'hidden') ? carried : kind == 'checkbox' || kind == 'radio' ? 'on' : kind == 'password' ? 'traced-secret' : "traced-${System.nanoTime()}".toString() diff --git a/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/TraceNativeMetadataTaskSpec.groovy b/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/TraceNativeMetadataTaskSpec.groovy index c49deb44f0d..e09ddf82f96 100644 --- a/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/TraceNativeMetadataTaskSpec.groovy +++ b/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/TraceNativeMetadataTaskSpec.groovy @@ -159,6 +159,24 @@ exec '${new File(System.getProperty('java.home'), 'bin/java').absolutePath}' \\ !posted.contains('nosuchfield') } + void 'a field rendered with an empty value is filled in, so that the form can succeed'() { + given: 'blank fields fail validation, the page answers with the form again, and the save is never recorded' + TraceNativeMetadataTask task = task([], ['/scaffolded']) + + when: + task.trace() + + then: + String submitted = requested.find { String line -> line.startsWith('POST /scaffolded-save') } + submitted =~ /username=traced-\d+/ + submitted.contains('password=traced-secret') + + and: 'what a field does say is sent, and a hidden field is the page\'s own, whatever it says' + submitted.contains('nickname=kept') + submitted.contains('_csrf=token') + submitted =~ /version=(&|$)/ + } + void 'the form with the most fields is the one submitted'() { given: 'a page carrying a layout search form ahead of its own' TraceNativeMetadataTask task = task([], ['/create']) @@ -279,7 +297,7 @@ exec '${new File(System.getProperty('java.home'), 'bin/java').absolutePath}' \\ void 'an application whose home page always answers that it is not ready is still traced'() { given: 'waited for no longer than the timeout, since nothing says that answer will change' TraceNativeMetadataTask task = task(['/page'], [], 'homePageDown') - task.startTimeoutSeconds.set(2) + task.startTimeoutSeconds.set(10) when: task.trace() diff --git a/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/TracedRunFixture.groovy b/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/TracedRunFixture.groovy index 4ae696d1047..29715dc7de9 100644 --- a/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/TracedRunFixture.groovy +++ b/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/TracedRunFixture.groovy @@ -61,6 +61,16 @@ class TracedRunFixture { ''' + /** What the fields plugin renders for a new instance: a value that is there and says nothing. */ + private static final String SCAFFOLDED_FORM = ''' +

+ + + + + +
''' + static void main(String[] args) { int port = Integer.parseInt(args[0]) File requested = new File(args[1]) @@ -98,6 +108,9 @@ class TracedRunFixture { else if (path == '/login') { response = LOGIN_FORM } + else if (path == '/scaffolded') { + response = SCAFFOLDED_FORM + } else if (path == '/authenticate') { exchange.responseHeaders.add('Set-Cookie', 'session=in; Path=/') status = 302 From b1befeece8be58db6dfd074612cd65e4f0059ca7 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Thu, 5 Nov 2026 20:31:49 -0800 Subject: [PATCH 31/78] Read a form's content type without failing on what a client sent BearerTokenReader parses the Content-Type of any request without a bearer header, and nothing caught the exception. Spring Framework 7.1 rejects a parameter without a value or a repeated one, so a request sending such a Content-Type, which used to be read, failed with a 500. Only the type matters here, so only the type is read, and a type that cannot be read is not a form. --- .../token/bearer/BearerTokenReader.groovy | 13 +++++- .../rest/rfc6750/BearerTokenReaderSpec.groovy | 41 +++++++++++++++++++ 2 files changed, 53 insertions(+), 1 deletion(-) diff --git a/grails-spring-security/rest/core/src/main/groovy/grails/plugin/springsecurity/rest/token/bearer/BearerTokenReader.groovy b/grails-spring-security/rest/core/src/main/groovy/grails/plugin/springsecurity/rest/token/bearer/BearerTokenReader.groovy index 4574a9ee77e..0fae3b0d44d 100644 --- a/grails-spring-security/rest/core/src/main/groovy/grails/plugin/springsecurity/rest/token/bearer/BearerTokenReader.groovy +++ b/grails-spring-security/rest/core/src/main/groovy/grails/plugin/springsecurity/rest/token/bearer/BearerTokenReader.groovy @@ -22,6 +22,7 @@ import groovy.util.logging.Slf4j import jakarta.servlet.http.HttpServletRequest +import org.springframework.http.InvalidMediaTypeException import org.springframework.http.MediaType import grails.plugin.springsecurity.rest.token.AccessToken @@ -64,6 +65,16 @@ class BearerTokenReader implements TokenReader { } private boolean isFormEncoded(HttpServletRequest servletRequest) { - servletRequest.contentType && MediaType.parseMediaType(servletRequest.contentType).isCompatibleWith(MediaType.APPLICATION_FORM_URLENCODED) + String contentType = servletRequest.contentType + if (!contentType) { + return false + } + try { + // Only the type matters here. Spring rejects a parameter it cannot read, and a client decides what it sends. + return MediaType.parseMediaType(contentType.split(';', 2)[0]).isCompatibleWith(MediaType.APPLICATION_FORM_URLENCODED) + } + catch (InvalidMediaTypeException ignored) { + return false + } } } diff --git a/grails-spring-security/rest/core/src/test/groovy/grails/plugin/springsecurity/rest/rfc6750/BearerTokenReaderSpec.groovy b/grails-spring-security/rest/core/src/test/groovy/grails/plugin/springsecurity/rest/rfc6750/BearerTokenReaderSpec.groovy index 97366d37323..480af9616c2 100644 --- a/grails-spring-security/rest/core/src/test/groovy/grails/plugin/springsecurity/rest/rfc6750/BearerTokenReaderSpec.groovy +++ b/grails-spring-security/rest/core/src/test/groovy/grails/plugin/springsecurity/rest/rfc6750/BearerTokenReaderSpec.groovy @@ -155,4 +155,45 @@ class BearerTokenReaderSpec extends Specification { notThrown(Throwable) } + @Unroll + def "a token in a form body is read whatever parameter the client sent with its content type: #contentType"() { + given: + request.method = 'POST' + request.contentType = contentType + request.addParameter('access_token', 'mytesttokenvalue') + + expect: + tokenReader.findToken(request) == new AccessToken('mytesttokenvalue') + + where: + contentType << [ + 'application/x-www-form-urlencoded;foo', + 'application/x-www-form-urlencoded;charset=UTF-8;CHARSET=ISO-8859-1' + ] + } + + @Unroll + def "a content type that cannot be read is not a form, and does not fail the request: #contentType"() { + given: + request.method = 'POST' + request.contentType = contentType + request.addParameter('access_token', 'mytesttokenvalue') + + expect: + tokenReader.findToken(request) == null + + where: + contentType << ['not a media type', 'text/plain;foo'] + } + + def "a token in the query string is still read when the content type cannot be"() { + given: + request.method = 'POST' + request.contentType = 'not a media type' + request.queryString = 'access_token=mytesttokenvalue' + request.addParameter('access_token', 'mytesttokenvalue') + + expect: + tokenReader.findToken(request) == new AccessToken('mytesttokenvalue') + } } From 8af7d9261025871e4378247a576edd4d102380e4 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Thu, 5 Nov 2026 20:31:49 -0800 Subject: [PATCH 32/78] Say in the upgrade guide that spring-boot-starter-amqp no longer means RabbitMQ Spring Boot 4.2 makes it the starter for generic AMQP 1.0 and gives RabbitMQ starters of its own. Grails uses neither, but an application using RabbitMQ through it has to change them. --- grails-doc/src/en/guide/upgrading/upgrading90x.adoc | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/grails-doc/src/en/guide/upgrading/upgrading90x.adoc b/grails-doc/src/en/guide/upgrading/upgrading90x.adoc index f9b4f401502..7f18f31b606 100644 --- a/grails-doc/src/en/guide/upgrading/upgrading90x.adoc +++ b/grails-doc/src/en/guide/upgrading/upgrading90x.adoc @@ -114,6 +114,11 @@ The default builder is `paketobuildpacks/ubuntu-resolute-builder`, in place of ` 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. +* *`spring-boot-starter-amqp` no longer means RabbitMQ.* +It is now the starter for generic AMQP 1.0, and RabbitMQ has starters of its own. +An application that uses RabbitMQ through `spring-boot-starter-amqp` or `spring-boot-starter-amqp-test` changes to `spring-boot-starter-rabbitmq` or `spring-boot-starter-rabbitmq-test`, and any import of `org.springframework.boot.amqp.autoconfigure` to `org.springframework.boot.rabbitmq.autoconfigure`. +RabbitMQ over AMQP 1.0 has `spring-boot-starter-amqp-rabbitmq`. + * *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 68f7825a1e734524bb2e5ef209a6fd2e1502e609 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Thu, 5 Nov 2026 20:47:10 -0800 Subject: [PATCH 33/78] Record an exception GrailsExceptionResolver handles on the HTTP server observation The resolver handled an exception out of sight of the observation of the request, so an action that threw answered with a 500 while http.server.requests tagged it with error=none and exception=none, and http.server.request.duration with error.type=none. Spring Framework 7.1 records the exceptions Spring MVC translates to a 5xx, but this one never reaches it. It now records them as Spring MVC does. The spec runs the resolver inside Spring's own ServerHttpObservationFilter, and fails without this. In a running application a 500 is tagged with the exception under both Micrometer's and OpenTelemetry's conventions, and a 404 still with none. --- .../src/en/guide/upgrading/upgrading90x.adoc | 7 ++ .../web/errors/GrailsExceptionResolver.java | 12 ++++ .../errors/GrailsExceptionResolverSpec.groovy | 67 +++++++++++++++++++ 3 files changed, 86 insertions(+) diff --git a/grails-doc/src/en/guide/upgrading/upgrading90x.adoc b/grails-doc/src/en/guide/upgrading/upgrading90x.adoc index 7f18f31b606..75007c62b12 100644 --- a/grails-doc/src/en/guide/upgrading/upgrading90x.adoc +++ b/grails-doc/src/en/guide/upgrading/upgrading90x.adoc @@ -114,6 +114,13 @@ The default builder is `paketobuildpacks/ubuntu-resolute-builder`, in place of ` 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. +* *An exception an action throws is now recorded as an error on the HTTP server observation.* +`GrailsExceptionResolver` handled the exception out of the observation's sight, so `http.server.requests` tagged a 500 with `error` and `exception` values of `none`, and tracing did not see a failure. +It now records the exception, as Spring Framework 7.1 does for the exceptions Spring MVC translates to a 5xx, including an async timeout. +These requests were already counted with `outcome=SERVER_ERROR`, but an alert that counts a non-`none` `error` value will see more server errors than before. +A client error is not recorded. +A custom `ObservationConvention` can leave out the error for particular exceptions. + * *`spring-boot-starter-amqp` no longer means RabbitMQ.* It is now the starter for generic AMQP 1.0, and RabbitMQ has starters of its own. An application that uses RabbitMQ through `spring-boot-starter-amqp` or `spring-boot-starter-amqp-test` changes to `spring-boot-starter-rabbitmq` or `spring-boot-starter-rabbitmq-test`, and any import of `org.springframework.boot.amqp.autoconfigure` to `org.springframework.boot.rabbitmq.autoconfigure`. diff --git a/grails-web-mvc/src/main/groovy/org/grails/web/errors/GrailsExceptionResolver.java b/grails-web-mvc/src/main/groovy/org/grails/web/errors/GrailsExceptionResolver.java index 9e5c87e3962..d0427785e9b 100644 --- a/grails-web-mvc/src/main/groovy/org/grails/web/errors/GrailsExceptionResolver.java +++ b/grails-web-mvc/src/main/groovy/org/grails/web/errors/GrailsExceptionResolver.java @@ -42,6 +42,7 @@ import org.springframework.context.ApplicationContext; import org.springframework.web.context.ServletContextAware; import org.springframework.web.context.request.async.AsyncRequestTimeoutException; +import org.springframework.web.filter.ServerHttpObservationFilter; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.View; import org.springframework.web.servlet.ViewResolver; @@ -104,6 +105,8 @@ public ModelAndView resolveException(HttpServletRequest request, HttpServletResp ex = findWrappedException(ex); + recordServerError(request, ex); + if (!(ex instanceof AsyncRequestTimeoutException)) { logFullStackTraceIfEnabled(ex); filterStackTrace(ex); @@ -128,6 +131,15 @@ public ModelAndView resolveException(HttpServletRequest request, HttpServletResp return mv; } + /** + * Every exception this resolves is a server error, and resolving it hides it from the observation of the request, + * whose metrics would otherwise say there was no error and whose trace would not be marked as failed. Spring MVC + * has recorded the exceptions it translates to a server error in the same way since Spring Framework 7.1. + */ + private static void recordServerError(HttpServletRequest request, Exception ex) { + ServerHttpObservationFilter.findObservationContext(request).ifPresent(context -> context.setError(ex)); + } + public String getRequestLogMessage(Throwable e, HttpServletRequest request) { Throwable cause = getRootCause(e); String exceptionName = cause.getClass().getSimpleName(); diff --git a/grails-web-mvc/src/test/groovy/org/grails/web/errors/GrailsExceptionResolverSpec.groovy b/grails-web-mvc/src/test/groovy/org/grails/web/errors/GrailsExceptionResolverSpec.groovy index 7fe2756f4f2..1016f0a9382 100644 --- a/grails-web-mvc/src/test/groovy/org/grails/web/errors/GrailsExceptionResolverSpec.groovy +++ b/grails-web-mvc/src/test/groovy/org/grails/web/errors/GrailsExceptionResolverSpec.groovy @@ -24,7 +24,12 @@ import grails.core.GrailsApplication import grails.web.mapping.UrlMappingInfo import grails.web.mapping.UrlMappingsHolder import grails.web.mapping.exceptions.UrlMappingException +import io.micrometer.observation.Observation +import io.micrometer.observation.ObservationHandler +import io.micrometer.observation.ObservationRegistry +import java.lang.reflect.InvocationTargetException import org.apache.grails.core.testing.support.LogCapture +import org.codehaus.groovy.runtime.InvokerInvocationException import org.grails.exceptions.reporting.DefaultStackTraceFilterer import org.apache.grails.core.GrailsBootstrapRegistryInitializer import org.grails.exceptions.reporting.StackTraceFilterer @@ -38,12 +43,14 @@ import org.springframework.beans.factory.BeanNotOfRequiredTypeException import org.springframework.beans.factory.NoSuchBeanDefinitionException import org.springframework.context.ApplicationContext import org.springframework.context.support.StaticApplicationContext +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.context.request.RequestContextHolder import org.springframework.web.context.request.ServletRequestAttributes import org.springframework.web.context.request.async.AsyncRequestTimeoutException +import org.springframework.web.filter.ServerHttpObservationFilter import org.springframework.web.util.WebUtils import org.springframework.web.context.WebApplicationContext import org.springframework.web.context.support.StaticWebApplicationContext @@ -53,6 +60,7 @@ import org.springframework.web.servlet.view.InternalResourceView import spock.lang.Issue import spock.lang.Specification +import jakarta.servlet.FilterChain import jakarta.servlet.http.HttpServletRequest import jakarta.servlet.http.HttpServletResponse @@ -62,6 +70,8 @@ class GrailsExceptionResolverSpec extends Specification { private static final String PLAIN_OVER_GRAILS = 'plain attributes over a stored GrailsWebRequest' private static final String PLAIN = 'plain attributes' private static final String NOTHING = 'nothing' + private static final Exception FAILURE = new IllegalStateException('failed') + private static final Exception ASYNC_TIMEOUT = new AsyncRequestTimeoutException() private final MockServletContext servletContext = new MockServletContext() private StaticWebApplicationContext webContext @@ -71,6 +81,63 @@ class GrailsExceptionResolverSpec extends Specification { webContext?.close() } + void 'an exception #description is recorded as the error of the HTTP server observation'() { + given: 'the filter a running application has around its requests' + ServerRequestObservationContext observed = null + def registry = ObservationRegistry.create() + registry.observationConfig().observationHandler(new ObservationHandler() { + @Override + boolean supportsContext(Observation.Context context) { + context instanceof ServerRequestObservationContext + } + + @Override + void onStop(Observation.Context context) { + observed = (ServerRequestObservationContext) context + } + }) + def resolver = observedResolver() + def request = new MockHttpServletRequest('GET', '/failing') + def response = new MockHttpServletResponse() + FilterChain application = { req, res -> + resolver.resolveException((HttpServletRequest) req, (HttpServletResponse) res, null, thrown) + } as FilterChain + + when: + new ServerHttpObservationFilter(registry).doFilter(request, response, application) + + then: 'as Spring MVC records one it translates to a server error, or its metrics and trace would say nothing failed' + response.status == status + observed.error.is(recorded) + + where: + description | thrown | recorded | status + 'an action threw' | FAILURE | FAILURE | 500 + 'wrapped by Groovy' | new InvokerInvocationException(new InvocationTargetException(FAILURE)) | FAILURE | 500 + 'of an async timeout' | ASYNC_TIMEOUT | ASYNC_TIMEOUT | 503 + } + + void 'an exception is resolved as usual without an observation'() { + when: + def response = new MockHttpServletResponse() + observedResolver().resolveException(new MockHttpServletRequest('GET', '/failing'), response, null, FAILURE) + + then: + response.status == 500 + } + + private GrailsExceptionResolver observedResolver() { + webContext = new StaticWebApplicationContext() + webContext.beanFactory.registerSingleton(GrailsApplication.APPLICATION_ID, Stub(GrailsApplication)) + webContext.refresh() + servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, webContext) + def resolver = new GrailsExceptionResolver() + resolver.servletContext = servletContext + resolver.defaultErrorView = '/error' + resolver.stackFilterer = new DefaultStackTraceFilterer() + resolver + } + void 'async timeouts resolve as 503 without an error stack trace'() { given: def resolverLog = new LogCapture(GrailsExceptionResolver) From dd6e74b1e76bd2f2eb440ad1cd18e4d86df14823 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Thu, 5 Nov 2026 20:48:00 -0800 Subject: [PATCH 34/78] Document the observability changes of Spring Boot 4.2 http.server.requests.active is no longer registered unless asked for, which a dashboard reading it needs to know, and metrics and spans can now use OpenTelemetry's semantic conventions. Under them http.route is /controller/action in a Grails application, which is worth saying since it is not the URL mapping's pattern. --- grails-doc/src/en/guide/introduction/whatsNew.adoc | 13 +++++++++++++ grails-doc/src/en/guide/upgrading/upgrading90x.adoc | 4 ++++ 2 files changed, 17 insertions(+) diff --git a/grails-doc/src/en/guide/introduction/whatsNew.adoc b/grails-doc/src/en/guide/introduction/whatsNew.adoc index d707a74d7b6..7918c538eaa 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. +Spring Boot 4.2 can switch metrics and spans to OpenTelemetry's semantic conventions: + +[source,yaml] +---- +management: + observations: + conventions: open-telemetry +---- + +`http.server.requests` then becomes `http.server.request.duration`, tagged with `http.route` and `error.type` in place of `uri` and `exception`. +In a Grails application `http.route` is `/controller/action`, not the pattern of the URL mapping, which keeps it low in cardinality. +Spring Boot's https://docs.spring.io/spring-boot/reference/actuator/observability.html#actuator.observability.semantic-conventions[documentation] lists what else changes, such as the properties that customize meter names no longer taking effect. + ==== 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 a command object is bound to the body of a `QUERY`, which is JSON or form-encoded: diff --git a/grails-doc/src/en/guide/upgrading/upgrading90x.adoc b/grails-doc/src/en/guide/upgrading/upgrading90x.adoc index 75007c62b12..6c954b61220 100644 --- a/grails-doc/src/en/guide/upgrading/upgrading90x.adoc +++ b/grails-doc/src/en/guide/upgrading/upgrading90x.adoc @@ -121,6 +121,10 @@ These requests were already counted with `outcome=SERVER_ERROR`, but an alert th A client error is not recorded. A custom `ObservationConvention` can leave out the error for particular exceptions. +* *`http.server.requests.active` is no longer registered by default.* +Spring Boot 4.2 makes this long task timer opt-in. +A dashboard or alert that reads it sets `management.metrics.observations.include-active-long-task-timer` to `true`, which replaces `management.metrics.observations.ignored-meters`. + * *`spring-boot-starter-amqp` no longer means RabbitMQ.* It is now the starter for generic AMQP 1.0, and RabbitMQ has starters of its own. An application that uses RabbitMQ through `spring-boot-starter-amqp` or `spring-boot-starter-amqp-test` changes to `spring-boot-starter-rabbitmq` or `spring-boot-starter-rabbitmq-test`, and any import of `org.springframework.boot.amqp.autoconfigure` to `org.springframework.boot.rabbitmq.autoconfigure`. From c59ca3eee5375f12acee99be143ac28cb36926f6 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Thu, 5 Nov 2026 21:28:07 -0800 Subject: [PATCH 35/78] Keep a failed action's exception and route on the observation across an error handler A "500" mapping to a controller forwards to it, which copies the resolver's model to the request and routes the request again. That left the GrailsWrappedRuntimeException in jakarta.servlet.error.exception, which ServerHttpObservationFilter reads last, so http.server.requests reported the wrapper over the exception the resolver had recorded, and the handler's route rather than the action's, so every failure a handler answered looked like the same route. The resolver now removes the attribute after the forward, as Spring MVC does once it has rendered an error view, and restores the route. Neither this nor the error=none the previous fix addressed comes from Spring Boot 4.2: 8.0.x on Boot 4.1.2 and 9.0.x report the same values. An application that has no error view to render, such as the cache example, hides the gap, because the failed render leaves the exception on the request for the filter. The new functional spec runs through a real dispatch for that reason: the unit spec cannot see what Spring MVC clears after rendering. --- .../src/en/guide/upgrading/upgrading90x.adoc | 7 +- .../issue11102/FailingController.groovy | 35 ++++++++++ .../controllers/issue11102/UrlMappings.groovy | 3 + .../FailedActionObservationSpec.groovy | 64 +++++++++++++++++++ .../web/errors/GrailsExceptionResolver.java | 16 +++++ .../errors/GrailsExceptionResolverSpec.groovy | 49 ++++++++++---- 6 files changed, 159 insertions(+), 15 deletions(-) create mode 100644 grails-test-examples/issue-11102/grails-app/controllers/issue11102/FailingController.groovy create mode 100644 grails-test-examples/issue-11102/src/integration-test/groovy/issue11102/FailedActionObservationSpec.groovy diff --git a/grails-doc/src/en/guide/upgrading/upgrading90x.adoc b/grails-doc/src/en/guide/upgrading/upgrading90x.adoc index 6c954b61220..85ece1eabcf 100644 --- a/grails-doc/src/en/guide/upgrading/upgrading90x.adoc +++ b/grails-doc/src/en/guide/upgrading/upgrading90x.adoc @@ -115,9 +115,10 @@ With no `builder` configured, the run image is `paketobuildpacks/ubuntu-resolute 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. * *An exception an action throws is now recorded as an error on the HTTP server observation.* -`GrailsExceptionResolver` handled the exception out of the observation's sight, so `http.server.requests` tagged a 500 with `error` and `exception` values of `none`, and tracing did not see a failure. -It now records the exception, as Spring Framework 7.1 does for the exceptions Spring MVC translates to a 5xx, including an async timeout. -These requests were already counted with `outcome=SERVER_ERROR`, but an alert that counts a non-`none` `error` value will see more server errors than before. +When an error view answered, as the `"500"(view: '/error')` mapping of a generated application does, `http.server.requests` tagged the 500 with `error` and `exception` values of `none`, and tracing did not see a failure. +A `500` mapping to a controller tagged it with `GrailsWrappedRuntimeException` and with the `uri` of that controller, so every failure it answered looked like the same route. +Both now report the exception the action threw and the route of the action. The exception is recorded as Spring Framework 7.1 records the exceptions Spring MVC translates to a 5xx, including an async timeout. +These requests were already counted with `outcome=SERVER_ERROR`, but an alert that counts a non-`none` `error` value will see more server errors than before, and a dashboard that reads the `uri` of an error controller will find those failures under the routes of the actions. A client error is not recorded. A custom `ObservationConvention` can leave out the error for particular exceptions. diff --git a/grails-test-examples/issue-11102/grails-app/controllers/issue11102/FailingController.groovy b/grails-test-examples/issue-11102/grails-app/controllers/issue11102/FailingController.groovy new file mode 100644 index 00000000000..f84840138c3 --- /dev/null +++ b/grails-test-examples/issue-11102/grails-app/controllers/issue11102/FailingController.groovy @@ -0,0 +1,35 @@ +/* + * 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 issue11102 + +class FailingController { + + def answeredByView() { + throw new IllegalStateException('answered by the error view') + } + + def answeredByController() { + throw new UnsupportedOperationException('answered by the error controller') + } + + def errorHandler() { + render status: 500, text: 'Answered by the error controller' + } +} diff --git a/grails-test-examples/issue-11102/grails-app/controllers/issue11102/UrlMappings.groovy b/grails-test-examples/issue-11102/grails-app/controllers/issue11102/UrlMappings.groovy index b46729c249c..cca628bf2a1 100644 --- a/grails-test-examples/issue-11102/grails-app/controllers/issue11102/UrlMappings.groovy +++ b/grails-test-examples/issue-11102/grails-app/controllers/issue11102/UrlMappings.groovy @@ -31,7 +31,10 @@ class UrlMappings { action = [GET: 'get2'] } + "/failing/$action"(controller: 'failing') + "/"(view:"/index") + "500"(controller: 'failing', action: 'errorHandler', exception: UnsupportedOperationException) "500"(view:'/error') "404"(view:'/notFound') } diff --git a/grails-test-examples/issue-11102/src/integration-test/groovy/issue11102/FailedActionObservationSpec.groovy b/grails-test-examples/issue-11102/src/integration-test/groovy/issue11102/FailedActionObservationSpec.groovy new file mode 100644 index 00000000000..e8daff640b5 --- /dev/null +++ b/grails-test-examples/issue-11102/src/integration-test/groovy/issue11102/FailedActionObservationSpec.groovy @@ -0,0 +1,64 @@ +/* + * 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 issue11102 + +import io.micrometer.core.instrument.MeterRegistry +import org.springframework.beans.factory.annotation.Autowired +import spock.lang.Specification +import spock.lang.Tag +import spock.util.concurrent.PollingConditions + +import grails.testing.mixin.integration.Integration +import org.apache.grails.testing.http.client.HttpClientSupport + +/** + * An error page that renders hides the failure from the filter that observes the request: Spring MVC clears the + * exception from the request once the error view has rendered, and a forward to an error controller replaces it, and + * the route, with its own. Only a real dispatch does that, so this goes through one. + */ +@Integration +@Tag('http-client') +class FailedActionObservationSpec extends Specification implements HttpClientSupport { + + @Autowired + MeterRegistry meterRegistry + + void 'a failed action answered by #handler is tagged with its own exception and route'() { + when: + def response = http("/failing/$action") + + then: 'the error page answered, so the exception did not reach the filter' + response.assertContains(500, page) + + and: + new PollingConditions(timeout: 5).eventually { + assert errorTags("/failing/$action") == [exception] + } + + where: + handler | action | page | exception + 'the error view' | 'answeredByView' | 'An error has occurred' | 'IllegalStateException' + 'an error controller' | 'answeredByController' | 'Answered by the error controller' | 'UnsupportedOperationException' + } + + private List errorTags(String route) { + meterRegistry.find('http.server.requests').tag('status', '500').tag('uri', route).timers()*.id*.getTag('error') + } +} diff --git a/grails-web-mvc/src/main/groovy/org/grails/web/errors/GrailsExceptionResolver.java b/grails-web-mvc/src/main/groovy/org/grails/web/errors/GrailsExceptionResolver.java index d0427785e9b..5179bde32b4 100644 --- a/grails-web-mvc/src/main/groovy/org/grails/web/errors/GrailsExceptionResolver.java +++ b/grails-web-mvc/src/main/groovy/org/grails/web/errors/GrailsExceptionResolver.java @@ -40,6 +40,7 @@ import org.springframework.beans.BeanUtils; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; +import org.springframework.http.server.observation.ServerRequestObservationContext; import org.springframework.web.context.ServletContextAware; import org.springframework.web.context.request.async.AsyncRequestTimeoutException; import org.springframework.web.filter.ServerHttpObservationFilter; @@ -140,6 +141,18 @@ private static void recordServerError(HttpServletRequest request, Exception ex) ServerHttpObservationFilter.findObservationContext(request).ifPresent(context -> context.setError(ex)); } + /** + * A forward to an error handler copies its model to the request and routes the request again. The wrapper this + * leaves in {@link WebUtils#ERROR_EXCEPTION_ATTRIBUTE} is what the observation reads last, over the exception that + * was recorded, and the handler's route replaces the one that failed, so every failure a handler answers would be + * reported as the same route. Spring MVC clears that attribute in the same way once it has rendered an error view. + */ + private static void keepFailureObserved(HttpServletRequest request, String failedRoute) { + request.removeAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE); + ServerHttpObservationFilter.findObservationContext(request) + .ifPresent(context -> context.setPathPattern(failedRoute)); + } + public String getRequestLogMessage(Throwable e, HttpServletRequest request) { Throwable cause = getRootCause(e); String exceptionName = cause.getClass().getSimpleName(); @@ -264,11 +277,14 @@ else if (mapsToController) { ((GrailsResponseMutator) response).deactivateResponseMutator(); } request.setAttribute(ERROR_HANDLER_FORWARD_IN_PROGRESS_ATTRIBUTE, Boolean.TRUE); + String failedRoute = ServerHttpObservationFilter.findObservationContext(request) + .map(ServerRequestObservationContext::getPathPattern).orElse(null); try { forwardRequest(info, request, response, mv, uri); } finally { request.removeAttribute(ERROR_HANDLER_FORWARD_IN_PROGRESS_ATTRIBUTE); + keepFailureObserved(request, failedRoute); } // return an empty ModelAndView since the error handler has been processed return new ModelAndView(); diff --git a/grails-web-mvc/src/test/groovy/org/grails/web/errors/GrailsExceptionResolverSpec.groovy b/grails-web-mvc/src/test/groovy/org/grails/web/errors/GrailsExceptionResolverSpec.groovy index 1016f0a9382..75e5058ebcc 100644 --- a/grails-web-mvc/src/test/groovy/org/grails/web/errors/GrailsExceptionResolverSpec.groovy +++ b/grails-web-mvc/src/test/groovy/org/grails/web/errors/GrailsExceptionResolverSpec.groovy @@ -84,18 +84,7 @@ class GrailsExceptionResolverSpec extends Specification { void 'an exception #description is recorded as the error of the HTTP server observation'() { given: 'the filter a running application has around its requests' ServerRequestObservationContext observed = null - def registry = ObservationRegistry.create() - registry.observationConfig().observationHandler(new ObservationHandler() { - @Override - boolean supportsContext(Observation.Context context) { - context instanceof ServerRequestObservationContext - } - - @Override - void onStop(Observation.Context context) { - observed = (ServerRequestObservationContext) context - } - }) + def registry = registryStoppingWith { observed = it } def resolver = observedResolver() def request = new MockHttpServletRequest('GET', '/failing') def response = new MockHttpServletResponse() @@ -117,6 +106,26 @@ class GrailsExceptionResolverSpec extends Specification { 'of an async timeout' | ASYNC_TIMEOUT | ASYNC_TIMEOUT | 503 } + void 'the exception an error handler answers stays the error of the HTTP server observation'() { + given: 'the filter a running application has around its requests, and an error handler to forward to' + ServerRequestObservationContext observed = null + def resolver = resolverFor({ '500'(controller: 'errors', action: 'serverError') }, true) + def request = new MockHttpServletRequest(servletContext, 'GET', '/fail') + def response = new MockHttpServletResponse() + bind(GRAILS, request, response) + def original = new IllegalStateException('original') + FilterChain application = { req, res -> + resolver.resolveException((HttpServletRequest) req, (HttpServletResponse) res, null, original) + } as FilterChain + + when: + new ServerHttpObservationFilter(registryStoppingWith { observed = it }).doFilter(request, response, application) + + then: 'the handler answered, and the wrapper its model left on the request is not what is reported' + response.forwardedUrl == '/errors/serverError' + observed.error.is(original) + } + void 'an exception is resolved as usual without an observation'() { when: def response = new MockHttpServletResponse() @@ -126,6 +135,22 @@ class GrailsExceptionResolverSpec extends Specification { response.status == 500 } + private static ObservationRegistry registryStoppingWith(Closure stopped) { + def registry = ObservationRegistry.create() + registry.observationConfig().observationHandler(new ObservationHandler() { + @Override + boolean supportsContext(Observation.Context context) { + context instanceof ServerRequestObservationContext + } + + @Override + void onStop(Observation.Context context) { + stopped.call(context) + } + }) + registry + } + private GrailsExceptionResolver observedResolver() { webContext = new StaticWebApplicationContext() webContext.beanFactory.registerSingleton(GrailsApplication.APPLICATION_ID, Stub(GrailsApplication)) From 5c6c65b78028282ca4639cdbba4d1130a1fe0d7e Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Thu, 5 Nov 2026 21:28:07 -0800 Subject: [PATCH 36/78] Throw an action's own exception when it is invoked by reflection In development mode an action is invoked by reflection, so it failed with an InvocationTargetException, while the method handle used everywhere else throws the exception itself. The resolver does not unwrap that one, so what reached it, the action's span and the observation of the request depended on the environment. --- .../core/DefaultGrailsControllerClass.java | 9 ++++- .../DefaultGrailsControllerClassSpec.groovy | 22 +++++++++++ .../ReflectivelyInvokedController.groovy | 37 +++++++++++++++++++ 3 files changed, 67 insertions(+), 1 deletion(-) create mode 100644 grails-core/src/test/groovy/org/grails/core/nonpublic/ReflectivelyInvokedController.groovy diff --git a/grails-core/src/main/groovy/org/grails/core/DefaultGrailsControllerClass.java b/grails-core/src/main/groovy/org/grails/core/DefaultGrailsControllerClass.java index e1709bf86ce..108a7f77abb 100644 --- a/grails-core/src/main/groovy/org/grails/core/DefaultGrailsControllerClass.java +++ b/grails-core/src/main/groovy/org/grails/core/DefaultGrailsControllerClass.java @@ -21,6 +21,7 @@ import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodType; +import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; @@ -212,7 +213,13 @@ public ReflectionInvoker(Method method) { @Override public Object invoke(Object controller) throws Throwable { - return method.invoke(controller); + try { + return method.invoke(controller); + } + catch (InvocationTargetException e) { + // what a method handle throws, so that what an action fails with does not depend on the environment + throw e.getTargetException(); + } } } diff --git a/grails-core/src/test/groovy/org/grails/core/DefaultGrailsControllerClassSpec.groovy b/grails-core/src/test/groovy/org/grails/core/DefaultGrailsControllerClassSpec.groovy index 8cd5264f7d2..6108b329037 100644 --- a/grails-core/src/test/groovy/org/grails/core/DefaultGrailsControllerClassSpec.groovy +++ b/grails-core/src/test/groovy/org/grails/core/DefaultGrailsControllerClassSpec.groovy @@ -20,6 +20,7 @@ package org.grails.core import grails.config.Settings import grails.core.DefaultGrailsApplication +import grails.web.Action import spock.lang.Specification /** @@ -81,6 +82,27 @@ class DefaultGrailsControllerClassSpec extends Specification { configScopeValue << [SINGLETON, SESSION] } + void "an action that fails throws its own exception when it is invoked #invocation"() { + when: + new DefaultGrailsControllerClass(controller).invoke(controller.newInstance(), 'failing') + + then: + def exception = thrown(IllegalStateException) + exception.message == 'thrown by the action' + + where: + invocation | controller + 'through a method handle' | MethodHandleInvokedController + 'by reflection, as in development mode' | Class.forName('org.grails.core.nonpublic.ReflectivelyInvokedController') + } + + static class MethodHandleInvokedController { + @Action + void failing() { + throw new IllegalStateException('thrown by the action') + } + } + class NotSpecifiedController { } diff --git a/grails-core/src/test/groovy/org/grails/core/nonpublic/ReflectivelyInvokedController.groovy b/grails-core/src/test/groovy/org/grails/core/nonpublic/ReflectivelyInvokedController.groovy new file mode 100644 index 00000000000..7ea0a0f58da --- /dev/null +++ b/grails-core/src/test/groovy/org/grails/core/nonpublic/ReflectivelyInvokedController.groovy @@ -0,0 +1,37 @@ +/* + * 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.core.nonpublic + +import groovy.transform.PackageScope + +import grails.web.Action + +/** + * A class in another package than {@code DefaultGrailsControllerClass} and not public, so it cannot look up a method + * handle for the action and invokes it by reflection, which is how it invokes every action in development mode. + */ +@PackageScope +class ReflectivelyInvokedController { + + @Action + void failing() { + throw new IllegalStateException('thrown by the action') + } +} From 4c190279410a5bde3bab1f939abd91b43dc1e154 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Thu, 5 Nov 2026 21:55:05 -0800 Subject: [PATCH 37/78] Keep the resolver's observation comment true on every release line The same fix goes to 8.0.x, on Spring Framework 7.0, so the comment and the spec no longer compare it with what Spring Framework 7.1 does. The upgrade guide still does. With the same text on both lines, the merge up does not conflict over it. --- .../groovy/org/grails/web/errors/GrailsExceptionResolver.java | 3 +-- .../org/grails/web/errors/GrailsExceptionResolverSpec.groovy | 2 +- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/grails-web-mvc/src/main/groovy/org/grails/web/errors/GrailsExceptionResolver.java b/grails-web-mvc/src/main/groovy/org/grails/web/errors/GrailsExceptionResolver.java index 5179bde32b4..839d1b7e9fe 100644 --- a/grails-web-mvc/src/main/groovy/org/grails/web/errors/GrailsExceptionResolver.java +++ b/grails-web-mvc/src/main/groovy/org/grails/web/errors/GrailsExceptionResolver.java @@ -134,8 +134,7 @@ public ModelAndView resolveException(HttpServletRequest request, HttpServletResp /** * Every exception this resolves is a server error, and resolving it hides it from the observation of the request, - * whose metrics would otherwise say there was no error and whose trace would not be marked as failed. Spring MVC - * has recorded the exceptions it translates to a server error in the same way since Spring Framework 7.1. + * whose metrics would otherwise say there was no error and whose trace would not be marked as failed. */ private static void recordServerError(HttpServletRequest request, Exception ex) { ServerHttpObservationFilter.findObservationContext(request).ifPresent(context -> context.setError(ex)); diff --git a/grails-web-mvc/src/test/groovy/org/grails/web/errors/GrailsExceptionResolverSpec.groovy b/grails-web-mvc/src/test/groovy/org/grails/web/errors/GrailsExceptionResolverSpec.groovy index 75e5058ebcc..17595888581 100644 --- a/grails-web-mvc/src/test/groovy/org/grails/web/errors/GrailsExceptionResolverSpec.groovy +++ b/grails-web-mvc/src/test/groovy/org/grails/web/errors/GrailsExceptionResolverSpec.groovy @@ -95,7 +95,7 @@ class GrailsExceptionResolverSpec extends Specification { when: new ServerHttpObservationFilter(registry).doFilter(request, response, application) - then: 'as Spring MVC records one it translates to a server error, or its metrics and trace would say nothing failed' + then: 'or its metrics and trace would say nothing failed' response.status == status observed.error.is(recorded) From f4cc7eb5d0fb64c6157a3024362c5141021d111f Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Fri, 6 Nov 2026 06:33:24 -0800 Subject: [PATCH 38/78] Keep the exception on the request after a forward to an error handler The previous commit removed jakarta.servlet.error.exception once the forward had returned, so a filter that reads it after chain.doFilter got null, with or without an observation, where it used to get a GrailsWrappedRuntimeException. It now holds the exception the action threw. Holding the wrapper is not an option, because ServerHttpObservationFilter reads that attribute last and would report the wrapper again. --- .../src/en/guide/upgrading/upgrading90x.adoc | 1 + .../web/errors/GrailsExceptionResolver.java | 14 +++++++------- .../errors/GrailsExceptionResolverSpec.groovy | 17 +++++++++++++++++ 3 files changed, 25 insertions(+), 7 deletions(-) diff --git a/grails-doc/src/en/guide/upgrading/upgrading90x.adoc b/grails-doc/src/en/guide/upgrading/upgrading90x.adoc index 85ece1eabcf..97d20e63704 100644 --- a/grails-doc/src/en/guide/upgrading/upgrading90x.adoc +++ b/grails-doc/src/en/guide/upgrading/upgrading90x.adoc @@ -119,6 +119,7 @@ When an error view answered, as the `"500"(view: '/error')` mapping of a generat A `500` mapping to a controller tagged it with `GrailsWrappedRuntimeException` and with the `uri` of that controller, so every failure it answered looked like the same route. Both now report the exception the action threw and the route of the action. The exception is recorded as Spring Framework 7.1 records the exceptions Spring MVC translates to a 5xx, including an async timeout. These requests were already counted with `outcome=SERVER_ERROR`, but an alert that counts a non-`none` `error` value will see more server errors than before, and a dashboard that reads the `uri` of an error controller will find those failures under the routes of the actions. +After a forward to an error controller, the `jakarta.servlet.error.exception` request attribute holds the exception the action threw rather than a `GrailsWrappedRuntimeException`, for a filter that reads it once the chain has returned. Inside the error controller it still holds the wrapper. A client error is not recorded. A custom `ObservationConvention` can leave out the error for particular exceptions. diff --git a/grails-web-mvc/src/main/groovy/org/grails/web/errors/GrailsExceptionResolver.java b/grails-web-mvc/src/main/groovy/org/grails/web/errors/GrailsExceptionResolver.java index 839d1b7e9fe..21edb501559 100644 --- a/grails-web-mvc/src/main/groovy/org/grails/web/errors/GrailsExceptionResolver.java +++ b/grails-web-mvc/src/main/groovy/org/grails/web/errors/GrailsExceptionResolver.java @@ -141,13 +141,13 @@ private static void recordServerError(HttpServletRequest request, Exception ex) } /** - * A forward to an error handler copies its model to the request and routes the request again. The wrapper this - * leaves in {@link WebUtils#ERROR_EXCEPTION_ATTRIBUTE} is what the observation reads last, over the exception that - * was recorded, and the handler's route replaces the one that failed, so every failure a handler answers would be - * reported as the same route. Spring MVC clears that attribute in the same way once it has rendered an error view. + * A forward to an error handler copies its model to the request and routes the request again. That leaves a wrapper + * in {@link WebUtils#ERROR_EXCEPTION_ATTRIBUTE}, and the handler's route in place of the one that failed, so every + * failure a handler answers would be reported as the same route. The attribute keeps the exception itself for + * whatever reads it once the chain has returned, which includes the filter that observes the request. */ - private static void keepFailureObserved(HttpServletRequest request, String failedRoute) { - request.removeAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE); + private static void keepFailureObserved(HttpServletRequest request, Exception ex, String failedRoute) { + request.setAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE, ex); ServerHttpObservationFilter.findObservationContext(request) .ifPresent(context -> context.setPathPattern(failedRoute)); } @@ -283,7 +283,7 @@ else if (mapsToController) { } finally { request.removeAttribute(ERROR_HANDLER_FORWARD_IN_PROGRESS_ATTRIBUTE); - keepFailureObserved(request, failedRoute); + keepFailureObserved(request, ex, failedRoute); } // return an empty ModelAndView since the error handler has been processed return new ModelAndView(); diff --git a/grails-web-mvc/src/test/groovy/org/grails/web/errors/GrailsExceptionResolverSpec.groovy b/grails-web-mvc/src/test/groovy/org/grails/web/errors/GrailsExceptionResolverSpec.groovy index 17595888581..76b11dfd235 100644 --- a/grails-web-mvc/src/test/groovy/org/grails/web/errors/GrailsExceptionResolverSpec.groovy +++ b/grails-web-mvc/src/test/groovy/org/grails/web/errors/GrailsExceptionResolverSpec.groovy @@ -61,6 +61,7 @@ import spock.lang.Issue import spock.lang.Specification import jakarta.servlet.FilterChain +import jakarta.servlet.RequestDispatcher import jakarta.servlet.http.HttpServletRequest import jakarta.servlet.http.HttpServletResponse @@ -126,6 +127,22 @@ class GrailsExceptionResolverSpec extends Specification { observed.error.is(original) } + void 'a filter can read the exception an error handler answered once the chain has returned, with no observation'() { + given: + def resolver = resolverFor({ '500'(controller: 'errors', action: 'serverError') }, true) + def request = new MockHttpServletRequest(servletContext, 'GET', '/fail') + def response = new MockHttpServletResponse() + bind(GRAILS, request, response) + def original = new IllegalStateException('original') + + when: + resolver.resolveException(request, response, null, original) + + then: + response.forwardedUrl == '/errors/serverError' + request.getAttribute(RequestDispatcher.ERROR_EXCEPTION).is(original) + } + void 'an exception is resolved as usual without an observation'() { when: def response = new MockHttpServletResponse() From 36f4967517333d731638c555d82a08f245d06f7c Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Fri, 6 Nov 2026 06:33:24 -0800 Subject: [PATCH 39/78] Tell the observation's handlers about a failed action Setting the error on the context reaches the metrics, which read it when the observation stops, but only Observation.error calls the handlers' onError, and that is how the server tracing handler marks a span. With a real OpenTelemetry tracer the span of a failed action ended with status UNSET and no exception event. The resolver now finds the observation through the registry's scopes and records the exception on it, once the error page has been resolved. An exception a forward left on the request is not recorded there, because the filter records what it finds in that attribute when it stops the observation, and the handlers would hear of it twice. --- .../src/en/guide/upgrading/upgrading90x.adoc | 2 +- .../FailedActionObservationSpec.groovy | 39 ++++++++++++- .../web/errors/GrailsExceptionResolver.java | 48 ++++++++++++++-- .../errors/GrailsExceptionResolverSpec.groovy | 56 ++++++++++++++++--- 4 files changed, 129 insertions(+), 16 deletions(-) diff --git a/grails-doc/src/en/guide/upgrading/upgrading90x.adoc b/grails-doc/src/en/guide/upgrading/upgrading90x.adoc index 97d20e63704..dc1d51ae50e 100644 --- a/grails-doc/src/en/guide/upgrading/upgrading90x.adoc +++ b/grails-doc/src/en/guide/upgrading/upgrading90x.adoc @@ -117,7 +117,7 @@ The builder no longer pins the version of the run image, so set both `builder` a * *An exception an action throws is now recorded as an error on the HTTP server observation.* When an error view answered, as the `"500"(view: '/error')` mapping of a generated application does, `http.server.requests` tagged the 500 with `error` and `exception` values of `none`, and tracing did not see a failure. A `500` mapping to a controller tagged it with `GrailsWrappedRuntimeException` and with the `uri` of that controller, so every failure it answered looked like the same route. -Both now report the exception the action threw and the route of the action. The exception is recorded as Spring Framework 7.1 records the exceptions Spring MVC translates to a 5xx, including an async timeout. +Both now report the exception the action threw and the route of the action, and the span of the request is marked as failed. An async timeout, which answers with a 503, is recorded in the same way. These requests were already counted with `outcome=SERVER_ERROR`, but an alert that counts a non-`none` `error` value will see more server errors than before, and a dashboard that reads the `uri` of an error controller will find those failures under the routes of the actions. After a forward to an error controller, the `jakarta.servlet.error.exception` request attribute holds the exception the action threw rather than a `GrailsWrappedRuntimeException`, for a filter that reads it once the chain has returned. Inside the error controller it still holds the wrapper. A client error is not recorded. diff --git a/grails-test-examples/issue-11102/src/integration-test/groovy/issue11102/FailedActionObservationSpec.groovy b/grails-test-examples/issue-11102/src/integration-test/groovy/issue11102/FailedActionObservationSpec.groovy index e8daff640b5..d463c64f566 100644 --- a/grails-test-examples/issue-11102/src/integration-test/groovy/issue11102/FailedActionObservationSpec.groovy +++ b/grails-test-examples/issue-11102/src/integration-test/groovy/issue11102/FailedActionObservationSpec.groovy @@ -19,8 +19,16 @@ package issue11102 +import java.util.concurrent.ConcurrentHashMap +import java.util.concurrent.CopyOnWriteArrayList +import java.util.concurrent.atomic.AtomicBoolean + import io.micrometer.core.instrument.MeterRegistry +import io.micrometer.observation.Observation +import io.micrometer.observation.ObservationHandler +import io.micrometer.observation.ObservationRegistry import org.springframework.beans.factory.annotation.Autowired +import org.springframework.http.server.observation.ServerRequestObservationContext import spock.lang.Specification import spock.lang.Tag import spock.util.concurrent.PollingConditions @@ -37,19 +45,32 @@ import org.apache.grails.testing.http.client.HttpClientSupport @Tag('http-client') class FailedActionObservationSpec extends Specification implements HttpClientSupport { + private static final AtomicBoolean LISTENING = new AtomicBoolean() + private static final Map> NOTIFIED = new ConcurrentHashMap<>() + @Autowired MeterRegistry meterRegistry - void 'a failed action answered by #handler is tagged with its own exception and route'() { + @Autowired + ObservationRegistry observationRegistry + + void setup() { + if (LISTENING.compareAndSet(false, true)) { + observationRegistry.observationConfig().observationHandler(new ErrorListener()) + } + } + + void 'a failed action answered by #handler is reported with its own exception and route'() { when: def response = http("/failing/$action") then: 'the error page answered, so the exception did not reach the filter' response.assertContains(500, page) - and: + and: 'its metrics say what failed and where, and the handlers that mark a span hear of it once' new PollingConditions(timeout: 5).eventually { assert errorTags("/failing/$action") == [exception] + assert NOTIFIED["/failing/$action".toString()] == [exception] } where: @@ -61,4 +82,18 @@ class FailedActionObservationSpec extends Specification implements HttpClientSup private List errorTags(String route) { meterRegistry.find('http.server.requests').tag('status', '500').tag('uri', route).timers()*.id*.getTag('error') } + + private static class ErrorListener implements ObservationHandler { + + @Override + boolean supportsContext(Observation.Context context) { + context instanceof ServerRequestObservationContext + } + + @Override + void onError(Observation.Context context) { + def route = ((ServerRequestObservationContext) context).pathPattern + NOTIFIED.computeIfAbsent(route) { new CopyOnWriteArrayList<>() } << context.error.class.simpleName + } + } } diff --git a/grails-web-mvc/src/main/groovy/org/grails/web/errors/GrailsExceptionResolver.java b/grails-web-mvc/src/main/groovy/org/grails/web/errors/GrailsExceptionResolver.java index 21edb501559..87c4fc5c82b 100644 --- a/grails-web-mvc/src/main/groovy/org/grails/web/errors/GrailsExceptionResolver.java +++ b/grails-web-mvc/src/main/groovy/org/grails/web/errors/GrailsExceptionResolver.java @@ -34,6 +34,8 @@ import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; +import io.micrometer.observation.Observation; +import io.micrometer.observation.ObservationRegistry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -43,6 +45,7 @@ import org.springframework.http.server.observation.ServerRequestObservationContext; import org.springframework.web.context.ServletContextAware; import org.springframework.web.context.request.async.AsyncRequestTimeoutException; +import org.springframework.web.context.support.WebApplicationContextUtils; import org.springframework.web.filter.ServerHttpObservationFilter; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.View; @@ -106,8 +109,6 @@ public ModelAndView resolveException(HttpServletRequest request, HttpServletResp ex = findWrappedException(ex); - recordServerError(request, ex); - if (!(ex instanceof AsyncRequestTimeoutException)) { logFullStackTraceIfEnabled(ex); filterStackTrace(ex); @@ -129,15 +130,52 @@ public ModelAndView resolveException(HttpServletRequest request, HttpServletResp mv = resolveViewOrForward(ex, urlMappings, request, response, mv); } + recordServerError(request, ex); + return mv; } /** * Every exception this resolves is a server error, and resolving it hides it from the observation of the request, - * whose metrics would otherwise say there was no error and whose trace would not be marked as failed. + * whose metrics would otherwise say there was no error and whose trace would not be marked as failed. Only + * {@link Observation#error(Throwable)} tells the observation's handlers, one of which marks the span, so setting the + * error on the context is what is left when the observation cannot be found. + *

+ * An exception left in {@link WebUtils#ERROR_EXCEPTION_ATTRIBUTE} is not recorded here, because the filter that stops + * the observation records what it finds there. */ - private static void recordServerError(HttpServletRequest request, Exception ex) { - ServerHttpObservationFilter.findObservationContext(request).ifPresent(context -> context.setError(ex)); + private void recordServerError(HttpServletRequest request, Exception ex) { + if (request.getAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE) == ex) { + return; + } + ServerHttpObservationFilter.findObservationContext(request).ifPresent(context -> { + Observation observation = findObservation(context); + if (observation != null) { + observation.error(ex); + } + else { + context.setError(ex); + } + }); + } + + /** + * The observation of a context, which the filter that started it keeps in scope while the request is dispatched, + * though not necessarily as the innermost one. + */ + private Observation findObservation(Observation.Context context) { + ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext); + ObservationRegistry registry = applicationContext != null ? + applicationContext.getBeanProvider(ObservationRegistry.class).getIfAvailable() : null; + Observation.Scope scope = registry != null ? registry.getCurrentObservationScope() : null; + while (scope != null) { + Observation observation = scope.getCurrentObservation(); + if (observation != null && observation.getContext() == context) { + return observation; + } + scope = scope.getPreviousObservationScope(); + } + return null; } /** diff --git a/grails-web-mvc/src/test/groovy/org/grails/web/errors/GrailsExceptionResolverSpec.groovy b/grails-web-mvc/src/test/groovy/org/grails/web/errors/GrailsExceptionResolverSpec.groovy index 76b11dfd235..4ed8d92fa3e 100644 --- a/grails-web-mvc/src/test/groovy/org/grails/web/errors/GrailsExceptionResolverSpec.groovy +++ b/grails-web-mvc/src/test/groovy/org/grails/web/errors/GrailsExceptionResolverSpec.groovy @@ -85,8 +85,9 @@ class GrailsExceptionResolverSpec extends Specification { void 'an exception #description is recorded as the error of the HTTP server observation'() { given: 'the filter a running application has around its requests' ServerRequestObservationContext observed = null - def registry = registryStoppingWith { observed = it } - def resolver = observedResolver() + List notified = [] + def registry = registryReporting({ observed = it }, { notified << it }) + def resolver = observedResolver(registry) def request = new MockHttpServletRequest('GET', '/failing') def response = new MockHttpServletResponse() FilterChain application = { req, res -> @@ -96,10 +97,14 @@ class GrailsExceptionResolverSpec extends Specification { when: new ServerHttpObservationFilter(registry).doFilter(request, response, application) - then: 'or its metrics and trace would say nothing failed' + then: 'or its metrics would say nothing failed' response.status == status observed.error.is(recorded) + and: 'or the handler that marks the span would not hear of it' + notified.size() == 1 + notified.first().is(recorded) + where: description | thrown | recorded | status 'an action threw' | FAILURE | FAILURE | 500 @@ -107,10 +112,29 @@ class GrailsExceptionResolverSpec extends Specification { 'of an async timeout' | ASYNC_TIMEOUT | ASYNC_TIMEOUT | 503 } + void 'an exception is still the error of the observation when the observation cannot be found'() { + given: 'a filter whose registry is not a bean of the application' + ServerRequestObservationContext observed = null + def registry = registryReporting({ observed = it }, { }) + def resolver = observedResolver() + FilterChain application = { req, res -> + resolver.resolveException((HttpServletRequest) req, (HttpServletResponse) res, null, FAILURE) + } as FilterChain + + when: + new ServerHttpObservationFilter(registry).doFilter( + new MockHttpServletRequest('GET', '/failing'), new MockHttpServletResponse(), application) + + then: + observed.error.is(FAILURE) + } + void 'the exception an error handler answers stays the error of the HTTP server observation'() { given: 'the filter a running application has around its requests, and an error handler to forward to' ServerRequestObservationContext observed = null - def resolver = resolverFor({ '500'(controller: 'errors', action: 'serverError') }, true) + List notified = [] + def registry = registryReporting({ observed = it }, { notified << it }) + def resolver = resolverFor({ '500'(controller: 'errors', action: 'serverError') }, true, registry) def request = new MockHttpServletRequest(servletContext, 'GET', '/fail') def response = new MockHttpServletResponse() bind(GRAILS, request, response) @@ -120,11 +144,15 @@ class GrailsExceptionResolverSpec extends Specification { } as FilterChain when: - new ServerHttpObservationFilter(registryStoppingWith { observed = it }).doFilter(request, response, application) + new ServerHttpObservationFilter(registry).doFilter(request, response, application) then: 'the handler answered, and the wrapper its model left on the request is not what is reported' response.forwardedUrl == '/errors/serverError' observed.error.is(original) + + and: 'the handlers hear of it once, though both the resolver and the filter could tell them' + notified.size() == 1 + notified.first().is(original) } void 'a filter can read the exception an error handler answered once the chain has returned, with no observation'() { @@ -152,7 +180,7 @@ class GrailsExceptionResolverSpec extends Specification { response.status == 500 } - private static ObservationRegistry registryStoppingWith(Closure stopped) { + private static ObservationRegistry registryReporting(Closure stopped, Closure errored) { def registry = ObservationRegistry.create() registry.observationConfig().observationHandler(new ObservationHandler() { @Override @@ -160,6 +188,11 @@ class GrailsExceptionResolverSpec extends Specification { context instanceof ServerRequestObservationContext } + @Override + void onError(Observation.Context context) { + errored.call(context.error) + } + @Override void onStop(Observation.Context context) { stopped.call(context) @@ -168,9 +201,12 @@ class GrailsExceptionResolverSpec extends Specification { registry } - private GrailsExceptionResolver observedResolver() { + private GrailsExceptionResolver observedResolver(ObservationRegistry registry = null) { webContext = new StaticWebApplicationContext() webContext.beanFactory.registerSingleton(GrailsApplication.APPLICATION_ID, Stub(GrailsApplication)) + if (registry) { + webContext.beanFactory.registerSingleton('observationRegistry', registry) + } webContext.refresh() servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, webContext) def resolver = new GrailsExceptionResolver() @@ -758,7 +794,8 @@ class GrailsExceptionResolverSpec extends Specification { attributes << [GRAILS, PLAIN_OVER_GRAILS, PLAIN, NOTHING] } - private GrailsExceptionResolver resolverFor(Closure mappings, boolean controllerMappings) { + private GrailsExceptionResolver resolverFor(Closure mappings, boolean controllerMappings, + ObservationRegistry registry = null) { def grailsApplication = new DefaultGrailsApplication().tap { initialise() } @@ -777,6 +814,9 @@ class GrailsExceptionResolverSpec extends Specification { webContext.beanFactory.registerSingleton(UrlMappingsHolder.BEAN_ID, urlMappings) webContext.beanFactory.registerSingleton(CompositeViewResolver.BEAN_NAME, new CompositeViewResolver(viewResolvers: [viewResolver])) + if (registry) { + webContext.beanFactory.registerSingleton('observationRegistry', registry) + } webContext.refresh() servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, webContext) From 2bf0865060d1b824a5ee58f3f738f4a3e3effb11 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Fri, 6 Nov 2026 06:43:35 -0800 Subject: [PATCH 40/78] Tell the observation's handlers about an exception written as a problem ActionExceptionHandlerResolver set the error on the context, as the Grails exception resolver did, which reaches the metrics but not the handlers' onError, so a tracing handler did not mark the span of a server error written as a problem. It now records the exception on the observation in the same way. --- .../mvc/ActionExceptionHandlerResolver.groovy | 36 +++++++++++++-- .../ActionExceptionProblemDetailsSpec.groovy | 46 ++++++++++++++++++- 2 files changed, 78 insertions(+), 4 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 9458bb9b713..efcaf106838 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 @@ -25,6 +25,9 @@ import org.codehaus.groovy.runtime.InvokerInvocationException import jakarta.servlet.http.HttpServletRequest import jakarta.servlet.http.HttpServletResponse +import io.micrometer.observation.Observation +import io.micrometer.observation.ObservationRegistry + import org.springframework.context.ApplicationContext import org.springframework.context.ApplicationContextAware import org.springframework.core.Ordered @@ -246,11 +249,38 @@ class ActionExceptionHandlerResolver implements HandlerExceptionResolver, Ordere 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) { + /** + * As Spring MVC records an exception it translates to a server error, which the observation would not see otherwise. + * Only the observation tells its handlers, one of which marks the span, so setting the error on the context is what + * is left when the observation cannot be found. + */ + private void recordServerError(HttpServletRequest request, Exception ex) { ServerHttpObservationFilter.findObservationContext(request).ifPresent { ServerRequestObservationContext context -> - context.error = ex + Observation observation = findObservation(context) + if (observation != null) { + observation.error(ex) + } + else { + context.error = ex + } + } + } + + /** + * The observation of a context, which the filter that started it keeps in scope while the request is dispatched, + * though not necessarily as the innermost one. + */ + private Observation findObservation(Observation.Context context) { + ObservationRegistry registry = applicationContext.getBeanProvider(ObservationRegistry).getIfAvailable() + Observation.Scope scope = registry?.currentObservationScope + while (scope != null) { + Observation observation = scope.currentObservation + if (observation?.context.is(context)) { + return observation + } + scope = scope.previousObservationScope } + return null } /** The action as a handler method: the controller that handles the request, and its method of the action. */ 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 e7d44cab6af..1499983d092 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,7 +21,14 @@ package org.grails.web.mapping.mvc import groovy.json.JsonSlurper import org.codehaus.groovy.runtime.InvokerInvocationException +import jakarta.servlet.FilterChain +import jakarta.servlet.http.HttpServletRequest +import jakarta.servlet.http.HttpServletResponse + import ch.qos.logback.classic.Level +import io.micrometer.observation.Observation +import io.micrometer.observation.ObservationHandler +import io.micrometer.observation.ObservationRegistry import org.springframework.core.env.MapPropertySource import org.springframework.http.HttpHeaders @@ -292,6 +299,39 @@ class ActionExceptionProblemDetailsSpec extends Specification { observation.error.is(serverError) } + void 'the handlers of the observation, one of which marks the span, are told of a server error and not of a client error'() { + given: 'the filter a running application has around its requests' + List notified = [] + def registry = ObservationRegistry.create() + registry.observationConfig().observationHandler(new ObservationHandler() { + @Override + boolean supportsContext(Observation.Context context) { + context instanceof ServerRequestObservationContext + } + + @Override + void onError(Observation.Context context) { + notified << context.error + } + }) + def resolver = resolver([problemDetails: true], null, registry) + def handler = action(new ProblemController()) + FilterChain application = { req, res -> + resolver.resolveException((HttpServletRequest) req, (HttpServletResponse) res, handler, thrown) + } as FilterChain + + when: + new ServerHttpObservationFilter(registry).doFilter(request, response, application) + + then: + notified == (told ? [thrown] : []) + + where: + thrown | told + new IllegalStateException('secret') | true + new ResponseStatusException(HttpStatus.BAD_REQUEST) | false + } + 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]) @@ -446,7 +486,8 @@ class ActionExceptionProblemDetailsSpec extends Specification { new JsonSlurper().parseText(response.contentAsString) as Map } - private ActionExceptionHandlerResolver resolver(Map settings, Closure mappings = null) { + private ActionExceptionHandlerResolver resolver(Map settings, Closure mappings = null, + ObservationRegistry registry = null) { context = new GenericWebApplicationContext() context.environment.propertySources.addFirst(new MapPropertySource('test', settings.collectEntries { key, value -> ["grails.exceptionresolver.$key".toString(), value] } as Map)) @@ -462,6 +503,9 @@ class ActionExceptionProblemDetailsSpec extends Specification { def holder = new DefaultUrlMappingsHolder(new DefaultUrlMappingEvaluator(grailsContext).evaluateMappings(mappings)) context.registerBean(UrlMappingsHolder.BEAN_ID, UrlMappingsHolder, { holder }) } + if (registry != null) { + context.registerBean('observationRegistry', ObservationRegistry, { registry }) + } context.registerBean(ActionExceptionHandlerResolver) context.refresh() context.getBean(ActionExceptionHandlerResolver) From 54285c29611c8ed990dff17715d996d843e68a67 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Fri, 6 Nov 2026 08:47:43 -0800 Subject: [PATCH 41/78] Load what Netty's leak detection needs before the embedded MongoDB's first client Netty tracks about one buffer in 128 for leaks, picked at random, and a tracked buffer loads classes an untracked one does not. The one request the server answers as it starts rarely gets that far, so each buffer allocated while Spring Boot has the jars of an executable jar closed still had about one chance in 128 of failing. EmbeddedMongoLifecycleSpec failed that way in CI, in ResourceLeakDetector.track0. The server now allocates buffers as it starts until one has been tracked, whatever the configured level. The spec allocates as many while the jars are closed, so it fails on every run without this instead of about once in 128. --- grails-data-mongodb/embedded/build.gradle | 3 +++ .../embedded/InMemoryMongoBackend.java | 17 ++++++++++++ .../ClearedJarsServerApplication.java | 26 +++++++++++++++++-- 3 files changed, 44 insertions(+), 2 deletions(-) diff --git a/grails-data-mongodb/embedded/build.gradle b/grails-data-mongodb/embedded/build.gradle index c595107b6e1..4476932ad76 100644 --- a/grails-data-mongodb/embedded/build.gradle +++ b/grails-data-mongodb/embedded/build.gradle @@ -55,6 +55,9 @@ dependencies { implementation 'org.slf4j:slf4j-api', { // impl: Logger, LoggerFactory } + implementation 'io.netty:netty-buffer', { + // impl: ByteBufAllocator — mongo-java-server only brings it to the runtime classpath + } // This module is written in Java so that a plain Spring Boot application can use it, // but every published module still produces a groovydoc jar, and groovydoc needs diff --git a/grails-data-mongodb/embedded/src/main/java/org/grails/datastore/gorm/mongodb/embedded/InMemoryMongoBackend.java b/grails-data-mongodb/embedded/src/main/java/org/grails/datastore/gorm/mongodb/embedded/InMemoryMongoBackend.java index f943b514aef..0b078a57689 100644 --- a/grails-data-mongodb/embedded/src/main/java/org/grails/datastore/gorm/mongodb/embedded/InMemoryMongoBackend.java +++ b/grails-data-mongodb/embedded/src/main/java/org/grails/datastore/gorm/mongodb/embedded/InMemoryMongoBackend.java @@ -27,6 +27,7 @@ import de.bwaldvogel.mongo.MongoServer; import de.bwaldvogel.mongo.backend.memory.MemoryBackend; +import io.netty.buffer.ByteBufAllocator; import org.springframework.util.ClassUtils; @@ -50,6 +51,9 @@ public class InMemoryMongoBackend implements EmbeddedMongoBackend { private static final int SERVE_ONE_REQUEST_TIMEOUT_MILLIS = 5000; + /** Netty tracks about one buffer in 128, so this many allocations reach that all but certainly. */ + private static final int ALLOCATIONS_TO_TRACK_ONE_BUFFER = 2048; + private static final int OP_MSG = 2013; private static final byte BSON_STRING = 0x02; @@ -86,9 +90,22 @@ public RunningEmbeddedMongo start(EmbeddedMongoSettings settings) { MongoServer server = new MongoServer(backend); server.bind("localhost", settings.getPort()); serveOneRequest(settings.getPort()); + allocateUntilOneBufferIsTracked(); return new RunningInMemoryMongo(backend, server); } + /** + * Allocates buffers until Netty's leak detection has tracked one, so that what only a tracked + * buffer needs is loaded as well. Netty picks the buffers it tracks at random, so the request + * {@link #serveOneRequest(int)} sends rarely gets that far, and a buffer picked while the jars are + * closed fails as the first one would. + */ + private static void allocateUntilOneBufferIsTracked() { + for (int i = 0; i < ALLOCATIONS_TO_TRACK_ONE_BUFFER; i++) { + ByteBufAllocator.DEFAULT.ioBuffer(1).release(); + } + } + /** * Has the server answer one request, so that what its event loops need is loaded while the * application is starting rather than when its first client connects. diff --git a/grails-data-mongodb/embedded/src/test/java/org/grails/datastore/gorm/mongodb/embedded/ClearedJarsServerApplication.java b/grails-data-mongodb/embedded/src/test/java/org/grails/datastore/gorm/mongodb/embedded/ClearedJarsServerApplication.java index 7e427790565..0ab288955b2 100644 --- a/grails-data-mongodb/embedded/src/test/java/org/grails/datastore/gorm/mongodb/embedded/ClearedJarsServerApplication.java +++ b/grails-data-mongodb/embedded/src/test/java/org/grails/datastore/gorm/mongodb/embedded/ClearedJarsServerApplication.java @@ -19,6 +19,8 @@ package org.grails.datastore.gorm.mongodb.embedded; import java.io.File; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.Socket; import java.net.URL; @@ -27,6 +29,8 @@ import java.util.List; import java.util.Map; +import io.netty.buffer.ByteBufAllocator; + import org.springframework.context.support.GenericApplicationContext; import org.springframework.core.env.MapPropertySource; @@ -53,14 +57,21 @@ public static void main(String[] args) throws Exception { int port = Integer.parseInt(args[0]); ClearedJarsClassLoader loader = new ClearedJarsClassLoader(); Thread.currentThread().setContextClassLoader(loader); - Runnable stop = (Runnable) loader.loadClass(Server.class.getName()) - .getMethod("start", int.class).invoke(null, port); + Class server = loader.loadClass(Server.class.getName()); + Runnable stop = (Runnable) server.getMethod("start", int.class).invoke(null, port); + Method allocate = server.getMethod("allocateAsAnEventLoopDoes"); try (Socket client = new Socket("localhost", port)) { Thread.sleep(1000L); loader.cleared = true; client.getOutputStream().write(1); client.getOutputStream().flush(); + try { + allocate.invoke(null); + } + catch (InvocationTargetException ex) { + System.out.println(ex.getCause()); + } Thread.sleep(1000L); loader.cleared = false; @@ -74,6 +85,17 @@ public static final class Server { private Server() { } + /** + * As many buffers as it takes for Netty's leak detection to track one, which it does at random + * and which loads classes of its own. Without this, a server missing those classes would pass + * all but about once in 128 runs. + */ + public static void allocateAsAnEventLoopDoes() { + for (int i = 0; i < 2048; i++) { + ByteBufAllocator.DEFAULT.ioBuffer(1).release(); + } + } + public static Runnable start(int port) { GenericApplicationContext context = new GenericApplicationContext(); context.getEnvironment().getPropertySources().addFirst(new MapPropertySource("application", Map.of( From b9125843ccbb6d0b91f2da6c53c05aa21441e5c3 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Fri, 6 Nov 2026 09:23:35 -0800 Subject: [PATCH 42/78] Tell the handlers through the observation the filter keeps on the request The resolver looked for the observation through the application's registry, so a filter built with a registry of its own was missed, and the error only reached the context, which does not call the handlers' onError. A tracing handler then left the span unmarked. ServerHttpObservationFilter keeps its observation in a request attribute, whatever registry built it, so the resolver now uses that one. The attribute is private to the filter, which offers only the context. The specs run Spring's real filter and fail if the attribute is renamed. --- .../web/errors/GrailsExceptionResolver.java | 47 ++++++------------- .../errors/GrailsExceptionResolverSpec.groovy | 36 +++++--------- 2 files changed, 28 insertions(+), 55 deletions(-) diff --git a/grails-web-mvc/src/main/groovy/org/grails/web/errors/GrailsExceptionResolver.java b/grails-web-mvc/src/main/groovy/org/grails/web/errors/GrailsExceptionResolver.java index 87c4fc5c82b..1d6bde20965 100644 --- a/grails-web-mvc/src/main/groovy/org/grails/web/errors/GrailsExceptionResolver.java +++ b/grails-web-mvc/src/main/groovy/org/grails/web/errors/GrailsExceptionResolver.java @@ -35,7 +35,6 @@ import jakarta.servlet.http.HttpServletResponse; import io.micrometer.observation.Observation; -import io.micrometer.observation.ObservationRegistry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -45,7 +44,6 @@ import org.springframework.http.server.observation.ServerRequestObservationContext; import org.springframework.web.context.ServletContextAware; import org.springframework.web.context.request.async.AsyncRequestTimeoutException; -import org.springframework.web.context.support.WebApplicationContextUtils; import org.springframework.web.filter.ServerHttpObservationFilter; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.View; @@ -86,6 +84,14 @@ public class GrailsExceptionResolver extends SimpleMappingExceptionResolver impl private static final String ERROR_HANDLER_FORWARD_IN_PROGRESS_ATTRIBUTE = "org.grails.web.errors.ERROR_HANDLER_FORWARD_IN_PROGRESS"; + /** + * Where {@link ServerHttpObservationFilter} keeps the observation of a request. The filter only offers its context, + * which cannot tell the handlers of an error, and a registry cannot be relied on to find it, because a filter can be + * built with a registry the application does not know. + */ + private static final String SERVER_OBSERVATION_ATTRIBUTE = + ServerHttpObservationFilter.class.getName() + ".observation"; + protected static final Logger LOG = LoggerFactory.getLogger(GrailsExceptionResolver.class); protected static final String LINE_SEPARATOR = System.getProperty("line.separator"); @@ -138,44 +144,21 @@ public ModelAndView resolveException(HttpServletRequest request, HttpServletResp /** * Every exception this resolves is a server error, and resolving it hides it from the observation of the request, * whose metrics would otherwise say there was no error and whose trace would not be marked as failed. Only - * {@link Observation#error(Throwable)} tells the observation's handlers, one of which marks the span, so setting the - * error on the context is what is left when the observation cannot be found. + * {@link Observation#error(Throwable)} tells the observation's handlers, one of which marks the span. *

* An exception left in {@link WebUtils#ERROR_EXCEPTION_ATTRIBUTE} is not recorded here, because the filter that stops * the observation records what it finds there. */ - private void recordServerError(HttpServletRequest request, Exception ex) { + private static void recordServerError(HttpServletRequest request, Exception ex) { if (request.getAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE) == ex) { return; } - ServerHttpObservationFilter.findObservationContext(request).ifPresent(context -> { - Observation observation = findObservation(context); - if (observation != null) { - observation.error(ex); - } - else { - context.setError(ex); - } - }); - } - - /** - * The observation of a context, which the filter that started it keeps in scope while the request is dispatched, - * though not necessarily as the innermost one. - */ - private Observation findObservation(Observation.Context context) { - ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext); - ObservationRegistry registry = applicationContext != null ? - applicationContext.getBeanProvider(ObservationRegistry.class).getIfAvailable() : null; - Observation.Scope scope = registry != null ? registry.getCurrentObservationScope() : null; - while (scope != null) { - Observation observation = scope.getCurrentObservation(); - if (observation != null && observation.getContext() == context) { - return observation; - } - scope = scope.getPreviousObservationScope(); + if (request.getAttribute(SERVER_OBSERVATION_ATTRIBUTE) instanceof Observation observation) { + observation.error(ex); + } + else { + ServerHttpObservationFilter.findObservationContext(request).ifPresent(context -> context.setError(ex)); } - return null; } /** diff --git a/grails-web-mvc/src/test/groovy/org/grails/web/errors/GrailsExceptionResolverSpec.groovy b/grails-web-mvc/src/test/groovy/org/grails/web/errors/GrailsExceptionResolverSpec.groovy index 4ed8d92fa3e..1df6e6e0d74 100644 --- a/grails-web-mvc/src/test/groovy/org/grails/web/errors/GrailsExceptionResolverSpec.groovy +++ b/grails-web-mvc/src/test/groovy/org/grails/web/errors/GrailsExceptionResolverSpec.groovy @@ -83,11 +83,11 @@ class GrailsExceptionResolverSpec extends Specification { } void 'an exception #description is recorded as the error of the HTTP server observation'() { - given: 'the filter a running application has around its requests' + given: 'the filter a running application has around its requests, whose registry the application need not know' ServerRequestObservationContext observed = null List notified = [] def registry = registryReporting({ observed = it }, { notified << it }) - def resolver = observedResolver(registry) + def resolver = observedResolver() def request = new MockHttpServletRequest('GET', '/failing') def response = new MockHttpServletResponse() FilterChain application = { req, res -> @@ -112,21 +112,18 @@ class GrailsExceptionResolverSpec extends Specification { 'of an async timeout' | ASYNC_TIMEOUT | ASYNC_TIMEOUT | 503 } - void 'an exception is still the error of the observation when the observation cannot be found'() { - given: 'a filter whose registry is not a bean of the application' - ServerRequestObservationContext observed = null - def registry = registryReporting({ observed = it }, { }) - def resolver = observedResolver() - FilterChain application = { req, res -> - resolver.resolveException((HttpServletRequest) req, (HttpServletResponse) res, null, FAILURE) - } as FilterChain + void 'an exception is still the error of a context that comes without its observation'() { + given: + def request = new MockHttpServletRequest('GET', '/failing') + def response = new MockHttpServletResponse() + def context = new ServerRequestObservationContext(request, response) + request.setAttribute(ServerHttpObservationFilter.CURRENT_OBSERVATION_CONTEXT_ATTRIBUTE, context) when: - new ServerHttpObservationFilter(registry).doFilter( - new MockHttpServletRequest('GET', '/failing'), new MockHttpServletResponse(), application) + observedResolver().resolveException(request, response, null, FAILURE) then: - observed.error.is(FAILURE) + context.error.is(FAILURE) } void 'the exception an error handler answers stays the error of the HTTP server observation'() { @@ -134,7 +131,7 @@ class GrailsExceptionResolverSpec extends Specification { ServerRequestObservationContext observed = null List notified = [] def registry = registryReporting({ observed = it }, { notified << it }) - def resolver = resolverFor({ '500'(controller: 'errors', action: 'serverError') }, true, registry) + def resolver = resolverFor({ '500'(controller: 'errors', action: 'serverError') }, true) def request = new MockHttpServletRequest(servletContext, 'GET', '/fail') def response = new MockHttpServletResponse() bind(GRAILS, request, response) @@ -201,12 +198,9 @@ class GrailsExceptionResolverSpec extends Specification { registry } - private GrailsExceptionResolver observedResolver(ObservationRegistry registry = null) { + private GrailsExceptionResolver observedResolver() { webContext = new StaticWebApplicationContext() webContext.beanFactory.registerSingleton(GrailsApplication.APPLICATION_ID, Stub(GrailsApplication)) - if (registry) { - webContext.beanFactory.registerSingleton('observationRegistry', registry) - } webContext.refresh() servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, webContext) def resolver = new GrailsExceptionResolver() @@ -794,8 +788,7 @@ class GrailsExceptionResolverSpec extends Specification { attributes << [GRAILS, PLAIN_OVER_GRAILS, PLAIN, NOTHING] } - private GrailsExceptionResolver resolverFor(Closure mappings, boolean controllerMappings, - ObservationRegistry registry = null) { + private GrailsExceptionResolver resolverFor(Closure mappings, boolean controllerMappings) { def grailsApplication = new DefaultGrailsApplication().tap { initialise() } @@ -814,9 +807,6 @@ class GrailsExceptionResolverSpec extends Specification { webContext.beanFactory.registerSingleton(UrlMappingsHolder.BEAN_ID, urlMappings) webContext.beanFactory.registerSingleton(CompositeViewResolver.BEAN_NAME, new CompositeViewResolver(viewResolvers: [viewResolver])) - if (registry) { - webContext.beanFactory.registerSingleton('observationRegistry', registry) - } webContext.refresh() servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, webContext) From 829e30b8726cb67abf6e14663900fc9886842d83 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Fri, 6 Nov 2026 09:23:36 -0800 Subject: [PATCH 43/78] Tell the handlers of an exception written as a problem in the same way ActionExceptionHandlerResolver had the same gap as the Grails exception resolver: a filter built with a registry the application does not know was missed, so the error only reached the context. It now uses the observation the filter keeps on the request. --- .../mvc/ActionExceptionHandlerResolver.groovy | 42 +++++++------------ .../ActionExceptionProblemDetailsSpec.groovy | 8 +--- 2 files changed, 17 insertions(+), 33 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 efcaf106838..38438a954ab 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 @@ -26,7 +26,6 @@ import jakarta.servlet.http.HttpServletRequest import jakarta.servlet.http.HttpServletResponse import io.micrometer.observation.Observation -import io.micrometer.observation.ObservationRegistry import org.springframework.context.ApplicationContext import org.springframework.context.ApplicationContextAware @@ -80,6 +79,13 @@ import org.grails.web.util.WebUtils @Slf4j class ActionExceptionHandlerResolver implements HandlerExceptionResolver, Ordered, ApplicationContextAware { + /** + * Where {@link ServerHttpObservationFilter} keeps the observation of a request. The filter only offers its context, + * which cannot tell the handlers of an error, and a registry cannot be relied on to find it, because a filter can be + * built with a registry the application does not know. + */ + private static final String SERVER_OBSERVATION_ATTRIBUTE = ServerHttpObservationFilter.name + '.observation' + /** The name of the bean Spring MVC's content negotiation manager is. */ private static final String MVC_CONTENT_NEGOTIATION_MANAGER = 'mvcContentNegotiationManager' @@ -251,36 +257,18 @@ class ActionExceptionHandlerResolver implements HandlerExceptionResolver, Ordere /** * As Spring MVC records an exception it translates to a server error, which the observation would not see otherwise. - * Only the observation tells its handlers, one of which marks the span, so setting the error on the context is what - * is left when the observation cannot be found. + * Only the observation tells its handlers, one of which marks the span. */ - private void recordServerError(HttpServletRequest request, Exception ex) { - ServerHttpObservationFilter.findObservationContext(request).ifPresent { ServerRequestObservationContext context -> - Observation observation = findObservation(context) - if (observation != null) { - observation.error(ex) - } - else { - context.error = ex - } + private static void recordServerError(HttpServletRequest request, Exception ex) { + Object observation = request.getAttribute(SERVER_OBSERVATION_ATTRIBUTE) + if (observation instanceof Observation) { + ((Observation) observation).error(ex) } - } - - /** - * The observation of a context, which the filter that started it keeps in scope while the request is dispatched, - * though not necessarily as the innermost one. - */ - private Observation findObservation(Observation.Context context) { - ObservationRegistry registry = applicationContext.getBeanProvider(ObservationRegistry).getIfAvailable() - Observation.Scope scope = registry?.currentObservationScope - while (scope != null) { - Observation observation = scope.currentObservation - if (observation?.context.is(context)) { - return observation + else { + ServerHttpObservationFilter.findObservationContext(request).ifPresent { ServerRequestObservationContext context -> + context.error = ex } - scope = scope.previousObservationScope } - return null } /** The action as a handler method: the controller that handles the request, and its method of the action. */ 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 1499983d092..6693d52000e 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 @@ -314,7 +314,7 @@ class ActionExceptionProblemDetailsSpec extends Specification { notified << context.error } }) - def resolver = resolver([problemDetails: true], null, registry) + def resolver = resolver([problemDetails: true]) def handler = action(new ProblemController()) FilterChain application = { req, res -> resolver.resolveException((HttpServletRequest) req, (HttpServletResponse) res, handler, thrown) @@ -486,8 +486,7 @@ class ActionExceptionProblemDetailsSpec extends Specification { new JsonSlurper().parseText(response.contentAsString) as Map } - private ActionExceptionHandlerResolver resolver(Map settings, Closure mappings = null, - ObservationRegistry registry = null) { + 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)) @@ -503,9 +502,6 @@ class ActionExceptionProblemDetailsSpec extends Specification { def holder = new DefaultUrlMappingsHolder(new DefaultUrlMappingEvaluator(grailsContext).evaluateMappings(mappings)) context.registerBean(UrlMappingsHolder.BEAN_ID, UrlMappingsHolder, { holder }) } - if (registry != null) { - context.registerBean('observationRegistry', ObservationRegistry, { registry }) - } context.registerBean(ActionExceptionHandlerResolver) context.refresh() context.getBean(ActionExceptionHandlerResolver) From d049b777f0e3a6b5460f2a13a01560e5686d2a97 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Fri, 6 Nov 2026 09:31:06 -0800 Subject: [PATCH 44/78] Record an exception an error handler answers on an asynchronous dispatch The resolver left an exception a forward kept on the request to the filter, which records what it finds in that attribute when it stops the observation. On an asynchronous dispatch the filter leaves stopping it to a listener that does not look, so an asynchronous action answered by an error controller left the span unmarked. The resolver now leaves it to the filter only where the filter will read it. The functional spec fails actions through Spring's own async handling, for both an error view and an error controller. --- .../issue11102/FailingController.groovy | 20 ++++++++++++++++ .../FailedActionObservationSpec.groovy | 8 ++++--- .../web/errors/GrailsExceptionResolver.java | 7 ++++-- .../errors/GrailsExceptionResolverSpec.groovy | 24 +++++++++++++++++++ 4 files changed, 54 insertions(+), 5 deletions(-) diff --git a/grails-test-examples/issue-11102/grails-app/controllers/issue11102/FailingController.groovy b/grails-test-examples/issue-11102/grails-app/controllers/issue11102/FailingController.groovy index f84840138c3..fc8fcdcc0a2 100644 --- a/grails-test-examples/issue-11102/grails-app/controllers/issue11102/FailingController.groovy +++ b/grails-test-examples/issue-11102/grails-app/controllers/issue11102/FailingController.groovy @@ -19,6 +19,10 @@ package issue11102 +import org.springframework.web.context.request.async.DeferredResult +import org.springframework.web.context.request.async.WebAsyncManager +import org.springframework.web.context.request.async.WebAsyncUtils + class FailingController { def answeredByView() { @@ -29,7 +33,23 @@ class FailingController { throw new UnsupportedOperationException('answered by the error controller') } + def answeredByViewAsynchronously() { + failAsynchronously(new IllegalStateException('answered by the error view')) + } + + def answeredByControllerAsynchronously() { + failAsynchronously(new UnsupportedOperationException('answered by the error controller')) + } + def errorHandler() { render status: 500, text: 'Answered by the error controller' } + + private void failAsynchronously(Exception failure) { + WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request) + asyncManager.asyncWebRequest = WebAsyncUtils.createAsyncWebRequest(request, response) + DeferredResult result = new DeferredResult<>() + asyncManager.startDeferredResultProcessing(result) + result.errorResult = failure + } } diff --git a/grails-test-examples/issue-11102/src/integration-test/groovy/issue11102/FailedActionObservationSpec.groovy b/grails-test-examples/issue-11102/src/integration-test/groovy/issue11102/FailedActionObservationSpec.groovy index d463c64f566..1c245036256 100644 --- a/grails-test-examples/issue-11102/src/integration-test/groovy/issue11102/FailedActionObservationSpec.groovy +++ b/grails-test-examples/issue-11102/src/integration-test/groovy/issue11102/FailedActionObservationSpec.groovy @@ -74,9 +74,11 @@ class FailedActionObservationSpec extends Specification implements HttpClientSup } where: - handler | action | page | exception - 'the error view' | 'answeredByView' | 'An error has occurred' | 'IllegalStateException' - 'an error controller' | 'answeredByController' | 'Answered by the error controller' | 'UnsupportedOperationException' + handler | action | page | exception + 'the error view' | 'answeredByView' | 'An error has occurred' | 'IllegalStateException' + 'an error controller' | 'answeredByController' | 'Answered by the error controller' | 'UnsupportedOperationException' + 'the error view, asynchronously' | 'answeredByViewAsynchronously' | 'An error has occurred' | 'IllegalStateException' + 'an error controller, asynchronously' | 'answeredByControllerAsynchronously' | 'Answered by the error controller' | 'UnsupportedOperationException' } private List errorTags(String route) { diff --git a/grails-web-mvc/src/main/groovy/org/grails/web/errors/GrailsExceptionResolver.java b/grails-web-mvc/src/main/groovy/org/grails/web/errors/GrailsExceptionResolver.java index 1d6bde20965..130bc403de3 100644 --- a/grails-web-mvc/src/main/groovy/org/grails/web/errors/GrailsExceptionResolver.java +++ b/grails-web-mvc/src/main/groovy/org/grails/web/errors/GrailsExceptionResolver.java @@ -29,6 +29,7 @@ import org.codehaus.groovy.control.CompilationFailedException; import org.codehaus.groovy.runtime.InvokerInvocationException; +import jakarta.servlet.DispatcherType; import jakarta.servlet.ServletContext; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; @@ -147,10 +148,12 @@ public ModelAndView resolveException(HttpServletRequest request, HttpServletResp * {@link Observation#error(Throwable)} tells the observation's handlers, one of which marks the span. *

* An exception left in {@link WebUtils#ERROR_EXCEPTION_ATTRIBUTE} is not recorded here, because the filter that stops - * the observation records what it finds there. + * the observation records what it finds there. On an asynchronous dispatch the filter leaves stopping it to a listener + * that does not look. */ private static void recordServerError(HttpServletRequest request, Exception ex) { - if (request.getAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE) == ex) { + if (request.getDispatcherType() != DispatcherType.ASYNC && + request.getAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE) == ex) { return; } if (request.getAttribute(SERVER_OBSERVATION_ATTRIBUTE) instanceof Observation observation) { diff --git a/grails-web-mvc/src/test/groovy/org/grails/web/errors/GrailsExceptionResolverSpec.groovy b/grails-web-mvc/src/test/groovy/org/grails/web/errors/GrailsExceptionResolverSpec.groovy index 1df6e6e0d74..4ca34ecafd6 100644 --- a/grails-web-mvc/src/test/groovy/org/grails/web/errors/GrailsExceptionResolverSpec.groovy +++ b/grails-web-mvc/src/test/groovy/org/grails/web/errors/GrailsExceptionResolverSpec.groovy @@ -60,6 +60,7 @@ import org.springframework.web.servlet.view.InternalResourceView import spock.lang.Issue import spock.lang.Specification +import jakarta.servlet.DispatcherType import jakarta.servlet.FilterChain import jakarta.servlet.RequestDispatcher import jakarta.servlet.http.HttpServletRequest @@ -152,6 +153,29 @@ class GrailsExceptionResolverSpec extends Specification { notified.first().is(original) } + void 'the handlers hear of an exception an error handler answers on an asynchronous dispatch'() { + given: 'the filter, which on that dispatch does not read the exception left on the request' + List notified = [] + def registry = registryReporting({ }, { notified << it }) + def resolver = resolverFor({ '500'(controller: 'errors', action: 'serverError') }, true) + def request = new MockHttpServletRequest(servletContext, 'GET', '/fail') + request.dispatcherType = DispatcherType.ASYNC + def response = new MockHttpServletResponse() + bind(GRAILS, request, response) + def original = new IllegalStateException('original') + FilterChain application = { req, res -> + resolver.resolveException((HttpServletRequest) req, (HttpServletResponse) res, null, original) + } as FilterChain + + when: + new ServerHttpObservationFilter(registry).doFilter(request, response, application) + + then: + response.forwardedUrl == '/errors/serverError' + notified.size() == 1 + notified.first().is(original) + } + void 'a filter can read the exception an error handler answered once the chain has returned, with no observation'() { given: def resolver = resolverFor({ '500'(controller: 'errors', action: 'serverError') }, true) From 647650940c2318b8a4b55ef3cae69392d0ae7ad7 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Fri, 6 Nov 2026 09:47:57 -0800 Subject: [PATCH 45/78] Recognise an asynchronous dispatch from an action forwarded to The previous commit went by the type of the dispatch, which is FORWARD for an action forwarded to from an asynchronous dispatch, so its exception was still left to a filter that would not read it. The attribute the container sets on an asynchronous dispatch stays through the forward, and WebUtils.isAsync already reads it for the handler adapter. --- .../org/grails/web/errors/GrailsExceptionResolver.java | 4 +--- .../web/errors/GrailsExceptionResolverSpec.groovy | 10 +++++++++- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/grails-web-mvc/src/main/groovy/org/grails/web/errors/GrailsExceptionResolver.java b/grails-web-mvc/src/main/groovy/org/grails/web/errors/GrailsExceptionResolver.java index 130bc403de3..40fc468cb8b 100644 --- a/grails-web-mvc/src/main/groovy/org/grails/web/errors/GrailsExceptionResolver.java +++ b/grails-web-mvc/src/main/groovy/org/grails/web/errors/GrailsExceptionResolver.java @@ -29,7 +29,6 @@ import org.codehaus.groovy.control.CompilationFailedException; import org.codehaus.groovy.runtime.InvokerInvocationException; -import jakarta.servlet.DispatcherType; import jakarta.servlet.ServletContext; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; @@ -152,8 +151,7 @@ public ModelAndView resolveException(HttpServletRequest request, HttpServletResp * that does not look. */ private static void recordServerError(HttpServletRequest request, Exception ex) { - if (request.getDispatcherType() != DispatcherType.ASYNC && - request.getAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE) == ex) { + if (!WebUtils.isAsync(request) && request.getAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE) == ex) { return; } if (request.getAttribute(SERVER_OBSERVATION_ATTRIBUTE) instanceof Observation observation) { diff --git a/grails-web-mvc/src/test/groovy/org/grails/web/errors/GrailsExceptionResolverSpec.groovy b/grails-web-mvc/src/test/groovy/org/grails/web/errors/GrailsExceptionResolverSpec.groovy index 4ca34ecafd6..3d8f04e1037 100644 --- a/grails-web-mvc/src/test/groovy/org/grails/web/errors/GrailsExceptionResolverSpec.groovy +++ b/grails-web-mvc/src/test/groovy/org/grails/web/errors/GrailsExceptionResolverSpec.groovy @@ -153,18 +153,21 @@ class GrailsExceptionResolverSpec extends Specification { notified.first().is(original) } - void 'the handlers hear of an exception an error handler answers on an asynchronous dispatch'() { + void 'the handlers hear of an exception an error handler answers on an asynchronous dispatch, #where'() { given: 'the filter, which on that dispatch does not read the exception left on the request' List notified = [] def registry = registryReporting({ }, { notified << it }) def resolver = resolverFor({ '500'(controller: 'errors', action: 'serverError') }, true) def request = new MockHttpServletRequest(servletContext, 'GET', '/fail') request.dispatcherType = DispatcherType.ASYNC + request.setAttribute(GrailsWebUtils.ASYNC_REQUEST_URI_ATTRIBUTE, '/fail') def response = new MockHttpServletResponse() bind(GRAILS, request, response) def original = new IllegalStateException('original') FilterChain application = { req, res -> + request.dispatcherType = resolvedOn resolver.resolveException((HttpServletRequest) req, (HttpServletResponse) res, null, original) + request.dispatcherType = DispatcherType.ASYNC } as FilterChain when: @@ -174,6 +177,11 @@ class GrailsExceptionResolverSpec extends Specification { response.forwardedUrl == '/errors/serverError' notified.size() == 1 notified.first().is(original) + + where: + where | resolvedOn + 'in the action dispatched' | DispatcherType.ASYNC + 'in an action forwarded to' | DispatcherType.FORWARD } void 'a filter can read the exception an error handler answered once the chain has returned, with no observation'() { From 24ecc0252fbf2660bb4d65f6fb1fbb62390579cb Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Fri, 6 Nov 2026 14:12:55 -0700 Subject: [PATCH 46/78] Keep the status of a wrapped exception when writing it as a problem Finding the exception an action threw followed the cause chain to its end, so a ResponseStatusException of 410 with a cause of its own, wrapped by a dynamic invocation, was written from that cause, as a 500. It now takes off only what Groovy and Grails wrap the exception in, and stops at the exception the action threw. --- .../mvc/ActionExceptionHandlerResolver.groovy | 15 +++++++------- .../ActionExceptionProblemDetailsSpec.groovy | 20 +++++++++++++++++++ 2 files changed, 28 insertions(+), 7 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 38438a954ab..6cf082b4020 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 @@ -201,15 +201,16 @@ class ActionExceptionHandlerResolver implements HandlerExceptionResolver, Ordere return request.getAttribute(WebUtils.FORWARD_REQUEST_URI_ATTRIBUTE) ?: request.requestURI } - /** As the Grails exception resolver finds the exception an action threw. */ + /** + * The exception an action threw, out of what Groovy and Grails wrap it in. Only those come off: what that exception + * wraps itself is its own cause, and the status it answers with is its own. + */ 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 - } + Throwable found = ex + while ((found instanceof InvokerInvocationException || found instanceof GrailsMVCException) && found.cause != null) { + found = found.cause } - return ex + return found instanceof Exception ? (Exception) found : ex } /** 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 6693d52000e..7b34a32c400 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 @@ -63,6 +63,7 @@ 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.servlet.mvc.exceptions.ControllerExecutionException import org.grails.web.util.GrailsApplicationAttributes import org.grails.web.util.WebUtils import spock.lang.Specification @@ -200,6 +201,25 @@ class ActionExceptionProblemDetailsSpec extends Specification { problem().detail == 'Taken' } + void 'an exception wrapped by #wrapper keeps its own status, whatever caused it'() { + given: + def resolver = resolver([problemDetails: true]) + def thrown = new ResponseStatusException(HttpStatus.GONE, 'Gone for good', new IllegalStateException('why')) + + when: + resolver.resolveException(request, response, action(new ProblemController()), wrap.call(thrown)) + + then: + response.status == 410 + problem().status == 410 + + where: + wrapper | wrap + 'a dynamic invocation' | { Throwable it -> new InvokerInvocationException(it) } + 'an action execution' | { Throwable it -> new ControllerExecutionException('Failed', it) } + 'both' | { Throwable it -> new ControllerExecutionException('Failed', new InvokerInvocationException(it)) } + } + void 'a request that can no longer be answered writes nothing'() { given: def resolver = resolver([problemDetails: true]) From 34f91c1c9f78264b61d91e3be1fe9a1bbd73bd0c Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Sat, 7 Nov 2026 07:04:59 -0800 Subject: [PATCH 47/78] Keep the route that failed when an error handler is routed The resolver put the failed route back on the observation once its forward to an error handler returned. When the action had started async processing before it threw, the error handler was routed again after that, and its route replaced the one that failed. The handler that sets the route now leaves it alone for a request routed to an error handler, so the restore is gone and the route is never replaced, whenever the error handler is routed. --- .../issue11102/FailingController.groovy | 7 ++++ .../FailedActionObservationSpec.groovy | 11 +++--- .../web/errors/GrailsExceptionResolver.java | 16 +++------ .../mvc/UrlMappingsHandlerMapping.groovy | 6 +++- .../mvc/UrlMappingsHandlerMappingSpec.groovy | 35 +++++++++++++++++++ 5 files changed, 58 insertions(+), 17 deletions(-) diff --git a/grails-test-examples/issue-11102/grails-app/controllers/issue11102/FailingController.groovy b/grails-test-examples/issue-11102/grails-app/controllers/issue11102/FailingController.groovy index fc8fcdcc0a2..a29e45cd945 100644 --- a/grails-test-examples/issue-11102/grails-app/controllers/issue11102/FailingController.groovy +++ b/grails-test-examples/issue-11102/grails-app/controllers/issue11102/FailingController.groovy @@ -41,6 +41,13 @@ class FailingController { failAsynchronously(new UnsupportedOperationException('answered by the error controller')) } + def answeredByControllerAfterStartingAsync() { + WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request) + asyncManager.asyncWebRequest = WebAsyncUtils.createAsyncWebRequest(request, response) + asyncManager.startDeferredResultProcessing(new DeferredResult()) + throw new UnsupportedOperationException('answered by the error controller') + } + def errorHandler() { render status: 500, text: 'Answered by the error controller' } diff --git a/grails-test-examples/issue-11102/src/integration-test/groovy/issue11102/FailedActionObservationSpec.groovy b/grails-test-examples/issue-11102/src/integration-test/groovy/issue11102/FailedActionObservationSpec.groovy index 1c245036256..bf2ef251dea 100644 --- a/grails-test-examples/issue-11102/src/integration-test/groovy/issue11102/FailedActionObservationSpec.groovy +++ b/grails-test-examples/issue-11102/src/integration-test/groovy/issue11102/FailedActionObservationSpec.groovy @@ -74,11 +74,12 @@ class FailedActionObservationSpec extends Specification implements HttpClientSup } where: - handler | action | page | exception - 'the error view' | 'answeredByView' | 'An error has occurred' | 'IllegalStateException' - 'an error controller' | 'answeredByController' | 'Answered by the error controller' | 'UnsupportedOperationException' - 'the error view, asynchronously' | 'answeredByViewAsynchronously' | 'An error has occurred' | 'IllegalStateException' - 'an error controller, asynchronously' | 'answeredByControllerAsynchronously' | 'Answered by the error controller' | 'UnsupportedOperationException' + handler | action | page | exception + 'the error view' | 'answeredByView' | 'An error has occurred' | 'IllegalStateException' + 'an error controller' | 'answeredByController' | 'Answered by the error controller' | 'UnsupportedOperationException' + 'the error view, asynchronously' | 'answeredByViewAsynchronously' | 'An error has occurred' | 'IllegalStateException' + 'an error controller, asynchronously' | 'answeredByControllerAsynchronously' | 'Answered by the error controller' | 'UnsupportedOperationException' + 'an error controller, after starting async' | 'answeredByControllerAfterStartingAsync' | 'Answered by the error controller' | 'UnsupportedOperationException' } private List errorTags(String route) { diff --git a/grails-web-mvc/src/main/groovy/org/grails/web/errors/GrailsExceptionResolver.java b/grails-web-mvc/src/main/groovy/org/grails/web/errors/GrailsExceptionResolver.java index 40fc468cb8b..b830acb6cfa 100644 --- a/grails-web-mvc/src/main/groovy/org/grails/web/errors/GrailsExceptionResolver.java +++ b/grails-web-mvc/src/main/groovy/org/grails/web/errors/GrailsExceptionResolver.java @@ -41,7 +41,6 @@ import org.springframework.beans.BeanUtils; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; -import org.springframework.http.server.observation.ServerRequestObservationContext; import org.springframework.web.context.ServletContextAware; import org.springframework.web.context.request.async.AsyncRequestTimeoutException; import org.springframework.web.filter.ServerHttpObservationFilter; @@ -163,15 +162,12 @@ private static void recordServerError(HttpServletRequest request, Exception ex) } /** - * A forward to an error handler copies its model to the request and routes the request again. That leaves a wrapper - * in {@link WebUtils#ERROR_EXCEPTION_ATTRIBUTE}, and the handler's route in place of the one that failed, so every - * failure a handler answers would be reported as the same route. The attribute keeps the exception itself for - * whatever reads it once the chain has returned, which includes the filter that observes the request. + * A forward to an error handler copies its model to the request, which leaves a wrapper in + * {@link WebUtils#ERROR_EXCEPTION_ATTRIBUTE}. The attribute keeps the exception itself for whatever reads it once the + * chain has returned, which includes the filter that observes the request. */ - private static void keepFailureObserved(HttpServletRequest request, Exception ex, String failedRoute) { + private static void keepFailureOnRequest(HttpServletRequest request, Exception ex) { request.setAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE, ex); - ServerHttpObservationFilter.findObservationContext(request) - .ifPresent(context -> context.setPathPattern(failedRoute)); } public String getRequestLogMessage(Throwable e, HttpServletRequest request) { @@ -298,14 +294,12 @@ else if (mapsToController) { ((GrailsResponseMutator) response).deactivateResponseMutator(); } request.setAttribute(ERROR_HANDLER_FORWARD_IN_PROGRESS_ATTRIBUTE, Boolean.TRUE); - String failedRoute = ServerHttpObservationFilter.findObservationContext(request) - .map(ServerRequestObservationContext::getPathPattern).orElse(null); try { forwardRequest(info, request, response, mv, uri); } finally { request.removeAttribute(ERROR_HANDLER_FORWARD_IN_PROGRESS_ATTRIBUTE); - keepFailureObserved(request, ex, failedRoute); + keepFailureOnRequest(request, ex); } // return an empty ModelAndView since the error handler has been processed return new ModelAndView(); diff --git a/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMapping.groovy b/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMapping.groovy index cc0b7e5e45b..4db8a8844a5 100644 --- a/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMapping.groovy +++ b/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMapping.groovy @@ -227,13 +227,17 @@ class UrlMappingsHandlerMapping extends AbstractHandlerMapping { * Sets the HTTP server observation's route from the matched controller/action, so the * {@code http.server.requests} {@code uri} tag is a low-cardinality route (e.g. {@code /book/show}) * instead of {@code UNKNOWN}. Runs at {@code preHandle}: at URL-mapping match the observation - * context is not yet on the request. + * context is not yet on the request. A request routed to an error handler keeps the route that failed, so + * that the failures an error handler answers are not all reported as its own route. */ @CompileStatic static class ObservationRouteHandler implements HandlerInterceptor { @Override boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { + if (request.getAttribute(WebUtils.ERROR_STATUS_CODE_ATTRIBUTE) != null) { + return true + } try { String controllerName = null String actionName = null diff --git a/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMappingSpec.groovy b/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMappingSpec.groovy index bfd59de9999..f9f6bd3c52b 100644 --- a/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMappingSpec.groovy +++ b/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMappingSpec.groovy @@ -27,11 +27,13 @@ import grails.web.mapping.AbstractUrlMappingsSpec import org.grails.web.mapping.DefaultUrlMappingData import org.grails.web.mapping.DefaultUrlMappingInfo import org.grails.web.util.WebUtils +import org.springframework.http.server.observation.ServerRequestObservationContext import org.springframework.ui.ModelMap import org.springframework.web.context.request.RequestContextHolder import org.springframework.web.context.request.WebRequest import org.springframework.web.context.request.WebRequestInterceptor import org.springframework.web.context.support.StaticWebApplicationContext +import org.springframework.web.filter.ServerHttpObservationFilter import org.springframework.web.servlet.HandlerInterceptor import org.springframework.web.servlet.handler.WebRequestHandlerInterceptorAdapter import org.springframework.web.servlet.view.InternalResourceView @@ -320,6 +322,39 @@ class UrlMappingsHandlerMappingSpec extends AbstractUrlMappingsSpec { new UrlMappingsHandlerMapping(holder) } + void "a request routed to an error handler keeps the route that failed on its observation"() { + given: + def grailsApplication = new DefaultGrailsApplication(FooController) + grailsApplication.initialise() + def holder = new GrailsControllerUrlMappings(grailsApplication, getUrlMappingsHolder { + "/foo/bar"(controller: 'foo', action: 'bar') + "500"(controller: 'foo', action: 'fooBar') + }) + def handler = new UrlMappingsHandlerMapping(holder) + def webRequest = GrailsWebMockUtil.bindMockWebRequest() + def request = webRequest.request + request.requestURI = '/foo/bar' + def context = new ServerRequestObservationContext(request, webRequest.response) + request.setAttribute(ServerHttpObservationFilter.CURRENT_OBSERVATION_CONTEXT_ATTRIBUTE, context) + + when: 'the action is routed' + def chain = handler.getHandler(request) + chain.interceptorList.each { it.preHandle(request, webRequest.response, chain.handler) } + + then: + context.pathPattern == '/foo/bar' + + when: 'it failed, and its error handler is routed, as a forward to it is' + request.setAttribute(WebUtils.ERROR_STATUS_CODE_ATTRIBUTE, 500) + chain = handler.getHandler(request) + chain.handler.configure(webRequest) + chain.interceptorList.each { it.preHandle(request, webRequest.response, chain.handler) } + + then: 'the error handler answers, and the route is still the one that failed' + webRequest.actionName == 'fooBar' + context.pathPattern == '/foo/bar' + } + void cleanup() { RequestContextHolder.resetRequestAttributes() } From bb6a5fee11e4d46fab7f47bc65d0276dedabe189 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Sat, 7 Nov 2026 07:42:20 -0800 Subject: [PATCH 48/78] Link the Spring Framework issue that asks for a public way to get the observation --- .../groovy/org/grails/web/errors/GrailsExceptionResolver.java | 3 ++- .../web/mapping/mvc/ActionExceptionHandlerResolver.groovy | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/grails-web-mvc/src/main/groovy/org/grails/web/errors/GrailsExceptionResolver.java b/grails-web-mvc/src/main/groovy/org/grails/web/errors/GrailsExceptionResolver.java index b830acb6cfa..b5291c53666 100644 --- a/grails-web-mvc/src/main/groovy/org/grails/web/errors/GrailsExceptionResolver.java +++ b/grails-web-mvc/src/main/groovy/org/grails/web/errors/GrailsExceptionResolver.java @@ -86,7 +86,8 @@ public class GrailsExceptionResolver extends SimpleMappingExceptionResolver impl /** * Where {@link ServerHttpObservationFilter} keeps the observation of a request. The filter only offers its context, * which cannot tell the handlers of an error, and a registry cannot be relied on to find it, because a filter can be - * built with a registry the application does not know. + * built with a registry the application does not know. A public way to get it is requested in + * spring-framework#37658. */ private static final String SERVER_OBSERVATION_ATTRIBUTE = ServerHttpObservationFilter.class.getName() + ".observation"; 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 6cf082b4020..a050f405e50 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 @@ -82,7 +82,8 @@ class ActionExceptionHandlerResolver implements HandlerExceptionResolver, Ordere /** * Where {@link ServerHttpObservationFilter} keeps the observation of a request. The filter only offers its context, * which cannot tell the handlers of an error, and a registry cannot be relied on to find it, because a filter can be - * built with a registry the application does not know. + * built with a registry the application does not know. A public way to get it is requested in + * spring-framework#37658. */ private static final String SERVER_OBSERVATION_ATTRIBUTE = ServerHttpObservationFilter.name + '.observation' From 28dc2dd6e503fe8c171882770222993c1322d2e4 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Sat, 7 Nov 2026 08:52:30 -0800 Subject: [PATCH 49/78] Set the route on the observation before an interceptor can fail The handler that sets the route ran after every other interceptor of the chain, so a request that failed in one, such as in a Grails interceptor's before(), never got a route of its own, and its observation was reported as UNKNOWN. It now runs right after the WebRequestInterceptors, ahead of the interceptors that can fail. --- .../issue11102/FailingController.groovy | 4 +++ .../issue11102/FailingInterceptor.groovy | 31 +++++++++++++++++++ .../FailedActionObservationSpec.groovy | 13 ++++---- .../mvc/UrlMappingsHandlerMapping.groovy | 11 ++++--- .../mvc/UrlMappingsHandlerMappingSpec.groovy | 7 +++-- 5 files changed, 52 insertions(+), 14 deletions(-) create mode 100644 grails-test-examples/issue-11102/grails-app/controllers/issue11102/FailingInterceptor.groovy diff --git a/grails-test-examples/issue-11102/grails-app/controllers/issue11102/FailingController.groovy b/grails-test-examples/issue-11102/grails-app/controllers/issue11102/FailingController.groovy index a29e45cd945..3f5845048ac 100644 --- a/grails-test-examples/issue-11102/grails-app/controllers/issue11102/FailingController.groovy +++ b/grails-test-examples/issue-11102/grails-app/controllers/issue11102/FailingController.groovy @@ -48,6 +48,10 @@ class FailingController { throw new UnsupportedOperationException('answered by the error controller') } + def failsInInterceptor() { + render 'never reached, because the interceptor fails' + } + def errorHandler() { render status: 500, text: 'Answered by the error controller' } diff --git a/grails-test-examples/issue-11102/grails-app/controllers/issue11102/FailingInterceptor.groovy b/grails-test-examples/issue-11102/grails-app/controllers/issue11102/FailingInterceptor.groovy new file mode 100644 index 00000000000..49d0395770c --- /dev/null +++ b/grails-test-examples/issue-11102/grails-app/controllers/issue11102/FailingInterceptor.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 issue11102 + +class FailingInterceptor { + + FailingInterceptor() { + match(controller: 'failing', action: 'failsInInterceptor') + } + + boolean before() { + throw new UnsupportedOperationException('answered by the error controller') + } +} diff --git a/grails-test-examples/issue-11102/src/integration-test/groovy/issue11102/FailedActionObservationSpec.groovy b/grails-test-examples/issue-11102/src/integration-test/groovy/issue11102/FailedActionObservationSpec.groovy index bf2ef251dea..f19f951b048 100644 --- a/grails-test-examples/issue-11102/src/integration-test/groovy/issue11102/FailedActionObservationSpec.groovy +++ b/grails-test-examples/issue-11102/src/integration-test/groovy/issue11102/FailedActionObservationSpec.groovy @@ -74,12 +74,13 @@ class FailedActionObservationSpec extends Specification implements HttpClientSup } where: - handler | action | page | exception - 'the error view' | 'answeredByView' | 'An error has occurred' | 'IllegalStateException' - 'an error controller' | 'answeredByController' | 'Answered by the error controller' | 'UnsupportedOperationException' - 'the error view, asynchronously' | 'answeredByViewAsynchronously' | 'An error has occurred' | 'IllegalStateException' - 'an error controller, asynchronously' | 'answeredByControllerAsynchronously' | 'Answered by the error controller' | 'UnsupportedOperationException' - 'an error controller, after starting async' | 'answeredByControllerAfterStartingAsync' | 'Answered by the error controller' | 'UnsupportedOperationException' + handler | action | page | exception + 'the error view' | 'answeredByView' | 'An error has occurred' | 'IllegalStateException' + 'an error controller' | 'answeredByController' | 'Answered by the error controller' | 'UnsupportedOperationException' + 'the error view, asynchronously' | 'answeredByViewAsynchronously' | 'An error has occurred' | 'IllegalStateException' + 'an error controller, asynchronously' | 'answeredByControllerAsynchronously' | 'Answered by the error controller' | 'UnsupportedOperationException' + 'an error controller, after starting async' | 'answeredByControllerAfterStartingAsync' | 'Answered by the error controller' | 'UnsupportedOperationException' + 'an error controller, after an interceptor failed' | 'failsInInterceptor' | 'Answered by the error controller' | 'UnsupportedOperationException' } private List errorTags(String route) { diff --git a/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMapping.groovy b/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMapping.groovy index 4db8a8844a5..b458f3cbbf2 100644 --- a/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMapping.groovy +++ b/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMapping.groovy @@ -143,13 +143,14 @@ class UrlMappingsHandlerMapping extends AbstractHandlerMapping { HandlerExecutionChain chain = super.getHandlerExecutionChain(handler, request) // WebRequestInterceptors have to come first, as these include things like Hibernate OSIV. - if (webRequestHandlerInterceptors) { - for (int i = 0; i < webRequestHandlerInterceptors.length; i++) { - chain.addInterceptor(i, webRequestHandlerInterceptors[i]) - } + int webRequestInterceptorCount = webRequestHandlerInterceptors ? webRequestHandlerInterceptors.length : 0 + for (int i = 0; i < webRequestInterceptorCount; i++) { + chain.addInterceptor(i, webRequestHandlerInterceptors[i]) } - chain.addInterceptor(OBSERVATION_ROUTE_HANDLER) + // The route goes on the observation ahead of the interceptors that can fail, such as a Grails interceptor's + // before(), so that a failure in one is reported under the route that failed + chain.addInterceptor(webRequestInterceptorCount, OBSERVATION_ROUTE_HANDLER) chain.addInterceptor(ERROR_HANDLING_HANDLER) return chain } diff --git a/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMappingSpec.groovy b/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMappingSpec.groovy index f9f6bd3c52b..51855846bb2 100644 --- a/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMappingSpec.groovy +++ b/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMappingSpec.groovy @@ -267,7 +267,7 @@ class UrlMappingsHandlerMappingSpec extends AbstractUrlMappingsSpec { result.view.getUrl() == "/index.html" } - void "the handler chain keeps WebRequestInterceptors first and appends the Grails interceptors last"() { + void "the handler chain keeps WebRequestInterceptors first, then the route, and appends the error handling last"() { given: "a handler mapping with both a WebRequestInterceptor and an ordinary HandlerInterceptor" def handlerMapping = handlerMapping() def plainInterceptor = new HandlerInterceptor() {} @@ -289,8 +289,9 @@ class UrlMappingsHandlerMappingSpec extends AbstractUrlMappingsSpec { interceptors[0] instanceof WebRequestHandlerInterceptorAdapter interceptors.contains(plainInterceptor) - and: "the Grails interceptors are appended last, in order" - interceptors[-2].class.simpleName == 'ObservationRouteHandler' + and: "the route is set ahead of the ordinary interceptors, which can fail, and the error handling is last" + interceptors[1].class.simpleName == 'ObservationRouteHandler' + interceptors.indexOf(plainInterceptor) > 1 interceptors[-1].class.simpleName == 'ErrorHandlingHandler' } From adadd8f29903461eb41d7f392b1c8243f6815019 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Sun, 8 Nov 2026 09:50:03 -0800 Subject: [PATCH 50/78] Read only Spring Boot's own Hibernate entry while configuring the Hibernate 7 BOM Configuring grails-hibernate7-bom walked every BOM spring-boot-dependencies imports to find the Hibernate ORM version, so any task that needed none of them failed on a configuration-cache miss when one was missing from the cache: an offline `help` failed on jooq-bom. spring-boot-dependencies manages hibernate-core in its own POM, and a BOM's own entry wins over the ones it imports, so configuring the project now reads that one entry (PomVersions.managedVersion) and nothing else. The two consistency checks, an override newer than Spring Boot's version and hibernate-models matching what that Hibernate ORM release depends on, move into validateHibernateVersion, which check and the BOM's POM generation run. They resolve in its inputs, so only a build that runs it resolves anything more. A parent BOM that does not manage hibernate-core now builds at hibernate7VersionOverride, as the error message says to do, instead of failing before the override is read. --- .agents/skills/gradle-developer/SKILL.md | 2 +- .../apache/grails/buildsrc/PomVersions.groovy | 27 +++++ .../grails/buildsrc/PomVersionsSpec.groovy | 111 ++++++++++++++++++ dependencies.gradle | 11 +- grails-bom/hibernate7/build.gradle | 65 ++++++---- 5 files changed, 189 insertions(+), 27 deletions(-) create mode 100644 build-logic/plugins/src/test/groovy/org/apache/grails/buildsrc/PomVersionsSpec.groovy diff --git a/.agents/skills/gradle-developer/SKILL.md b/.agents/skills/gradle-developer/SKILL.md index 6748a85a995..204b7d6c1eb 100644 --- a/.agents/skills/gradle-developer/SKILL.md +++ b/.agents/skills/gradle-developer/SKILL.md @@ -366,7 +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. +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`; `validateHibernateVersion` fails while it is not newer than Spring Boot's version, so a Boot bump that catches up forces its removal. It also fails when `hibernate-models.version` differs from the version the managed Hibernate ORM release depends on. Configuring the project reads only `spring-boot-dependencies`' own entry for `hibernate-core` (`PomVersions.managedVersion`), never the BOMs it imports, so a task that resolves none of them does not fail when one is missing from the cache; both checks resolve in the task's inputs, and `check` and the BOM's POM generation run it. ### Exclusions diff --git a/build-logic/plugins/src/main/groovy/org/apache/grails/buildsrc/PomVersions.groovy b/build-logic/plugins/src/main/groovy/org/apache/grails/buildsrc/PomVersions.groovy index db065940092..5a3f1b6c896 100644 --- a/build-logic/plugins/src/main/groovy/org/apache/grails/buildsrc/PomVersions.groovy +++ b/build-logic/plugins/src/main/groovy/org/apache/grails/buildsrc/PomVersions.groovy @@ -24,6 +24,8 @@ import java.util.regex.Pattern import groovy.transform.CompileStatic +import org.gradle.api.GradleException + import org.apache.maven.model.Dependency import org.apache.maven.model.Model import org.apache.maven.model.io.xpp3.MavenXpp3Reader @@ -68,6 +70,31 @@ class PomVersions { dependency.scope == 'import' } + /** + * Returns the version the model's own {@code } gives {@code module}, a + * {@code group:artifact}, or {@code null} when it has no entry for it. The BOMs it imports are not + * read, so this resolves no other POM, and since a BOM's own entry wins over the ones it imports, + * a version found here is the one the BOM manages. + * + * @throws GradleException when the entry's version cannot be resolved from the model's own + * properties and the Maven built-ins + */ + static String managedVersion(Model model, String module) { + Map properties = properties(model) + Dependency entry = managedDependencies(model).find { Dependency dependency -> + !isImport(dependency) && key(dependency, properties) == module + } + if (entry == null) { + return null + } + String version = interpolate(entry.version, properties) + if (!version) { + throw new GradleException("Cannot resolve ${module}:${entry.version.trim()}, managed by " + + "${properties['project.groupId']}:${model.artifactId}:${properties['project.version']}, from that POM's own properties.") + } + version + } + /** * The properties the model's coordinates and versions may refer to: its own * {@code }, and the Maven built-ins, which are never declared there. A parent POM's diff --git a/build-logic/plugins/src/test/groovy/org/apache/grails/buildsrc/PomVersionsSpec.groovy b/build-logic/plugins/src/test/groovy/org/apache/grails/buildsrc/PomVersionsSpec.groovy new file mode 100644 index 00000000000..8e090bab914 --- /dev/null +++ b/build-logic/plugins/src/test/groovy/org/apache/grails/buildsrc/PomVersionsSpec.groovy @@ -0,0 +1,111 @@ +/* + * 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.apache.grails.buildsrc + +import java.nio.file.Path + +import org.gradle.api.GradleException +import spock.lang.Specification +import spock.lang.TempDir + +import org.apache.maven.model.Model + +/** + * Reads the version a BOM's own entries give a module, as {@code grails-hibernate7-bom} reads the + * Hibernate ORM version from {@code spring-boot-dependencies}: + * + *
+ * test:parent-bom:1.0, with test:grand-parent:1.0 as its parent
+ *   test:lib-a                    ${lib-a.version} = 1.0
+ *   test:lib-literal              5.0
+ *   ${project.groupId}:lib-own    ${project.version}
+ *   test:lib-inherited            ${inherited.version} - declared only by the parent POM
+ *   test:family-bom               ${family-bom.version} = 3.0, imported, and managing test:family-core
+ * 
+ */ +class PomVersionsSpec extends Specification { + + @TempDir + Path testDir + + Model bom + + def setup() { + File pom = testDir.resolve('parent-bom-1.0.pom').toFile() + pom.text = ''' + + 4.0.0 + testgrand-parent1.0 + test + parent-bom + 1.0 + pom + + 1.0 + 3.0 + + + + testlib-a${lib-a.version} + testlib-literal5.0 + ${project.groupId}lib-own${project.version} + testlib-inherited${inherited.version} + + testfamily-bom${family-bom.version} + pomimport + + + + +''' + bom = PomVersions.read(pom) + } + + def "an entry's version is resolved from the BOM's own properties and the Maven built-ins"() { + expect: + PomVersions.managedVersion(bom, module) == version + + where: + module || version + 'test:lib-a' || '1.0' + 'test:lib-literal' || '5.0' + 'test:lib-own' || '1.0' + } + + def "a module the BOM has no entry for has no version"() { + expect: + PomVersions.managedVersion(bom, 'test:lib-unknown') == null + } + + def "the BOMs it imports are not read, so a module only an imported BOM manages has no version"() { + expect: 'test:family-core, which only test:family-bom manages, and the imported BOM itself' + PomVersions.managedVersion(bom, 'test:family-core') == null + PomVersions.managedVersion(bom, 'test:family-bom') == null + } + + def "an entry whose version only the parent POM declares fails instead of going unread"() { + when: + PomVersions.managedVersion(bom, 'test:lib-inherited') + + then: + GradleException e = thrown() + e.message == 'Cannot resolve test:lib-inherited:${inherited.version}, managed by test:parent-bom:1.0, from that POM\'s own properties.' + } +} diff --git a/dependencies.gradle b/dependencies.gradle index 40a827d0c79..121d8d97b5d 100644 --- a/dependencies.gradle +++ b/dependencies.gradle @@ -318,11 +318,12 @@ 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. + // from that POM's own entries 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. + // It must be newer than the version Spring Boot manages, so validateHibernateVersion, which + // check and the BOM's POM generation run, fails once Spring Boot catches up with it: remove it then. hibernate7VersionOverride = null customBomVersions = [ 'cache-ri-impl.version' : '1.1.1', @@ -330,8 +331,8 @@ ext { // 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. grails-hibernate7-bom fails the build when it - // differs from the version the managed Hibernate ORM release depends on. + // platform() import is not enforced. validateHibernateVersion fails 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', 'jandex.version' : '3.6.0', diff --git a/grails-bom/hibernate7/build.gradle b/grails-bom/hibernate7/build.gradle index c6a8be10a78..f55eadd9b73 100644 --- a/grails-bom/hibernate7/build.gradle +++ b/grails-bom/hibernate7/build.gradle @@ -17,7 +17,6 @@ * 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 @@ -62,35 +61,59 @@ def pomFile = { String coordinates -> } // 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: " + +// hibernate7VersionOverride to a newer release. Configuring this project reads only the parent BOMs' own +// entries, not the BOMs they import, so a task that needs none of them does not fail when one is missing +// from the cache; validateHibernateVersion checks the rest +String springBootHibernateVersion = parentBoms.findResult { String parentBom -> + PomVersions.managedVersion(PomVersions.read(pomFile(parentBom)), 'org.hibernate.orm:hibernate-core') +} +String overrideHibernateVersion = hibernate7VersionOverride ?: '' +String hibernateVersion = overrideHibernateVersion ?: springBootHibernateVersion +if (!hibernateVersion) { + throw new GradleException("${parentBoms.join(', ')} does not manage org.hibernate.orm:hibernate-core in its own POM: " + '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 + +// Gradle's conflict resolution selects the newer of two requested versions, by its own version ordering +Provider newerHibernateVersion = provider { + if (!overrideHibernateVersion || !springBootHibernateVersion) { + return '' + } Configuration bothVersions = configurations.detachedConfiguration( - dependencies.create("org.hibernate.orm:hibernate-core:${hibernate7VersionOverride}"), + dependencies.create("org.hibernate.orm:hibernate-core:${overrideHibernateVersion}"), dependencies.create("org.hibernate.orm:hibernate-core:${springBootHibernateVersion}")) bothVersions.transitive = false - String newer = bothVersions.incoming.resolutionResult.allComponents + 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}") +Provider ormHibernateModels = provider { + PomVersions.read(pomFile("org.hibernate.orm:hibernate-core:${hibernateVersion}")).dependencies + .find { it.groupId == 'org.hibernate.models' && it.artifactId == 'hibernate-models' }?.version ?: '' +} +String managedHibernateModels = customBomVersions['hibernate-models.version'] +String bootHibernateVersion = springBootHibernateVersion ?: '' +def validateHibernateVersion = tasks.register('validateHibernateVersion') { Task task -> + task.group = 'verification' + task.description = 'Validates that hibernate7VersionOverride is newer than the Hibernate ORM version Spring Boot manages, ' + + 'and that hibernate-models.version is the version the managed Hibernate ORM release depends on.' + task.inputs.property('newerHibernateVersion', newerHibernateVersion) + task.inputs.property('ormHibernateModels', ormHibernateModels) + task.doLast { + if (overrideHibernateVersion && bootHibernateVersion && + (overrideHibernateVersion == bootHibernateVersion || newerHibernateVersion.get() != overrideHibernateVersion)) { + throw new GradleException("hibernate7VersionOverride ${overrideHibernateVersion} is not newer than the " + + "Hibernate ORM ${bootHibernateVersion} that spring-boot-dependencies manages: remove it from dependencies.gradle") + } + String ormModels = ormHibernateModels.get() + if (ormModels && ormModels != managedHibernateModels) { + throw new GradleException("Hibernate ORM ${hibernateVersion} depends on hibernate-models ${ormModels}, " + + "but dependencies.gradle manages ${managedHibernateModels}: set hibernate-models.version to ${ormModels}") + } + } } +tasks.named('check') { Task task -> task.dependsOn(validateHibernateVersion) } +tasks.withType(GenerateMavenPom).configureEach { GenerateMavenPom task -> task.dependsOn(validateHibernateVersion) } customBomVersions['hibernate.version'] = hibernateVersion combinedVersions['hibernate.version'] = hibernateVersion From 09cc09df954f782cd6f047cce236e16c6d509771 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Sun, 8 Nov 2026 11:46:25 -0800 Subject: [PATCH 51/78] Stop saying an async timeout is recorded on the observation The request's observation is stopped by the filter's async listener when the request times out, before the timeout is resolved, and in a running application Spring's own resolver answers the 503 before Grails' resolver sees it. The upgrade guide said the timeout was recorded like an action's exception, and a unit row backed that by resolving a timeout inside an observation that was still open, which a real request never does. --- grails-doc/src/en/guide/upgrading/upgrading90x.adoc | 2 +- .../org/grails/web/errors/GrailsExceptionResolverSpec.groovy | 2 -- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/grails-doc/src/en/guide/upgrading/upgrading90x.adoc b/grails-doc/src/en/guide/upgrading/upgrading90x.adoc index dc1d51ae50e..d2329c002bf 100644 --- a/grails-doc/src/en/guide/upgrading/upgrading90x.adoc +++ b/grails-doc/src/en/guide/upgrading/upgrading90x.adoc @@ -117,7 +117,7 @@ The builder no longer pins the version of the run image, so set both `builder` a * *An exception an action throws is now recorded as an error on the HTTP server observation.* When an error view answered, as the `"500"(view: '/error')` mapping of a generated application does, `http.server.requests` tagged the 500 with `error` and `exception` values of `none`, and tracing did not see a failure. A `500` mapping to a controller tagged it with `GrailsWrappedRuntimeException` and with the `uri` of that controller, so every failure it answered looked like the same route. -Both now report the exception the action threw and the route of the action, and the span of the request is marked as failed. An async timeout, which answers with a 503, is recorded in the same way. +Both now report the exception the action threw and the route of the action, and the span of the request is marked as failed. These requests were already counted with `outcome=SERVER_ERROR`, but an alert that counts a non-`none` `error` value will see more server errors than before, and a dashboard that reads the `uri` of an error controller will find those failures under the routes of the actions. After a forward to an error controller, the `jakarta.servlet.error.exception` request attribute holds the exception the action threw rather than a `GrailsWrappedRuntimeException`, for a filter that reads it once the chain has returned. Inside the error controller it still holds the wrapper. A client error is not recorded. diff --git a/grails-web-mvc/src/test/groovy/org/grails/web/errors/GrailsExceptionResolverSpec.groovy b/grails-web-mvc/src/test/groovy/org/grails/web/errors/GrailsExceptionResolverSpec.groovy index 3d8f04e1037..858c3c39637 100644 --- a/grails-web-mvc/src/test/groovy/org/grails/web/errors/GrailsExceptionResolverSpec.groovy +++ b/grails-web-mvc/src/test/groovy/org/grails/web/errors/GrailsExceptionResolverSpec.groovy @@ -73,7 +73,6 @@ class GrailsExceptionResolverSpec extends Specification { private static final String PLAIN = 'plain attributes' private static final String NOTHING = 'nothing' private static final Exception FAILURE = new IllegalStateException('failed') - private static final Exception ASYNC_TIMEOUT = new AsyncRequestTimeoutException() private final MockServletContext servletContext = new MockServletContext() private StaticWebApplicationContext webContext @@ -110,7 +109,6 @@ class GrailsExceptionResolverSpec extends Specification { description | thrown | recorded | status 'an action threw' | FAILURE | FAILURE | 500 'wrapped by Groovy' | new InvokerInvocationException(new InvocationTargetException(FAILURE)) | FAILURE | 500 - 'of an async timeout' | ASYNC_TIMEOUT | ASYNC_TIMEOUT | 503 } void 'an exception is still the error of a context that comes without its observation'() { From 06fe2a84c55a2cd7b0435e8e25079a5ff5afd5eb Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Sun, 8 Nov 2026 11:51:08 -0800 Subject: [PATCH 52/78] Record a failure once on Undertow when the forward stays on the request Undertow leaves a request that was forwarded reading as a forward once the forward has returned. The filter that observes the request then takes an asynchronous dispatch for a plain one and records the exception left on the request, which the resolver had already recorded because the request reads as asynchronous, so the handlers heard twice of an asynchronous action's failure that an error controller answered. The resolver now also leaves the exception to the filter when its own forward has left the request reading as a forward. The Jetty and Undertow test applications now run the failed-action observation spec too. An action that starts asynchronous processing and then fails is recorded once on each container, by a different path: Tomcat reports the exception left on the request to the filter's listener, Jetty's request already reads as asynchronous so the resolver records it, and on Undertow the filter does. --- .../issue12688/FailingController.groovy | 62 +++++++++++ .../controllers/issue12688/UrlMappings.groovy | 3 + .../JettyFailedActionObservationSpec.groovy | 101 ++++++++++++++++++ .../undertowapp/FailingController.groovy | 62 +++++++++++ .../undertowapp/UrlMappings.groovy | 3 + ...UndertowFailedActionObservationSpec.groovy | 101 ++++++++++++++++++ .../web/errors/GrailsExceptionResolver.java | 34 ++++-- .../errors/GrailsExceptionResolverSpec.groovy | 54 ++++++++++ 8 files changed, 414 insertions(+), 6 deletions(-) create mode 100644 grails-test-examples/jetty/grails-app/controllers/issue12688/FailingController.groovy create mode 100644 grails-test-examples/jetty/src/integration-test/groovy/issue12688/JettyFailedActionObservationSpec.groovy create mode 100644 grails-test-examples/undertow/grails-app/controllers/undertowapp/FailingController.groovy create mode 100644 grails-test-examples/undertow/src/integration-test/groovy/undertowapp/UndertowFailedActionObservationSpec.groovy diff --git a/grails-test-examples/jetty/grails-app/controllers/issue12688/FailingController.groovy b/grails-test-examples/jetty/grails-app/controllers/issue12688/FailingController.groovy new file mode 100644 index 00000000000..0fd6e5ad978 --- /dev/null +++ b/grails-test-examples/jetty/grails-app/controllers/issue12688/FailingController.groovy @@ -0,0 +1,62 @@ +/* + * 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 issue12688 + +import org.springframework.web.context.request.async.DeferredResult +import org.springframework.web.context.request.async.WebAsyncManager +import org.springframework.web.context.request.async.WebAsyncUtils + +class FailingController { + + def answeredByView() { + throw new IllegalStateException('answered by the error view') + } + + def answeredByController() { + throw new UnsupportedOperationException('answered by the error controller') + } + + def answeredByViewAsynchronously() { + failAsynchronously(new IllegalStateException('answered by the error view')) + } + + def answeredByControllerAsynchronously() { + failAsynchronously(new UnsupportedOperationException('answered by the error controller')) + } + + def answeredByControllerAfterStartingAsync() { + WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request) + asyncManager.asyncWebRequest = WebAsyncUtils.createAsyncWebRequest(request, response) + // nothing completes the processing this starts, so Jetty ends the request when it times out + asyncManager.startDeferredResultProcessing(new DeferredResult(500L)) + throw new UnsupportedOperationException('answered by the error controller') + } + + def errorHandler() { + render status: 500, text: 'Answered by the error controller' + } + + private void failAsynchronously(Exception failure) { + WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request) + asyncManager.asyncWebRequest = WebAsyncUtils.createAsyncWebRequest(request, response) + DeferredResult result = new DeferredResult<>() + asyncManager.startDeferredResultProcessing(result) + result.errorResult = failure + } +} diff --git a/grails-test-examples/jetty/grails-app/controllers/issue12688/UrlMappings.groovy b/grails-test-examples/jetty/grails-app/controllers/issue12688/UrlMappings.groovy index f8aa7f9d126..75786d0e28e 100644 --- a/grails-test-examples/jetty/grails-app/controllers/issue12688/UrlMappings.groovy +++ b/grails-test-examples/jetty/grails-app/controllers/issue12688/UrlMappings.groovy @@ -27,7 +27,10 @@ class UrlMappings { } "/"(view: "/index") + "/failing/$action"(controller: 'failing') + "500"(view: '/error') + "500"(controller: 'failing', action: 'errorHandler', exception: UnsupportedOperationException) "413"(controller: 'upload', action: 'tooLarge') "404"(view: '/notFound') } diff --git a/grails-test-examples/jetty/src/integration-test/groovy/issue12688/JettyFailedActionObservationSpec.groovy b/grails-test-examples/jetty/src/integration-test/groovy/issue12688/JettyFailedActionObservationSpec.groovy new file mode 100644 index 00000000000..ae8bda64691 --- /dev/null +++ b/grails-test-examples/jetty/src/integration-test/groovy/issue12688/JettyFailedActionObservationSpec.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 issue12688 + +import java.util.concurrent.ConcurrentHashMap +import java.util.concurrent.CopyOnWriteArrayList +import java.util.concurrent.atomic.AtomicBoolean + +import io.micrometer.core.instrument.MeterRegistry +import io.micrometer.observation.Observation +import io.micrometer.observation.ObservationHandler +import io.micrometer.observation.ObservationRegistry +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.http.server.observation.ServerRequestObservationContext +import spock.lang.Specification +import spock.lang.Tag +import spock.util.concurrent.PollingConditions + +import grails.testing.mixin.integration.Integration +import org.apache.grails.testing.http.client.HttpClientSupport + +/** + * The failure of an action reaches the observation of its request once, however the container ends the request. On + * Jetty, a request whose action started asynchronous processing before it failed is not reported to the listener the + * filter leaves the observation to, as Tomcat reports it, so the exception resolver records it. + */ +@Integration +@Tag('http-client') +class JettyFailedActionObservationSpec extends Specification implements HttpClientSupport { + + private static final AtomicBoolean LISTENING = new AtomicBoolean() + private static final Map> NOTIFIED = new ConcurrentHashMap<>() + + @Autowired + MeterRegistry meterRegistry + + @Autowired + ObservationRegistry observationRegistry + + void setup() { + if (LISTENING.compareAndSet(false, true)) { + observationRegistry.observationConfig().observationHandler(new ErrorListener()) + } + } + + void 'a failed action answered by #handler is reported once with its own exception and route'() { + when: + def response = http("/failing/$action") + + then: + response.assertContains(500, page) + + and: 'its metrics say what failed and where, and the handlers that mark a span hear of it once' + new PollingConditions(timeout: 5).eventually { + assert errorTags("/failing/$action") == [exception] + assert NOTIFIED["/failing/$action".toString()] == [exception] + } + + where: + handler | action | page | exception + 'the error view' | 'answeredByView' | 'An error has occurred' | 'IllegalStateException' + 'an error controller' | 'answeredByController' | 'Answered by the error controller' | 'UnsupportedOperationException' + 'the error view, asynchronously' | 'answeredByViewAsynchronously' | 'An error has occurred' | 'IllegalStateException' + 'an error controller, asynchronously' | 'answeredByControllerAsynchronously' | 'Answered by the error controller' | 'UnsupportedOperationException' + 'an error controller, after starting async' | 'answeredByControllerAfterStartingAsync' | 'Answered by the error controller' | 'UnsupportedOperationException' + } + + private List errorTags(String route) { + meterRegistry.find('http.server.requests').tag('status', '500').tag('uri', route).timers()*.id*.getTag('error') + } + + private static class ErrorListener implements ObservationHandler { + + @Override + boolean supportsContext(Observation.Context context) { + context instanceof ServerRequestObservationContext + } + + @Override + void onError(Observation.Context context) { + def route = ((ServerRequestObservationContext) context).pathPattern + NOTIFIED.computeIfAbsent(route) { new CopyOnWriteArrayList<>() } << context.error.class.simpleName + } + } +} diff --git a/grails-test-examples/undertow/grails-app/controllers/undertowapp/FailingController.groovy b/grails-test-examples/undertow/grails-app/controllers/undertowapp/FailingController.groovy new file mode 100644 index 00000000000..befd28b8ec9 --- /dev/null +++ b/grails-test-examples/undertow/grails-app/controllers/undertowapp/FailingController.groovy @@ -0,0 +1,62 @@ +/* + * 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 undertowapp + +import org.springframework.web.context.request.async.DeferredResult +import org.springframework.web.context.request.async.WebAsyncManager +import org.springframework.web.context.request.async.WebAsyncUtils + +class FailingController { + + def answeredByView() { + throw new IllegalStateException('answered by the error view') + } + + def answeredByController() { + throw new UnsupportedOperationException('answered by the error controller') + } + + def answeredByViewAsynchronously() { + failAsynchronously(new IllegalStateException('answered by the error view')) + } + + def answeredByControllerAsynchronously() { + failAsynchronously(new UnsupportedOperationException('answered by the error controller')) + } + + def answeredByControllerAfterStartingAsync() { + WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request) + asyncManager.asyncWebRequest = WebAsyncUtils.createAsyncWebRequest(request, response) + // nothing completes the processing this starts, so Undertow ends the request when it times out + asyncManager.startDeferredResultProcessing(new DeferredResult(500L)) + throw new UnsupportedOperationException('answered by the error controller') + } + + def errorHandler() { + render status: 500, text: 'Answered by the error controller' + } + + private void failAsynchronously(Exception failure) { + WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request) + asyncManager.asyncWebRequest = WebAsyncUtils.createAsyncWebRequest(request, response) + DeferredResult result = new DeferredResult<>() + asyncManager.startDeferredResultProcessing(result) + result.errorResult = failure + } +} diff --git a/grails-test-examples/undertow/grails-app/controllers/undertowapp/UrlMappings.groovy b/grails-test-examples/undertow/grails-app/controllers/undertowapp/UrlMappings.groovy index 9b2377aea33..519db0d9776 100644 --- a/grails-test-examples/undertow/grails-app/controllers/undertowapp/UrlMappings.groovy +++ b/grails-test-examples/undertow/grails-app/controllers/undertowapp/UrlMappings.groovy @@ -28,7 +28,10 @@ class UrlMappings { } "/"(view: "/index") + "/failing/$action"(controller: 'failing') + "500"(view: '/error') + "500"(controller: 'failing', action: 'errorHandler', exception: UnsupportedOperationException) "500"(controller: 'errorPage', action: 'handle', exception: StaticInitFailure) "413"(controller: 'upload', action: 'tooLarge') "404"(view: '/notFound') diff --git a/grails-test-examples/undertow/src/integration-test/groovy/undertowapp/UndertowFailedActionObservationSpec.groovy b/grails-test-examples/undertow/src/integration-test/groovy/undertowapp/UndertowFailedActionObservationSpec.groovy new file mode 100644 index 00000000000..37377efa063 --- /dev/null +++ b/grails-test-examples/undertow/src/integration-test/groovy/undertowapp/UndertowFailedActionObservationSpec.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 undertowapp + +import java.util.concurrent.ConcurrentHashMap +import java.util.concurrent.CopyOnWriteArrayList +import java.util.concurrent.atomic.AtomicBoolean + +import io.micrometer.core.instrument.MeterRegistry +import io.micrometer.observation.Observation +import io.micrometer.observation.ObservationHandler +import io.micrometer.observation.ObservationRegistry +import org.springframework.beans.factory.annotation.Autowired +import org.springframework.http.server.observation.ServerRequestObservationContext +import spock.lang.Specification +import spock.lang.Tag +import spock.util.concurrent.PollingConditions + +import grails.testing.mixin.integration.Integration +import org.apache.grails.testing.http.client.HttpClientSupport + +/** + * The failure of an action reaches the observation of its request once, however the container ends the request. + * Undertow leaves a request that was forwarded to an error handler reading as a forward, so the filter that observes + * it records the exception left on it even on an asynchronous dispatch, and the exception resolver must not. + */ +@Integration +@Tag('http-client') +class UndertowFailedActionObservationSpec extends Specification implements HttpClientSupport { + + private static final AtomicBoolean LISTENING = new AtomicBoolean() + private static final Map> NOTIFIED = new ConcurrentHashMap<>() + + @Autowired + MeterRegistry meterRegistry + + @Autowired + ObservationRegistry observationRegistry + + void setup() { + if (LISTENING.compareAndSet(false, true)) { + observationRegistry.observationConfig().observationHandler(new ErrorListener()) + } + } + + void 'a failed action answered by #handler is reported once with its own exception and route'() { + when: + def response = http("/failing/$action") + + then: + response.assertContains(500, page) + + and: 'its metrics say what failed and where, and the handlers that mark a span hear of it once' + new PollingConditions(timeout: 5).eventually { + assert errorTags("/failing/$action") == [exception] + assert NOTIFIED["/failing/$action".toString()] == [exception] + } + + where: + handler | action | page | exception + 'the error view' | 'answeredByView' | 'An error has occurred' | 'IllegalStateException' + 'an error controller' | 'answeredByController' | 'Answered by the error controller' | 'UnsupportedOperationException' + 'the error view, asynchronously' | 'answeredByViewAsynchronously' | 'An error has occurred' | 'IllegalStateException' + 'an error controller, asynchronously' | 'answeredByControllerAsynchronously' | 'Answered by the error controller' | 'UnsupportedOperationException' + 'an error controller, after starting async' | 'answeredByControllerAfterStartingAsync' | 'Answered by the error controller' | 'UnsupportedOperationException' + } + + private List errorTags(String route) { + meterRegistry.find('http.server.requests').tag('status', '500').tag('uri', route).timers()*.id*.getTag('error') + } + + private static class ErrorListener implements ObservationHandler { + + @Override + boolean supportsContext(Observation.Context context) { + context instanceof ServerRequestObservationContext + } + + @Override + void onError(Observation.Context context) { + def route = ((ServerRequestObservationContext) context).pathPattern + NOTIFIED.computeIfAbsent(route) { new CopyOnWriteArrayList<>() } << context.error.class.simpleName + } + } +} diff --git a/grails-web-mvc/src/main/groovy/org/grails/web/errors/GrailsExceptionResolver.java b/grails-web-mvc/src/main/groovy/org/grails/web/errors/GrailsExceptionResolver.java index b5291c53666..9edd061aa0b 100644 --- a/grails-web-mvc/src/main/groovy/org/grails/web/errors/GrailsExceptionResolver.java +++ b/grails-web-mvc/src/main/groovy/org/grails/web/errors/GrailsExceptionResolver.java @@ -29,6 +29,7 @@ import org.codehaus.groovy.control.CompilationFailedException; import org.codehaus.groovy.runtime.InvokerInvocationException; +import jakarta.servlet.DispatcherType; import jakarta.servlet.ServletContext; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; @@ -112,6 +113,7 @@ public ModelAndView resolveException(HttpServletRequest request, HttpServletResp Object handler, Exception ex) { // don't reuse cached controller attribute request.removeAttribute(GrailsApplicationAttributes.GRAILS_CONTROLLER_CLASS_AVAILABLE); + DispatcherType dispatchedAs = request.getDispatcherType(); ex = findWrappedException(ex); @@ -136,7 +138,7 @@ public ModelAndView resolveException(HttpServletRequest request, HttpServletResp mv = resolveViewOrForward(ex, urlMappings, request, response, mv); } - recordServerError(request, ex); + recordServerError(request, ex, dispatchedAs); return mv; } @@ -146,12 +148,13 @@ public ModelAndView resolveException(HttpServletRequest request, HttpServletResp * whose metrics would otherwise say there was no error and whose trace would not be marked as failed. Only * {@link Observation#error(Throwable)} tells the observation's handlers, one of which marks the span. *

- * An exception left in {@link WebUtils#ERROR_EXCEPTION_ATTRIBUTE} is not recorded here, because the filter that stops - * the observation records what it finds there. On an asynchronous dispatch the filter leaves stopping it to a listener - * that does not look. + * An exception left in {@link WebUtils#ERROR_EXCEPTION_ATTRIBUTE} is not recorded here when it is recorded from there + * once the dispatch returns, so that the handlers hear of it once. + * + * @param dispatchedAs how the request was dispatched before an error handler was forwarded to */ - private static void recordServerError(HttpServletRequest request, Exception ex) { - if (!WebUtils.isAsync(request) && request.getAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE) == ex) { + private static void recordServerError(HttpServletRequest request, Exception ex, DispatcherType dispatchedAs) { + if (request.getAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE) == ex && recordedFromRequest(request, dispatchedAs)) { return; } if (request.getAttribute(SERVER_OBSERVATION_ATTRIBUTE) instanceof Observation observation) { @@ -162,6 +165,25 @@ private static void recordServerError(HttpServletRequest request, Exception ex) } } + /** + * Whether the exception left in {@link WebUtils#ERROR_EXCEPTION_ATTRIBUTE} is recorded from there once the dispatch + * returns. + *

    + *
  • The filter that observes the request records it at the end of a plain dispatch. It does not look at the end of + * an asynchronous dispatch, which {@link WebUtils#isAsync} tells even inside a forward.
  • + *
  • A dispatch that has started asynchronous processing leaves stopping the observation to a listener of the filter. + * Tomcat reports the exception to that listener when the dispatch returns. Jetty does not, but the request already + * reads as asynchronous there, so the exception is recorded here.
  • + *
  • Undertow leaves a request that was forwarded reading as a forward, so the filter takes it for a plain dispatch + * and records the exception however the request was dispatched.
  • + *
+ */ + private static boolean recordedFromRequest(HttpServletRequest request, DispatcherType dispatchedAs) { + boolean forwardLeftOnRequest = dispatchedAs != DispatcherType.FORWARD && + request.getDispatcherType() == DispatcherType.FORWARD; + return forwardLeftOnRequest || !WebUtils.isAsync(request); + } + /** * A forward to an error handler copies its model to the request, which leaves a wrapper in * {@link WebUtils#ERROR_EXCEPTION_ATTRIBUTE}. The attribute keeps the exception itself for whatever reads it once the diff --git a/grails-web-mvc/src/test/groovy/org/grails/web/errors/GrailsExceptionResolverSpec.groovy b/grails-web-mvc/src/test/groovy/org/grails/web/errors/GrailsExceptionResolverSpec.groovy index 858c3c39637..c5fb999b972 100644 --- a/grails-web-mvc/src/test/groovy/org/grails/web/errors/GrailsExceptionResolverSpec.groovy +++ b/grails-web-mvc/src/test/groovy/org/grails/web/errors/GrailsExceptionResolverSpec.groovy @@ -46,6 +46,7 @@ import org.springframework.context.support.StaticApplicationContext import org.springframework.http.server.observation.ServerRequestObservationContext import org.springframework.mock.web.MockHttpServletRequest import org.springframework.mock.web.MockHttpServletResponse +import org.springframework.mock.web.MockRequestDispatcher import org.springframework.mock.web.MockServletContext import org.springframework.web.context.request.RequestContextHolder import org.springframework.web.context.request.ServletRequestAttributes @@ -63,6 +64,9 @@ import spock.lang.Specification import jakarta.servlet.DispatcherType import jakarta.servlet.FilterChain import jakarta.servlet.RequestDispatcher +import jakarta.servlet.ServletContext +import jakarta.servlet.ServletRequest +import jakarta.servlet.ServletResponse import jakarta.servlet.http.HttpServletRequest import jakarta.servlet.http.HttpServletResponse @@ -182,6 +186,36 @@ class GrailsExceptionResolverSpec extends Specification { 'in an action forwarded to' | DispatcherType.FORWARD } + void 'the handlers hear once of an exception an error handler answers on #dispatch, when the request still reads as a forward afterwards'() { + given: 'a container that leaves a forwarded request reading as a forward, as Undertow does, so the filter reads the exception left on it' + List notified = [] + def registry = registryReporting({ }, { notified << it }) + def resolver = resolverFor({ '500'(controller: 'errors', action: 'serverError') }, true) + def request = new ForwardLeftOnRequest(servletContext, 'GET', '/fail') + request.dispatcherType = dispatch + if (dispatch == DispatcherType.ASYNC) { + request.setAttribute(GrailsWebUtils.ASYNC_REQUEST_URI_ATTRIBUTE, '/fail') + } + def response = new MockHttpServletResponse() + bind(GRAILS, request, response) + def original = new IllegalStateException('original') + FilterChain application = { req, res -> + resolver.resolveException((HttpServletRequest) req, (HttpServletResponse) res, null, original) + } as FilterChain + + when: + new ServerHttpObservationFilter(registry).doFilter(request, response, application) + + then: + response.forwardedUrl == '/errors/serverError' + request.dispatcherType == DispatcherType.FORWARD + notified.size() == 1 + notified.first().is(original) + + where: + dispatch << [DispatcherType.REQUEST, DispatcherType.ASYNC] + } + void 'a filter can read the exception an error handler answered once the chain has returned, with no observation'() { given: def resolver = resolverFor({ '500'(controller: 'errors', action: 'serverError') }, true) @@ -847,6 +881,26 @@ class GrailsExceptionResolverSpec extends Specification { resolver } + /** A request that still reads as a forward once a forward has returned, as Undertow leaves it. */ + private static class ForwardLeftOnRequest extends MockHttpServletRequest { + + ForwardLeftOnRequest(ServletContext servletContext, String method, String requestURI) { + super(servletContext, method, requestURI) + } + + @Override + RequestDispatcher getRequestDispatcher(String path) { + MockHttpServletRequest forwarded = this + new MockRequestDispatcher(path) { + @Override + void forward(ServletRequest request, ServletResponse response) { + super.forward(request, response) + forwarded.dispatcherType = DispatcherType.FORWARD + } + } + } + } + private void bind(String attributes, MockHttpServletRequest request, MockHttpServletResponse response) { switch (attributes) { case GRAILS: From f9316cf6ee471c3905d1c285efffd9c0563e57e6 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Sun, 8 Nov 2026 19:21:17 -0800 Subject: [PATCH 53/78] Count what the observation handlers heard once the observation has stopped The failed-action specs passed as soon as one notification had arrived, so a second one arriving later went unnoticed, and they read the metrics before the meter handler, which Micrometer stops after the spec's own handler, had recorded them. Each request is now told apart by a header, and the spec waits until its observation has stopped on the route that failed and its timer is recorded before it counts the notifications. The specs on Tomcat, Jetty and Undertow also cover an action that starts asynchronous processing and then fails into the error view, and an action forwarded to that fails into the error view or an error controller. --- .../issue11102/FailingController.groovy | 33 +++++++++++--- .../FailedActionObservationSpec.groovy | 44 +++++++++++++------ .../issue12688/FailingController.groovy | 34 +++++++++++--- .../JettyFailedActionObservationSpec.groovy | 42 ++++++++++++------ .../undertowapp/FailingController.groovy | 34 +++++++++++--- ...UndertowFailedActionObservationSpec.groovy | 42 ++++++++++++------ 6 files changed, 172 insertions(+), 57 deletions(-) diff --git a/grails-test-examples/issue-11102/grails-app/controllers/issue11102/FailingController.groovy b/grails-test-examples/issue-11102/grails-app/controllers/issue11102/FailingController.groovy index 3f5845048ac..a9b351c0585 100644 --- a/grails-test-examples/issue-11102/grails-app/controllers/issue11102/FailingController.groovy +++ b/grails-test-examples/issue-11102/grails-app/controllers/issue11102/FailingController.groovy @@ -41,13 +41,24 @@ class FailingController { failAsynchronously(new UnsupportedOperationException('answered by the error controller')) } + def answeredByViewAfterStartingAsync() { + startAsyncThatTimesOut() + throw new IllegalStateException('answered by the error view') + } + def answeredByControllerAfterStartingAsync() { - WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request) - asyncManager.asyncWebRequest = WebAsyncUtils.createAsyncWebRequest(request, response) - asyncManager.startDeferredResultProcessing(new DeferredResult()) + startAsync(new DeferredResult()) throw new UnsupportedOperationException('answered by the error controller') } + def forwardedToView() { + forward(action: 'answeredByView') + } + + def forwardedToController() { + forward(action: 'answeredByController') + } + def failsInInterceptor() { render 'never reached, because the interceptor fails' } @@ -57,10 +68,22 @@ class FailingController { } private void failAsynchronously(Exception failure) { + DeferredResult result = new DeferredResult<>() + startAsync(result) + result.errorResult = failure + } + + /** + * Starts asynchronous processing that nothing completes. Unless the container ends it when the action fails, as + * Tomcat does when the exception is left on the request, it ends when it times out. + */ + private void startAsyncThatTimesOut() { + startAsync(new DeferredResult(500L)) + } + + private void startAsync(DeferredResult result) { WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request) asyncManager.asyncWebRequest = WebAsyncUtils.createAsyncWebRequest(request, response) - DeferredResult result = new DeferredResult<>() asyncManager.startDeferredResultProcessing(result) - result.errorResult = failure } } diff --git a/grails-test-examples/issue-11102/src/integration-test/groovy/issue11102/FailedActionObservationSpec.groovy b/grails-test-examples/issue-11102/src/integration-test/groovy/issue11102/FailedActionObservationSpec.groovy index f19f951b048..826ebf4a655 100644 --- a/grails-test-examples/issue-11102/src/integration-test/groovy/issue11102/FailedActionObservationSpec.groovy +++ b/grails-test-examples/issue-11102/src/integration-test/groovy/issue11102/FailedActionObservationSpec.groovy @@ -46,7 +46,9 @@ import org.apache.grails.testing.http.client.HttpClientSupport class FailedActionObservationSpec extends Specification implements HttpClientSupport { private static final AtomicBoolean LISTENING = new AtomicBoolean() + private static final String REQUEST_HEADER = 'X-Failing-Request' private static final Map> NOTIFIED = new ConcurrentHashMap<>() + private static final Map STOPPED_ON_ROUTE = new ConcurrentHashMap<>() @Autowired MeterRegistry meterRegistry @@ -60,27 +62,33 @@ class FailedActionObservationSpec extends Specification implements HttpClientSup } } - void 'a failed action answered by #handler is reported with its own exception and route'() { + void 'a failed action answered by #handler is reported once with its own exception and route'() { when: - def response = http("/failing/$action") + def response = http([(REQUEST_HEADER): path], path) then: 'the error page answered, so the exception did not reach the filter' response.assertContains(500, page) - and: 'its metrics say what failed and where, and the handlers that mark a span hear of it once' + and: 'the observation stopped on the route that failed, and its metrics say what failed' new PollingConditions(timeout: 5).eventually { - assert errorTags("/failing/$action") == [exception] - assert NOTIFIED["/failing/$action".toString()] == [exception] + assert STOPPED_ON_ROUTE[path] == route + assert errorTags(route) == [exception] } + and: 'the handlers that mark a span, all told of the failure before the observation stopped, heard of it once' + NOTIFIED[path] == [exception] + where: - handler | action | page | exception - 'the error view' | 'answeredByView' | 'An error has occurred' | 'IllegalStateException' - 'an error controller' | 'answeredByController' | 'Answered by the error controller' | 'UnsupportedOperationException' - 'the error view, asynchronously' | 'answeredByViewAsynchronously' | 'An error has occurred' | 'IllegalStateException' - 'an error controller, asynchronously' | 'answeredByControllerAsynchronously' | 'Answered by the error controller' | 'UnsupportedOperationException' - 'an error controller, after starting async' | 'answeredByControllerAfterStartingAsync' | 'Answered by the error controller' | 'UnsupportedOperationException' - 'an error controller, after an interceptor failed' | 'failsInInterceptor' | 'Answered by the error controller' | 'UnsupportedOperationException' + handler | path | route | page || exception + 'the error view' | '/failing/answeredByView' | '/failing/answeredByView' | 'An error has occurred' || 'IllegalStateException' + 'an error controller' | '/failing/answeredByController' | '/failing/answeredByController' | 'Answered by the error controller' || 'UnsupportedOperationException' + 'the error view, asynchronously' | '/failing/answeredByViewAsynchronously' | '/failing/answeredByViewAsynchronously' | 'An error has occurred' || 'IllegalStateException' + 'an error controller, asynchronously' | '/failing/answeredByControllerAsynchronously' | '/failing/answeredByControllerAsynchronously' | 'Answered by the error controller' || 'UnsupportedOperationException' + 'the error view, after starting async' | '/failing/answeredByViewAfterStartingAsync' | '/failing/answeredByViewAfterStartingAsync' | 'An error has occurred' || 'IllegalStateException' + 'an error controller, after starting async' | '/failing/answeredByControllerAfterStartingAsync' | '/failing/answeredByControllerAfterStartingAsync' | 'Answered by the error controller' || 'UnsupportedOperationException' + 'the error view, after a forward' | '/failing/forwardedToView' | '/failing/answeredByView' | 'An error has occurred' || 'IllegalStateException' + 'an error controller, after a forward' | '/failing/forwardedToController' | '/failing/answeredByController' | 'Answered by the error controller' || 'UnsupportedOperationException' + 'an error controller, after an interceptor failed' | '/failing/failsInInterceptor' | '/failing/failsInInterceptor' | 'Answered by the error controller' || 'UnsupportedOperationException' } private List errorTags(String route) { @@ -96,8 +104,16 @@ class FailedActionObservationSpec extends Specification implements HttpClientSup @Override void onError(Observation.Context context) { - def route = ((ServerRequestObservationContext) context).pathPattern - NOTIFIED.computeIfAbsent(route) { new CopyOnWriteArrayList<>() } << context.error.class.simpleName + NOTIFIED.computeIfAbsent(requestOf(context)) { new CopyOnWriteArrayList<>() } << context.error.class.simpleName + } + + @Override + void onStop(Observation.Context context) { + STOPPED_ON_ROUTE[requestOf(context)] = ((ServerRequestObservationContext) context).pathPattern ?: 'none' + } + + private static String requestOf(Observation.Context context) { + ((ServerRequestObservationContext) context).carrier.getHeader(REQUEST_HEADER) ?: 'none' } } } diff --git a/grails-test-examples/jetty/grails-app/controllers/issue12688/FailingController.groovy b/grails-test-examples/jetty/grails-app/controllers/issue12688/FailingController.groovy index 0fd6e5ad978..c1cc72b2bd2 100644 --- a/grails-test-examples/jetty/grails-app/controllers/issue12688/FailingController.groovy +++ b/grails-test-examples/jetty/grails-app/controllers/issue12688/FailingController.groovy @@ -40,23 +40,45 @@ class FailingController { failAsynchronously(new UnsupportedOperationException('answered by the error controller')) } + def answeredByViewAfterStartingAsync() { + startAsyncThatTimesOut() + throw new IllegalStateException('answered by the error view') + } + def answeredByControllerAfterStartingAsync() { - WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request) - asyncManager.asyncWebRequest = WebAsyncUtils.createAsyncWebRequest(request, response) - // nothing completes the processing this starts, so Jetty ends the request when it times out - asyncManager.startDeferredResultProcessing(new DeferredResult(500L)) + startAsyncThatTimesOut() throw new UnsupportedOperationException('answered by the error controller') } + def forwardedToView() { + forward(action: 'answeredByView') + } + + def forwardedToController() { + forward(action: 'answeredByController') + } + def errorHandler() { render status: 500, text: 'Answered by the error controller' } private void failAsynchronously(Exception failure) { + DeferredResult result = new DeferredResult<>() + startAsync(result) + result.errorResult = failure + } + + /** + * Starts asynchronous processing that nothing completes. Unless the container ends it when the action fails, as + * Tomcat does when the exception is left on the request, it ends when it times out. + */ + private void startAsyncThatTimesOut() { + startAsync(new DeferredResult(500L)) + } + + private void startAsync(DeferredResult result) { WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request) asyncManager.asyncWebRequest = WebAsyncUtils.createAsyncWebRequest(request, response) - DeferredResult result = new DeferredResult<>() asyncManager.startDeferredResultProcessing(result) - result.errorResult = failure } } diff --git a/grails-test-examples/jetty/src/integration-test/groovy/issue12688/JettyFailedActionObservationSpec.groovy b/grails-test-examples/jetty/src/integration-test/groovy/issue12688/JettyFailedActionObservationSpec.groovy index ae8bda64691..9949ccbcc08 100644 --- a/grails-test-examples/jetty/src/integration-test/groovy/issue12688/JettyFailedActionObservationSpec.groovy +++ b/grails-test-examples/jetty/src/integration-test/groovy/issue12688/JettyFailedActionObservationSpec.groovy @@ -45,7 +45,9 @@ import org.apache.grails.testing.http.client.HttpClientSupport class JettyFailedActionObservationSpec extends Specification implements HttpClientSupport { private static final AtomicBoolean LISTENING = new AtomicBoolean() + private static final String REQUEST_HEADER = 'X-Failing-Request' private static final Map> NOTIFIED = new ConcurrentHashMap<>() + private static final Map STOPPED_ON_ROUTE = new ConcurrentHashMap<>() @Autowired MeterRegistry meterRegistry @@ -61,24 +63,30 @@ class JettyFailedActionObservationSpec extends Specification implements HttpClie void 'a failed action answered by #handler is reported once with its own exception and route'() { when: - def response = http("/failing/$action") + def response = http([(REQUEST_HEADER): path], path) - then: + then: 'the error page answered, so the exception did not reach the filter' response.assertContains(500, page) - and: 'its metrics say what failed and where, and the handlers that mark a span hear of it once' + and: 'the observation stopped on the route that failed, and its metrics say what failed' new PollingConditions(timeout: 5).eventually { - assert errorTags("/failing/$action") == [exception] - assert NOTIFIED["/failing/$action".toString()] == [exception] + assert STOPPED_ON_ROUTE[path] == route + assert errorTags(route) == [exception] } + and: 'the handlers that mark a span, all told of the failure before the observation stopped, heard of it once' + NOTIFIED[path] == [exception] + where: - handler | action | page | exception - 'the error view' | 'answeredByView' | 'An error has occurred' | 'IllegalStateException' - 'an error controller' | 'answeredByController' | 'Answered by the error controller' | 'UnsupportedOperationException' - 'the error view, asynchronously' | 'answeredByViewAsynchronously' | 'An error has occurred' | 'IllegalStateException' - 'an error controller, asynchronously' | 'answeredByControllerAsynchronously' | 'Answered by the error controller' | 'UnsupportedOperationException' - 'an error controller, after starting async' | 'answeredByControllerAfterStartingAsync' | 'Answered by the error controller' | 'UnsupportedOperationException' + handler | path | route | page || exception + 'the error view' | '/failing/answeredByView' | '/failing/answeredByView' | 'An error has occurred' || 'IllegalStateException' + 'an error controller' | '/failing/answeredByController' | '/failing/answeredByController' | 'Answered by the error controller' || 'UnsupportedOperationException' + 'the error view, asynchronously' | '/failing/answeredByViewAsynchronously' | '/failing/answeredByViewAsynchronously' | 'An error has occurred' || 'IllegalStateException' + 'an error controller, asynchronously' | '/failing/answeredByControllerAsynchronously' | '/failing/answeredByControllerAsynchronously' | 'Answered by the error controller' || 'UnsupportedOperationException' + 'the error view, after starting async' | '/failing/answeredByViewAfterStartingAsync' | '/failing/answeredByViewAfterStartingAsync' | 'An error has occurred' || 'IllegalStateException' + 'an error controller, after starting async' | '/failing/answeredByControllerAfterStartingAsync' | '/failing/answeredByControllerAfterStartingAsync' | 'Answered by the error controller' || 'UnsupportedOperationException' + 'the error view, after a forward' | '/failing/forwardedToView' | '/failing/answeredByView' | 'An error has occurred' || 'IllegalStateException' + 'an error controller, after a forward' | '/failing/forwardedToController' | '/failing/answeredByController' | 'Answered by the error controller' || 'UnsupportedOperationException' } private List errorTags(String route) { @@ -94,8 +102,16 @@ class JettyFailedActionObservationSpec extends Specification implements HttpClie @Override void onError(Observation.Context context) { - def route = ((ServerRequestObservationContext) context).pathPattern - NOTIFIED.computeIfAbsent(route) { new CopyOnWriteArrayList<>() } << context.error.class.simpleName + NOTIFIED.computeIfAbsent(requestOf(context)) { new CopyOnWriteArrayList<>() } << context.error.class.simpleName + } + + @Override + void onStop(Observation.Context context) { + STOPPED_ON_ROUTE[requestOf(context)] = ((ServerRequestObservationContext) context).pathPattern ?: 'none' + } + + private static String requestOf(Observation.Context context) { + ((ServerRequestObservationContext) context).carrier.getHeader(REQUEST_HEADER) ?: 'none' } } } diff --git a/grails-test-examples/undertow/grails-app/controllers/undertowapp/FailingController.groovy b/grails-test-examples/undertow/grails-app/controllers/undertowapp/FailingController.groovy index befd28b8ec9..0f0da28013d 100644 --- a/grails-test-examples/undertow/grails-app/controllers/undertowapp/FailingController.groovy +++ b/grails-test-examples/undertow/grails-app/controllers/undertowapp/FailingController.groovy @@ -40,23 +40,45 @@ class FailingController { failAsynchronously(new UnsupportedOperationException('answered by the error controller')) } + def answeredByViewAfterStartingAsync() { + startAsyncThatTimesOut() + throw new IllegalStateException('answered by the error view') + } + def answeredByControllerAfterStartingAsync() { - WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request) - asyncManager.asyncWebRequest = WebAsyncUtils.createAsyncWebRequest(request, response) - // nothing completes the processing this starts, so Undertow ends the request when it times out - asyncManager.startDeferredResultProcessing(new DeferredResult(500L)) + startAsyncThatTimesOut() throw new UnsupportedOperationException('answered by the error controller') } + def forwardedToView() { + forward(action: 'answeredByView') + } + + def forwardedToController() { + forward(action: 'answeredByController') + } + def errorHandler() { render status: 500, text: 'Answered by the error controller' } private void failAsynchronously(Exception failure) { + DeferredResult result = new DeferredResult<>() + startAsync(result) + result.errorResult = failure + } + + /** + * Starts asynchronous processing that nothing completes. Unless the container ends it when the action fails, as + * Tomcat does when the exception is left on the request, it ends when it times out. + */ + private void startAsyncThatTimesOut() { + startAsync(new DeferredResult(500L)) + } + + private void startAsync(DeferredResult result) { WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request) asyncManager.asyncWebRequest = WebAsyncUtils.createAsyncWebRequest(request, response) - DeferredResult result = new DeferredResult<>() asyncManager.startDeferredResultProcessing(result) - result.errorResult = failure } } diff --git a/grails-test-examples/undertow/src/integration-test/groovy/undertowapp/UndertowFailedActionObservationSpec.groovy b/grails-test-examples/undertow/src/integration-test/groovy/undertowapp/UndertowFailedActionObservationSpec.groovy index 37377efa063..f5b82f45691 100644 --- a/grails-test-examples/undertow/src/integration-test/groovy/undertowapp/UndertowFailedActionObservationSpec.groovy +++ b/grails-test-examples/undertow/src/integration-test/groovy/undertowapp/UndertowFailedActionObservationSpec.groovy @@ -45,7 +45,9 @@ import org.apache.grails.testing.http.client.HttpClientSupport class UndertowFailedActionObservationSpec extends Specification implements HttpClientSupport { private static final AtomicBoolean LISTENING = new AtomicBoolean() + private static final String REQUEST_HEADER = 'X-Failing-Request' private static final Map> NOTIFIED = new ConcurrentHashMap<>() + private static final Map STOPPED_ON_ROUTE = new ConcurrentHashMap<>() @Autowired MeterRegistry meterRegistry @@ -61,24 +63,30 @@ class UndertowFailedActionObservationSpec extends Specification implements HttpC void 'a failed action answered by #handler is reported once with its own exception and route'() { when: - def response = http("/failing/$action") + def response = http([(REQUEST_HEADER): path], path) - then: + then: 'the error page answered, so the exception did not reach the filter' response.assertContains(500, page) - and: 'its metrics say what failed and where, and the handlers that mark a span hear of it once' + and: 'the observation stopped on the route that failed, and its metrics say what failed' new PollingConditions(timeout: 5).eventually { - assert errorTags("/failing/$action") == [exception] - assert NOTIFIED["/failing/$action".toString()] == [exception] + assert STOPPED_ON_ROUTE[path] == route + assert errorTags(route) == [exception] } + and: 'the handlers that mark a span, all told of the failure before the observation stopped, heard of it once' + NOTIFIED[path] == [exception] + where: - handler | action | page | exception - 'the error view' | 'answeredByView' | 'An error has occurred' | 'IllegalStateException' - 'an error controller' | 'answeredByController' | 'Answered by the error controller' | 'UnsupportedOperationException' - 'the error view, asynchronously' | 'answeredByViewAsynchronously' | 'An error has occurred' | 'IllegalStateException' - 'an error controller, asynchronously' | 'answeredByControllerAsynchronously' | 'Answered by the error controller' | 'UnsupportedOperationException' - 'an error controller, after starting async' | 'answeredByControllerAfterStartingAsync' | 'Answered by the error controller' | 'UnsupportedOperationException' + handler | path | route | page || exception + 'the error view' | '/failing/answeredByView' | '/failing/answeredByView' | 'An error has occurred' || 'IllegalStateException' + 'an error controller' | '/failing/answeredByController' | '/failing/answeredByController' | 'Answered by the error controller' || 'UnsupportedOperationException' + 'the error view, asynchronously' | '/failing/answeredByViewAsynchronously' | '/failing/answeredByViewAsynchronously' | 'An error has occurred' || 'IllegalStateException' + 'an error controller, asynchronously' | '/failing/answeredByControllerAsynchronously' | '/failing/answeredByControllerAsynchronously' | 'Answered by the error controller' || 'UnsupportedOperationException' + 'the error view, after starting async' | '/failing/answeredByViewAfterStartingAsync' | '/failing/answeredByViewAfterStartingAsync' | 'An error has occurred' || 'IllegalStateException' + 'an error controller, after starting async' | '/failing/answeredByControllerAfterStartingAsync' | '/failing/answeredByControllerAfterStartingAsync' | 'Answered by the error controller' || 'UnsupportedOperationException' + 'the error view, after a forward' | '/failing/forwardedToView' | '/failing/answeredByView' | 'An error has occurred' || 'IllegalStateException' + 'an error controller, after a forward' | '/failing/forwardedToController' | '/failing/answeredByController' | 'Answered by the error controller' || 'UnsupportedOperationException' } private List errorTags(String route) { @@ -94,8 +102,16 @@ class UndertowFailedActionObservationSpec extends Specification implements HttpC @Override void onError(Observation.Context context) { - def route = ((ServerRequestObservationContext) context).pathPattern - NOTIFIED.computeIfAbsent(route) { new CopyOnWriteArrayList<>() } << context.error.class.simpleName + NOTIFIED.computeIfAbsent(requestOf(context)) { new CopyOnWriteArrayList<>() } << context.error.class.simpleName + } + + @Override + void onStop(Observation.Context context) { + STOPPED_ON_ROUTE[requestOf(context)] = ((ServerRequestObservationContext) context).pathPattern ?: 'none' + } + + private static String requestOf(Observation.Context context) { + ((ServerRequestObservationContext) context).carrier.getHeader(REQUEST_HEADER) ?: 'none' } } } From 15ad3330a121f876b9ac4713a972dacc8659150c Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Sun, 8 Nov 2026 19:21:25 -0800 Subject: [PATCH 54/78] Decide whether to record a failure left on the request once the dispatch returns Inside a forward the exception resolver cannot tell whether the filter that observes the request will read the exception it leaves there. Tomcat and Jetty restore the request when a forward returns, while Undertow leaves it reading as the forward, which the filter takes for a plain dispatch. So when an asynchronous dispatch forwarded to a handler that failed and an error controller answered, Undertow reported the failure twice: the resolver recorded it because the dispatch was asynchronous, and the filter recorded it again because the request still read as a forward. GrailsDispatcherServlet now holds that exception for the dispatch it handles and has the resolver decide when the dispatch returns, when the request reads as the filter will read it. Outside that servlet the resolver decides when it resolves, as before. The example apps on Tomcat, Jetty and Undertow add a Spring MVC handler that an asynchronous dispatch forwards to and that fails into the error view or an error controller. The Undertow row answered by an error controller failed with two notifications before this change. --- .../grails-app/conf/spring/resources.groovy | 4 +- .../FailedActionObservationSpec.groovy | 22 +++-- .../issue11102/SpringMvcHandlers.groovy | 62 ++++++++++++ .../grails-app/conf/spring/resources.groovy | 4 +- .../JettyFailedActionObservationSpec.groovy | 20 ++-- .../issue12688/SpringMvcHandlers.groovy | 62 ++++++++++++ .../grails-app/conf/spring/resources.groovy | 2 + ...UndertowFailedActionObservationSpec.groovy | 26 ++--- .../undertowapp/SpringMvcHandlers.groovy | 62 ++++++++++++ .../web/errors/GrailsExceptionResolver.java | 60 +++++++++++- .../mvc/GrailsDispatcherServlet.groovy | 16 ++++ .../errors/GrailsExceptionResolverSpec.groovy | 96 +++++++++++++++++++ 12 files changed, 401 insertions(+), 35 deletions(-) create mode 100644 grails-test-examples/issue-11102/src/main/groovy/issue11102/SpringMvcHandlers.groovy create mode 100644 grails-test-examples/jetty/src/main/groovy/issue12688/SpringMvcHandlers.groovy create mode 100644 grails-test-examples/undertow/src/main/groovy/undertowapp/SpringMvcHandlers.groovy diff --git a/grails-test-examples/issue-11102/grails-app/conf/spring/resources.groovy b/grails-test-examples/issue-11102/grails-app/conf/spring/resources.groovy index f2d41482dbf..5671c4d4b14 100644 --- a/grails-test-examples/issue-11102/grails-app/conf/spring/resources.groovy +++ b/grails-test-examples/issue-11102/grails-app/conf/spring/resources.groovy @@ -17,6 +17,8 @@ * under the License. */ -// Place your Spring DSL code here +import issue11102.SpringMvcHandlers + beans = { + springMvcHandlers(SpringMvcHandlers) } diff --git a/grails-test-examples/issue-11102/src/integration-test/groovy/issue11102/FailedActionObservationSpec.groovy b/grails-test-examples/issue-11102/src/integration-test/groovy/issue11102/FailedActionObservationSpec.groovy index 826ebf4a655..d0be2a71d33 100644 --- a/grails-test-examples/issue-11102/src/integration-test/groovy/issue11102/FailedActionObservationSpec.groovy +++ b/grails-test-examples/issue-11102/src/integration-test/groovy/issue11102/FailedActionObservationSpec.groovy @@ -79,16 +79,18 @@ class FailedActionObservationSpec extends Specification implements HttpClientSup NOTIFIED[path] == [exception] where: - handler | path | route | page || exception - 'the error view' | '/failing/answeredByView' | '/failing/answeredByView' | 'An error has occurred' || 'IllegalStateException' - 'an error controller' | '/failing/answeredByController' | '/failing/answeredByController' | 'Answered by the error controller' || 'UnsupportedOperationException' - 'the error view, asynchronously' | '/failing/answeredByViewAsynchronously' | '/failing/answeredByViewAsynchronously' | 'An error has occurred' || 'IllegalStateException' - 'an error controller, asynchronously' | '/failing/answeredByControllerAsynchronously' | '/failing/answeredByControllerAsynchronously' | 'Answered by the error controller' || 'UnsupportedOperationException' - 'the error view, after starting async' | '/failing/answeredByViewAfterStartingAsync' | '/failing/answeredByViewAfterStartingAsync' | 'An error has occurred' || 'IllegalStateException' - 'an error controller, after starting async' | '/failing/answeredByControllerAfterStartingAsync' | '/failing/answeredByControllerAfterStartingAsync' | 'Answered by the error controller' || 'UnsupportedOperationException' - 'the error view, after a forward' | '/failing/forwardedToView' | '/failing/answeredByView' | 'An error has occurred' || 'IllegalStateException' - 'an error controller, after a forward' | '/failing/forwardedToController' | '/failing/answeredByController' | 'Answered by the error controller' || 'UnsupportedOperationException' - 'an error controller, after an interceptor failed' | '/failing/failsInInterceptor' | '/failing/failsInInterceptor' | 'Answered by the error controller' || 'UnsupportedOperationException' + handler | path | route | page || exception + 'the error view' | '/failing/answeredByView' | '/failing/answeredByView' | 'An error has occurred' || 'IllegalStateException' + 'an error controller' | '/failing/answeredByController' | '/failing/answeredByController' | 'Answered by the error controller' || 'UnsupportedOperationException' + 'the error view, asynchronously' | '/failing/answeredByViewAsynchronously' | '/failing/answeredByViewAsynchronously' | 'An error has occurred' || 'IllegalStateException' + 'an error controller, asynchronously' | '/failing/answeredByControllerAsynchronously' | '/failing/answeredByControllerAsynchronously' | 'Answered by the error controller' || 'UnsupportedOperationException' + 'the error view, after starting async' | '/failing/answeredByViewAfterStartingAsync' | '/failing/answeredByViewAfterStartingAsync' | 'An error has occurred' || 'IllegalStateException' + 'an error controller, after starting async' | '/failing/answeredByControllerAfterStartingAsync' | '/failing/answeredByControllerAfterStartingAsync' | 'Answered by the error controller' || 'UnsupportedOperationException' + 'the error view, after a forward' | '/failing/forwardedToView' | '/failing/answeredByView' | 'An error has occurred' || 'IllegalStateException' + 'an error controller, after a forward' | '/failing/forwardedToController' | '/failing/answeredByController' | 'Answered by the error controller' || 'UnsupportedOperationException' + 'the error view, after an asynchronous forward' | '/spring/forwardedToViewAsynchronously' | '/spring/answeredByView' | 'An error has occurred' || 'IllegalStateException' + 'an error controller, after an asynchronous forward' | '/spring/forwardedToControllerAsynchronously' | '/spring/answeredByController' | 'Answered by the error controller' || 'UnsupportedOperationException' + 'an error controller, after an interceptor failed' | '/failing/failsInInterceptor' | '/failing/failsInInterceptor' | 'Answered by the error controller' || 'UnsupportedOperationException' } private List errorTags(String route) { diff --git a/grails-test-examples/issue-11102/src/main/groovy/issue11102/SpringMvcHandlers.groovy b/grails-test-examples/issue-11102/src/main/groovy/issue11102/SpringMvcHandlers.groovy new file mode 100644 index 00000000000..7e9059499ee --- /dev/null +++ b/grails-test-examples/issue-11102/src/main/groovy/issue11102/SpringMvcHandlers.groovy @@ -0,0 +1,62 @@ +/* + * 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 issue11102 + +import groovy.transform.CompileStatic + +import org.springframework.stereotype.Controller +import org.springframework.web.bind.annotation.GetMapping +import org.springframework.web.context.request.async.DeferredResult +import org.springframework.web.servlet.ModelAndView +import org.springframework.web.servlet.view.InternalResourceView + +/** + * Spring MVC handlers beside the controllers of the application, one of which an asynchronous dispatch forwards to. + */ +@Controller +@CompileStatic +class SpringMvcHandlers { + + @GetMapping('/spring/forwardedToViewAsynchronously') + DeferredResult forwardedToViewAsynchronously() { + forwardAsynchronously('/spring/answeredByView') + } + + @GetMapping('/spring/forwardedToControllerAsynchronously') + DeferredResult forwardedToControllerAsynchronously() { + forwardAsynchronously('/spring/answeredByController') + } + + @GetMapping('/spring/answeredByView') + String answeredByView() { + throw new IllegalStateException('answered by the error view') + } + + @GetMapping('/spring/answeredByController') + String answeredByController() { + throw new UnsupportedOperationException('answered by the error controller') + } + + private static DeferredResult forwardAsynchronously(String path) { + DeferredResult result = new DeferredResult<>() + result.result = new ModelAndView(new InternalResourceView(path)) + result + } +} diff --git a/grails-test-examples/jetty/grails-app/conf/spring/resources.groovy b/grails-test-examples/jetty/grails-app/conf/spring/resources.groovy index f2d41482dbf..88078141ed9 100644 --- a/grails-test-examples/jetty/grails-app/conf/spring/resources.groovy +++ b/grails-test-examples/jetty/grails-app/conf/spring/resources.groovy @@ -17,6 +17,8 @@ * under the License. */ -// Place your Spring DSL code here +import issue12688.SpringMvcHandlers + beans = { + springMvcHandlers(SpringMvcHandlers) } diff --git a/grails-test-examples/jetty/src/integration-test/groovy/issue12688/JettyFailedActionObservationSpec.groovy b/grails-test-examples/jetty/src/integration-test/groovy/issue12688/JettyFailedActionObservationSpec.groovy index 9949ccbcc08..322cde4f8e5 100644 --- a/grails-test-examples/jetty/src/integration-test/groovy/issue12688/JettyFailedActionObservationSpec.groovy +++ b/grails-test-examples/jetty/src/integration-test/groovy/issue12688/JettyFailedActionObservationSpec.groovy @@ -78,15 +78,17 @@ class JettyFailedActionObservationSpec extends Specification implements HttpClie NOTIFIED[path] == [exception] where: - handler | path | route | page || exception - 'the error view' | '/failing/answeredByView' | '/failing/answeredByView' | 'An error has occurred' || 'IllegalStateException' - 'an error controller' | '/failing/answeredByController' | '/failing/answeredByController' | 'Answered by the error controller' || 'UnsupportedOperationException' - 'the error view, asynchronously' | '/failing/answeredByViewAsynchronously' | '/failing/answeredByViewAsynchronously' | 'An error has occurred' || 'IllegalStateException' - 'an error controller, asynchronously' | '/failing/answeredByControllerAsynchronously' | '/failing/answeredByControllerAsynchronously' | 'Answered by the error controller' || 'UnsupportedOperationException' - 'the error view, after starting async' | '/failing/answeredByViewAfterStartingAsync' | '/failing/answeredByViewAfterStartingAsync' | 'An error has occurred' || 'IllegalStateException' - 'an error controller, after starting async' | '/failing/answeredByControllerAfterStartingAsync' | '/failing/answeredByControllerAfterStartingAsync' | 'Answered by the error controller' || 'UnsupportedOperationException' - 'the error view, after a forward' | '/failing/forwardedToView' | '/failing/answeredByView' | 'An error has occurred' || 'IllegalStateException' - 'an error controller, after a forward' | '/failing/forwardedToController' | '/failing/answeredByController' | 'Answered by the error controller' || 'UnsupportedOperationException' + handler | path | route | page || exception + 'the error view' | '/failing/answeredByView' | '/failing/answeredByView' | 'An error has occurred' || 'IllegalStateException' + 'an error controller' | '/failing/answeredByController' | '/failing/answeredByController' | 'Answered by the error controller' || 'UnsupportedOperationException' + 'the error view, asynchronously' | '/failing/answeredByViewAsynchronously' | '/failing/answeredByViewAsynchronously' | 'An error has occurred' || 'IllegalStateException' + 'an error controller, asynchronously' | '/failing/answeredByControllerAsynchronously' | '/failing/answeredByControllerAsynchronously' | 'Answered by the error controller' || 'UnsupportedOperationException' + 'the error view, after starting async' | '/failing/answeredByViewAfterStartingAsync' | '/failing/answeredByViewAfterStartingAsync' | 'An error has occurred' || 'IllegalStateException' + 'an error controller, after starting async' | '/failing/answeredByControllerAfterStartingAsync' | '/failing/answeredByControllerAfterStartingAsync' | 'Answered by the error controller' || 'UnsupportedOperationException' + 'the error view, after a forward' | '/failing/forwardedToView' | '/failing/answeredByView' | 'An error has occurred' || 'IllegalStateException' + 'an error controller, after a forward' | '/failing/forwardedToController' | '/failing/answeredByController' | 'Answered by the error controller' || 'UnsupportedOperationException' + 'the error view, after an asynchronous forward' | '/spring/forwardedToViewAsynchronously' | '/spring/answeredByView' | 'An error has occurred' || 'IllegalStateException' + 'an error controller, after an asynchronous forward' | '/spring/forwardedToControllerAsynchronously' | '/spring/answeredByController' | 'Answered by the error controller' || 'UnsupportedOperationException' } private List errorTags(String route) { diff --git a/grails-test-examples/jetty/src/main/groovy/issue12688/SpringMvcHandlers.groovy b/grails-test-examples/jetty/src/main/groovy/issue12688/SpringMvcHandlers.groovy new file mode 100644 index 00000000000..f58605af585 --- /dev/null +++ b/grails-test-examples/jetty/src/main/groovy/issue12688/SpringMvcHandlers.groovy @@ -0,0 +1,62 @@ +/* + * 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 issue12688 + +import groovy.transform.CompileStatic + +import org.springframework.stereotype.Controller +import org.springframework.web.bind.annotation.GetMapping +import org.springframework.web.context.request.async.DeferredResult +import org.springframework.web.servlet.ModelAndView +import org.springframework.web.servlet.view.InternalResourceView + +/** + * Spring MVC handlers beside the controllers of the application, one of which an asynchronous dispatch forwards to. + */ +@Controller +@CompileStatic +class SpringMvcHandlers { + + @GetMapping('/spring/forwardedToViewAsynchronously') + DeferredResult forwardedToViewAsynchronously() { + forwardAsynchronously('/spring/answeredByView') + } + + @GetMapping('/spring/forwardedToControllerAsynchronously') + DeferredResult forwardedToControllerAsynchronously() { + forwardAsynchronously('/spring/answeredByController') + } + + @GetMapping('/spring/answeredByView') + String answeredByView() { + throw new IllegalStateException('answered by the error view') + } + + @GetMapping('/spring/answeredByController') + String answeredByController() { + throw new UnsupportedOperationException('answered by the error controller') + } + + private static DeferredResult forwardAsynchronously(String path) { + DeferredResult result = new DeferredResult<>() + result.result = new ModelAndView(new InternalResourceView(path)) + result + } +} diff --git a/grails-test-examples/undertow/grails-app/conf/spring/resources.groovy b/grails-test-examples/undertow/grails-app/conf/spring/resources.groovy index f6bcc8e82af..c0afa4fb8f6 100644 --- a/grails-test-examples/undertow/grails-app/conf/spring/resources.groovy +++ b/grails-test-examples/undertow/grails-app/conf/spring/resources.groovy @@ -19,6 +19,7 @@ import org.springframework.boot.web.servlet.FilterRegistrationBean +import undertowapp.SpringMvcHandlers import undertowapp.StaticInitFailureFilter beans = { @@ -26,4 +27,5 @@ beans = { filter = new StaticInitFailureFilter() urlPatterns = ['/staticInitFailure/*'] } + springMvcHandlers(SpringMvcHandlers) } diff --git a/grails-test-examples/undertow/src/integration-test/groovy/undertowapp/UndertowFailedActionObservationSpec.groovy b/grails-test-examples/undertow/src/integration-test/groovy/undertowapp/UndertowFailedActionObservationSpec.groovy index f5b82f45691..a2f90987a0e 100644 --- a/grails-test-examples/undertow/src/integration-test/groovy/undertowapp/UndertowFailedActionObservationSpec.groovy +++ b/grails-test-examples/undertow/src/integration-test/groovy/undertowapp/UndertowFailedActionObservationSpec.groovy @@ -37,8 +37,10 @@ import org.apache.grails.testing.http.client.HttpClientSupport /** * The failure of an action reaches the observation of its request once, however the container ends the request. - * Undertow leaves a request that was forwarded to an error handler reading as a forward, so the filter that observes - * it records the exception left on it even on an asynchronous dispatch, and the exception resolver must not. + * Undertow leaves a request that was forwarded reading as a forward, so the filter that observes it records the + * exception left on it even on an asynchronous dispatch, and the exception resolver must not. When the asynchronous + * dispatch forwarded to the handler that failed, the request reads as a forward whichever container runs it, so the + * resolver can only tell once the dispatch has returned. */ @Integration @Tag('http-client') @@ -78,15 +80,17 @@ class UndertowFailedActionObservationSpec extends Specification implements HttpC NOTIFIED[path] == [exception] where: - handler | path | route | page || exception - 'the error view' | '/failing/answeredByView' | '/failing/answeredByView' | 'An error has occurred' || 'IllegalStateException' - 'an error controller' | '/failing/answeredByController' | '/failing/answeredByController' | 'Answered by the error controller' || 'UnsupportedOperationException' - 'the error view, asynchronously' | '/failing/answeredByViewAsynchronously' | '/failing/answeredByViewAsynchronously' | 'An error has occurred' || 'IllegalStateException' - 'an error controller, asynchronously' | '/failing/answeredByControllerAsynchronously' | '/failing/answeredByControllerAsynchronously' | 'Answered by the error controller' || 'UnsupportedOperationException' - 'the error view, after starting async' | '/failing/answeredByViewAfterStartingAsync' | '/failing/answeredByViewAfterStartingAsync' | 'An error has occurred' || 'IllegalStateException' - 'an error controller, after starting async' | '/failing/answeredByControllerAfterStartingAsync' | '/failing/answeredByControllerAfterStartingAsync' | 'Answered by the error controller' || 'UnsupportedOperationException' - 'the error view, after a forward' | '/failing/forwardedToView' | '/failing/answeredByView' | 'An error has occurred' || 'IllegalStateException' - 'an error controller, after a forward' | '/failing/forwardedToController' | '/failing/answeredByController' | 'Answered by the error controller' || 'UnsupportedOperationException' + handler | path | route | page || exception + 'the error view' | '/failing/answeredByView' | '/failing/answeredByView' | 'An error has occurred' || 'IllegalStateException' + 'an error controller' | '/failing/answeredByController' | '/failing/answeredByController' | 'Answered by the error controller' || 'UnsupportedOperationException' + 'the error view, asynchronously' | '/failing/answeredByViewAsynchronously' | '/failing/answeredByViewAsynchronously' | 'An error has occurred' || 'IllegalStateException' + 'an error controller, asynchronously' | '/failing/answeredByControllerAsynchronously' | '/failing/answeredByControllerAsynchronously' | 'Answered by the error controller' || 'UnsupportedOperationException' + 'the error view, after starting async' | '/failing/answeredByViewAfterStartingAsync' | '/failing/answeredByViewAfterStartingAsync' | 'An error has occurred' || 'IllegalStateException' + 'an error controller, after starting async' | '/failing/answeredByControllerAfterStartingAsync' | '/failing/answeredByControllerAfterStartingAsync' | 'Answered by the error controller' || 'UnsupportedOperationException' + 'the error view, after a forward' | '/failing/forwardedToView' | '/failing/answeredByView' | 'An error has occurred' || 'IllegalStateException' + 'an error controller, after a forward' | '/failing/forwardedToController' | '/failing/answeredByController' | 'Answered by the error controller' || 'UnsupportedOperationException' + 'the error view, after an asynchronous forward' | '/spring/forwardedToViewAsynchronously' | '/spring/answeredByView' | 'An error has occurred' || 'IllegalStateException' + 'an error controller, after an asynchronous forward' | '/spring/forwardedToControllerAsynchronously' | '/spring/answeredByController' | 'Answered by the error controller' || 'UnsupportedOperationException' } private List errorTags(String route) { diff --git a/grails-test-examples/undertow/src/main/groovy/undertowapp/SpringMvcHandlers.groovy b/grails-test-examples/undertow/src/main/groovy/undertowapp/SpringMvcHandlers.groovy new file mode 100644 index 00000000000..8f5db585740 --- /dev/null +++ b/grails-test-examples/undertow/src/main/groovy/undertowapp/SpringMvcHandlers.groovy @@ -0,0 +1,62 @@ +/* + * 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 undertowapp + +import groovy.transform.CompileStatic + +import org.springframework.stereotype.Controller +import org.springframework.web.bind.annotation.GetMapping +import org.springframework.web.context.request.async.DeferredResult +import org.springframework.web.servlet.ModelAndView +import org.springframework.web.servlet.view.InternalResourceView + +/** + * Spring MVC handlers beside the controllers of the application, one of which an asynchronous dispatch forwards to. + */ +@Controller +@CompileStatic +class SpringMvcHandlers { + + @GetMapping('/spring/forwardedToViewAsynchronously') + DeferredResult forwardedToViewAsynchronously() { + forwardAsynchronously('/spring/answeredByView') + } + + @GetMapping('/spring/forwardedToControllerAsynchronously') + DeferredResult forwardedToControllerAsynchronously() { + forwardAsynchronously('/spring/answeredByController') + } + + @GetMapping('/spring/answeredByView') + String answeredByView() { + throw new IllegalStateException('answered by the error view') + } + + @GetMapping('/spring/answeredByController') + String answeredByController() { + throw new UnsupportedOperationException('answered by the error controller') + } + + private static DeferredResult forwardAsynchronously(String path) { + DeferredResult result = new DeferredResult<>() + result.result = new ModelAndView(new InternalResourceView(path)) + result + } +} diff --git a/grails-web-mvc/src/main/groovy/org/grails/web/errors/GrailsExceptionResolver.java b/grails-web-mvc/src/main/groovy/org/grails/web/errors/GrailsExceptionResolver.java index 9edd061aa0b..4b0096f5ff3 100644 --- a/grails-web-mvc/src/main/groovy/org/grails/web/errors/GrailsExceptionResolver.java +++ b/grails-web-mvc/src/main/groovy/org/grails/web/errors/GrailsExceptionResolver.java @@ -93,6 +93,10 @@ public class GrailsExceptionResolver extends SimpleMappingExceptionResolver impl private static final String SERVER_OBSERVATION_ATTRIBUTE = ServerHttpObservationFilter.class.getName() + ".observation"; + /** Where a dispatch holds the exception left on its request until it returns. */ + private static final String FAILURE_LEFT_ON_REQUEST_ATTRIBUTE = + GrailsExceptionResolver.class.getName() + ".FAILURE_LEFT_ON_REQUEST"; + protected static final Logger LOG = LoggerFactory.getLogger(GrailsExceptionResolver.class); protected static final String LINE_SEPARATOR = System.getProperty("line.separator"); @@ -143,17 +147,53 @@ public ModelAndView resolveException(HttpServletRequest request, HttpServletResp return mv; } + /** + * Holds the exception this resolver leaves on the request until the dispatch has returned, because only then does + * the request read as the filter that observes it will read it. Inside a forward it does not yet: Tomcat and Jetty + * restore a request when a forward returns, and Undertow leaves it reading as the forward. + * {@link org.grails.web.servlet.mvc.GrailsDispatcherServlet} calls this when a dispatch enters it, and runs what + * this returns when the dispatch returns. + * + * @param request the request of the dispatch + * @return what records the exception left on the request, unless the filter will; it does nothing for a forward or + * include within a dispatch that already holds it + */ + public static Runnable holdFailureLeftOnRequest(HttpServletRequest request) { + if (request.getAttribute(FAILURE_LEFT_ON_REQUEST_ATTRIBUTE) != null) { + return () -> { }; + } + FailureLeftOnRequest held = new FailureLeftOnRequest(request.getDispatcherType()); + request.setAttribute(FAILURE_LEFT_ON_REQUEST_ATTRIBUTE, held); + return () -> { + request.removeAttribute(FAILURE_LEFT_ON_REQUEST_ATTRIBUTE); + if (held.failure != null) { + recordUnlessRecordedFromRequest(request, held.failure, held.dispatchedAs); + } + }; + } + /** * Every exception this resolves is a server error, and resolving it hides it from the observation of the request, * whose metrics would otherwise say there was no error and whose trace would not be marked as failed. Only * {@link Observation#error(Throwable)} tells the observation's handlers, one of which marks the span. *

* An exception left in {@link WebUtils#ERROR_EXCEPTION_ATTRIBUTE} is not recorded here when it is recorded from there - * once the dispatch returns, so that the handlers hear of it once. + * once the dispatch returns, so that the handlers hear of it once. A dispatch that holds it decides when it returns. * * @param dispatchedAs how the request was dispatched before an error handler was forwarded to */ private static void recordServerError(HttpServletRequest request, Exception ex, DispatcherType dispatchedAs) { + if (request.getAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE) == ex && + request.getAttribute(FAILURE_LEFT_ON_REQUEST_ATTRIBUTE) instanceof FailureLeftOnRequest held) { + held.failure = ex; + } + else { + recordUnlessRecordedFromRequest(request, ex, dispatchedAs); + } + } + + private static void recordUnlessRecordedFromRequest(HttpServletRequest request, Exception ex, + DispatcherType dispatchedAs) { if (request.getAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE) == ex && recordedFromRequest(request, dispatchedAs)) { return; } @@ -167,7 +207,7 @@ private static void recordServerError(HttpServletRequest request, Exception ex, /** * Whether the exception left in {@link WebUtils#ERROR_EXCEPTION_ATTRIBUTE} is recorded from there once the dispatch - * returns. + * returns, judged from how the request reads now. *

    *
  • The filter that observes the request records it at the end of a plain dispatch. It does not look at the end of * an asynchronous dispatch, which {@link WebUtils#isAsync} tells even inside a forward.
  • @@ -175,8 +215,11 @@ private static void recordServerError(HttpServletRequest request, Exception ex, * Tomcat reports the exception to that listener when the dispatch returns. Jetty does not, but the request already * reads as asynchronous there, so the exception is recorded here. *
  • Undertow leaves a request that was forwarded reading as a forward, so the filter takes it for a plain dispatch - * and records the exception however the request was dispatched.
  • + * and records the exception however the request was dispatched. A request that reads as a forward although the + * dispatch did not begin as one was left that way. *
+ * + * @param dispatchedAs how the dispatch began */ private static boolean recordedFromRequest(HttpServletRequest request, DispatcherType dispatchedAs) { boolean forwardLeftOnRequest = dispatchedAs != DispatcherType.FORWARD && @@ -641,4 +684,15 @@ protected void applyLogFullStackTraceOnFilter() { ((DefaultStackTraceFilterer) stackFilterer).setLogFullStackTraceOnFilter(logOnFilter); } } + + /** The exception left on the request of a dispatch, held until the dispatch returns. */ + private static final class FailureLeftOnRequest { + + private final DispatcherType dispatchedAs; + private Exception failure; + + private FailureLeftOnRequest(DispatcherType dispatchedAs) { + this.dispatchedAs = dispatchedAs; + } + } } diff --git a/grails-web-mvc/src/main/groovy/org/grails/web/servlet/mvc/GrailsDispatcherServlet.groovy b/grails-web-mvc/src/main/groovy/org/grails/web/servlet/mvc/GrailsDispatcherServlet.groovy index e74d82cbb7d..49cc06f4627 100644 --- a/grails-web-mvc/src/main/groovy/org/grails/web/servlet/mvc/GrailsDispatcherServlet.groovy +++ b/grails-web-mvc/src/main/groovy/org/grails/web/servlet/mvc/GrailsDispatcherServlet.groovy @@ -37,6 +37,7 @@ import org.springframework.web.servlet.DispatcherServlet import grails.util.Holders import org.grails.web.context.ServletEnvironmentGrailsApplicationDiscoveryStrategy +import org.grails.web.errors.GrailsExceptionResolver import org.grails.web.util.HiddenHttpMethod import org.grails.web.util.WebUtils @@ -74,6 +75,21 @@ class GrailsDispatcherServlet extends DispatcherServlet implements ServletContex } } + /** + * Records an exception an error handler answered on the observation of the request once the dispatch has returned, + * unless the filter that observes the request will read it from there. + */ + @Override + protected void doService(HttpServletRequest request, HttpServletResponse response) throws Exception { + Runnable recordFailureLeftOnRequest = GrailsExceptionResolver.holdFailureLeftOnRequest(request) + try { + super.doService(request, response) + } + finally { + recordFailureLeftOnRequest.run() + } + } + protected GrailsWebRequest buildGrailsWebRequest(HttpServletRequest request, HttpServletResponse response) { def webRequest = new GrailsWebRequest(request, response, request.getServletContext()) webRequest.informParameterCreationListeners() diff --git a/grails-web-mvc/src/test/groovy/org/grails/web/errors/GrailsExceptionResolverSpec.groovy b/grails-web-mvc/src/test/groovy/org/grails/web/errors/GrailsExceptionResolverSpec.groovy index c5fb999b972..75eb78bab07 100644 --- a/grails-web-mvc/src/test/groovy/org/grails/web/errors/GrailsExceptionResolverSpec.groovy +++ b/grails-web-mvc/src/test/groovy/org/grails/web/errors/GrailsExceptionResolverSpec.groovy @@ -36,6 +36,7 @@ import org.grails.exceptions.reporting.StackTraceFilterer import org.grails.web.mapping.DefaultUrlMappingEvaluator import org.grails.web.mapping.DefaultUrlMappingsHolder import org.grails.web.mapping.mvc.GrailsControllerUrlMappings +import org.grails.web.servlet.mvc.GrailsDispatcherServlet import org.grails.web.servlet.mvc.GrailsWebRequest import org.grails.web.servlet.view.CompositeViewResolver import org.grails.web.util.WebUtils as GrailsWebUtils @@ -47,6 +48,7 @@ import org.springframework.http.server.observation.ServerRequestObservationConte import org.springframework.mock.web.MockHttpServletRequest import org.springframework.mock.web.MockHttpServletResponse import org.springframework.mock.web.MockRequestDispatcher +import org.springframework.mock.web.MockServletConfig import org.springframework.mock.web.MockServletContext import org.springframework.web.context.request.RequestContextHolder import org.springframework.web.context.request.ServletRequestAttributes @@ -57,6 +59,9 @@ import org.springframework.web.context.WebApplicationContext import org.springframework.web.context.support.StaticWebApplicationContext import org.springframework.web.servlet.ModelAndView import org.springframework.web.servlet.ViewResolver +import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping +import org.springframework.web.servlet.mvc.Controller +import org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter import org.springframework.web.servlet.view.InternalResourceView import spock.lang.Issue import spock.lang.Specification @@ -64,6 +69,7 @@ import spock.lang.Specification import jakarta.servlet.DispatcherType import jakarta.servlet.FilterChain import jakarta.servlet.RequestDispatcher +import jakarta.servlet.Servlet import jakarta.servlet.ServletContext import jakarta.servlet.ServletRequest import jakarta.servlet.ServletResponse @@ -216,6 +222,42 @@ class GrailsExceptionResolverSpec extends Specification { dispatch << [DispatcherType.REQUEST, DispatcherType.ASYNC] } + void 'the handlers hear once of an exception an error controller answers in a forward from #dispatch, when #container'() { + given: 'the Grails dispatcher servlet behind the filter, and a handler that forwards to one that fails' + List notified = [] + def registry = registryReporting({ }, { notified << it }) + def resolver = resolverFor({ '500'(controller: 'errors', action: 'serverError') }, true) + def original = new IllegalStateException('original') + def servlet = dispatcherServletWith(resolver, [ + '/forwarding': { req, res -> req.getRequestDispatcher('/failing').forward(req, res); null } as Controller, + '/failing' : { req, res -> throw original } as Controller]) + def request = new ForwardingRequest(servletContext, '/forwarding', servlet, ['/forwarding', '/failing'] as Set, + restoresForward) + request.dispatcherType = dispatch + if (dispatch == DispatcherType.ASYNC) { + request.setAttribute(GrailsWebUtils.ASYNC_REQUEST_URI_ATTRIBUTE, '/forwarding') + } + def response = new MockHttpServletResponse() + + when: + new ServerHttpObservationFilter(registry).doFilter(request, response, { req, res -> + servlet.service(req, res) + } as FilterChain) + + then: + response.forwardedUrl == '/errors/serverError' + request.dispatcherType == (restoresForward ? dispatch : DispatcherType.FORWARD) + notified.size() == 1 + notified.first().is(original) + + where: + dispatch | restoresForward | container + DispatcherType.REQUEST | true | 'the container restores the request, as Tomcat and Jetty do' + DispatcherType.REQUEST | false | 'the request still reads as the forward, as on Undertow' + DispatcherType.ASYNC | true | 'the container restores the request, as Tomcat and Jetty do' + DispatcherType.ASYNC | false | 'the request still reads as the forward, as on Undertow' + } + void 'a filter can read the exception an error handler answered once the chain has returned, with no observation'() { given: def resolver = resolverFor({ '500'(controller: 'errors', action: 'serverError') }, true) @@ -881,6 +923,60 @@ class GrailsExceptionResolverSpec extends Specification { resolver } + private GrailsDispatcherServlet dispatcherServletWith(GrailsExceptionResolver resolver, Map handlers) { + def handlerMapping = new SimpleUrlHandlerMapping(handlers) + handlerMapping.applicationContext = webContext + webContext.beanFactory.registerSingleton('handlerMapping', handlerMapping) + webContext.beanFactory.registerSingleton('handlerAdapter', new SimpleControllerHandlerAdapter()) + webContext.beanFactory.registerSingleton('exceptionResolver', resolver) + def servlet = new GrailsDispatcherServlet(webContext) + servlet.init(new MockServletConfig(servletContext, 'grails')) + servlet + } + + /** + * A request whose forwards to the handlers of a servlet dispatch through it, and which reads as the forward once it + * has returned, unless the container restores it, as Tomcat and Jetty do and Undertow does not. + */ + private static class ForwardingRequest extends MockHttpServletRequest { + + final Servlet servlet + final Set handled + final boolean restoresForward + + ForwardingRequest(ServletContext servletContext, String requestURI, Servlet servlet, Set handled, + boolean restoresForward) { + super(servletContext, 'GET', requestURI) + this.servlet = servlet + this.handled = handled + this.restoresForward = restoresForward + } + + @Override + RequestDispatcher getRequestDispatcher(String path) { + ForwardingRequest forwarded = this + new MockRequestDispatcher(path) { + @Override + void forward(ServletRequest request, ServletResponse response) { + DispatcherType dispatchedAs = forwarded.dispatcherType + String requestURI = forwarded.requestURI + forwarded.dispatcherType = DispatcherType.FORWARD + forwarded.requestURI = path + if (path in forwarded.handled) { + forwarded.servlet.service(request, response) + } + else { + super.forward(request, response) + } + if (forwarded.restoresForward) { + forwarded.dispatcherType = dispatchedAs + forwarded.requestURI = requestURI + } + } + } + } + } + /** A request that still reads as a forward once a forward has returned, as Undertow leaves it. */ private static class ForwardLeftOnRequest extends MockHttpServletRequest { From 8e479420f7fce871a44a9a00bc0b50af3cee2614 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Sun, 8 Nov 2026 19:31:00 -0800 Subject: [PATCH 55/78] Judge the observation of a failed request by what it carried when it first stopped Spring's listener stops the observation of a request that times out twice: on the timeout, and again when the request completes. A request whose action started asynchronous processing and then failed into the error view is left to time out, and with Spring Boot 4.2 its second stop carries the timeout as its error, which the specs took for a second failure. They now read the route and the error the observation carried when it first stopped, and check that the metrics tag the failure. --- .../issue11102/FailedActionObservationSpec.groovy | 15 ++++++++++----- .../JettyFailedActionObservationSpec.groovy | 15 ++++++++++----- .../UndertowFailedActionObservationSpec.groovy | 15 ++++++++++----- 3 files changed, 30 insertions(+), 15 deletions(-) diff --git a/grails-test-examples/issue-11102/src/integration-test/groovy/issue11102/FailedActionObservationSpec.groovy b/grails-test-examples/issue-11102/src/integration-test/groovy/issue11102/FailedActionObservationSpec.groovy index d0be2a71d33..bbe738f365b 100644 --- a/grails-test-examples/issue-11102/src/integration-test/groovy/issue11102/FailedActionObservationSpec.groovy +++ b/grails-test-examples/issue-11102/src/integration-test/groovy/issue11102/FailedActionObservationSpec.groovy @@ -48,7 +48,7 @@ class FailedActionObservationSpec extends Specification implements HttpClientSup private static final AtomicBoolean LISTENING = new AtomicBoolean() private static final String REQUEST_HEADER = 'X-Failing-Request' private static final Map> NOTIFIED = new ConcurrentHashMap<>() - private static final Map STOPPED_ON_ROUTE = new ConcurrentHashMap<>() + private static final Map> STOPPED = new ConcurrentHashMap<>() @Autowired MeterRegistry meterRegistry @@ -69,10 +69,10 @@ class FailedActionObservationSpec extends Specification implements HttpClientSup then: 'the error page answered, so the exception did not reach the filter' response.assertContains(500, page) - and: 'the observation stopped on the route that failed, and its metrics say what failed' + and: 'the observation stopped on the route that failed with what failed, as its metrics say' new PollingConditions(timeout: 5).eventually { - assert STOPPED_ON_ROUTE[path] == route - assert errorTags(route) == [exception] + assert STOPPED[path] == [route, exception] + assert exception in errorTags(route) } and: 'the handlers that mark a span, all told of the failure before the observation stopped, heard of it once' @@ -109,9 +109,14 @@ class FailedActionObservationSpec extends Specification implements HttpClientSup NOTIFIED.computeIfAbsent(requestOf(context)) { new CopyOnWriteArrayList<>() } << context.error.class.simpleName } + /** + * Spring stops the observation of a request it times out twice, on the timeout and again when the request + * completes, so what the observation reported is what it carried when it first stopped. + */ @Override void onStop(Observation.Context context) { - STOPPED_ON_ROUTE[requestOf(context)] = ((ServerRequestObservationContext) context).pathPattern ?: 'none' + STOPPED.putIfAbsent(requestOf(context), [((ServerRequestObservationContext) context).pathPattern ?: 'none', + context.error?.class?.simpleName ?: 'none']) } private static String requestOf(Observation.Context context) { diff --git a/grails-test-examples/jetty/src/integration-test/groovy/issue12688/JettyFailedActionObservationSpec.groovy b/grails-test-examples/jetty/src/integration-test/groovy/issue12688/JettyFailedActionObservationSpec.groovy index 322cde4f8e5..5239e4099e3 100644 --- a/grails-test-examples/jetty/src/integration-test/groovy/issue12688/JettyFailedActionObservationSpec.groovy +++ b/grails-test-examples/jetty/src/integration-test/groovy/issue12688/JettyFailedActionObservationSpec.groovy @@ -47,7 +47,7 @@ class JettyFailedActionObservationSpec extends Specification implements HttpClie private static final AtomicBoolean LISTENING = new AtomicBoolean() private static final String REQUEST_HEADER = 'X-Failing-Request' private static final Map> NOTIFIED = new ConcurrentHashMap<>() - private static final Map STOPPED_ON_ROUTE = new ConcurrentHashMap<>() + private static final Map> STOPPED = new ConcurrentHashMap<>() @Autowired MeterRegistry meterRegistry @@ -68,10 +68,10 @@ class JettyFailedActionObservationSpec extends Specification implements HttpClie then: 'the error page answered, so the exception did not reach the filter' response.assertContains(500, page) - and: 'the observation stopped on the route that failed, and its metrics say what failed' + and: 'the observation stopped on the route that failed with what failed, as its metrics say' new PollingConditions(timeout: 5).eventually { - assert STOPPED_ON_ROUTE[path] == route - assert errorTags(route) == [exception] + assert STOPPED[path] == [route, exception] + assert exception in errorTags(route) } and: 'the handlers that mark a span, all told of the failure before the observation stopped, heard of it once' @@ -107,9 +107,14 @@ class JettyFailedActionObservationSpec extends Specification implements HttpClie NOTIFIED.computeIfAbsent(requestOf(context)) { new CopyOnWriteArrayList<>() } << context.error.class.simpleName } + /** + * Spring stops the observation of a request it times out twice, on the timeout and again when the request + * completes, so what the observation reported is what it carried when it first stopped. + */ @Override void onStop(Observation.Context context) { - STOPPED_ON_ROUTE[requestOf(context)] = ((ServerRequestObservationContext) context).pathPattern ?: 'none' + STOPPED.putIfAbsent(requestOf(context), [((ServerRequestObservationContext) context).pathPattern ?: 'none', + context.error?.class?.simpleName ?: 'none']) } private static String requestOf(Observation.Context context) { diff --git a/grails-test-examples/undertow/src/integration-test/groovy/undertowapp/UndertowFailedActionObservationSpec.groovy b/grails-test-examples/undertow/src/integration-test/groovy/undertowapp/UndertowFailedActionObservationSpec.groovy index a2f90987a0e..d776c93e17c 100644 --- a/grails-test-examples/undertow/src/integration-test/groovy/undertowapp/UndertowFailedActionObservationSpec.groovy +++ b/grails-test-examples/undertow/src/integration-test/groovy/undertowapp/UndertowFailedActionObservationSpec.groovy @@ -49,7 +49,7 @@ class UndertowFailedActionObservationSpec extends Specification implements HttpC private static final AtomicBoolean LISTENING = new AtomicBoolean() private static final String REQUEST_HEADER = 'X-Failing-Request' private static final Map> NOTIFIED = new ConcurrentHashMap<>() - private static final Map STOPPED_ON_ROUTE = new ConcurrentHashMap<>() + private static final Map> STOPPED = new ConcurrentHashMap<>() @Autowired MeterRegistry meterRegistry @@ -70,10 +70,10 @@ class UndertowFailedActionObservationSpec extends Specification implements HttpC then: 'the error page answered, so the exception did not reach the filter' response.assertContains(500, page) - and: 'the observation stopped on the route that failed, and its metrics say what failed' + and: 'the observation stopped on the route that failed with what failed, as its metrics say' new PollingConditions(timeout: 5).eventually { - assert STOPPED_ON_ROUTE[path] == route - assert errorTags(route) == [exception] + assert STOPPED[path] == [route, exception] + assert exception in errorTags(route) } and: 'the handlers that mark a span, all told of the failure before the observation stopped, heard of it once' @@ -109,9 +109,14 @@ class UndertowFailedActionObservationSpec extends Specification implements HttpC NOTIFIED.computeIfAbsent(requestOf(context)) { new CopyOnWriteArrayList<>() } << context.error.class.simpleName } + /** + * Spring stops the observation of a request it times out twice, on the timeout and again when the request + * completes, so what the observation reported is what it carried when it first stopped. + */ @Override void onStop(Observation.Context context) { - STOPPED_ON_ROUTE[requestOf(context)] = ((ServerRequestObservationContext) context).pathPattern ?: 'none' + STOPPED.putIfAbsent(requestOf(context), [((ServerRequestObservationContext) context).pathPattern ?: 'none', + context.error?.class?.simpleName ?: 'none']) } private static String requestOf(Observation.Context context) { From 96ffe78e15c2f8913026b832a621e881d7076db0 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Sun, 8 Nov 2026 19:37:25 -0800 Subject: [PATCH 56/78] Write a problem with the advice for the controller the request is mapped to The ResponseBodyAdvice beans that apply to a problem were found by the class of the controller instance on the request. A failure in an interceptor's before(), or in creating the controller, comes before the request has one, so the advice scoped to that controller was skipped, and after a forward the request still holds the controller that forwarded, whose advice applied instead. The problem is now written as a value of the controller class the request is mapped to, as Spring MVC finds the advice for a handler method by its bean's type. --- .../mvc/ActionExceptionHandlerResolver.groovy | 8 ++- .../web/mapping/mvc/ActionReturnValues.groovy | 12 ++-- .../ActionExceptionProblemDetailsSpec.groovy | 55 +++++++++++++++++++ 3 files changed, 67 insertions(+), 8 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 a050f405e50..66f0959d654 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 @@ -143,7 +143,8 @@ class ActionExceptionHandlerResolver implements HandlerExceptionResolver, Ordere return null } ModelAndView resolved = enabled ? resolveWithHandlerMethods(request, response, (GrailsControllerUrlMappingInfo) handler, ex) : null - return resolved == null && problemDetails ? resolveAsProblem(request, response, ex) : resolved + return resolved == null && problemDetails ? + resolveAsProblem(request, response, (GrailsControllerUrlMappingInfo) handler, ex) : resolved } private ModelAndView resolveWithHandlerMethods(HttpServletRequest request, HttpServletResponse response, @@ -159,7 +160,8 @@ class ActionExceptionHandlerResolver implements HandlerExceptionResolver, Ordere * 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) { + private ModelAndView resolveAsProblem(HttpServletRequest request, HttpServletResponse response, + GrailsControllerUrlMappingInfo handler, Exception thrown) { Exception ex = unwrap(thrown) try { if (response.committed || WebUtils.isIncludeRequest(request) || !returnValues.writesErrorResponses() || @@ -170,7 +172,7 @@ class ActionExceptionHandlerResolver implements HandlerExceptionResolver, Ordere // 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) + handler.controllerClass?.clazz, request, response) if (isServerError(response)) { recordServerError(request, ex) // Spring MVC's translation logs an unexpected exception without the request it failed 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 0bb20417adb..54e6fa4243e 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 @@ -192,20 +192,22 @@ class ActionReturnValues { /** * 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. + * beans and the {@code ResponseBodyAdvice} beans that apply to the controller. Those are found by the controller's + * class, since the request may not have got as far as creating the controller, as when an interceptor's + * {@code before()} fails, or may still hold the one that forwarded to it. * * @param errorResponse the error response - * @param controller the controller, or {@code null} + * @param controllerType the class of the controller the request is mapped to, 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) { + ModelAndView writeErrorResponse(ErrorResponse errorResponse, Class controllerType, HttpServletRequest request, + HttpServletResponse response) { // 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) + .withContainingClass(controllerType ?: 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 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 7b34a32c400..6e49773c40c 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 @@ -30,12 +30,16 @@ import io.micrometer.observation.Observation import io.micrometer.observation.ObservationHandler import io.micrometer.observation.ObservationRegistry +import org.springframework.core.MethodParameter import org.springframework.core.env.MapPropertySource import org.springframework.http.HttpHeaders import org.springframework.http.HttpStatus +import org.springframework.http.MediaType import org.springframework.http.ProblemDetail import org.springframework.http.converter.HttpMessageConverter import org.springframework.http.converter.json.JacksonJsonHttpMessageConverter +import org.springframework.http.server.ServerHttpRequest +import org.springframework.http.server.ServerHttpResponse import org.springframework.http.server.observation.ServerRequestObservationContext import org.springframework.mock.web.MockHttpServletRequest import org.springframework.mock.web.MockHttpServletResponse @@ -52,6 +56,7 @@ 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 org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice import grails.core.DefaultGrailsApplication import grails.core.GrailsApplication @@ -377,6 +382,30 @@ class ActionExceptionProblemDetailsSpec extends Specification { logCapture.close() } + void 'the advice for the controller the request is mapped to applies to the problem when the request holds #held'() { + given: + def resolver = resolver([problemDetails: true]) + if (controller != null) { + request.setAttribute(GrailsApplicationAttributes.CONTROLLER, controller) + } + def info = new GrailsControllerUrlMappingInfo(new DefaultGrailsControllerClass(ProblemController), Stub(UrlMappingInfo) { + getActionName() >> 'index' + }) + + when: + resolver.resolveException(request, response, info, new IllegalStateException('secret')) + + then: + problem().status == 500 + response.getHeader(ProblemResponseAdvice.HEADER) == ProblemController.simpleName + + where: + held | controller + 'no controller, as when an interceptor fails before creating it' | null + 'the controller that forwarded to it' | new ForwardingProblemController() + 'that controller' | new ProblemController() + } + void 'an ErrorResponse.Interceptor sees the problem, as it sees one a handler method returns'() { given: interceptors = [new ErrorResponse.Interceptor() { @@ -512,6 +541,7 @@ class ActionExceptionProblemDetailsSpec extends Specification { settings.collectEntries { key, value -> ["grails.exceptionresolver.$key".toString(), value] } as Map)) List> converters = [new JacksonJsonHttpMessageConverter()] context.registerBean(ProblemControllerAdvice) + context.registerBean(ProblemResponseAdvice) context.registerBean(ExceptionHandlerExceptionResolver, { new ExceptionHandlerExceptionResolver(messageConverters: converters) }) context.registerBean('requestMappingHandlerAdapter', RequestMappingHandlerAdapter, { new RequestMappingHandlerAdapter(messageConverters: converters, errorResponseInterceptors: interceptors) @@ -541,6 +571,12 @@ class ProblemController { } } +class ForwardingProblemController { + + def index() { + } +} + @ResponseStatus(code = HttpStatus.I_AM_A_TEAPOT, reason = 'Short and stout') class TeapotException extends RuntimeException { } @@ -558,3 +594,22 @@ class ProblemControllerAdvice { throw e } } + +@ControllerAdvice(assignableTypes = ProblemController) +class ProblemResponseAdvice implements ResponseBodyAdvice { + + static final String HEADER = 'X-Advised-For' + + @Override + boolean supports(MethodParameter returnType, Class> converterType) { + true + } + + @Override + Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, + Class> selectedConverterType, ServerHttpRequest request, + ServerHttpResponse response) { + response.headers.set(HEADER, ProblemController.simpleName) + body + } +} From 56d08d13c66425443bc7185a8cbae864b53fcaae Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Mon, 9 Nov 2026 08:25:40 -0800 Subject: [PATCH 57/78] Report an Error an action throws, not the ServletException around it DispatcherServlet wraps an Error a handler throws, such as a failed assert, in a ServletException, and findWrappedException only takes off the wrappers Groovy and Grails add, so an action that threw an AssertionError was recorded on the observation of its request as a ServletException. ServerHttpObservationFilter takes a ServletException off an exception that reaches it. The resolver now does the same for what it records and for what it leaves in jakarta.servlet.error.exception for the filter, and takes an Error out of the Groovy wrapper findWrappedException leaves around it. What is logged and rendered is unchanged. ActionExceptionHandlerResolver records what it writes as a problem the same way. The example apps throw an AssertionError answered by the error view and a StackOverflowError answered by an error controller, on Tomcat, Jetty and Undertow, and GrailsExceptionResolverSpec and ActionExceptionProblemDetailsSpec cover both wrappers. --- .../src/en/guide/upgrading/upgrading90x.adoc | 1 + .../issue11102/FailingController.groovy | 8 +++++ .../controllers/issue11102/UrlMappings.groovy | 1 + .../FailedActionObservationSpec.groovy | 2 ++ .../issue12688/FailingController.groovy | 8 +++++ .../controllers/issue12688/UrlMappings.groovy | 1 + .../JettyFailedActionObservationSpec.groovy | 2 ++ .../undertowapp/FailingController.groovy | 8 +++++ .../undertowapp/UrlMappings.groovy | 1 + ...UndertowFailedActionObservationSpec.groovy | 2 ++ .../web/errors/GrailsExceptionResolver.java | 29 +++++++++++++++---- .../errors/GrailsExceptionResolverSpec.groovy | 25 +++++++++++----- .../mvc/ActionExceptionHandlerResolver.groovy | 24 +++++++++++++-- .../ActionExceptionProblemDetailsSpec.groovy | 21 ++++++++++++++ 14 files changed, 117 insertions(+), 16 deletions(-) diff --git a/grails-doc/src/en/guide/upgrading/upgrading90x.adoc b/grails-doc/src/en/guide/upgrading/upgrading90x.adoc index d2329c002bf..2892a52351c 100644 --- a/grails-doc/src/en/guide/upgrading/upgrading90x.adoc +++ b/grails-doc/src/en/guide/upgrading/upgrading90x.adoc @@ -118,6 +118,7 @@ The builder no longer pins the version of the run image, so set both `builder` a When an error view answered, as the `"500"(view: '/error')` mapping of a generated application does, `http.server.requests` tagged the 500 with `error` and `exception` values of `none`, and tracing did not see a failure. A `500` mapping to a controller tagged it with `GrailsWrappedRuntimeException` and with the `uri` of that controller, so every failure it answered looked like the same route. Both now report the exception the action threw and the route of the action, and the span of the request is marked as failed. +That includes an `Error`, such as a failed `assert`, rather than the `ServletException` Spring MVC wraps it in. These requests were already counted with `outcome=SERVER_ERROR`, but an alert that counts a non-`none` `error` value will see more server errors than before, and a dashboard that reads the `uri` of an error controller will find those failures under the routes of the actions. After a forward to an error controller, the `jakarta.servlet.error.exception` request attribute holds the exception the action threw rather than a `GrailsWrappedRuntimeException`, for a filter that reads it once the chain has returned. Inside the error controller it still holds the wrapper. A client error is not recorded. diff --git a/grails-test-examples/issue-11102/grails-app/controllers/issue11102/FailingController.groovy b/grails-test-examples/issue-11102/grails-app/controllers/issue11102/FailingController.groovy index a9b351c0585..9aeaab9d988 100644 --- a/grails-test-examples/issue-11102/grails-app/controllers/issue11102/FailingController.groovy +++ b/grails-test-examples/issue-11102/grails-app/controllers/issue11102/FailingController.groovy @@ -51,6 +51,14 @@ class FailingController { throw new UnsupportedOperationException('answered by the error controller') } + def answeredByViewForAnError() { + throw new AssertionError('answered by the error view') + } + + def answeredByControllerForAnError() { + throw new StackOverflowError('answered by the error controller') + } + def forwardedToView() { forward(action: 'answeredByView') } diff --git a/grails-test-examples/issue-11102/grails-app/controllers/issue11102/UrlMappings.groovy b/grails-test-examples/issue-11102/grails-app/controllers/issue11102/UrlMappings.groovy index cca628bf2a1..d619e89f58f 100644 --- a/grails-test-examples/issue-11102/grails-app/controllers/issue11102/UrlMappings.groovy +++ b/grails-test-examples/issue-11102/grails-app/controllers/issue11102/UrlMappings.groovy @@ -35,6 +35,7 @@ class UrlMappings { "/"(view:"/index") "500"(controller: 'failing', action: 'errorHandler', exception: UnsupportedOperationException) + "500"(controller: 'failing', action: 'errorHandler', exception: StackOverflowError) "500"(view:'/error') "404"(view:'/notFound') } diff --git a/grails-test-examples/issue-11102/src/integration-test/groovy/issue11102/FailedActionObservationSpec.groovy b/grails-test-examples/issue-11102/src/integration-test/groovy/issue11102/FailedActionObservationSpec.groovy index bbe738f365b..4e554d006b8 100644 --- a/grails-test-examples/issue-11102/src/integration-test/groovy/issue11102/FailedActionObservationSpec.groovy +++ b/grails-test-examples/issue-11102/src/integration-test/groovy/issue11102/FailedActionObservationSpec.groovy @@ -90,6 +90,8 @@ class FailedActionObservationSpec extends Specification implements HttpClientSup 'an error controller, after a forward' | '/failing/forwardedToController' | '/failing/answeredByController' | 'Answered by the error controller' || 'UnsupportedOperationException' 'the error view, after an asynchronous forward' | '/spring/forwardedToViewAsynchronously' | '/spring/answeredByView' | 'An error has occurred' || 'IllegalStateException' 'an error controller, after an asynchronous forward' | '/spring/forwardedToControllerAsynchronously' | '/spring/answeredByController' | 'Answered by the error controller' || 'UnsupportedOperationException' + 'the error view, for an Error' | '/failing/answeredByViewForAnError' | '/failing/answeredByViewForAnError' | 'An error has occurred' || 'AssertionError' + 'an error controller, for an Error' | '/failing/answeredByControllerForAnError' | '/failing/answeredByControllerForAnError' | 'Answered by the error controller' || 'StackOverflowError' 'an error controller, after an interceptor failed' | '/failing/failsInInterceptor' | '/failing/failsInInterceptor' | 'Answered by the error controller' || 'UnsupportedOperationException' } diff --git a/grails-test-examples/jetty/grails-app/controllers/issue12688/FailingController.groovy b/grails-test-examples/jetty/grails-app/controllers/issue12688/FailingController.groovy index c1cc72b2bd2..df2af298421 100644 --- a/grails-test-examples/jetty/grails-app/controllers/issue12688/FailingController.groovy +++ b/grails-test-examples/jetty/grails-app/controllers/issue12688/FailingController.groovy @@ -50,6 +50,14 @@ class FailingController { throw new UnsupportedOperationException('answered by the error controller') } + def answeredByViewForAnError() { + throw new AssertionError('answered by the error view') + } + + def answeredByControllerForAnError() { + throw new StackOverflowError('answered by the error controller') + } + def forwardedToView() { forward(action: 'answeredByView') } diff --git a/grails-test-examples/jetty/grails-app/controllers/issue12688/UrlMappings.groovy b/grails-test-examples/jetty/grails-app/controllers/issue12688/UrlMappings.groovy index 75786d0e28e..fbab282439d 100644 --- a/grails-test-examples/jetty/grails-app/controllers/issue12688/UrlMappings.groovy +++ b/grails-test-examples/jetty/grails-app/controllers/issue12688/UrlMappings.groovy @@ -31,6 +31,7 @@ class UrlMappings { "500"(view: '/error') "500"(controller: 'failing', action: 'errorHandler', exception: UnsupportedOperationException) + "500"(controller: 'failing', action: 'errorHandler', exception: StackOverflowError) "413"(controller: 'upload', action: 'tooLarge') "404"(view: '/notFound') } diff --git a/grails-test-examples/jetty/src/integration-test/groovy/issue12688/JettyFailedActionObservationSpec.groovy b/grails-test-examples/jetty/src/integration-test/groovy/issue12688/JettyFailedActionObservationSpec.groovy index 5239e4099e3..5afc1dc2589 100644 --- a/grails-test-examples/jetty/src/integration-test/groovy/issue12688/JettyFailedActionObservationSpec.groovy +++ b/grails-test-examples/jetty/src/integration-test/groovy/issue12688/JettyFailedActionObservationSpec.groovy @@ -89,6 +89,8 @@ class JettyFailedActionObservationSpec extends Specification implements HttpClie 'an error controller, after a forward' | '/failing/forwardedToController' | '/failing/answeredByController' | 'Answered by the error controller' || 'UnsupportedOperationException' 'the error view, after an asynchronous forward' | '/spring/forwardedToViewAsynchronously' | '/spring/answeredByView' | 'An error has occurred' || 'IllegalStateException' 'an error controller, after an asynchronous forward' | '/spring/forwardedToControllerAsynchronously' | '/spring/answeredByController' | 'Answered by the error controller' || 'UnsupportedOperationException' + 'the error view, for an Error' | '/failing/answeredByViewForAnError' | '/failing/answeredByViewForAnError' | 'An error has occurred' || 'AssertionError' + 'an error controller, for an Error' | '/failing/answeredByControllerForAnError' | '/failing/answeredByControllerForAnError' | 'Answered by the error controller' || 'StackOverflowError' } private List errorTags(String route) { diff --git a/grails-test-examples/undertow/grails-app/controllers/undertowapp/FailingController.groovy b/grails-test-examples/undertow/grails-app/controllers/undertowapp/FailingController.groovy index 0f0da28013d..0c59e8adef1 100644 --- a/grails-test-examples/undertow/grails-app/controllers/undertowapp/FailingController.groovy +++ b/grails-test-examples/undertow/grails-app/controllers/undertowapp/FailingController.groovy @@ -50,6 +50,14 @@ class FailingController { throw new UnsupportedOperationException('answered by the error controller') } + def answeredByViewForAnError() { + throw new AssertionError('answered by the error view') + } + + def answeredByControllerForAnError() { + throw new StackOverflowError('answered by the error controller') + } + def forwardedToView() { forward(action: 'answeredByView') } diff --git a/grails-test-examples/undertow/grails-app/controllers/undertowapp/UrlMappings.groovy b/grails-test-examples/undertow/grails-app/controllers/undertowapp/UrlMappings.groovy index 519db0d9776..e8ab06b4ea1 100644 --- a/grails-test-examples/undertow/grails-app/controllers/undertowapp/UrlMappings.groovy +++ b/grails-test-examples/undertow/grails-app/controllers/undertowapp/UrlMappings.groovy @@ -32,6 +32,7 @@ class UrlMappings { "500"(view: '/error') "500"(controller: 'failing', action: 'errorHandler', exception: UnsupportedOperationException) + "500"(controller: 'failing', action: 'errorHandler', exception: StackOverflowError) "500"(controller: 'errorPage', action: 'handle', exception: StaticInitFailure) "413"(controller: 'upload', action: 'tooLarge') "404"(view: '/notFound') diff --git a/grails-test-examples/undertow/src/integration-test/groovy/undertowapp/UndertowFailedActionObservationSpec.groovy b/grails-test-examples/undertow/src/integration-test/groovy/undertowapp/UndertowFailedActionObservationSpec.groovy index d776c93e17c..3f629e4ace2 100644 --- a/grails-test-examples/undertow/src/integration-test/groovy/undertowapp/UndertowFailedActionObservationSpec.groovy +++ b/grails-test-examples/undertow/src/integration-test/groovy/undertowapp/UndertowFailedActionObservationSpec.groovy @@ -91,6 +91,8 @@ class UndertowFailedActionObservationSpec extends Specification implements HttpC 'an error controller, after a forward' | '/failing/forwardedToController' | '/failing/answeredByController' | 'Answered by the error controller' || 'UnsupportedOperationException' 'the error view, after an asynchronous forward' | '/spring/forwardedToViewAsynchronously' | '/spring/answeredByView' | 'An error has occurred' || 'IllegalStateException' 'an error controller, after an asynchronous forward' | '/spring/forwardedToControllerAsynchronously' | '/spring/answeredByController' | 'Answered by the error controller' || 'UnsupportedOperationException' + 'the error view, for an Error' | '/failing/answeredByViewForAnError' | '/failing/answeredByViewForAnError' | 'An error has occurred' || 'AssertionError' + 'an error controller, for an Error' | '/failing/answeredByControllerForAnError' | '/failing/answeredByControllerForAnError' | 'Answered by the error controller' || 'StackOverflowError' } private List errorTags(String route) { diff --git a/grails-web-mvc/src/main/groovy/org/grails/web/errors/GrailsExceptionResolver.java b/grails-web-mvc/src/main/groovy/org/grails/web/errors/GrailsExceptionResolver.java index 4b0096f5ff3..6c477ff020d 100644 --- a/grails-web-mvc/src/main/groovy/org/grails/web/errors/GrailsExceptionResolver.java +++ b/grails-web-mvc/src/main/groovy/org/grails/web/errors/GrailsExceptionResolver.java @@ -142,7 +142,7 @@ public ModelAndView resolveException(HttpServletRequest request, HttpServletResp mv = resolveViewOrForward(ex, urlMappings, request, response, mv); } - recordServerError(request, ex, dispatchedAs); + recordServerError(request, reportedFailure(ex), dispatchedAs); return mv; } @@ -182,7 +182,7 @@ public static Runnable holdFailureLeftOnRequest(HttpServletRequest request) { * * @param dispatchedAs how the request was dispatched before an error handler was forwarded to */ - private static void recordServerError(HttpServletRequest request, Exception ex, DispatcherType dispatchedAs) { + private static void recordServerError(HttpServletRequest request, Throwable ex, DispatcherType dispatchedAs) { if (request.getAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE) == ex && request.getAttribute(FAILURE_LEFT_ON_REQUEST_ATTRIBUTE) instanceof FailureLeftOnRequest held) { held.failure = ex; @@ -192,7 +192,7 @@ private static void recordServerError(HttpServletRequest request, Exception ex, } } - private static void recordUnlessRecordedFromRequest(HttpServletRequest request, Exception ex, + private static void recordUnlessRecordedFromRequest(HttpServletRequest request, Throwable ex, DispatcherType dispatchedAs) { if (request.getAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE) == ex && recordedFromRequest(request, dispatchedAs)) { return; @@ -233,7 +233,26 @@ private static boolean recordedFromRequest(HttpServletRequest request, Dispatche * chain has returned, which includes the filter that observes the request. */ private static void keepFailureOnRequest(HttpServletRequest request, Exception ex) { - request.setAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE, ex); + request.setAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE, reportedFailure(ex)); + } + + /** + * What the action threw, as the observation of the request reports it. {@code DispatcherServlet} wraps an + * {@link Error}, such as a failed {@code assert}, in a {@link ServletException}, which + * {@link ServerHttpObservationFilter} takes off an exception that reaches it, and + * {@link #findWrappedException(Exception)} leaves a Groovy wrapper around an {@code Error}, since it resolves + * exceptions only. + */ + private static Throwable reportedFailure(Exception resolved) { + Throwable failure = resolved; + if (failure instanceof ServletException && failure.getCause() != null) { + failure = failure.getCause(); + } + while ((failure instanceof InvokerInvocationException || failure instanceof GrailsMVCException) && + failure.getCause() != null) { + failure = failure.getCause(); + } + return failure; } public String getRequestLogMessage(Throwable e, HttpServletRequest request) { @@ -689,7 +708,7 @@ protected void applyLogFullStackTraceOnFilter() { private static final class FailureLeftOnRequest { private final DispatcherType dispatchedAs; - private Exception failure; + private Throwable failure; private FailureLeftOnRequest(DispatcherType dispatchedAs) { this.dispatchedAs = dispatchedAs; diff --git a/grails-web-mvc/src/test/groovy/org/grails/web/errors/GrailsExceptionResolverSpec.groovy b/grails-web-mvc/src/test/groovy/org/grails/web/errors/GrailsExceptionResolverSpec.groovy index 75eb78bab07..ac43d3d5d82 100644 --- a/grails-web-mvc/src/test/groovy/org/grails/web/errors/GrailsExceptionResolverSpec.groovy +++ b/grails-web-mvc/src/test/groovy/org/grails/web/errors/GrailsExceptionResolverSpec.groovy @@ -71,6 +71,7 @@ import jakarta.servlet.FilterChain import jakarta.servlet.RequestDispatcher import jakarta.servlet.Servlet import jakarta.servlet.ServletContext +import jakarta.servlet.ServletException import jakarta.servlet.ServletRequest import jakarta.servlet.ServletResponse import jakarta.servlet.http.HttpServletRequest @@ -83,6 +84,8 @@ class GrailsExceptionResolverSpec extends Specification { private static final String PLAIN = 'plain attributes' private static final String NOTHING = 'nothing' private static final Exception FAILURE = new IllegalStateException('failed') + private static final AssertionError FAILED_ASSERT = new AssertionError('failed') + private static final StackOverflowError TOO_DEEP = new StackOverflowError('too deep') private final MockServletContext servletContext = new MockServletContext() private StaticWebApplicationContext webContext @@ -116,9 +119,11 @@ class GrailsExceptionResolverSpec extends Specification { notified.first().is(recorded) where: - description | thrown | recorded | status - 'an action threw' | FAILURE | FAILURE | 500 - 'wrapped by Groovy' | new InvokerInvocationException(new InvocationTargetException(FAILURE)) | FAILURE | 500 + description | thrown | recorded | status + 'an action threw' | FAILURE | FAILURE | 500 + 'wrapped by Groovy' | new InvokerInvocationException(new InvocationTargetException(FAILURE)) | FAILURE | 500 + 'that is an Error DispatcherServlet wrapped' | new ServletException("Handler dispatch failed: $FAILED_ASSERT", FAILED_ASSERT) | FAILED_ASSERT | 500 + 'that is an Error Groovy wrapped' | new InvokerInvocationException(TOO_DEEP) | TOO_DEEP | 500 } void 'an exception is still the error of a context that comes without its observation'() { @@ -258,20 +263,24 @@ class GrailsExceptionResolverSpec extends Specification { DispatcherType.ASYNC | false | 'the request still reads as the forward, as on Undertow' } - void 'a filter can read the exception an error handler answered once the chain has returned, with no observation'() { + void 'a filter can read the exception an error handler answered once the chain has returned, with no observation, when #description'() { given: def resolver = resolverFor({ '500'(controller: 'errors', action: 'serverError') }, true) def request = new MockHttpServletRequest(servletContext, 'GET', '/fail') def response = new MockHttpServletResponse() bind(GRAILS, request, response) - def original = new IllegalStateException('original') when: - resolver.resolveException(request, response, null, original) + resolver.resolveException(request, response, null, thrown) - then: + then: 'what the action threw, as the filter that observes the request reports an exception that reaches it' response.forwardedUrl == '/errors/serverError' - request.getAttribute(RequestDispatcher.ERROR_EXCEPTION).is(original) + request.getAttribute(RequestDispatcher.ERROR_EXCEPTION).is(left) + + where: + description | thrown | left + 'an action threw an exception' | FAILURE | FAILURE + 'an action threw an Error DispatcherServlet wrapped' | new ServletException("Handler dispatch failed: $FAILED_ASSERT", FAILED_ASSERT) | FAILED_ASSERT } void 'an exception is resolved as usual without an observation'() { 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 66f0959d654..188867ed097 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 @@ -22,6 +22,7 @@ import groovy.transform.CompileStatic import groovy.util.logging.Slf4j import org.codehaus.groovy.runtime.InvokerInvocationException +import jakarta.servlet.ServletException import jakarta.servlet.http.HttpServletRequest import jakarta.servlet.http.HttpServletResponse @@ -174,7 +175,7 @@ class ActionExceptionHandlerResolver implements HandlerExceptionResolver, Ordere ModelAndView written = errorResponse == null ? new ModelAndView() : returnValues.writeErrorResponse(errorResponse, handler.controllerClass?.clazz, request, response) if (isServerError(response)) { - recordServerError(request, ex) + recordServerError(request, reportedFailure(thrown)) // Spring MVC's translation logs an unexpected exception without the request it failed if (!(ex instanceof ErrorResponse) && !DisconnectedClientHelper.isClientDisconnectedException(ex)) { log.error('{} occurred when processing request: [{}] {}', ex.class.simpleName, request.method, requestUri(request)) @@ -185,7 +186,7 @@ class ActionExceptionHandlerResolver implements HandlerExceptionResolver, Ordere catch (Exception e) { if (DISCONNECTED_CLIENTS.checkAndLogClientDisconnectedException(e)) { if (isServerError(response)) { - recordServerError(request, ex) + recordServerError(request, reportedFailure(thrown)) } return new ModelAndView() } @@ -259,11 +260,28 @@ class ActionExceptionHandlerResolver implements HandlerExceptionResolver, Ordere return urlMappings.matchStatusCode(status, ex) != null || urlMappings.matchStatusCode(status, ExceptionUtils.getRootCause(ex)) != null } + /** + * What the action threw, as the observation of the request reports it. {@code DispatcherServlet} wraps an + * {@link Error}, such as a failed {@code assert}, in a {@link ServletException}, which + * {@link ServerHttpObservationFilter} takes off an exception that reaches it, and {@link #unwrap} leaves a Groovy + * wrapper around an {@code Error}, since a problem is written for an exception. + */ + private static Throwable reportedFailure(Exception thrown) { + Throwable failure = thrown + if (failure instanceof ServletException && failure.cause != null) { + failure = failure.cause + } + while ((failure instanceof InvokerInvocationException || failure instanceof GrailsMVCException) && failure.cause != null) { + failure = failure.cause + } + return failure + } + /** * As Spring MVC records an exception it translates to a server error, which the observation would not see otherwise. * Only the observation tells its handlers, one of which marks the span. */ - private static void recordServerError(HttpServletRequest request, Exception ex) { + private static void recordServerError(HttpServletRequest request, Throwable ex) { Object observation = request.getAttribute(SERVER_OBSERVATION_ATTRIBUTE) if (observation instanceof Observation) { ((Observation) observation).error(ex) 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 6e49773c40c..1caf9777b0e 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 @@ -22,6 +22,7 @@ import groovy.json.JsonSlurper import org.codehaus.groovy.runtime.InvokerInvocationException import jakarta.servlet.FilterChain +import jakarta.servlet.ServletException import jakarta.servlet.http.HttpServletRequest import jakarta.servlet.http.HttpServletResponse @@ -357,6 +358,26 @@ class ActionExceptionProblemDetailsSpec extends Specification { new ResponseStatusException(HttpStatus.BAD_REQUEST) | false } + void 'an Error an action threw is recorded on the HTTP server observation as itself, when #wrapper wrapped it'() { + given: + def resolver = resolver([problemDetails: true]) + def observation = new ServerRequestObservationContext(request, response) + request.setAttribute(ServerHttpObservationFilter.CURRENT_OBSERVATION_CONTEXT_ATTRIBUTE, observation) + + when: + resolver.resolveException(request, response, action(new ProblemController()), thrown) + + then: 'as the filter that observes the request reports one that reaches it' + response.status == 500 + problem().status == 500 + observation.error.is(error) + + where: + wrapper | error | thrown + 'Spring MVC' | new AssertionError('failed') | new ServletException("Handler dispatch failed: $error", error) + 'a dynamic invocation' | new StackOverflowError('deep') | new InvokerInvocationException(error) + } + 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]) From 28a5485e688685264b87ecf48bd317f8fb109d4c Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Mon, 9 Nov 2026 08:24:53 -0800 Subject: [PATCH 58/78] Keep the route that failed when its error controller forwards An error controller that called forward() replaced the route of the action that failed with its own. RequestForwarder takes jakarta.servlet.error.status_code off the request before it dispatches, so ObservationRouteHandler, which kept the route only while that attribute was there, took the forward for a new request. It now also keeps the route while jakarta.servlet.error.exception is set, which the forward leaves in place. The example apps answer an ArithmeticException with an error controller that forwards to another action, on Tomcat, Jetty and Undertow. --- .../controllers/issue11102/FailingController.groovy | 8 ++++++++ .../controllers/issue11102/UrlMappings.groovy | 1 + .../issue11102/FailedActionObservationSpec.groovy | 1 + .../controllers/issue12688/FailingController.groovy | 8 ++++++++ .../controllers/issue12688/UrlMappings.groovy | 1 + .../JettyFailedActionObservationSpec.groovy | 1 + .../controllers/undertowapp/FailingController.groovy | 8 ++++++++ .../controllers/undertowapp/UrlMappings.groovy | 1 + .../UndertowFailedActionObservationSpec.groovy | 1 + .../web/mapping/mvc/UrlMappingsHandlerMapping.groovy | 5 +++-- .../mapping/mvc/UrlMappingsHandlerMappingSpec.groovy | 11 +++++++++++ 11 files changed, 44 insertions(+), 2 deletions(-) diff --git a/grails-test-examples/issue-11102/grails-app/controllers/issue11102/FailingController.groovy b/grails-test-examples/issue-11102/grails-app/controllers/issue11102/FailingController.groovy index 9aeaab9d988..60a6397d2a1 100644 --- a/grails-test-examples/issue-11102/grails-app/controllers/issue11102/FailingController.groovy +++ b/grails-test-examples/issue-11102/grails-app/controllers/issue11102/FailingController.groovy @@ -59,6 +59,10 @@ class FailingController { throw new StackOverflowError('answered by the error controller') } + def answeredByForwardingController() { + throw new ArithmeticException('answered by an error controller that forwards') + } + def forwardedToView() { forward(action: 'answeredByView') } @@ -75,6 +79,10 @@ class FailingController { render status: 500, text: 'Answered by the error controller' } + def forwardingErrorHandler() { + forward(action: 'errorHandler') + } + private void failAsynchronously(Exception failure) { DeferredResult result = new DeferredResult<>() startAsync(result) diff --git a/grails-test-examples/issue-11102/grails-app/controllers/issue11102/UrlMappings.groovy b/grails-test-examples/issue-11102/grails-app/controllers/issue11102/UrlMappings.groovy index d619e89f58f..1bc22d7f735 100644 --- a/grails-test-examples/issue-11102/grails-app/controllers/issue11102/UrlMappings.groovy +++ b/grails-test-examples/issue-11102/grails-app/controllers/issue11102/UrlMappings.groovy @@ -36,6 +36,7 @@ class UrlMappings { "/"(view:"/index") "500"(controller: 'failing', action: 'errorHandler', exception: UnsupportedOperationException) "500"(controller: 'failing', action: 'errorHandler', exception: StackOverflowError) + "500"(controller: 'failing', action: 'forwardingErrorHandler', exception: ArithmeticException) "500"(view:'/error') "404"(view:'/notFound') } diff --git a/grails-test-examples/issue-11102/src/integration-test/groovy/issue11102/FailedActionObservationSpec.groovy b/grails-test-examples/issue-11102/src/integration-test/groovy/issue11102/FailedActionObservationSpec.groovy index 4e554d006b8..15565b34b7e 100644 --- a/grails-test-examples/issue-11102/src/integration-test/groovy/issue11102/FailedActionObservationSpec.groovy +++ b/grails-test-examples/issue-11102/src/integration-test/groovy/issue11102/FailedActionObservationSpec.groovy @@ -92,6 +92,7 @@ class FailedActionObservationSpec extends Specification implements HttpClientSup 'an error controller, after an asynchronous forward' | '/spring/forwardedToControllerAsynchronously' | '/spring/answeredByController' | 'Answered by the error controller' || 'UnsupportedOperationException' 'the error view, for an Error' | '/failing/answeredByViewForAnError' | '/failing/answeredByViewForAnError' | 'An error has occurred' || 'AssertionError' 'an error controller, for an Error' | '/failing/answeredByControllerForAnError' | '/failing/answeredByControllerForAnError' | 'Answered by the error controller' || 'StackOverflowError' + 'an error controller that forwards' | '/failing/answeredByForwardingController' | '/failing/answeredByForwardingController' | 'Answered by the error controller' || 'ArithmeticException' 'an error controller, after an interceptor failed' | '/failing/failsInInterceptor' | '/failing/failsInInterceptor' | 'Answered by the error controller' || 'UnsupportedOperationException' } diff --git a/grails-test-examples/jetty/grails-app/controllers/issue12688/FailingController.groovy b/grails-test-examples/jetty/grails-app/controllers/issue12688/FailingController.groovy index df2af298421..15b208942f1 100644 --- a/grails-test-examples/jetty/grails-app/controllers/issue12688/FailingController.groovy +++ b/grails-test-examples/jetty/grails-app/controllers/issue12688/FailingController.groovy @@ -58,6 +58,10 @@ class FailingController { throw new StackOverflowError('answered by the error controller') } + def answeredByForwardingController() { + throw new ArithmeticException('answered by an error controller that forwards') + } + def forwardedToView() { forward(action: 'answeredByView') } @@ -70,6 +74,10 @@ class FailingController { render status: 500, text: 'Answered by the error controller' } + def forwardingErrorHandler() { + forward(action: 'errorHandler') + } + private void failAsynchronously(Exception failure) { DeferredResult result = new DeferredResult<>() startAsync(result) diff --git a/grails-test-examples/jetty/grails-app/controllers/issue12688/UrlMappings.groovy b/grails-test-examples/jetty/grails-app/controllers/issue12688/UrlMappings.groovy index fbab282439d..0ee14cc6cb9 100644 --- a/grails-test-examples/jetty/grails-app/controllers/issue12688/UrlMappings.groovy +++ b/grails-test-examples/jetty/grails-app/controllers/issue12688/UrlMappings.groovy @@ -32,6 +32,7 @@ class UrlMappings { "500"(view: '/error') "500"(controller: 'failing', action: 'errorHandler', exception: UnsupportedOperationException) "500"(controller: 'failing', action: 'errorHandler', exception: StackOverflowError) + "500"(controller: 'failing', action: 'forwardingErrorHandler', exception: ArithmeticException) "413"(controller: 'upload', action: 'tooLarge') "404"(view: '/notFound') } diff --git a/grails-test-examples/jetty/src/integration-test/groovy/issue12688/JettyFailedActionObservationSpec.groovy b/grails-test-examples/jetty/src/integration-test/groovy/issue12688/JettyFailedActionObservationSpec.groovy index 5afc1dc2589..ee1e357a8ba 100644 --- a/grails-test-examples/jetty/src/integration-test/groovy/issue12688/JettyFailedActionObservationSpec.groovy +++ b/grails-test-examples/jetty/src/integration-test/groovy/issue12688/JettyFailedActionObservationSpec.groovy @@ -91,6 +91,7 @@ class JettyFailedActionObservationSpec extends Specification implements HttpClie 'an error controller, after an asynchronous forward' | '/spring/forwardedToControllerAsynchronously' | '/spring/answeredByController' | 'Answered by the error controller' || 'UnsupportedOperationException' 'the error view, for an Error' | '/failing/answeredByViewForAnError' | '/failing/answeredByViewForAnError' | 'An error has occurred' || 'AssertionError' 'an error controller, for an Error' | '/failing/answeredByControllerForAnError' | '/failing/answeredByControllerForAnError' | 'Answered by the error controller' || 'StackOverflowError' + 'an error controller that forwards' | '/failing/answeredByForwardingController' | '/failing/answeredByForwardingController' | 'Answered by the error controller' || 'ArithmeticException' } private List errorTags(String route) { diff --git a/grails-test-examples/undertow/grails-app/controllers/undertowapp/FailingController.groovy b/grails-test-examples/undertow/grails-app/controllers/undertowapp/FailingController.groovy index 0c59e8adef1..c7e3170d8f2 100644 --- a/grails-test-examples/undertow/grails-app/controllers/undertowapp/FailingController.groovy +++ b/grails-test-examples/undertow/grails-app/controllers/undertowapp/FailingController.groovy @@ -58,6 +58,10 @@ class FailingController { throw new StackOverflowError('answered by the error controller') } + def answeredByForwardingController() { + throw new ArithmeticException('answered by an error controller that forwards') + } + def forwardedToView() { forward(action: 'answeredByView') } @@ -70,6 +74,10 @@ class FailingController { render status: 500, text: 'Answered by the error controller' } + def forwardingErrorHandler() { + forward(action: 'errorHandler') + } + private void failAsynchronously(Exception failure) { DeferredResult result = new DeferredResult<>() startAsync(result) diff --git a/grails-test-examples/undertow/grails-app/controllers/undertowapp/UrlMappings.groovy b/grails-test-examples/undertow/grails-app/controllers/undertowapp/UrlMappings.groovy index e8ab06b4ea1..6d76946c00e 100644 --- a/grails-test-examples/undertow/grails-app/controllers/undertowapp/UrlMappings.groovy +++ b/grails-test-examples/undertow/grails-app/controllers/undertowapp/UrlMappings.groovy @@ -33,6 +33,7 @@ class UrlMappings { "500"(view: '/error') "500"(controller: 'failing', action: 'errorHandler', exception: UnsupportedOperationException) "500"(controller: 'failing', action: 'errorHandler', exception: StackOverflowError) + "500"(controller: 'failing', action: 'forwardingErrorHandler', exception: ArithmeticException) "500"(controller: 'errorPage', action: 'handle', exception: StaticInitFailure) "413"(controller: 'upload', action: 'tooLarge') "404"(view: '/notFound') diff --git a/grails-test-examples/undertow/src/integration-test/groovy/undertowapp/UndertowFailedActionObservationSpec.groovy b/grails-test-examples/undertow/src/integration-test/groovy/undertowapp/UndertowFailedActionObservationSpec.groovy index 3f629e4ace2..9c17fb177f0 100644 --- a/grails-test-examples/undertow/src/integration-test/groovy/undertowapp/UndertowFailedActionObservationSpec.groovy +++ b/grails-test-examples/undertow/src/integration-test/groovy/undertowapp/UndertowFailedActionObservationSpec.groovy @@ -93,6 +93,7 @@ class UndertowFailedActionObservationSpec extends Specification implements HttpC 'an error controller, after an asynchronous forward' | '/spring/forwardedToControllerAsynchronously' | '/spring/answeredByController' | 'Answered by the error controller' || 'UnsupportedOperationException' 'the error view, for an Error' | '/failing/answeredByViewForAnError' | '/failing/answeredByViewForAnError' | 'An error has occurred' || 'AssertionError' 'an error controller, for an Error' | '/failing/answeredByControllerForAnError' | '/failing/answeredByControllerForAnError' | 'Answered by the error controller' || 'StackOverflowError' + 'an error controller that forwards' | '/failing/answeredByForwardingController' | '/failing/answeredByForwardingController' | 'Answered by the error controller' || 'ArithmeticException' } private List errorTags(String route) { diff --git a/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMapping.groovy b/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMapping.groovy index b458f3cbbf2..a0c9dae0095 100644 --- a/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMapping.groovy +++ b/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMapping.groovy @@ -229,14 +229,15 @@ class UrlMappingsHandlerMapping extends AbstractHandlerMapping { * {@code http.server.requests} {@code uri} tag is a low-cardinality route (e.g. {@code /book/show}) * instead of {@code UNKNOWN}. Runs at {@code preHandle}: at URL-mapping match the observation * context is not yet on the request. A request routed to an error handler keeps the route that failed, so - * that the failures an error handler answers are not all reported as its own route. + * that the failures an error handler answers are not all reported as its own route. That includes a handler + * that forwards: a forward takes the status code off the request, and leaves the exception. */ @CompileStatic static class ObservationRouteHandler implements HandlerInterceptor { @Override boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { - if (request.getAttribute(WebUtils.ERROR_STATUS_CODE_ATTRIBUTE) != null) { + if (WebUtils.isError(request) || request.getAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE) != null) { return true } try { diff --git a/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMappingSpec.groovy b/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMappingSpec.groovy index 51855846bb2..e137bfb8bd2 100644 --- a/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMappingSpec.groovy +++ b/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMappingSpec.groovy @@ -329,6 +329,7 @@ class UrlMappingsHandlerMappingSpec extends AbstractUrlMappingsSpec { grailsApplication.initialise() def holder = new GrailsControllerUrlMappings(grailsApplication, getUrlMappingsHolder { "/foo/bar"(controller: 'foo', action: 'bar') + "/handled"(controller: 'foo', action: 'fooBar') "500"(controller: 'foo', action: 'fooBar') }) def handler = new UrlMappingsHandlerMapping(holder) @@ -354,6 +355,16 @@ class UrlMappingsHandlerMappingSpec extends AbstractUrlMappingsSpec { then: 'the error handler answers, and the route is still the one that failed' webRequest.actionName == 'fooBar' context.pathPattern == '/foo/bar' + + when: 'the error handler forwards, which takes the status code off the request and leaves the exception' + request.removeAttribute(WebUtils.ERROR_STATUS_CODE_ATTRIBUTE) + request.setAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE, new IllegalStateException('failed')) + request.requestURI = '/handled' + chain = handler.getHandler(request) + chain.interceptorList.each { it.preHandle(request, webRequest.response, chain.handler) } + + then: + context.pathPattern == '/foo/bar' } void cleanup() { From f58e481f24f0038355bfed365f2eaeaf9e0ab466 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Mon, 9 Nov 2026 08:24:53 -0800 Subject: [PATCH 59/78] Leave an include out of the observation of the page that includes it A failure inside g:include was recorded on the observation of the page that included it, although its error page was rendered inside that page and the page answered 200, so an alert on error values and a tracing handler took the page for failed. The resolver now leaves a failure on an include dispatch unrecorded, judged by how the dispatch began, since an error controller that answers inside the include forwards first. The example apps also showed that an action a page includes replaced the route of the page, as it does on 8.0.x, because ObservationRouteHandler ran for the include too. A page that failed after an include was reported under the included action. The route handler now leaves an include alone. GrailsExceptionResolverSpec includes a failing handler through GrailsDispatcherServlet, answered by the error view and by an error controller. The example apps have a page that includes a failing action, and one that fails after an include, on Tomcat, Jetty and Undertow. --- .../src/en/guide/upgrading/upgrading90x.adoc | 2 +- .../issue11102/FailingController.groovy | 13 ++++ .../FailedActionObservationSpec.groovy | 19 ++++++ .../issue12688/FailingController.groovy | 17 +++++ .../JettyFailedActionObservationSpec.groovy | 20 ++++++ .../undertowapp/FailingController.groovy | 17 +++++ ...UndertowFailedActionObservationSpec.groovy | 20 ++++++ .../web/errors/GrailsExceptionResolver.java | 6 ++ .../errors/GrailsExceptionResolverSpec.groovy | 67 ++++++++++++++++++- .../mvc/UrlMappingsHandlerMapping.groovy | 6 +- .../mvc/UrlMappingsHandlerMappingSpec.groovy | 27 ++++++++ 11 files changed, 209 insertions(+), 5 deletions(-) diff --git a/grails-doc/src/en/guide/upgrading/upgrading90x.adoc b/grails-doc/src/en/guide/upgrading/upgrading90x.adoc index 2892a52351c..5c004971d08 100644 --- a/grails-doc/src/en/guide/upgrading/upgrading90x.adoc +++ b/grails-doc/src/en/guide/upgrading/upgrading90x.adoc @@ -121,7 +121,7 @@ Both now report the exception the action threw and the route of the action, and That includes an `Error`, such as a failed `assert`, rather than the `ServletException` Spring MVC wraps it in. These requests were already counted with `outcome=SERVER_ERROR`, but an alert that counts a non-`none` `error` value will see more server errors than before, and a dashboard that reads the `uri` of an error controller will find those failures under the routes of the actions. After a forward to an error controller, the `jakarta.servlet.error.exception` request attribute holds the exception the action threw rather than a `GrailsWrappedRuntimeException`, for a filter that reads it once the chain has returned. Inside the error controller it still holds the wrapper. -A client error is not recorded. +A client error is not recorded, and neither is a failure inside `g:include`, whose error page is rendered inside a page that goes on to answer the request. A custom `ObservationConvention` can leave out the error for particular exceptions. * *`http.server.requests.active` is no longer registered by default.* diff --git a/grails-test-examples/issue-11102/grails-app/controllers/issue11102/FailingController.groovy b/grails-test-examples/issue-11102/grails-app/controllers/issue11102/FailingController.groovy index 60a6397d2a1..ac053e1c8b7 100644 --- a/grails-test-examples/issue-11102/grails-app/controllers/issue11102/FailingController.groovy +++ b/grails-test-examples/issue-11102/grails-app/controllers/issue11102/FailingController.groovy @@ -75,6 +75,19 @@ class FailingController { render 'never reached, because the interceptor fails' } + def failsAfterInclude() { + g.include(action: 'included') + throw new IllegalStateException('answered by the error view') + } + + def includesAnswerOfView() { + render "before ${g.include(action: 'answeredByView')} after" + } + + def included() { + render 'included' + } + def errorHandler() { render status: 500, text: 'Answered by the error controller' } diff --git a/grails-test-examples/issue-11102/src/integration-test/groovy/issue11102/FailedActionObservationSpec.groovy b/grails-test-examples/issue-11102/src/integration-test/groovy/issue11102/FailedActionObservationSpec.groovy index 15565b34b7e..51d5b44b97e 100644 --- a/grails-test-examples/issue-11102/src/integration-test/groovy/issue11102/FailedActionObservationSpec.groovy +++ b/grails-test-examples/issue-11102/src/integration-test/groovy/issue11102/FailedActionObservationSpec.groovy @@ -93,9 +93,28 @@ class FailedActionObservationSpec extends Specification implements HttpClientSup 'the error view, for an Error' | '/failing/answeredByViewForAnError' | '/failing/answeredByViewForAnError' | 'An error has occurred' || 'AssertionError' 'an error controller, for an Error' | '/failing/answeredByControllerForAnError' | '/failing/answeredByControllerForAnError' | 'Answered by the error controller' || 'StackOverflowError' 'an error controller that forwards' | '/failing/answeredByForwardingController' | '/failing/answeredByForwardingController' | 'Answered by the error controller' || 'ArithmeticException' + 'the error view, after an include' | '/failing/failsAfterInclude' | '/failing/failsAfterInclude' | 'An error has occurred' || 'IllegalStateException' 'an error controller, after an interceptor failed' | '/failing/failsInInterceptor' | '/failing/failsInInterceptor' | 'Answered by the error controller' || 'UnsupportedOperationException' } + void 'a failure #handler answers inside an include is not the failure of the page that included it'() { + when: + def response = http([(REQUEST_HEADER): path], path) + + then: 'the page answered, with the error page inside it' + response.assertContains(200, 'before').assertContains('after') + + and: 'its observation stopped on its own route, with no error' + new PollingConditions(timeout: 30).eventually { + assert STOPPED[path] == [path, 'none'] + } + !NOTIFIED.containsKey(path) + + where: + handler | path + 'the error view' | '/failing/includesAnswerOfView' + } + private List errorTags(String route) { meterRegistry.find('http.server.requests').tag('status', '500').tag('uri', route).timers()*.id*.getTag('error') } diff --git a/grails-test-examples/jetty/grails-app/controllers/issue12688/FailingController.groovy b/grails-test-examples/jetty/grails-app/controllers/issue12688/FailingController.groovy index 15b208942f1..3e5fa7d619b 100644 --- a/grails-test-examples/jetty/grails-app/controllers/issue12688/FailingController.groovy +++ b/grails-test-examples/jetty/grails-app/controllers/issue12688/FailingController.groovy @@ -70,6 +70,23 @@ class FailingController { forward(action: 'answeredByController') } + def failsAfterInclude() { + g.include(action: 'included') + throw new IllegalStateException('answered by the error view') + } + + def includesAnswerOfView() { + render "before ${g.include(action: 'answeredByView')} after" + } + + def includesAnswerOfController() { + render "before ${g.include(action: 'answeredByController')} after" + } + + def included() { + render 'included' + } + def errorHandler() { render status: 500, text: 'Answered by the error controller' } diff --git a/grails-test-examples/jetty/src/integration-test/groovy/issue12688/JettyFailedActionObservationSpec.groovy b/grails-test-examples/jetty/src/integration-test/groovy/issue12688/JettyFailedActionObservationSpec.groovy index ee1e357a8ba..b75f30ceffc 100644 --- a/grails-test-examples/jetty/src/integration-test/groovy/issue12688/JettyFailedActionObservationSpec.groovy +++ b/grails-test-examples/jetty/src/integration-test/groovy/issue12688/JettyFailedActionObservationSpec.groovy @@ -92,6 +92,26 @@ class JettyFailedActionObservationSpec extends Specification implements HttpClie 'the error view, for an Error' | '/failing/answeredByViewForAnError' | '/failing/answeredByViewForAnError' | 'An error has occurred' || 'AssertionError' 'an error controller, for an Error' | '/failing/answeredByControllerForAnError' | '/failing/answeredByControllerForAnError' | 'Answered by the error controller' || 'StackOverflowError' 'an error controller that forwards' | '/failing/answeredByForwardingController' | '/failing/answeredByForwardingController' | 'Answered by the error controller' || 'ArithmeticException' + 'the error view, after an include' | '/failing/failsAfterInclude' | '/failing/failsAfterInclude' | 'An error has occurred' || 'IllegalStateException' + } + + void 'a failure #handler answers inside an include is not the failure of the page that included it'() { + when: + def response = http([(REQUEST_HEADER): path], path) + + then: 'the page answered, with the error page inside it' + response.assertContains(200, 'before').assertContains('after') + + and: 'its observation stopped on its own route, with no error' + new PollingConditions(timeout: 30).eventually { + assert STOPPED[path] == [path, 'none'] + } + !NOTIFIED.containsKey(path) + + where: + handler | path + 'the error view' | '/failing/includesAnswerOfView' + 'an error controller' | '/failing/includesAnswerOfController' } private List errorTags(String route) { diff --git a/grails-test-examples/undertow/grails-app/controllers/undertowapp/FailingController.groovy b/grails-test-examples/undertow/grails-app/controllers/undertowapp/FailingController.groovy index c7e3170d8f2..60754fc0070 100644 --- a/grails-test-examples/undertow/grails-app/controllers/undertowapp/FailingController.groovy +++ b/grails-test-examples/undertow/grails-app/controllers/undertowapp/FailingController.groovy @@ -70,6 +70,23 @@ class FailingController { forward(action: 'answeredByController') } + def failsAfterInclude() { + g.include(action: 'included') + throw new IllegalStateException('answered by the error view') + } + + def includesAnswerOfView() { + render "before ${g.include(action: 'answeredByView')} after" + } + + def includesAnswerOfController() { + render "before ${g.include(action: 'answeredByController')} after" + } + + def included() { + render 'included' + } + def errorHandler() { render status: 500, text: 'Answered by the error controller' } diff --git a/grails-test-examples/undertow/src/integration-test/groovy/undertowapp/UndertowFailedActionObservationSpec.groovy b/grails-test-examples/undertow/src/integration-test/groovy/undertowapp/UndertowFailedActionObservationSpec.groovy index 9c17fb177f0..9c1027164ee 100644 --- a/grails-test-examples/undertow/src/integration-test/groovy/undertowapp/UndertowFailedActionObservationSpec.groovy +++ b/grails-test-examples/undertow/src/integration-test/groovy/undertowapp/UndertowFailedActionObservationSpec.groovy @@ -94,6 +94,26 @@ class UndertowFailedActionObservationSpec extends Specification implements HttpC 'the error view, for an Error' | '/failing/answeredByViewForAnError' | '/failing/answeredByViewForAnError' | 'An error has occurred' || 'AssertionError' 'an error controller, for an Error' | '/failing/answeredByControllerForAnError' | '/failing/answeredByControllerForAnError' | 'Answered by the error controller' || 'StackOverflowError' 'an error controller that forwards' | '/failing/answeredByForwardingController' | '/failing/answeredByForwardingController' | 'Answered by the error controller' || 'ArithmeticException' + 'the error view, after an include' | '/failing/failsAfterInclude' | '/failing/failsAfterInclude' | 'An error has occurred' || 'IllegalStateException' + } + + void 'a failure #handler answers inside an include is not the failure of the page that included it'() { + when: + def response = http([(REQUEST_HEADER): path], path) + + then: 'the page answered, with the error page inside it' + response.assertContains(200, 'before').assertContains('after') + + and: 'its observation stopped on its own route, with no error' + new PollingConditions(timeout: 30).eventually { + assert STOPPED[path] == [path, 'none'] + } + !NOTIFIED.containsKey(path) + + where: + handler | path + 'the error view' | '/failing/includesAnswerOfView' + 'an error controller' | '/failing/includesAnswerOfController' } private List errorTags(String route) { diff --git a/grails-web-mvc/src/main/groovy/org/grails/web/errors/GrailsExceptionResolver.java b/grails-web-mvc/src/main/groovy/org/grails/web/errors/GrailsExceptionResolver.java index 6c477ff020d..d9e970cdda3 100644 --- a/grails-web-mvc/src/main/groovy/org/grails/web/errors/GrailsExceptionResolver.java +++ b/grails-web-mvc/src/main/groovy/org/grails/web/errors/GrailsExceptionResolver.java @@ -179,10 +179,16 @@ public static Runnable holdFailureLeftOnRequest(HttpServletRequest request) { *

* An exception left in {@link WebUtils#ERROR_EXCEPTION_ATTRIBUTE} is not recorded here when it is recorded from there * once the dispatch returns, so that the handlers hear of it once. A dispatch that holds it decides when it returns. + *

+ * A failure inside an include is not recorded: its error page is rendered inside the page that included it, which + * goes on to answer the request. * * @param dispatchedAs how the request was dispatched before an error handler was forwarded to */ private static void recordServerError(HttpServletRequest request, Throwable ex, DispatcherType dispatchedAs) { + if (dispatchedAs == DispatcherType.INCLUDE) { + return; + } if (request.getAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE) == ex && request.getAttribute(FAILURE_LEFT_ON_REQUEST_ATTRIBUTE) instanceof FailureLeftOnRequest held) { held.failure = ex; diff --git a/grails-web-mvc/src/test/groovy/org/grails/web/errors/GrailsExceptionResolverSpec.groovy b/grails-web-mvc/src/test/groovy/org/grails/web/errors/GrailsExceptionResolverSpec.groovy index ac43d3d5d82..ae4fa2cc033 100644 --- a/grails-web-mvc/src/test/groovy/org/grails/web/errors/GrailsExceptionResolverSpec.groovy +++ b/grails-web-mvc/src/test/groovy/org/grails/web/errors/GrailsExceptionResolverSpec.groovy @@ -76,6 +76,7 @@ import jakarta.servlet.ServletRequest import jakarta.servlet.ServletResponse import jakarta.servlet.http.HttpServletRequest import jakarta.servlet.http.HttpServletResponse +import jakarta.servlet.http.HttpServletResponseWrapper class GrailsExceptionResolverSpec extends Specification { @@ -283,6 +284,38 @@ class GrailsExceptionResolverSpec extends Specification { 'an action threw an Error DispatcherServlet wrapped' | new ServletException("Handler dispatch failed: $FAILED_ASSERT", FAILED_ASSERT) | FAILED_ASSERT } + void 'an exception #handler answers inside an include is not recorded on the observation of the page that included it'() { + given: 'the Grails dispatcher servlet behind the filter, and a page that includes a handler that fails' + ServerRequestObservationContext observed = null + List notified = [] + def registry = registryReporting({ observed = it }, { notified << it }) + def resolver = resolverFor(mappings, controllerMappings) + def servlet = dispatcherServletWith(resolver, [ + '/page' : { req, res -> req.getRequestDispatcher('/failing').include(req, res); null } as Controller, + '/failing': { req, res -> throw FAILURE } as Controller]) + def request = new ForwardingRequest(servletContext, '/page', servlet, ['/page', '/failing'] as Set, true) + def response = new MockHttpServletResponse() + + when: + new ServerHttpObservationFilter(registry).doFilter(request, response, { req, res -> + servlet.service(req, res) + } as FilterChain) + + then: 'the error page answered inside the page, which answered the request' + response.status == 200 + response.includedUrls == included + response.forwardedUrl == forwarded + + and: 'so the request did not fail' + observed.error == null + notified.empty + + where: + handler | mappings | controllerMappings | included | forwarded + 'the error view' | { '500'(view: '/error') } | false | ['/error'] | null + 'an error controller' | { '500'(controller: 'errors', action: 'serverError') } | true | [] | '/errors/serverError' + } + void 'an exception is resolved as usual without an observation'() { when: def response = new MockHttpServletResponse() @@ -944,8 +977,8 @@ class GrailsExceptionResolverSpec extends Specification { } /** - * A request whose forwards to the handlers of a servlet dispatch through it, and which reads as the forward once it - * has returned, unless the container restores it, as Tomcat and Jetty do and Undertow does not. + * A request whose forwards and includes to the handlers of a servlet dispatch through it, and which reads as the + * forward once it has returned, unless the container restores it, as Tomcat and Jetty do and Undertow does not. */ private static class ForwardingRequest extends MockHttpServletRequest { @@ -982,10 +1015,40 @@ class GrailsExceptionResolverSpec extends Specification { forwarded.requestURI = requestURI } } + + @Override + void include(ServletRequest request, ServletResponse response) { + if (!(path in forwarded.handled)) { + super.include(request, response) + return + } + DispatcherType dispatchedAs = forwarded.dispatcherType + forwarded.dispatcherType = DispatcherType.INCLUDE + forwarded.setAttribute(WebUtils.INCLUDE_REQUEST_URI_ATTRIBUTE, path) + try { + forwarded.servlet.service(request, new IncludedResponse((HttpServletResponse) response)) + } + finally { + forwarded.removeAttribute(WebUtils.INCLUDE_REQUEST_URI_ATTRIBUTE) + forwarded.dispatcherType = dispatchedAs + } + } } } } + /** The response an include writes to, which cannot change the status of the response that includes it. */ + private static class IncludedResponse extends HttpServletResponseWrapper { + + IncludedResponse(HttpServletResponse response) { + super(response) + } + + @Override + void setStatus(int status) { + } + } + /** A request that still reads as a forward once a forward has returned, as Undertow leaves it. */ private static class ForwardLeftOnRequest extends MockHttpServletRequest { diff --git a/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMapping.groovy b/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMapping.groovy index a0c9dae0095..32485cdea50 100644 --- a/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMapping.groovy +++ b/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMapping.groovy @@ -230,14 +230,16 @@ class UrlMappingsHandlerMapping extends AbstractHandlerMapping { * instead of {@code UNKNOWN}. Runs at {@code preHandle}: at URL-mapping match the observation * context is not yet on the request. A request routed to an error handler keeps the route that failed, so * that the failures an error handler answers are not all reported as its own route. That includes a handler - * that forwards: a forward takes the status code off the request, and leaves the exception. + * that forwards: a forward takes the status code off the request, and leaves the exception. An action a page + * includes is part of that page, so it leaves the route of the page. */ @CompileStatic static class ObservationRouteHandler implements HandlerInterceptor { @Override boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { - if (WebUtils.isError(request) || request.getAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE) != null) { + if (WebUtils.isError(request) || request.getAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE) != null || + WebUtils.isInclude(request)) { return true } try { diff --git a/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMappingSpec.groovy b/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMappingSpec.groovy index e137bfb8bd2..4a6228ac825 100644 --- a/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMappingSpec.groovy +++ b/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMappingSpec.groovy @@ -367,6 +367,33 @@ class UrlMappingsHandlerMappingSpec extends AbstractUrlMappingsSpec { context.pathPattern == '/foo/bar' } + void "an action a page includes leaves the route of the page on its observation"() { + given: + def grailsApplication = new DefaultGrailsApplication(FooController) + grailsApplication.initialise() + def holder = new GrailsControllerUrlMappings(grailsApplication, getUrlMappingsHolder { + "/foo/bar"(controller: 'foo', action: 'bar') + "/included"(controller: 'foo', action: 'fooBar') + }) + def handler = new UrlMappingsHandlerMapping(holder) + def webRequest = GrailsWebMockUtil.bindMockWebRequest() + def request = webRequest.request + request.requestURI = '/foo/bar' + def context = new ServerRequestObservationContext(request, webRequest.response) + request.setAttribute(ServerHttpObservationFilter.CURRENT_OBSERVATION_CONTEXT_ATTRIBUTE, context) + def chain = handler.getHandler(request) + chain.interceptorList.each { it.preHandle(request, webRequest.response, chain.handler) } + + when: 'the page includes another action' + request.setAttribute(WebUtils.INCLUDE_REQUEST_URI_ATTRIBUTE, '/included') + request.requestURI = '/included' + chain = handler.getHandler(request) + chain.interceptorList.each { it.preHandle(request, webRequest.response, chain.handler) } + + then: + context.pathPattern == '/foo/bar' + } + void cleanup() { RequestContextHolder.resetRequestAttributes() } From 4c27c50275281e4ed1f1306bccf5eddedc2974cc Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Mon, 9 Nov 2026 08:24:54 -0800 Subject: [PATCH 60/78] Correct the upgrade note on routes, and drop an opt-out that does not work The note offered a custom ObservationConvention to leave out the error, but the error tag comes from the meter handler, which reads the error of the context, and the handlers have been told of it by the time a convention runs. There is no opt-out to offer, so the bullet is gone. It also left out that the route is now set before the Grails interceptors, so an interceptor whose before() returns false, as one that renders a 403 does, is reported under the route of the action rather than UNKNOWN or REDIRECTION. The Tomcat example app checks that, and that a status code handler the container sends a request to leaves its route as it was, as it must: the observation has stopped by then. --- .../src/en/guide/upgrading/upgrading90x.adoc | 4 ++- .../issue11102/DenyingInterceptor.groovy | 31 +++++++++++++++++++ .../issue11102/FailingController.groovy | 12 +++++++ .../controllers/issue11102/UrlMappings.groovy | 2 +- .../FailedActionObservationSpec.groovy | 22 +++++++++++++ 5 files changed, 69 insertions(+), 2 deletions(-) create mode 100644 grails-test-examples/issue-11102/grails-app/controllers/issue11102/DenyingInterceptor.groovy diff --git a/grails-doc/src/en/guide/upgrading/upgrading90x.adoc b/grails-doc/src/en/guide/upgrading/upgrading90x.adoc index 5c004971d08..418460783f5 100644 --- a/grails-doc/src/en/guide/upgrading/upgrading90x.adoc +++ b/grails-doc/src/en/guide/upgrading/upgrading90x.adoc @@ -122,7 +122,9 @@ That includes an `Error`, such as a failed `assert`, rather than the `ServletExc These requests were already counted with `outcome=SERVER_ERROR`, but an alert that counts a non-`none` `error` value will see more server errors than before, and a dashboard that reads the `uri` of an error controller will find those failures under the routes of the actions. After a forward to an error controller, the `jakarta.servlet.error.exception` request attribute holds the exception the action threw rather than a `GrailsWrappedRuntimeException`, for a filter that reads it once the chain has returned. Inside the error controller it still holds the wrapper. A client error is not recorded, and neither is a failure inside `g:include`, whose error page is rendered inside a page that goes on to answer the request. -A custom `ObservationConvention` can leave out the error for particular exceptions. +The route is now set before the Grails interceptors run, so that a failure in one is reported under the route of the action. +An interceptor whose `before()` returns `false`, to render a 403 or to redirect, stopped the request before its route was set, so the request was reported with a `uri` of `UNKNOWN`, or `REDIRECTION` for a redirect. +It is now reported under the route of the action, so a dashboard or alert keyed on those `uri` values sees those requests move. * *`http.server.requests.active` is no longer registered by default.* Spring Boot 4.2 makes this long task timer opt-in. diff --git a/grails-test-examples/issue-11102/grails-app/controllers/issue11102/DenyingInterceptor.groovy b/grails-test-examples/issue-11102/grails-app/controllers/issue11102/DenyingInterceptor.groovy new file mode 100644 index 00000000000..65e68f36b1e --- /dev/null +++ b/grails-test-examples/issue-11102/grails-app/controllers/issue11102/DenyingInterceptor.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 issue11102 + +class DenyingInterceptor { + + DenyingInterceptor() { + match(controller: 'failing', action: 'deniedByInterceptor') + } + + boolean before() { + render status: 403, text: 'Denied by the interceptor' + false + } +} diff --git a/grails-test-examples/issue-11102/grails-app/controllers/issue11102/FailingController.groovy b/grails-test-examples/issue-11102/grails-app/controllers/issue11102/FailingController.groovy index ac053e1c8b7..088dc227243 100644 --- a/grails-test-examples/issue-11102/grails-app/controllers/issue11102/FailingController.groovy +++ b/grails-test-examples/issue-11102/grails-app/controllers/issue11102/FailingController.groovy @@ -75,6 +75,18 @@ class FailingController { render 'never reached, because the interceptor fails' } + def deniedByInterceptor() { + render 'never reached, because the interceptor denies it' + } + + def sendsNotFound() { + response.sendError(404) + } + + def notFoundHandler() { + render status: 404, text: 'Answered by the not found handler' + } + def failsAfterInclude() { g.include(action: 'included') throw new IllegalStateException('answered by the error view') diff --git a/grails-test-examples/issue-11102/grails-app/controllers/issue11102/UrlMappings.groovy b/grails-test-examples/issue-11102/grails-app/controllers/issue11102/UrlMappings.groovy index 1bc22d7f735..684d60b8aa0 100644 --- a/grails-test-examples/issue-11102/grails-app/controllers/issue11102/UrlMappings.groovy +++ b/grails-test-examples/issue-11102/grails-app/controllers/issue11102/UrlMappings.groovy @@ -38,6 +38,6 @@ class UrlMappings { "500"(controller: 'failing', action: 'errorHandler', exception: StackOverflowError) "500"(controller: 'failing', action: 'forwardingErrorHandler', exception: ArithmeticException) "500"(view:'/error') - "404"(view:'/notFound') + "404"(controller: 'failing', action: 'notFoundHandler') } } diff --git a/grails-test-examples/issue-11102/src/integration-test/groovy/issue11102/FailedActionObservationSpec.groovy b/grails-test-examples/issue-11102/src/integration-test/groovy/issue11102/FailedActionObservationSpec.groovy index 51d5b44b97e..1eebb857090 100644 --- a/grails-test-examples/issue-11102/src/integration-test/groovy/issue11102/FailedActionObservationSpec.groovy +++ b/grails-test-examples/issue-11102/src/integration-test/groovy/issue11102/FailedActionObservationSpec.groovy @@ -115,6 +115,28 @@ class FailedActionObservationSpec extends Specification implements HttpClientSup 'the error view' | '/failing/includesAnswerOfView' } + void 'a request #what is reported under #reported'() { + when: + def response = http([(REQUEST_HEADER): path], path) + + then: + response.assertContains(status, page) + + and: 'the route is set before the interceptors, and the container sends a request to a status code handler once its observation has stopped' + new PollingConditions(timeout: 30).eventually { + assert STOPPED[path] == [route, 'none'] + } + !NOTIFIED.containsKey(path) + + where: + what | path | status | page || route + 'an interceptor denied' | '/failing/deniedByInterceptor' | 403 | 'Denied by the interceptor' || '/failing/deniedByInterceptor' + 'whose action sent a 404, answered by a status handler' | '/failing/sendsNotFound' | 404 | 'Answered by the not found handler' || '/failing/sendsNotFound' + 'for a URL nothing maps, answered by a status handler' | '/nowhere' | 404 | 'Answered by the not found handler' || 'none' + + reported = route == 'none' ? 'no route' : 'its own route' + } + private List errorTags(String route) { meterRegistry.find('http.server.requests').tag('status', '500').tag('uri', route).timers()*.id*.getTag('error') } From 0842986821e97eaecf143220b2ae3bb672333434 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Mon, 9 Nov 2026 08:24:54 -0800 Subject: [PATCH 61/78] Wait up to 30 seconds for the observation in the failed-action specs 5 seconds is short for the slower GitHub runners. eventually returns as soon as the condition holds, so a passing run is no slower. --- .../groovy/issue11102/FailedActionObservationSpec.groovy | 2 +- .../groovy/issue12688/JettyFailedActionObservationSpec.groovy | 2 +- .../undertowapp/UndertowFailedActionObservationSpec.groovy | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/grails-test-examples/issue-11102/src/integration-test/groovy/issue11102/FailedActionObservationSpec.groovy b/grails-test-examples/issue-11102/src/integration-test/groovy/issue11102/FailedActionObservationSpec.groovy index 1eebb857090..05d6ddca417 100644 --- a/grails-test-examples/issue-11102/src/integration-test/groovy/issue11102/FailedActionObservationSpec.groovy +++ b/grails-test-examples/issue-11102/src/integration-test/groovy/issue11102/FailedActionObservationSpec.groovy @@ -70,7 +70,7 @@ class FailedActionObservationSpec extends Specification implements HttpClientSup response.assertContains(500, page) and: 'the observation stopped on the route that failed with what failed, as its metrics say' - new PollingConditions(timeout: 5).eventually { + new PollingConditions(timeout: 30).eventually { assert STOPPED[path] == [route, exception] assert exception in errorTags(route) } diff --git a/grails-test-examples/jetty/src/integration-test/groovy/issue12688/JettyFailedActionObservationSpec.groovy b/grails-test-examples/jetty/src/integration-test/groovy/issue12688/JettyFailedActionObservationSpec.groovy index b75f30ceffc..29d9afabed7 100644 --- a/grails-test-examples/jetty/src/integration-test/groovy/issue12688/JettyFailedActionObservationSpec.groovy +++ b/grails-test-examples/jetty/src/integration-test/groovy/issue12688/JettyFailedActionObservationSpec.groovy @@ -69,7 +69,7 @@ class JettyFailedActionObservationSpec extends Specification implements HttpClie response.assertContains(500, page) and: 'the observation stopped on the route that failed with what failed, as its metrics say' - new PollingConditions(timeout: 5).eventually { + new PollingConditions(timeout: 30).eventually { assert STOPPED[path] == [route, exception] assert exception in errorTags(route) } diff --git a/grails-test-examples/undertow/src/integration-test/groovy/undertowapp/UndertowFailedActionObservationSpec.groovy b/grails-test-examples/undertow/src/integration-test/groovy/undertowapp/UndertowFailedActionObservationSpec.groovy index 9c1027164ee..e6b7e7682f8 100644 --- a/grails-test-examples/undertow/src/integration-test/groovy/undertowapp/UndertowFailedActionObservationSpec.groovy +++ b/grails-test-examples/undertow/src/integration-test/groovy/undertowapp/UndertowFailedActionObservationSpec.groovy @@ -71,7 +71,7 @@ class UndertowFailedActionObservationSpec extends Specification implements HttpC response.assertContains(500, page) and: 'the observation stopped on the route that failed with what failed, as its metrics say' - new PollingConditions(timeout: 5).eventually { + new PollingConditions(timeout: 30).eventually { assert STOPPED[path] == [route, exception] assert exception in errorTags(route) } From bedc91f27684ea2d59d5ac14262fcafd9e2e0467 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Mon, 9 Nov 2026 08:11:38 -0800 Subject: [PATCH 62/78] Serve the embedded MongoDB's first request on the port it bound, whatever the reply The in-memory backend has its server answer one isMaster as it starts, so the event loop loads what the first client needs before Spring Boot closes the jars of an executable jar. Two things were wrong with it. It connected to the port that was asked for, so a server asked for port 0, as mongodb://embedded:0/db asks, was never sent the request. It now connects to the address the server reports it bound. It read the reply's length with ByteBuffer.getInt, which throws BufferUnderflowException when the reply ends within its first four bytes, and read the rest with readNBytes, which throws IllegalArgumentException for a length below four. Neither is an IOException, so neither was caught: start() threw with the server it had bound still listening, and the initializer reported the failure as a port something else may be using. The reply is now read with DataInputStream.readInt, which reports a short reply as an EOFException, and skipNBytes, which skips nothing for such a length. The request is best-effort by design - whatever goes wrong goes wrong again for the first real client, where it says more - so a failure is logged at debug and the started server is handed back. InMemoryMongoBackendSpec starts a server on port 0 through a class loader that records what it loads, and sees the server encode a reply; with the old port it never does. It also points the request, through a package-private seam like FlapdoodleMongoBackend's, at a peer answering short, with a bad length or cut short, and sees the server handed back and answering a driver. Four of those five rows fail with the old reading, with the exceptions above. --- .../embedded/InMemoryMongoBackend.java | 43 +++++-- .../embedded/InMemoryMongoBackendSpec.groovy | 110 ++++++++++++++++++ 2 files changed, 141 insertions(+), 12 deletions(-) diff --git a/grails-data-mongodb/embedded/src/main/java/org/grails/datastore/gorm/mongodb/embedded/InMemoryMongoBackend.java b/grails-data-mongodb/embedded/src/main/java/org/grails/datastore/gorm/mongodb/embedded/InMemoryMongoBackend.java index 0b078a57689..85035750331 100644 --- a/grails-data-mongodb/embedded/src/main/java/org/grails/datastore/gorm/mongodb/embedded/InMemoryMongoBackend.java +++ b/grails-data-mongodb/embedded/src/main/java/org/grails/datastore/gorm/mongodb/embedded/InMemoryMongoBackend.java @@ -18,8 +18,9 @@ */ package org.grails.datastore.gorm.mongodb.embedded; +import java.io.DataInputStream; import java.io.IOException; -import java.io.InputStream; +import java.net.InetSocketAddress; import java.net.Socket; import java.nio.ByteBuffer; import java.nio.ByteOrder; @@ -28,6 +29,8 @@ import de.bwaldvogel.mongo.MongoServer; import de.bwaldvogel.mongo.backend.memory.MemoryBackend; import io.netty.buffer.ByteBufAllocator; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.util.ClassUtils; @@ -60,6 +63,8 @@ public class InMemoryMongoBackend implements EmbeddedMongoBackend { private static final byte BSON_INT32 = 0x10; + private static final Logger log = LoggerFactory.getLogger(InMemoryMongoBackend.class); + @Override public String getName() { return NAME; @@ -89,16 +94,27 @@ public RunningEmbeddedMongo start(EmbeddedMongoSettings settings) { MemoryBackend backend = new RetainingMemoryBackend(); MongoServer server = new MongoServer(backend); server.bind("localhost", settings.getPort()); - serveOneRequest(settings.getPort()); + serveOneRequest(addressOf(server)); allocateUntilOneBufferIsTracked(); return new RunningInMemoryMongo(backend, server); } + /** + * Where {@link #serveOneRequest(InetSocketAddress)} sends its request: the address the server has + * just bound, which is not the port asked for when that was 0. + * + *

Not private, so that the specification can put a peer there that answers as no server would, + * and see that the server this started is handed back all the same. + */ + InetSocketAddress addressOf(MongoServer server) { + return server.getLocalAddress(); + } + /** * Allocates buffers until Netty's leak detection has tracked one, so that what only a tracked * buffer needs is loaded as well. Netty picks the buffers it tracks at random, so the request - * {@link #serveOneRequest(int)} sends rarely gets that far, and a buffer picked while the jars are - * closed fails as the first one would. + * {@link #serveOneRequest(InetSocketAddress)} sends rarely gets that far, and a buffer picked while + * the jars are closed fails as the first one would. */ private static void allocateUntilOneBufferIsTracked() { for (int i = 0; i < ALLOCATIONS_TO_TRACK_ONE_BUFFER; i++) { @@ -118,19 +134,22 @@ private static void allocateUntilOneBufferIsTracked() { * stopping the server waits forever for them to close. * *

Whatever goes wrong here goes wrong again for the first real client, where it says more, so - * it is not reported. + * it is only logged, and the server is handed back all the same. That includes a reply that is + * cut short or gives a length it cannot have: the reply is read with what reports the end of the + * stream as an {@link IOException}, and a length shorter than the one already read skips nothing. */ - private static void serveOneRequest(int port) { - try (Socket client = new Socket("localhost", port)) { + private static void serveOneRequest(InetSocketAddress address) { + try (Socket client = new Socket()) { + client.connect(address, SERVE_ONE_REQUEST_TIMEOUT_MILLIS); client.setSoTimeout(SERVE_ONE_REQUEST_TIMEOUT_MILLIS); client.getOutputStream().write(isMaster()); // the whole reply, since closing with some of it unread resets the connection, which the server logs as an error - InputStream reply = client.getInputStream(); - int length = ByteBuffer.wrap(reply.readNBytes(4)).order(ByteOrder.LITTLE_ENDIAN).getInt(); - reply.readNBytes(length - 4); + DataInputStream reply = new DataInputStream(client.getInputStream()); + int length = Integer.reverseBytes(reply.readInt()); + reply.skipNBytes(length - (long) Integer.BYTES); } - catch (IOException ignored) { - return; + catch (IOException ex) { + log.debug("The embedded MongoDB at {} did not answer the request it serves as it starts", address, ex); } } diff --git a/grails-data-mongodb/embedded/src/test/groovy/org/grails/datastore/gorm/mongodb/embedded/InMemoryMongoBackendSpec.groovy b/grails-data-mongodb/embedded/src/test/groovy/org/grails/datastore/gorm/mongodb/embedded/InMemoryMongoBackendSpec.groovy index 8e50972c8c0..c4f318f6740 100644 --- a/grails-data-mongodb/embedded/src/test/groovy/org/grails/datastore/gorm/mongodb/embedded/InMemoryMongoBackendSpec.groovy +++ b/grails-data-mongodb/embedded/src/test/groovy/org/grails/datastore/gorm/mongodb/embedded/InMemoryMongoBackendSpec.groovy @@ -20,11 +20,19 @@ package org.grails.datastore.gorm.mongodb.embedded import com.mongodb.client.MongoClient import com.mongodb.client.MongoClients +import de.bwaldvogel.mongo.MongoServer import org.bson.Document import spock.lang.Specification +import java.nio.ByteBuffer +import java.nio.ByteOrder +import java.nio.charset.StandardCharsets +import java.util.concurrent.CompletableFuture +import java.util.concurrent.ConcurrentHashMap +import java.util.concurrent.TimeUnit + class InMemoryMongoBackendSpec extends Specification { InMemoryMongoBackend backend = new InMemoryMongoBackend() @@ -95,6 +103,62 @@ class InMemoryMongoBackendSpec extends Specification { running?.stop() } + void 'a server asked for any free port serves the request it sends itself on the port it bound'() { + given: 'the backend loaded by a class loader of its own, which notes the classes the server loads' + RecordingClassLoader loader = new RecordingClassLoader() + def inMemory = loader.loadClass(InMemoryMongoBackend.name).getConstructor().newInstance() + def settings = loader.loadClass(EmbeddedMongoSettings.name) + .getConstructor(int, String, String).newInstance(0, null, null) + + when: + def running = inMemory.start(settings) + + then: 'the server bound a port of its own' + running.port > 0 + + and: 'it has encoded a reply, which nothing but a request makes it do' + loader.loaded.contains('de.bwaldvogel.mongo.wire.bson.BsonEncoder') + + cleanup: + running?.stop() + loader?.close() + } + + void 'a reply #description to the request the server is sent as it starts does not keep it from being handed back'() { + given: 'a peer that answers that request the way no MongoDB does' + ServerSocket peer = new ServerSocket(0, 1, InetAddress.loopbackAddress) + peer.soTimeout = 10000 + CompletableFuture request = CompletableFuture.supplyAsync { answer(peer, reply as byte[]) } + InMemoryMongoBackend sendingToThePeer = new InMemoryMongoBackend() { + @Override + InetSocketAddress addressOf(MongoServer server) { + peer.localSocketAddress as InetSocketAddress + } + } + + when: + RunningEmbeddedMongo running = sendingToThePeer.start(new EmbeddedMongoSettings(0, null, null)) + + then: 'the request reached the peer' + new String(request.get(10, TimeUnit.SECONDS), StandardCharsets.ISO_8859_1).contains('isMaster') + + and: 'the server that was started is handed back, and answers a client' + insertOneDocument(running.host, running.port) + countDocuments(running.host, running.port) == 1 + + cleanup: + running?.stop() + peer?.close() + + where: + description | reply + 'that ends before it gives a length' | [] + 'that ends part way through its length' | [16, 0] + 'giving a length shorter than the length itself' | littleEndian(2) + 'giving a negative length' | littleEndian(-1) + 'that ends before the length it gave' | littleEndian(64) + [1, 2, 3] + } + private static void insertOneDocument(String host, int port) { try (MongoClient client = MongoClients.create("mongodb://${host}:${port}")) { client.getDatabase('test').getCollection('things').insertOne(new Document('name', 'Bob')) @@ -106,4 +170,50 @@ class InMemoryMongoBackendSpec extends Specification { return client.getDatabase('test').getCollection('things').countDocuments() } } + + /** + * Reads the whole request, so that closing does not reset the connection, then answers with the + * reply and waits for the client to close its end. + */ + private static byte[] answer(ServerSocket peer, byte[] reply) { + peer.accept().withCloseable { Socket client -> + DataInputStream input = new DataInputStream(client.inputStream) + byte[] length = input.readNBytes(Integer.BYTES) + byte[] rest = input.readNBytes(ByteBuffer.wrap(length).order(ByteOrder.LITTLE_ENDIAN).int - Integer.BYTES) + client.outputStream.write(reply) + client.outputStream.flush() + client.shutdownOutput() + input.read() + (length.toList() + rest.toList()) as byte[] + } + } + + private static List littleEndian(int value) { + ByteBuffer.allocate(Integer.BYTES).order(ByteOrder.LITTLE_ENDIAN).putInt(value).array().toList() + } + + /** + * Loads the server's classes itself rather than leaving them to the class loader the spec runs in, + * whose classes other features have already loaded, and notes each one it does. + */ + private static final class RecordingClassLoader extends URLClassLoader { + + final Set loaded = ConcurrentHashMap.newKeySet() + + RecordingClassLoader() { + super(classPath(), ClassLoader.platformClassLoader) + } + + @Override + protected Class findClass(String name) throws ClassNotFoundException { + Class found = super.findClass(name) + loaded << name + found + } + + private static URL[] classPath() { + System.getProperty('java.class.path').split(File.pathSeparator) + .collect { String entry -> new File(entry).toURI().toURL() } as URL[] + } + } } From da2ca8e7a12ac8be6875b3a99b3ad64c96e71d02 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Mon, 9 Nov 2026 08:25:05 -0800 Subject: [PATCH 63/78] Move every Boot-managed Hibernate ORM module with hibernate7VersionOverride grails-hibernate7-bom strictly re-declares hibernate-core, hibernate-envers and hibernate-jcache at the Hibernate ORM version it manages. With hibernate7VersionOverride set, that left every other org.hibernate.orm module spring-boot-dependencies manages - hibernate-hikaricp, hibernate-processor, hibernate-micrometer and nine more - at Spring Boot's version for an enforcedPlatform consumer, while the published hibernate.version moves them all for a Maven consumer. With the override set, the BOM now also re-declares, strictly and at the override, every org.hibernate.orm artifact in the dependencyManagement of spring-boot-dependencies' own POM, which configuring the project already reads; PomVersions.managedArtifactIds lists them without reading the BOMs it imports or resolving anything more. The list is derived rather than kept in dependencies.gradle so that a module Spring Boot adds is moved without anyone having to notice it. With the override unset nothing changes: the published POM and Gradle module metadata are byte-identical to before. PomVersionsSpec covers the derivation: the group's own entries in order and once each, its group written as ${project.groupId}, and neither an imported BOM, a managed plugin nor another group. Set to 7.4.15.Final locally, the override published all 15 modules at it under ${hibernate.version}, where before it published 3, and validateHibernateVersion and validateBomProperties passed. --- .agents/skills/gradle-developer/SKILL.md | 2 +- .../apache/grails/buildsrc/PomVersions.groovy | 16 +++++++++++++ .../grails/buildsrc/PomVersionsSpec.groovy | 24 +++++++++++++++++++ dependencies.gradle | 2 ++ grails-bom/hibernate7/build.gradle | 17 ++++++++++--- 5 files changed, 57 insertions(+), 4 deletions(-) diff --git a/.agents/skills/gradle-developer/SKILL.md b/.agents/skills/gradle-developer/SKILL.md index 204b7d6c1eb..47b3cb149aa 100644 --- a/.agents/skills/gradle-developer/SKILL.md +++ b/.agents/skills/gradle-developer/SKILL.md @@ -366,7 +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`; `validateHibernateVersion` fails while it is not newer than Spring Boot's version, so a Boot bump that catches up forces its removal. It also fails when `hibernate-models.version` differs from the version the managed Hibernate ORM release depends on. Configuring the project reads only `spring-boot-dependencies`' own entry for `hibernate-core` (`PomVersions.managedVersion`), never the BOMs it imports, so a task that resolves none of them does not fail when one is missing from the cache; both checks resolve in the task's inputs, and `check` and the BOM's POM generation run it. +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 BOM then strictly re-declares at it every `org.hibernate.orm` module `spring-boot-dependencies` manages in its own POM (`PomVersions.managedArtifactIds`), not only `hibernateOrmModules`, so `enforcedPlatform` consumers move the whole family as a Maven consumer setting `hibernate.version` does. `validateHibernateVersion` fails while it is not newer than Spring Boot's version, so a Boot bump that catches up forces its removal. It also fails when `hibernate-models.version` differs from the version the managed Hibernate ORM release depends on. Configuring the project reads only `spring-boot-dependencies`' own entry for `hibernate-core` (`PomVersions.managedVersion`), never the BOMs it imports, so a task that resolves none of them does not fail when one is missing from the cache; both checks resolve in the task's inputs, and `check` and the BOM's POM generation run it. ### Exclusions diff --git a/build-logic/plugins/src/main/groovy/org/apache/grails/buildsrc/PomVersions.groovy b/build-logic/plugins/src/main/groovy/org/apache/grails/buildsrc/PomVersions.groovy index 5a3f1b6c896..d4a82bd4a4d 100644 --- a/build-logic/plugins/src/main/groovy/org/apache/grails/buildsrc/PomVersions.groovy +++ b/build-logic/plugins/src/main/groovy/org/apache/grails/buildsrc/PomVersions.groovy @@ -95,6 +95,22 @@ class PomVersions { version } + /** + * Returns the artifacts of {@code groupId} the model's own {@code } manages, in + * the order it lists them. As with {@link #managedVersion}, the BOMs it imports are not read, so this + * resolves no other POM; {@code } is not read either, since it manages plugins. + * An entry whose coordinates cannot be resolved from the model's own properties is not included. + */ + static List managedArtifactIds(Model model, String groupId) { + Map properties = properties(model) + String prefix = "${groupId}:" + managedDependencies(model).findAll { Dependency dependency -> !isImport(dependency) } + .collect { Dependency dependency -> key(dependency, properties) } + .findAll { String module -> module?.startsWith(prefix) } + .collect { String module -> module.substring(prefix.length()) } + .unique() + } + /** * The properties the model's coordinates and versions may refer to: its own * {@code }, and the Maven built-ins, which are never declared there. A parent POM's diff --git a/build-logic/plugins/src/test/groovy/org/apache/grails/buildsrc/PomVersionsSpec.groovy b/build-logic/plugins/src/test/groovy/org/apache/grails/buildsrc/PomVersionsSpec.groovy index 8e090bab914..ba12973d0a1 100644 --- a/build-logic/plugins/src/test/groovy/org/apache/grails/buildsrc/PomVersionsSpec.groovy +++ b/build-logic/plugins/src/test/groovy/org/apache/grails/buildsrc/PomVersionsSpec.groovy @@ -37,7 +37,10 @@ import org.apache.maven.model.Model * test:lib-literal 5.0 * ${project.groupId}:lib-own ${project.version} * test:lib-inherited ${inherited.version} - declared only by the parent POM + * other:lib-other 2.0 + * test:lib-literal:tests 5.0 - the same artifact again, with a classifier * test:family-bom ${family-bom.version} = 3.0, imported, and managing test:family-core + * test:test-maven-plugin 1.0 - in pluginManagement * */ class PomVersionsSpec extends Specification { @@ -67,12 +70,21 @@ class PomVersionsSpec extends Specification { testlib-literal5.0 ${project.groupId}lib-own${project.version} testlib-inherited${inherited.version} + otherlib-other2.0 + testlib-literal5.0tests testfamily-bom${family-bom.version} pomimport + + + + testtest-maven-plugin1.0 + + + ''' bom = PomVersions.read(pom) @@ -108,4 +120,16 @@ class PomVersionsSpec extends Specification { GradleException e = thrown() e.message == 'Cannot resolve test:lib-inherited:${inherited.version}, managed by test:parent-bom:1.0, from that POM\'s own properties.' } + + def "the artifacts of a group are the ones the BOM's own entries list, in their order and each once"() { + expect: 'its own group resolved, and neither the BOM it imports, the plugin it manages nor the other group' + PomVersions.managedArtifactIds(bom, 'test') == ['lib-a', 'lib-literal', 'lib-own', 'lib-inherited'] + PomVersions.managedArtifactIds(bom, 'other') == ['lib-other'] + } + + def "a group the BOM manages nothing of has no artifacts, whatever it shares a prefix with"() { + expect: + PomVersions.managedArtifactIds(bom, 'tes').isEmpty() + PomVersions.managedArtifactIds(bom, 'unknown').isEmpty() + } } diff --git a/dependencies.gradle b/dependencies.gradle index 121d8d97b5d..6c8adfcca6b 100644 --- a/dependencies.gradle +++ b/dependencies.gradle @@ -324,6 +324,8 @@ ext { // 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 validateHibernateVersion, which // check and the BOM's POM generation run, fails once Spring Boot catches up with it: remove it then. + // Set, it moves every org.hibernate.orm module spring-boot-dependencies manages in its own POM, + // not only the ones above, as setting hibernate.version moves them all for a Maven consumer. hibernate7VersionOverride = null customBomVersions = [ 'cache-ri-impl.version' : '1.1.1', diff --git a/grails-bom/hibernate7/build.gradle b/grails-bom/hibernate7/build.gradle index f55eadd9b73..9203f403387 100644 --- a/grails-bom/hibernate7/build.gradle +++ b/grails-bom/hibernate7/build.gradle @@ -17,6 +17,8 @@ * under the License. */ +import org.apache.maven.model.Model + import org.apache.grails.buildsrc.PomVersions import org.apache.grails.gradle.tasks.bom.ExtractDependenciesTask import org.apache.grails.gradle.tasks.bom.ExtractedDependencyConstraint @@ -64,11 +66,20 @@ def pomFile = { String coordinates -> // hibernate7VersionOverride to a newer release. Configuring this project reads only the parent BOMs' own // entries, not the BOMs they import, so a task that needs none of them does not fail when one is missing // from the cache; validateHibernateVersion checks the rest -String springBootHibernateVersion = parentBoms.findResult { String parentBom -> - PomVersions.managedVersion(PomVersions.read(pomFile(parentBom)), 'org.hibernate.orm:hibernate-core') +List parentBomModels = parentBoms.collect { String parentBom -> PomVersions.read(pomFile(parentBom)) } +String springBootHibernateVersion = parentBomModels.findResult { Model parentBom -> + PomVersions.managedVersion(parentBom, 'org.hibernate.orm:hibernate-core') } String overrideHibernateVersion = hibernate7VersionOverride ?: '' String hibernateVersion = overrideHibernateVersion ?: springBootHibernateVersion +// An override moves every Hibernate ORM module the parent BOMs manage, not only the ones Grails uses: an +// enforcedPlatform consumer would otherwise get it for those and Spring Boot's version for the rest, such +// as hibernate-hikaricp, while a Maven consumer setting the published hibernate.version moves them all +List managedHibernateOrmModules = overrideHibernateVersion ? + (hibernateOrmModules + parentBomModels.collectMany { Model parentBom -> + PomVersions.managedArtifactIds(parentBom, 'org.hibernate.orm') + }).unique() : + hibernateOrmModules if (!hibernateVersion) { throw new GradleException("${parentBoms.join(', ')} does not manage org.hibernate.orm:hibernate-core in its own POM: " + 'set hibernate7VersionOverride in dependencies.gradle to the Hibernate ORM 7 release to manage') @@ -117,7 +128,7 @@ tasks.withType(GenerateMavenPom).configureEach { GenerateMavenPom task -> task.d customBomVersions['hibernate.version'] = hibernateVersion combinedVersions['hibernate.version'] = hibernateVersion -for (String module : hibernateOrmModules) { +for (String module : managedHibernateOrmModules) { String coordinates = "org.hibernate.orm:${module}:${hibernateVersion}" customBomDependencies[module] = coordinates combinedDependencies[module] = coordinates From e161a31278fa7420a311832296679a00fd049f0c Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Mon, 9 Nov 2026 08:05:39 -0800 Subject: [PATCH 64/78] Fill in an empty form field with a value its type accepts when tracing Since a field rendered with value="" is filled in, every such field was sent traced-, whatever its type. The fields plugin renders an optional number as type="number" and a constrained string as type="email" or type="url", all with value="", so those failed to bind or failed their constraints. The page answered with the form again and a 200, which the trace counts as a submitted form, so the save path went unrecorded with no warning: the outcome filling the fields in was meant to prevent. A blank field is now filled by its input type: a number or range within its min and max, an ISO value for date, datetime-local, time, month and week (kept within min and max), an address for email, a URL for url, digits for tel, a colour for color, and the recognisable text as before for text-like fields, cut to the field's maxlength. A type with a second word, as the fields plugin's "number decimal", is read by its first. A hidden field without a value attribute is now sent empty, as a browser sends it, rather than as made-up text. --- .../en/guide/deployment/deploymentAot.adoc | 2 + .../plugin/aot/TraceNativeMetadataTask.groovy | 142 ++++++++++++++++-- .../aot/TraceNativeMetadataTaskSpec.groovy | 50 ++++++ .../gradle/plugin/aot/TracedRunFixture.groovy | 32 ++++ 4 files changed, 216 insertions(+), 10 deletions(-) diff --git a/grails-doc/src/en/guide/deployment/deploymentAot.adoc b/grails-doc/src/en/guide/deployment/deploymentAot.adoc index 551b999b34c..d92d335958e 100644 --- a/grails-doc/src/en/guide/deployment/deploymentAot.adoc +++ b/grails-doc/src/en/guide/deployment/deploymentAot.adoc @@ -147,6 +147,8 @@ 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. +A field that carries a value sends it, as a hidden field does whatever it carries. A field rendered empty, as the fields plugin renders those of a new instance, is filled in with something its type accepts: a number within the field's `min` and `max`, a date for a date field, an address for an email field, and recognisable text, no longer than the field's `maxlength`, for a text field. A value its type does not accept would fail to bind, and the page would answer with the form again, which looks to the trace like a save that succeeded. + ==== 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: diff --git a/grails-gradle/plugins/src/main/groovy/org/apache/grails/gradle/plugin/aot/TraceNativeMetadataTask.groovy b/grails-gradle/plugins/src/main/groovy/org/apache/grails/gradle/plugin/aot/TraceNativeMetadataTask.groovy index 2e2e80ca17b..5750d6159e5 100644 --- a/grails-gradle/plugins/src/main/groovy/org/apache/grails/gradle/plugin/aot/TraceNativeMetadataTask.groovy +++ b/grails-gradle/plugins/src/main/groovy/org/apache/grails/gradle/plugin/aot/TraceNativeMetadataTask.groovy @@ -22,6 +22,10 @@ import java.net.http.HttpClient import java.net.http.HttpRequest import java.net.http.HttpResponse import java.time.Duration +import java.time.LocalDateTime +import java.time.format.DateTimeFormatter +import java.time.temporal.ChronoUnit +import java.time.temporal.IsoFields import java.util.concurrent.TimeUnit import java.util.regex.Matcher import java.util.regex.Pattern @@ -125,6 +129,12 @@ abstract class TraceNativeMetadataTask extends DefaultTask { private static final Pattern NAME = Pattern.compile(/(?i)\bname\s*=\s*"([^"]+)"/) private static final Pattern VALUE = Pattern.compile(/(?i)\bvalue\s*=\s*"([^"]*)"/) private static final Pattern TYPE = Pattern.compile(/(?i)\btype\s*=\s*"([^"]+)"/) + private static final Pattern MAXLENGTH = Pattern.compile(/(?i)\bmaxlength\s*=\s*"\s*(\d{1,9})\s*"/) + private static final Pattern MIN = Pattern.compile(/(?i)\bmin\s*=\s*"([^"]*)"/) + private static final Pattern MAX = Pattern.compile(/(?i)\bmax\s*=\s*"([^"]*)"/) + + private static final String EMAIL_DOMAIN = '@example.com' + private static final String URL_BASE = 'https://example.com/' /** * Carries the session from one request to the next, which is what makes a form that @@ -465,11 +475,10 @@ abstract class TraceNativeMetadataTask extends DefaultTask { /** * What the form would send. A field that carries a value sends it, which is how the token a - * security filter demands is carried; a checkbox sends what a ticked one sends; anything else - * sends something recognisable, so a row in a database says where it came from. That includes a - * field rendered with an empty value, as the fields plugin renders them for a new instance: - * sent blank it fails validation, the page answers with the form again, and what a save does - * when it succeeds is never recorded. A hidden field is the page's own, so it is sent as it is. + * security filter demands is carried, and a hidden field is the page's own, so it is sent as it + * is even when that is nothing. Any other field without a value is filled in, as the fields + * plugin renders every field of a new instance: sent blank it fails validation, the page answers + * with the form again, and what a save does when it succeeds is never recorded. */ private static Map fieldsOf(String markup) { Map fields = [:] @@ -482,19 +491,132 @@ abstract class TraceNativeMetadataTask extends DefaultTask { } Matcher value = VALUE.matcher(tag) Matcher type = TYPE.matcher(tag) - String kind = type.find() ? type.group(1).toLowerCase(Locale.ROOT) : 'text' + // The first word only: the fields plugin renders a decimal property as type="number decimal". + String kind = type.find() ? type.group(1).trim().toLowerCase(Locale.ROOT).split(/\s+/)[0] : 'text' if (kind in ['submit', 'button', 'reset', 'image', 'file']) { continue } String carried = value.find() ? value.group(1) : null - fields[name.group(1)] = carried || (carried != null && kind == 'hidden') ? carried - : kind == 'checkbox' || kind == 'radio' ? 'on' - : kind == 'password' ? 'traced-secret' - : "traced-${System.nanoTime()}".toString() + fields[name.group(1)] = carried || kind == 'hidden' ? (carried ?: '') : fill(kind, tag) } fields } + /** + * Something a field of this type accepts, so that what fails is never the value the trace made up. + * + *

A number field sent text, or an email field sent something that is not an address, fails to + * bind or fails its constraint, and the page answers with the form again -- with a 200, which is + * what a save that succeeded answers with too. So the trace would report the form as covered + * while what a save does went unrecorded, which is the gap filling the field in was meant to + * close. A checkbox sends what a ticked one sends, and text sends something recognisable, so a + * row in a database says where it came from.

+ * + *

What the field says about itself is kept to: a number lies within its {@code min} and + * {@code max}, as a date does, and nothing is longer than its {@code maxlength}, which is how the + * fields plugin renders the constraints of the property behind it.

+ */ + private static String fill(String kind, String tag) { + String declaredLength = attribute(MAXLENGTH, tag) + Integer maxLength = declaredLength ? Integer.valueOf(declaredLength) : null + LocalDateTime now = LocalDateTime.now().truncatedTo(ChronoUnit.MINUTES) + switch (kind) { + case 'checkbox': + case 'radio': + return 'on' + case 'number': + case 'range': + return numberWithin(tag) + case 'date': + return within(now.toLocalDate().toString(), tag) + case 'datetime-local': + return within(now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm", Locale.ROOT)), tag) + case 'time': + return within(now.format(DateTimeFormatter.ofPattern('HH:mm', Locale.ROOT)), tag) + case 'month': + return within(now.format(DateTimeFormatter.ofPattern('yyyy-MM', Locale.ROOT)), tag) + case 'week': + return within(String.format(Locale.ROOT, '%d-W%02d', + now.get(IsoFields.WEEK_BASED_YEAR), now.get(IsoFields.WEEK_OF_WEEK_BASED_YEAR)), tag) + case 'email': + return traced(maxLength == null ? null : Math.max(maxLength - EMAIL_DOMAIN.length(), 1)) + EMAIL_DOMAIN + case 'url': + return URL_BASE + traced(maxLength == null ? null : Math.max(maxLength - URL_BASE.length(), 0)) + case 'tel': + return cut('5550100', maxLength) + case 'color': + return '#000000' + case 'password': + return cut('traced-secret', maxLength) + default: + return traced(maxLength) + } + } + + /** One, or the nearest number to it the field's {@code min} and {@code max} allow. */ + private static String numberWithin(String tag) { + BigDecimal number = BigDecimal.ONE + BigDecimal min = decimal(attribute(MIN, tag)) + BigDecimal max = decimal(attribute(MAX, tag)) + if (min != null && number < min) { + number = min + } + if (max != null && number > max) { + number = max + } + number.toPlainString() + } + + /** + * The value, or the nearest end of the field's {@code min} and {@code max}. A date, a time, a month and a week + * are each written so that the earlier of two sorts first, which is what lets them be compared as they are. + */ + private static String within(String value, String tag) { + String min = attribute(MIN, tag) + String max = attribute(MAX, tag) + if (min && value < min) { + return min + } + if (max && value > max) { + return max + } + value + } + + /** + * Something recognisable, and different from one trace to the next, so that a field the application keeps + * unique is given a value it has not seen. Where it does not fit, the name is given up before the digits that + * change are. + */ + private static String traced(Integer maxLength) { + String unique = String.valueOf(System.nanoTime() & Long.MAX_VALUE) + String value = "traced-${unique}".toString() + if (maxLength == null || value.length() <= maxLength) { + return value + } + int room = maxLength - 'traced-'.length() + room > 0 ? "traced-${unique.substring(unique.length() - room)}".toString() + : unique.substring(Math.max(unique.length() - maxLength, 0)) + } + + private static String cut(String value, Integer maxLength) { + maxLength == null || value.length() <= maxLength ? value : value.substring(0, maxLength) + } + + private static String attribute(Pattern pattern, String tag) { + Matcher matcher = pattern.matcher(tag) + matcher.find() ? matcher.group(1).trim() : null + } + + private static BigDecimal decimal(String text) { + try { + text ? new BigDecimal(text) : null + } + catch (NumberFormatException ignored) { + null + } + } + private HttpRequest.Builder requestTo(String path) { HttpRequest.newBuilder(uriOf(path)) .timeout(Duration.ofSeconds(60)) diff --git a/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/TraceNativeMetadataTaskSpec.groovy b/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/TraceNativeMetadataTaskSpec.groovy index e09ddf82f96..968efc1affd 100644 --- a/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/TraceNativeMetadataTaskSpec.groovy +++ b/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/TraceNativeMetadataTaskSpec.groovy @@ -20,6 +20,10 @@ package org.apache.grails.gradle.plugin.aot import java.net.CookieHandler import java.net.CookieManager +import java.time.LocalDate +import java.time.LocalDateTime +import java.time.LocalTime +import java.time.YearMonth import org.gradle.api.GradleException import org.gradle.api.Project @@ -177,6 +181,42 @@ exec '${new File(System.getProperty('java.home'), 'bin/java').absolutePath}' \\ submitted =~ /version=(&|$)/ } + void 'a field rendered empty is filled in with something its type accepts'() { + given: 'a number or a date sent text fails to bind, and the form answering again with a 200 reads as a save' + TraceNativeMetadataTask task = task([], ['/typed']) + + when: + task.trace() + + then: + Map sent = postedTo('/typed-save') + with(sent) { + available == 'on' + (title =~ /^traced-\d+$/) && title.size() <= 12 + (notes =~ /^\d+$/) && notes.size() <= 5 + query =~ /^traced-\d+$/ + secret == 'traced-secret' + new BigDecimal(pages) >= 0 + new BigDecimal(rating) >= 3 && new BigDecimal(rating) <= 5 + new BigDecimal(price) <= 0.5 + new BigDecimal(volume) >= 10 && new BigDecimal(volume) <= 20 + LocalDate.parse(released) + launched == '2999-01-01' + LocalDateTime.parse(startsAt) + LocalTime.parse(opensAt) + YearMonth.parse(issue) + sprint ==~ /\d{4}-W\d{2}/ + contact ==~ /traced-\d+@example\.com/ + (shortContact ==~ /[^@]+@example\.com/) && shortContact.size() <= 16 + new URI(homepage).scheme == 'https' && new URI(homepage).host + phone ==~ /\d+/ + colour ==~ /#[0-9a-f]{6}/ + } + + and: 'a hidden field is the page\'s own, so one that says nothing is sent saying nothing' + sent._available == '' + } + void 'the form with the most fields is the one submitted'() { given: 'a page carrying a layout search form ahead of its own' TraceNativeMetadataTask task = task([], ['/create']) @@ -438,6 +478,16 @@ exec '${new File(System.getProperty('java.home'), 'bin/java').absolutePath}' \\ CookieHandler.default = null } + /** The fields a form was submitted with, by name, from what the application was sent. */ + private Map postedTo(String action) { + String line = requested.find { String request -> request.startsWith("POST ${action} ") } + assert line, "nothing was posted to ${action}: ${requested}" + line.substring("POST ${action} ".length()).split('&').collectEntries { String pair -> + List parts = pair.split('=', 2) as List + [(URLDecoder.decode(parts[0], 'UTF-8')): URLDecoder.decode(parts.size() > 1 ? parts[1] : '', 'UTF-8')] + } as Map + } + void 'a java without the agent is refused before the application is started'() { given: 'the agent ships with GraalVM, so the JDK running the build is usually not one' File plain = new File(temporaryFolder, 'plain-jdk/bin/java') diff --git a/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/TracedRunFixture.groovy b/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/TracedRunFixture.groovy index 29715dc7de9..bd55e189311 100644 --- a/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/TracedRunFixture.groovy +++ b/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/TracedRunFixture.groovy @@ -71,6 +71,35 @@ class TracedRunFixture { ''' + /** + * A field of every type rendered with nothing in it, as the fields plugin renders a new instance's: a number + * or a date sent text fails to bind, and the page answers with the form again and a 200. + */ + private static final String TYPED_FORM = ''' +
+ + + + + + + + + + + + + + + + + + + + + +
''' + static void main(String[] args) { int port = Integer.parseInt(args[0]) File requested = new File(args[1]) @@ -111,6 +140,9 @@ class TracedRunFixture { else if (path == '/scaffolded') { response = SCAFFOLDED_FORM } + else if (path == '/typed') { + response = TYPED_FORM + } else if (path == '/authenticate') { exchange.responseHeaders.add('Set-Cookie', 'session=in; Path=/') status = 302 From 60db0814cdd06783851e51789935a20cba0443c2 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Mon, 9 Nov 2026 08:09:05 -0800 Subject: [PATCH 65/78] Send one of a select's options when tracing a form A select was read by its start tag alone, which has no value, so it was sent traced- like a text field. The fields plugin renders an enum, an association, an inList property and each part of a date picker as a select, and made-up text fails to convert for every one of them: the page answered with the form again and a 200, and the save the form was listed for went unrecorded while the trace reported it covered. A select now sends what a browser sends: the selected option, or the first one that is not disabled, and an option without a value attribute sends its text. Whether an option is selected or disabled is read with the attribute values blanked out, so an option whose value is "selected" is not taken for one that is. A select with no options sends nothing in its value. --- .../en/guide/deployment/deploymentAot.adoc | 2 +- .../plugin/aot/TraceNativeMetadataTask.groovy | 47 ++++++++++++++++++- .../aot/TraceNativeMetadataTaskSpec.groovy | 28 +++++++++++ .../gradle/plugin/aot/TracedRunFixture.groovy | 39 +++++++++++++++ 4 files changed, 113 insertions(+), 3 deletions(-) diff --git a/grails-doc/src/en/guide/deployment/deploymentAot.adoc b/grails-doc/src/en/guide/deployment/deploymentAot.adoc index d92d335958e..1d2e826df1d 100644 --- a/grails-doc/src/en/guide/deployment/deploymentAot.adoc +++ b/grails-doc/src/en/guide/deployment/deploymentAot.adoc @@ -147,7 +147,7 @@ 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. -A field that carries a value sends it, as a hidden field does whatever it carries. A field rendered empty, as the fields plugin renders those of a new instance, is filled in with something its type accepts: a number within the field's `min` and `max`, a date for a date field, an address for an email field, and recognisable text, no longer than the field's `maxlength`, for a text field. A value its type does not accept would fail to bind, and the page would answer with the form again, which looks to the trace like a save that succeeded. +A field that carries a value sends it, as a hidden field does whatever it carries. A field rendered empty, as the fields plugin renders those of a new instance, is filled in with something its type accepts: a number within the field's `min` and `max`, a date for a date field, an address for an email field, and recognisable text, no longer than the field's `maxlength`, for a text field. A select, which is how an enum, an association and each part of a date picker are rendered, sends the option a browser would: the one selected, or the first that can be chosen. A value its type does not accept would fail to bind, and the page would answer with the form again, which looks to the trace like a save that succeeded. ==== Other methods and bodies diff --git a/grails-gradle/plugins/src/main/groovy/org/apache/grails/gradle/plugin/aot/TraceNativeMetadataTask.groovy b/grails-gradle/plugins/src/main/groovy/org/apache/grails/gradle/plugin/aot/TraceNativeMetadataTask.groovy index 5750d6159e5..0ff082683cd 100644 --- a/grails-gradle/plugins/src/main/groovy/org/apache/grails/gradle/plugin/aot/TraceNativeMetadataTask.groovy +++ b/grails-gradle/plugins/src/main/groovy/org/apache/grails/gradle/plugin/aot/TraceNativeMetadataTask.groovy @@ -125,7 +125,11 @@ abstract class TraceNativeMetadataTask extends DefaultTask { private static final Pattern FORM = Pattern.compile(/(?is)]*>.*?<\/form>/) private static final Pattern ACTION = Pattern.compile(/(?i)\baction\s*=\s*"([^"]*)"/) private static final Pattern ID = Pattern.compile(/(?i)\bid\s*=\s*"([^"]+)"/) - private static final Pattern FIELD = Pattern.compile(/(?is)<(?:input|select|textarea)\b[^>]*>/) + private static final Pattern FIELD = Pattern.compile(/(?is)<(input|select|textarea)\b[^>]*>/) + private static final Pattern SELECT_END = Pattern.compile(/(?i)<\/select\s*>/) + private static final Pattern OPTION = Pattern.compile(/(?is)]*)>([^<]*)/) + private static final Pattern SELECTED = Pattern.compile(/(?i)(? fieldsOf(String markup) { Map fields = [:] @@ -489,6 +494,13 @@ abstract class TraceNativeMetadataTask extends DefaultTask { if (!name.find()) { continue } + if (field.group(1).equalsIgnoreCase('select')) { + Matcher end = SELECT_END.matcher(markup) + fields[name.group(1)] = optionOf(end.find(field.end()) + ? markup.substring(field.end(), end.start()) + : markup.substring(field.end())) + continue + } Matcher value = VALUE.matcher(tag) Matcher type = TYPE.matcher(tag) // The first word only: the fields plugin renders a decimal property as type="number decimal". @@ -502,6 +514,37 @@ abstract class TraceNativeMetadataTask extends DefaultTask { fields } + /** + * What a browser sends for a select: the option selected, or the first that can be chosen where + * none is, and an option without a value sends its text. + * + *

The select's options rather than made-up text, because only one of them binds. An enum, an + * association and each part of a date picker are rendered as a select, and text sent for any of + * them fails to convert -- so the page answers with the form again, and a 200, and the save the + * form was listed for is never recorded.

+ */ + private static String optionOf(String options) { + String first = null + Matcher option = OPTION.matcher(options) + while (option.find()) { + String attributes = option.group(1) + // Without what the attributes say, so that an option whose value is "selected" is not taken for one that is. + String flags = attributes.replaceAll(/"[^"]*"/, '""') + if (DISABLED.matcher(flags).find()) { + continue + } + Matcher value = VALUE.matcher(attributes) + String sent = value.find() ? value.group(1) : option.group(2).trim() + if (SELECTED.matcher(flags).find()) { + return sent + } + if (first == null) { + first = sent + } + } + first != null ? first : '' + } + /** * Something a field of this type accepts, so that what fails is never the value the trace made up. * diff --git a/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/TraceNativeMetadataTaskSpec.groovy b/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/TraceNativeMetadataTaskSpec.groovy index 968efc1affd..5eb93bddbc1 100644 --- a/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/TraceNativeMetadataTaskSpec.groovy +++ b/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/TraceNativeMetadataTaskSpec.groovy @@ -217,6 +217,34 @@ exec '${new File(System.getProperty('java.home'), 'bin/java').absolutePath}' \\ sent._available == '' } + void 'a select sends one of its options'() { + given: 'an enum, an association and a date picker are rendered as selects, and only an option binds' + TraceNativeMetadataTask task = task([], ['/select']) + + when: + task.trace() + + then: 'the first option where none is selected, as a browser sends' + Map sent = postedTo('/select-save') + sent.status == 'DRAFT' + sent.author == 'null' + + and: 'the selected one where one is' + sent.released_day == '9' + sent.tags == '2' + sent.released == 'date.struct' + + and: 'never one that cannot be chosen, nor one whose value only reads like the attribute' + sent.format == 'HARDBACK' + + and: 'the text of an option that has no value, inside a group as much as outside one' + sent.genre == 'Crime' + + and: 'and nothing for a select with no options, while the fields after it are still read' + sent.nothing == '' + sent.title =~ /^traced-\d+$/ + } + void 'the form with the most fields is the one submitted'() { given: 'a page carrying a layout search form ahead of its own' TraceNativeMetadataTask task = task([], ['/create']) diff --git a/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/TracedRunFixture.groovy b/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/TracedRunFixture.groovy index bd55e189311..4a6723f2c7d 100644 --- a/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/TracedRunFixture.groovy +++ b/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/TracedRunFixture.groovy @@ -100,6 +100,42 @@ class TracedRunFixture { ''' + /** + * What the fields plugin renders as a select: an enum, an association, and a date picker's parts. Each binds + * only one of its options, so text sent for any of them fails to convert. + */ + private static final String SELECT_FORM = ''' +
+ + + + + + + + + +
''' + static void main(String[] args) { int port = Integer.parseInt(args[0]) File requested = new File(args[1]) @@ -143,6 +179,9 @@ class TracedRunFixture { else if (path == '/typed') { response = TYPED_FORM } + else if (path == '/select') { + response = SELECT_FORM + } else if (path == '/authenticate') { exchange.responseHeaders.add('Set-Cookie', 'session=in; Path=/') status = 302 From c72ff06df6bddff7876fe3d805a4a5cbc031a254 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Mon, 9 Nov 2026 08:11:39 -0800 Subject: [PATCH 66/78] Say that the startup gate's 503 is temporary with Retry-After The Spring Security plugin answers every request with 503 until the application has started, and set nothing else on the response. A client had no way to tell that answer, which changes within moments, from a 503 the application gives for reasons of its own, so traceNativeMetadata and trainAotCache waited out their whole start timeout for an application whose home page answers 503 by design. The gate now also sends Retry-After: 1. RFC 9110 lets a 503 carry it to say the unavailability is temporary and when to ask again, which is what this one is. The grails-startup-progress page already answers a request made during startup the same way. --- .../springSecurity/core/filters.adoc | 2 +- .../web/filter/StartupGateFilter.groovy | 15 ++++++++++++++- .../web/filter/StartupGateFilterSpec.groovy | 10 ++++++++++ 3 files changed, 25 insertions(+), 2 deletions(-) diff --git a/grails-doc/src/en/guide/security/securityPlugins/springSecurity/core/filters.adoc b/grails-doc/src/en/guide/security/securityPlugins/springSecurity/core/filters.adoc index 5a31eb1ad6d..7406fc0d664 100644 --- a/grails-doc/src/en/guide/security/securityPlugins/springSecurity/core/filters.adoc +++ b/grails-doc/src/en/guide/security/securityPlugins/springSecurity/core/filters.adoc @@ -24,7 +24,7 @@ There are a few different approaches to configuring filter chains. === Requests that arrive before startup -While the application is starting, the plugin responds to every request with `503 Service Unavailable`. That includes a request for a static resource. Requests are allowed through only after both of these have happened, in either order: the plugin has finished `doWithApplicationContext()`, and Spring Boot has published `ApplicationStartedEvent`. +While the application is starting, the plugin responds to every request with `503 Service Unavailable` and a `Retry-After` header of one second, which says the unavailability is temporary. That includes a request for a static resource. Requests are allowed through only after both of these have happened, in either order: the plugin has finished `doWithApplicationContext()`, and Spring Boot has published `ApplicationStartedEvent`. The property is `grails.plugin.springsecurity.rejectRequestsDuringStartup`. It defaults to `true`. Set it to `false` to let requests through during startup: diff --git a/grails-spring-security/plugin/src/main/groovy/grails/plugin/springsecurity/web/filter/StartupGateFilter.groovy b/grails-spring-security/plugin/src/main/groovy/grails/plugin/springsecurity/web/filter/StartupGateFilter.groovy index 141e363e765..84a980055aa 100644 --- a/grails-spring-security/plugin/src/main/groovy/grails/plugin/springsecurity/web/filter/StartupGateFilter.groovy +++ b/grails-spring-security/plugin/src/main/groovy/grails/plugin/springsecurity/web/filter/StartupGateFilter.groovy @@ -30,17 +30,28 @@ import jakarta.servlet.http.HttpServletResponse import org.springframework.boot.context.event.ApplicationStartedEvent import org.springframework.context.ApplicationListener +import org.springframework.http.HttpHeaders import org.springframework.web.filter.GenericFilterBean /** * Responds to every request with 503 Service Unavailable until the application has started, * that is, until the plugin has initialized and Spring Boot has published * ApplicationStartedEvent. + * + *

The response carries Retry-After, which is how a 503 says the unavailability + * is temporary (RFC 9110, section 15.6.4). A client can then tell this answer, which changes once + * the application has started, from a 503 the application gives for reasons of its own.

*/ @Slf4j @CompileStatic class StartupGateFilter extends GenericFilterBean implements ApplicationListener { + /** + * How many seconds a rejected request is asked to wait before it is made again: one, since the + * gate is closed only while the application finishes starting. + */ + private static final String RETRY_AFTER_SECONDS = '1' + private boolean initialized private boolean started private volatile boolean opened @@ -66,7 +77,9 @@ class StartupGateFilter extends GenericFilterBean implements ApplicationListener if (!opened) { log.debug('Rejecting request to {}, the application has not started yet', ((HttpServletRequest) req).requestURI) // set the status rather than calling sendError() to avoid an error dispatch - ((HttpServletResponse) res).status = HttpServletResponse.SC_SERVICE_UNAVAILABLE + HttpServletResponse response = (HttpServletResponse) res + response.status = HttpServletResponse.SC_SERVICE_UNAVAILABLE + response.setHeader(HttpHeaders.RETRY_AFTER, RETRY_AFTER_SECONDS) return } diff --git a/grails-spring-security/plugin/src/test/groovy/grails/plugin/springsecurity/web/filter/StartupGateFilterSpec.groovy b/grails-spring-security/plugin/src/test/groovy/grails/plugin/springsecurity/web/filter/StartupGateFilterSpec.groovy index b70c99788b8..fffad8daeb5 100644 --- a/grails-spring-security/plugin/src/test/groovy/grails/plugin/springsecurity/web/filter/StartupGateFilterSpec.groovy +++ b/grails-spring-security/plugin/src/test/groovy/grails/plugin/springsecurity/web/filter/StartupGateFilterSpec.groovy @@ -45,6 +45,15 @@ class StartupGateFilterSpec extends Specification { chain.request == null } + void 'says the rejection is temporary, so it can be told from a 503 the application gives itself'() { + when: + filter.doFilter(request, response, chain) + + then: + response.status == 503 + response.getHeader('Retry-After') == '1' + } + void 'sets the status instead of sending an error'() { when: filter.doFilter(request, response, chain) @@ -85,6 +94,7 @@ class StartupGateFilterSpec extends Specification { then: filter.open response.status == 200 + !response.containsHeader('Retry-After') chain.request.is(request) chain.response.is(response) } From 32a04aa182d6ec94aff27bc8bac049fbb083b1e1 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Mon, 9 Nov 2026 08:16:03 -0800 Subject: [PATCH 67/78] Wait for a 503 at startup only while it carries Retry-After traceNativeMetadata and trainAotCache wait while the application's home page answers 503, so that the Spring Security plugin's startup gate is not recorded in place of the page. Any 503 counted, so an application whose / answers 503 for reasons of its own made both tasks sit out the whole start timeout, 180 seconds by default, before going on. A 503 says its unavailability is temporary by carrying Retry-After, which the gate now sends. The wait now asks for that: a 503 with Retry-After is waited for, up to the timeout, and one without it is the application's own answer and the run goes on at once. --- .../en/guide/deployment/deploymentAot.adoc | 2 +- .../grails/gradle/plugin/aot/RunPort.groovy | 9 +++++-- .../plugin/aot/TraceNativeMetadataTask.groovy | 8 +++++- .../plugin/aot/TrainAotCacheTask.groovy | 8 +++--- .../gradle/plugin/aot/RunPortSpec.groovy | 17 ++++++++----- .../aot/TraceNativeMetadataTaskSpec.groovy | 24 +++++++++++++++--- .../gradle/plugin/aot/TracedRunFixture.groovy | 8 +++++- .../plugin/aot/TrainAotCacheTaskSpec.groovy | 25 ++++++++++++++++--- .../plugin/aot/TrainingRunFixture.groovy | 13 +++++++--- 9 files changed, 89 insertions(+), 25 deletions(-) diff --git a/grails-doc/src/en/guide/deployment/deploymentAot.adoc b/grails-doc/src/en/guide/deployment/deploymentAot.adoc index 1d2e826df1d..5df14c38d48 100644 --- a/grails-doc/src/en/guide/deployment/deploymentAot.adoc +++ b/grails-doc/src/en/guide/deployment/deploymentAot.adoc @@ -195,7 +195,7 @@ grails { } ---- -The plugin answers every request with a 503 until the application has started, so the trace and an AOT cache training run wait for that answer to change before they make their first request, for no longer than `startTimeoutSeconds`. What the plugin declares and the default configuration it loads are ready for an image. Its companion plugins (REST, LDAP, ACL, CAS, OAuth2 and UI) are not yet: each compiles a default configuration script as it starts, which an image cannot do. +The plugin answers every request with a 503 and a `Retry-After` header until the application has started, so the trace and an AOT cache training run wait for that answer to change before they make their first request, for no longer than `startTimeoutSeconds`. A 503 without `Retry-After` is the application's own answer, which waiting will not change, so it is not waited for. What the plugin declares and the default configuration it loads are ready for an image. Its companion plugins (REST, LDAP, ACL, CAS, OAuth2 and UI) are not yet: each compiles a default configuration script as it starts, which an image cannot do. ==== Choosing which form diff --git a/grails-gradle/plugins/src/main/groovy/org/apache/grails/gradle/plugin/aot/RunPort.groovy b/grails-gradle/plugins/src/main/groovy/org/apache/grails/gradle/plugin/aot/RunPort.groovy index 2c7588ad8f9..dd0bf8a5317 100644 --- a/grails-gradle/plugins/src/main/groovy/org/apache/grails/gradle/plugin/aot/RunPort.groovy +++ b/grails-gradle/plugins/src/main/groovy/org/apache/grails/gradle/plugin/aot/RunPort.groovy @@ -46,8 +46,12 @@ final class RunPort { * started both come before its {@code ApplicationStartedEvent}, and a filter that holds requests until then, such * as the Spring Security plugin's, answers them with 503, which a run would record in place of the page. * + *

Only a 503 that carries {@code Retry-After}, which is how a 503 says the unavailability is temporary, and + * how the Spring Security plugin's says it. A 503 without it is the application's own answer, which waiting will + * not change, and a run that waited for it would sit out its whole start timeout before going on.

+ * * @param port the port the run is reached on - * @return whether it answers with 503, and not where nothing answers at all + * @return whether it answers with 503 and {@code Retry-After}, and not where nothing answers at all * @since 9.1 */ static boolean answersNotReady(int port) { @@ -58,7 +62,8 @@ final class RunPort { connection.connectTimeout = 500 connection.readTimeout = 2000 try { - return connection.responseCode == HttpURLConnection.HTTP_UNAVAILABLE + return connection.responseCode == HttpURLConnection.HTTP_UNAVAILABLE && + connection.getHeaderField('Retry-After') != null } finally { connection.disconnect() diff --git a/grails-gradle/plugins/src/main/groovy/org/apache/grails/gradle/plugin/aot/TraceNativeMetadataTask.groovy b/grails-gradle/plugins/src/main/groovy/org/apache/grails/gradle/plugin/aot/TraceNativeMetadataTask.groovy index 0ff082683cd..608ea2ee7bf 100644 --- a/grails-gradle/plugins/src/main/groovy/org/apache/grails/gradle/plugin/aot/TraceNativeMetadataTask.groovy +++ b/grails-gradle/plugins/src/main/groovy/org/apache/grails/gradle/plugin/aot/TraceNativeMetadataTask.groovy @@ -670,6 +670,11 @@ abstract class TraceNativeMetadataTask extends DefaultTask { URI.create("http://localhost:${port.get()}${path.startsWith('/') ? path : '/' + path}") } + /** + * Waits for the application to serve and, where it answers 503 with {@code Retry-After} as the Spring Security + * plugin does until the application has started, for that answer to change, up to the timeout. A 503 without + * {@code Retry-After} is the application's own answer, and is not waited for. + */ private void awaitStarted(Process process, File output) { long deadline = System.currentTimeMillis() + Duration.ofSeconds(startTimeoutSeconds.get()).toMillis() StartupLog log = new StartupLog(output) @@ -686,7 +691,8 @@ abstract class TraceNativeMetadataTask extends DefaultTask { Thread.sleep(250L) } if (started) { - // Its home page is what answers 503, as it may for reasons of its own, so the requests are its to answer. + // Its home page still says to come back after the whole of the timeout, which is longer than a start + // takes to finish, so the requests are its to answer. return } throw new GradleException("The application did not start within ${startTimeoutSeconds.get()}s. " + diff --git a/grails-gradle/plugins/src/main/groovy/org/apache/grails/gradle/plugin/aot/TrainAotCacheTask.groovy b/grails-gradle/plugins/src/main/groovy/org/apache/grails/gradle/plugin/aot/TrainAotCacheTask.groovy index 1a92e31c51d..22d97067915 100644 --- a/grails-gradle/plugins/src/main/groovy/org/apache/grails/gradle/plugin/aot/TrainAotCacheTask.groovy +++ b/grails-gradle/plugins/src/main/groovy/org/apache/grails/gradle/plugin/aot/TrainAotCacheTask.groovy @@ -273,8 +273,9 @@ abstract class TrainAotCacheTask extends DefaultTask { * or reword; a port that accepts a connection is the application's own doing and cannot be * configured away while it is still an application worth training.

* - *

Both come before its {@code ApplicationStartedEvent}, so a filter that holds requests until then is waited - * for, up to the timeout.

+ *

Both come before its {@code ApplicationStartedEvent}, so a filter that holds requests until then, answering + * them with 503 and {@code Retry-After}, is waited for, up to the timeout. A 503 without {@code Retry-After} is the + * application's own answer, and is not.

*/ private void awaitStarted(Process process, File output) { long deadline = System.currentTimeMillis() + Duration.ofSeconds(startTimeoutSeconds.get()).toMillis() @@ -292,7 +293,8 @@ abstract class TrainAotCacheTask extends DefaultTask { Thread.sleep(250L) } if (started) { - // Its home page is what answers 503, as it may for reasons of its own, so the requests are its to answer. + // Its home page still says to come back after the whole of the timeout, which is longer than a start + // takes to finish, so the requests are its to answer. return } throw new GradleException("The training run did not start within ${startTimeoutSeconds.get()}s. " + diff --git a/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/RunPortSpec.groovy b/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/RunPortSpec.groovy index 8786bd92da3..5e2d11c2322 100644 --- a/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/RunPortSpec.groovy +++ b/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/RunPortSpec.groovy @@ -34,6 +34,9 @@ class RunPortSpec extends Specification { given: HttpServer server = HttpServer.create(new InetSocketAddress('localhost', 0), 0) server.createContext('/') { HttpExchange exchange -> + if (retryAfter) { + exchange.responseHeaders.add('Retry-After', '1') + } exchange.sendResponseHeaders(status, -1) exchange.close() } @@ -46,12 +49,14 @@ class RunPortSpec extends Specification { server?.stop(0) where: - status | notReady | description - 503 | true | 'not ready' - 200 | false | 'ready' - 302 | false | 'ready, wherever it sends the request' - 404 | false | 'ready, whatever it has at its home page' - 500 | false | 'ready, since only 503 says to come back' + status | retryAfter | notReady | description + 503 | true | true | 'not ready where it says to come back, as the Spring Security plugin does until the application has started' + 503 | false | false | 'ready where it does not say to come back, since that is the application\'s own answer' + 200 | false | false | 'ready' + 302 | false | false | 'ready, wherever it sends the request' + 404 | false | false | 'ready, whatever it has at its home page' + 500 | false | false | 'ready, since only 503 says to come back' + 500 | true | false | 'ready even with Retry-After, since only a 503 says it is not ready yet' } void 'a port nothing answers on is not said to be not ready'() { diff --git a/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/TraceNativeMetadataTaskSpec.groovy b/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/TraceNativeMetadataTaskSpec.groovy index 5eb93bddbc1..3f315dfbf10 100644 --- a/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/TraceNativeMetadataTaskSpec.groovy +++ b/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/TraceNativeMetadataTaskSpec.groovy @@ -20,6 +20,7 @@ package org.apache.grails.gradle.plugin.aot import java.net.CookieHandler import java.net.CookieManager +import java.time.Duration import java.time.LocalDate import java.time.LocalDateTime import java.time.LocalTime @@ -351,7 +352,7 @@ exec '${new File(System.getProperty('java.home'), 'bin/java').absolutePath}' \\ } void 'a path is not asked for while the application still answers that it is not ready'() { - given: 'the Spring Security plugin answers every request with 503 until the application has started' + given: 'the Spring Security plugin answers every request with 503 and Retry-After until the application has started' TraceNativeMetadataTask task = task(['/'], [], 'gated') when: @@ -362,10 +363,25 @@ exec '${new File(System.getProperty('java.home'), 'bin/java').absolutePath}' \\ requested.contains('GET /') } - void 'an application whose home page always answers that it is not ready is still traced'() { - given: 'waited for no longer than the timeout, since nothing says that answer will change' + void 'an application whose home page answers 503 of its own accord is traced without waiting'() { + given: 'a 503 without Retry-After, which does not say it will change' TraceNativeMetadataTask task = task(['/page'], [], 'homePageDown') - task.startTimeoutSeconds.set(10) + task.startTimeoutSeconds.set(60) + long began = System.nanoTime() + + when: + task.trace() + + then: 'rather than after sitting out the whole of the start timeout' + notThrown(GradleException) + requested.contains('GET /page') + Duration.ofNanos(System.nanoTime() - began) < Duration.ofSeconds(30) + } + + void 'an application whose home page always says to come back is still traced once the timeout has passed'() { + given: 'waited for no longer than the timeout' + TraceNativeMetadataTask task = task(['/page'], [], 'homePageRetrying') + task.startTimeoutSeconds.set(5) when: task.trace() diff --git a/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/TracedRunFixture.groovy b/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/TracedRunFixture.groovy index 4a6723f2c7d..8210a65901d 100644 --- a/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/TracedRunFixture.groovy +++ b/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/TracedRunFixture.groovy @@ -147,9 +147,15 @@ class TracedRunFixture { server.createContext('/') { HttpExchange exchange -> String path = exchange.requestURI.path String method = exchange.requestMethod + // Held as the Spring Security plugin holds a request until the application has started: a 503 that says + // to come back. A home page that is down answers 503 for reasons of its own, which says nothing of the kind. boolean holding = behaviour == 'gated' && System.currentTimeMillis() < openAt + boolean homePageRetrying = behaviour == 'homePageRetrying' && path == '/' boolean homePageDown = behaviour == 'homePageDown' && path == '/' - if (holding || homePageDown) { + if (holding || homePageRetrying || homePageDown) { + if (!homePageDown) { + exchange.responseHeaders.add('Retry-After', '1') + } exchange.sendResponseHeaders(503, -1) exchange.close() return diff --git a/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/TrainAotCacheTaskSpec.groovy b/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/TrainAotCacheTaskSpec.groovy index 3e5f5b8f7f9..1e97219133f 100644 --- a/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/TrainAotCacheTaskSpec.groovy +++ b/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/TrainAotCacheTaskSpec.groovy @@ -18,6 +18,8 @@ */ package org.apache.grails.gradle.plugin.aot +import java.time.Duration + import org.gradle.api.GradleException import org.gradle.api.Project import org.gradle.testfixtures.ProjectBuilder @@ -310,7 +312,7 @@ exit 1 } void 'a path is not asked for while the run still answers that it is not ready'() { - given: 'the Spring Security plugin answers every request with 503 until the application has started' + given: 'the Spring Security plugin answers every request with 503 and Retry-After until the application has started' TrainAotCacheTask task = servingTask(['/'], true, 'gated') when: @@ -321,10 +323,25 @@ exit 1 requested == ['/'] } - void 'a run whose home page always answers that it is not ready is still exercised'() { - given: 'waited for no longer than the timeout, since nothing says that answer will change' + void 'a run whose home page answers 503 of its own accord is exercised without waiting'() { + given: 'a 503 without Retry-After, which does not say it will change' TrainAotCacheTask task = servingTask(['/page'], true, 'homePageDown') - task.startTimeoutSeconds.set(10) + task.startTimeoutSeconds.set(60) + long began = System.nanoTime() + + when: + task.train() + + then: 'rather than after sitting out the whole of the start timeout' + noExceptionThrown() + requested == ['/page'] + Duration.ofNanos(System.nanoTime() - began) < Duration.ofSeconds(30) + } + + void 'a run whose home page always says to come back is still exercised once the timeout has passed'() { + given: 'waited for no longer than the timeout' + TrainAotCacheTask task = servingTask(['/page'], true, 'homePageRetrying') + task.startTimeoutSeconds.set(5) when: task.train() diff --git a/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/TrainingRunFixture.groovy b/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/TrainingRunFixture.groovy index c1774784c9a..b5924acb24c 100644 --- a/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/TrainingRunFixture.groovy +++ b/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/TrainingRunFixture.groovy @@ -43,10 +43,17 @@ class TrainingRunFixture { File requested = new File(args[2]) HttpServer server = HttpServer.create(new InetSocketAddress('localhost', port), 0) - long openAt = args.length > 4 && args[4] == 'gated' ? System.currentTimeMillis() + 1500 : 0 - boolean homePageDown = args.length > 4 && args[4] == 'homePageDown' + String behaviour = args.length > 4 ? args[4] : 'ok' + long openAt = behaviour == 'gated' ? System.currentTimeMillis() + 1500 : 0 server.createContext('/') { HttpExchange exchange -> - if (System.currentTimeMillis() < openAt || (homePageDown && exchange.requestURI.path == '/')) { + // Held as the Spring Security plugin holds a request until the application has started: a 503 that says + // to come back. A home page that is down answers 503 for reasons of its own, which says nothing of the kind. + boolean homePage = exchange.requestURI.path == '/' + boolean homePageDown = behaviour == 'homePageDown' && homePage + if (System.currentTimeMillis() < openAt || (behaviour == 'homePageRetrying' && homePage) || homePageDown) { + if (!homePageDown) { + exchange.responseHeaders.add('Retry-After', '1') + } exchange.sendResponseHeaders(503, -1) exchange.close() return From 073006eddfb46b1d6ad963a2724d78f248601bf8 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Mon, 9 Nov 2026 08:18:12 -0800 Subject: [PATCH 68/78] Refuse a nativeMetadata request that cannot be made before starting the trace A request that did not name its method and path, or that named a key the task does not know, was found only when the trace came to make it: after the application had been started under the agent, the forms submitted and the other requests made. The build then failed on a mistake that was plain from the configuration before anything ran. The requests are now checked first, before the agent is looked for or the port claimed, and each one that cannot be made is named with the same message as before. Making a request no longer checks it again. --- .../en/guide/deployment/deploymentAot.adoc | 2 +- .../plugin/aot/NativeMetadataExtension.groovy | 3 +- .../plugin/aot/TraceNativeMetadataTask.groovy | 28 ++++++++++++++----- .../aot/TraceNativeMetadataTaskSpec.groovy | 14 ++++++---- 4 files changed, 33 insertions(+), 14 deletions(-) diff --git a/grails-doc/src/en/guide/deployment/deploymentAot.adoc b/grails-doc/src/en/guide/deployment/deploymentAot.adoc index 5df14c38d48..710b3d211e1 100644 --- a/grails-doc/src/en/guide/deployment/deploymentAot.adoc +++ b/grails-doc/src/en/guide/deployment/deploymentAot.adoc @@ -165,7 +165,7 @@ grails { } ---- -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. +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 before the application is started, and one that answers with an error fails it too. ==== Pages behind a login 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 956b683c07a..e4d31034945 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 @@ -48,7 +48,8 @@ abstract class NativeMetadataExtension { /** * 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}. + * {@code contentType}, {@code body} and {@code accept}. One that does not, or that names anything else, fails + * the trace before the application is started. * * @since 9.1 */ diff --git a/grails-gradle/plugins/src/main/groovy/org/apache/grails/gradle/plugin/aot/TraceNativeMetadataTask.groovy b/grails-gradle/plugins/src/main/groovy/org/apache/grails/gradle/plugin/aot/TraceNativeMetadataTask.groovy index 608ea2ee7bf..8b1a2f16766 100644 --- a/grails-gradle/plugins/src/main/groovy/org/apache/grails/gradle/plugin/aot/TraceNativeMetadataTask.groovy +++ b/grails-gradle/plugins/src/main/groovy/org/apache/grails/gradle/plugin/aot/TraceNativeMetadataTask.groovy @@ -200,6 +200,7 @@ abstract class TraceNativeMetadataTask extends DefaultTask { @TaskAction void trace() { + refuseRequestsThatCannotBeMade() File java = new File(javaExecutable.get()) File metadata = outputDirectory.get().asFile metadata.mkdirs() @@ -281,6 +282,24 @@ abstract class TraceNativeMetadataTask extends DefaultTask { } } + /** + * Refuses a request that does not name its method and path, or names what a request cannot have, before + * anything is started. Found as the request was made, it failed the build only after the application had been + * started and the rest traced, which for a misspelt key is the whole wait for an answer known before it began. + */ + private void refuseRequestsThatCannotBeMade() { + List refused = requests.get().findAll { Map request -> + Map declared = request + (declared.keySet() - REQUEST_KEYS) || !declared.method || !declared.path + }.collect { Map request -> + "REQUEST ${request} -> a request names its method and path, and may name ${REQUEST_KEYS - ['method', 'path']}".toString() + } + if (refused) { + throw new GradleException('grails.nativeMetadata.requests names a request that cannot be made, so the ' + + "application was not started:\n ${refused.join('\n ')}") + } + } + /** * Refuses before starting rather than after. Without the agent the JVM stops at load with a * message about a library path, which reads as a broken machine rather than as the wrong JDK. @@ -323,13 +342,8 @@ abstract class TraceNativeMetadataTask extends DefaultTask { */ private Answer send(Map request) { Map declared = request - Collection unknown = declared.keySet() - REQUEST_KEYS - String method = declared.method?.toString()?.toUpperCase(Locale.ROOT) - String path = declared.path?.toString() - if (unknown || !method || !path) { - return new Answer("REQUEST ${declared} -> a request names its method and path, and may name " + - "${REQUEST_KEYS - ['method', 'path']}".toString(), false) - } + String method = declared.method.toString().toUpperCase(Locale.ROOT) + String path = declared.path.toString() HttpRequest.Builder builder = requestTo(path) if (declared.accept) { builder.setHeader('Accept', declared.accept.toString()) diff --git a/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/TraceNativeMetadataTaskSpec.groovy b/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/TraceNativeMetadataTaskSpec.groovy index 3f315dfbf10..874236b6911 100644 --- a/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/TraceNativeMetadataTaskSpec.groovy +++ b/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/TraceNativeMetadataTaskSpec.groovy @@ -473,17 +473,21 @@ exec '${new File(System.getProperty('java.home'), 'bin/java').absolutePath}' \\ } void 'a request that does not say what to send, or misspells it, fails the trace rather than sending something else'() { - given: - TraceNativeMetadataTask task = task([], []) - task.requests.set([request]) + given: 'listed after one that can be made, and alongside a path' + TraceNativeMetadataTask task = task(['/'], []) + task.requests.set([[method: 'QUERY', path: '/book/valid'], request]) when: task.trace() - then: + then: 'the one that cannot be made is named' GradleException e = thrown() e.message.contains('a request names its method and path') - !requested.any { it.contains('/book/search') } + !e.message.contains('/book/valid') + + and: 'before the application is started, rather than once it has been started and traced' + requested.isEmpty() + !new File(task.temporaryDir, 'trace.log').exists() where: request << [[path: '/book/search'], [method: 'QUERY'], [method: 'QUERY', path: '/book/search', bodyy: '{}']] From 90983ea97378648a306fc4cbd79f745b23e882c7 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Mon, 9 Nov 2026 08:11:11 -0800 Subject: [PATCH 69/78] Compare what Digest authentication stores without replacing passwordEncoder With useDigestAuth the plugin replaced passwordEncoder with a NoOpPasswordEncoder for the whole application, so that what DigestAuthenticationFilter hands the authentication manager, the stored value as the credentials, would match itself. That encoder reached every other provider too: the stored hash typed into a login form signed the user in, the user spring.security.user.* describes, stored as {noop}password, could no longer sign in, and form and Basic sign-ins lost their constant-time comparison. passwordEncoder now stays as configured in both modes. With Digest authentication the plugin's daoAuthenticationProvider is a DigestDaoAuthenticationProvider, which hashes a password that a form or Basic authentication sends as a browser does, and accepts the stored value as it is only in a token whose principal is the UserDetails it was loaded with, as the filter's is; the principal a form or Basic authentication sends is the username. It compares with MessageDigest.isEqual, and its own encoder is a NoOpPasswordEncoder, so that a sign-in for an unknown username costs about what one for a user does. A class named with daoAuthenticationProviderBeanClass is still given passwordEncoder unless it extends the new one. DigestAuthenticationSpec signs a user in by Digest through the plugin's filter chain, through its login form and through its authentication manager, in both modes. Without the change the form, Basic, configured encoder and spring.security.user cases fail. --- .../authentication/basicAndDigestAuth.adoc | 4 +- .../src/en/guide/upgrading/upgrading90x.adoc | 5 +- .../SpringSecurityCoreGrailsPlugin.groovy | 35 +++-- .../DigestDaoAuthenticationProvider.groovy | 108 ++++++++++++++ .../DigestAuthenticationSpec.groovy | 138 ++++++++++++++---- .../springsecurity/PluginBeansSpec.groovy | 73 +++++++++ 6 files changed, 316 insertions(+), 47 deletions(-) create mode 100644 grails-spring-security/plugin/src/main/groovy/grails/plugin/springsecurity/authentication/DigestDaoAuthenticationProvider.groovy diff --git a/grails-doc/src/en/guide/security/securityPlugins/springSecurity/core/authentication/basicAndDigestAuth.adoc b/grails-doc/src/en/guide/security/securityPlugins/springSecurity/core/authentication/basicAndDigestAuth.adoc index 6a5af9cf84b..b4ee17eaa11 100644 --- a/grails-doc/src/en/guide/security/securityPlugins/springSecurity/core/authentication/basicAndDigestAuth.adoc +++ b/grails-doc/src/en/guide/security/securityPlugins/springSecurity/core/authentication/basicAndDigestAuth.adoc @@ -123,5 +123,7 @@ Digest authentication cannot be applied to a subset of URLs like Basic authentic [NOTE] ==== -What `s2-quickstart` generates hashes a password with `springSecurityService.encodePassword(password)`, in the user class or in its password encoder listener, which gives the wrong value for Digest authentication. Replace that call with the hash above, or set `digest.useCleartextPasswords` to `true`. With Digest authentication `passwordEncoder` compares a password as it is with what is stored, because the filter hands it what is stored as the credentials. So a form can sign a user in with cleartext passwords stored, and cannot with the hash stored. +What `s2-quickstart` generates hashes a password with `springSecurityService.encodePassword(password)`, in the user class or in its password encoder listener, which gives the wrong value for Digest authentication. Replace that call with the hash above, or set `digest.useCleartextPasswords` to `true` and store the password as it was typed. + +Digest authentication leaves `passwordEncoder` as configured, so `springSecurityService.encodePassword` and the users that other `UserDetailsService` beans or `spring.security.user.*` describe work as they do without it. The plugin's `daoAuthenticationProvider` does not use it: it hashes a password that a form or Basic authentication sends the way a browser does, so a form signs a user in with their password in either mode, and not with the hash stored. A class named with `daoAuthenticationProviderBeanClass` is given `passwordEncoder` instead, unless it extends `grails.plugin.springsecurity.authentication.DigestDaoAuthenticationProvider`. ==== diff --git a/grails-doc/src/en/guide/upgrading/upgrading90x.adoc b/grails-doc/src/en/guide/upgrading/upgrading90x.adoc index 418460783f5..e9141dbf818 100644 --- a/grails-doc/src/en/guide/upgrading/upgrading90x.adoc +++ b/grails-doc/src/en/guide/upgrading/upgrading90x.adoc @@ -143,8 +143,9 @@ An application that secures a page at one of these paths and wants a login to re * *Digest authentication in the Spring Security plugin starts and signs users in.* `useDigestAuth` with its default of hashed passwords used to fail at startup, naming an encoder that no longer exists. What a user has stored is now the hash a browser computes, which the application computes, as the link:security.html#core-basicAndDigestAuth[guide] shows. -With `digest.useCleartextPasswords`, nobody could sign in with Digest authentication, because the password encoder stored `{noop}secret`. -It now stores what was typed, so an application that signed in through a form with stored values such as `{noop}secret` removes the `{noop}` prefix from them. +With `digest.useCleartextPasswords`, nobody could sign in with Digest authentication, because the plugin replaced `passwordEncoder` with one that stored `{noop}secret`. +`passwordEncoder` now stays as configured, and the application stores the password as it was typed, so an application with stored values such as `{noop}secret` removes the `{noop}` prefix from them and no longer stores them with `springSecurityService.encodePassword`. +A form or Basic authentication signs a user in with their password in either mode. * *`fii.alwaysReauthenticate` in the Spring Security plugin takes effect.* The setting did nothing, because the plugin's security interceptor went straight to the access decision. An application that sets it now has every request authenticated again, as the setting describes. 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 019e8eab638..f8a9070d0db 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 @@ -22,6 +22,7 @@ import grails.plugin.springsecurity.access.NullAfterInvocationProvider import grails.plugin.springsecurity.access.intercept.NullAfterInvocationManager import grails.plugin.springsecurity.access.vote.AuthenticatedVetoableDecisionManager import grails.plugin.springsecurity.access.vote.ClosureVoter +import grails.plugin.springsecurity.authentication.DigestDaoAuthenticationProvider import grails.plugin.springsecurity.authentication.GrailsAnonymousAuthenticationProvider import grails.plugin.springsecurity.authentication.NullAuthenticationEventPublisher import grails.plugin.springsecurity.cache.SpringUserCacheFactoryBean @@ -495,8 +496,25 @@ class SpringSecurityCoreGrailsPlugin extends Plugin { preAuthenticationChecks(classFor('preAuthenticationChecks', DefaultPreAuthenticationChecks)) postAuthenticationChecks(classFor('postAuthenticationChecks', DefaultPostAuthenticationChecks)) - daoAuthenticationProvider(classFor('daoAuthenticationProvider', DaoAuthenticationProvider), ref('userDetailsService')) { - passwordEncoder = ref('passwordEncoder') + if (conf.useDigestAuth && !conf.digest.useCleartextPasswords) { + // what is stored is the hash a browser computes, which no PasswordEncoder can make since it is not given + // the username, so the application makes it + conf.digest.passwordAlreadyEncoded = true + } + + // with Digest authentication what is stored is what the filter needs, which passwordEncoder cannot compare + // with a password, so the provider compares it itself and passwordEncoder stays as configured + Class daoAuthenticationProviderClass = classFor('daoAuthenticationProvider', + conf.useDigestAuth ? DigestDaoAuthenticationProvider : DaoAuthenticationProvider) + boolean digestProvider = DigestDaoAuthenticationProvider.isAssignableFrom(daoAuthenticationProviderClass) + daoAuthenticationProvider(daoAuthenticationProviderClass, ref('userDetailsService')) { + if (digestProvider) { + realmName = conf.digest.realmName // 'Grails Realm' + passwordAlreadyEncoded = conf.digest.passwordAlreadyEncoded + } + else { + passwordEncoder = ref('passwordEncoder') + } userCache = ref('userCache') preAuthenticationChecks = ref('preAuthenticationChecks') postAuthenticationChecks = ref('postAuthenticationChecks') @@ -903,19 +921,6 @@ class SpringSecurityCoreGrailsPlugin extends Plugin { private configureDigestAuth = { conf -> - // the filter hands what is stored to the authentication manager as the credentials, to be compared with itself - if (classFor('passwordEncoder', NoOpPasswordEncoder) == NoOpPasswordEncoder) { - passwordEncoder(NoOpPasswordEncoder) { bean -> - bean.factoryMethod = 'getInstance' - } - } - - // what is stored is the hash a browser computes, which no PasswordEncoder can make since it is not given the - // username, so the application makes it - if (!conf.digest.useCleartextPasswords) { - conf.digest.passwordAlreadyEncoded = true - } - digestAuthenticationEntryPoint(classFor('digestAuthenticationEntryPoint', DigestAuthenticationEntryPoint)) { realmName = conf.digest.realmName // 'Grails Realm' key = conf.digest.key // 'changeme' diff --git a/grails-spring-security/plugin/src/main/groovy/grails/plugin/springsecurity/authentication/DigestDaoAuthenticationProvider.groovy b/grails-spring-security/plugin/src/main/groovy/grails/plugin/springsecurity/authentication/DigestDaoAuthenticationProvider.groovy new file mode 100644 index 00000000000..f2665f832e4 --- /dev/null +++ b/grails-spring-security/plugin/src/main/groovy/grails/plugin/springsecurity/authentication/DigestDaoAuthenticationProvider.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.authentication + +import java.nio.charset.StandardCharsets +import java.security.MessageDigest + +import groovy.transform.CompileStatic + +import org.springframework.security.authentication.BadCredentialsException +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken +import org.springframework.security.authentication.dao.DaoAuthenticationProvider +import org.springframework.security.core.AuthenticationException +import org.springframework.security.core.userdetails.UserDetails +import org.springframework.security.core.userdetails.UserDetailsService +import org.springframework.security.crypto.password.NoOpPasswordEncoder + +/** + * The {@code daoAuthenticationProvider} the plugin defines with {@code useDigestAuth}, which compares what is presented + * with what Digest authentication has a user store: the hash a browser computes from the username, the realm name and + * the password, or with {@code digest.useCleartextPasswords} the password as it was typed. + * + *

A password that a form or Basic authentication sends is hashed as a browser hashes it before it is compared, so a + * user signs in with their password in either mode. {@code DigestAuthenticationFilter} leaves a token whose principal + * is the {@code UserDetails} it loaded and whose credentials are what is stored, for the security interceptor to + * authenticate; only in a token whose principal is a {@code UserDetails} is what is stored accepted as it is. The + * principal of what a form or Basic authentication sends is the username, so the stored hash does not sign anyone in + * there.

+ * + *

The {@code passwordEncoder} bean is not used to compare, so it stays as configured for everything else.

+ * + * @since 9.1 + */ +@CompileStatic +class DigestDaoAuthenticationProvider extends DaoAuthenticationProvider { + + private static final String BAD_CREDENTIALS = 'AbstractUserDetailsAuthenticationProvider.badCredentials' + + /** The realm name a browser hashes the password with, {@code digest.realmName}. */ + String realmName + + /** + * Whether what is stored is the hash a browser computes rather than the password, as the filter's + * {@code passwordAlreadyEncoded} is. + */ + boolean passwordAlreadyEncoded = true + + DigestDaoAuthenticationProvider(UserDetailsService userDetailsService) { + super(userDetailsService) + // Not used to compare a password. A sign-in for a username nobody has is compared with what this encoder made, + // so that it takes about as long as one for a user, and with what is compared here as cheap as it is, a slower + // encoder would tell from the time a sign-in takes which usernames exist. + setPasswordEncoder(NoOpPasswordEncoder.getInstance()) + } + + @Override + protected void additionalAuthenticationChecks(UserDetails user, UsernamePasswordAuthenticationToken authentication) + throws AuthenticationException { + Object credentials = authentication.credentials + if (credentials == null) { + logger.debug('Failed to authenticate since no credentials provided') + throw new BadCredentialsException(messages.getMessage(BAD_CREDENTIALS, 'Bad credentials')) + } + if (!matches(user, authentication.principal, credentials.toString())) { + logger.debug('Failed to authenticate since password does not match stored value') + throw new BadCredentialsException(messages.getMessage(BAD_CREDENTIALS, 'Bad credentials')) + } + } + + private boolean matches(UserDetails user, Object principal, String presented) { + String stored = user.password + if (stored == null) { + return false + } + if (!passwordAlreadyEncoded) { + return isEqual(presented, stored) + } + if (isEqual(md5Hex("${user.username}:${realmName}:${presented}"), stored)) { + return true + } + // what the filter left, or a token authenticated before that still holds what it was authenticated with + principal instanceof UserDetails && isEqual(presented, stored) + } + + private static String md5Hex(String value) { + HexFormat.of().formatHex(MessageDigest.getInstance('MD5').digest(value.getBytes(StandardCharsets.UTF_8))) + } + + private static boolean isEqual(String presented, String stored) { + MessageDigest.isEqual(presented.getBytes(StandardCharsets.UTF_8), stored.getBytes(StandardCharsets.UTF_8)) + } +} diff --git a/grails-spring-security/plugin/src/test/groovy/grails/plugin/springsecurity/DigestAuthenticationSpec.groovy b/grails-spring-security/plugin/src/test/groovy/grails/plugin/springsecurity/DigestAuthenticationSpec.groovy index 7b5b9222e93..7f5039b77b8 100644 --- a/grails-spring-security/plugin/src/test/groovy/grails/plugin/springsecurity/DigestAuthenticationSpec.groovy +++ b/grails-spring-security/plugin/src/test/groovy/grails/plugin/springsecurity/DigestAuthenticationSpec.groovy @@ -20,17 +20,23 @@ package grails.plugin.springsecurity import jakarta.servlet.FilterChain +import org.springframework.mock.web.MockFilterChain import org.springframework.mock.web.MockHttpServletRequest import org.springframework.mock.web.MockHttpServletResponse +import org.springframework.security.authentication.AuthenticationManager import org.springframework.security.authentication.BadCredentialsException import org.springframework.security.authentication.UsernamePasswordAuthenticationToken import org.springframework.security.core.Authentication import org.springframework.security.core.authority.SimpleGrantedAuthority +import org.springframework.security.core.context.SecurityContext import org.springframework.security.core.context.SecurityContextHolder import org.springframework.security.core.userdetails.User import org.springframework.security.core.userdetails.UserDetails import org.springframework.security.core.userdetails.UserDetailsService +import org.springframework.security.core.userdetails.UsernameNotFoundException +import org.springframework.security.crypto.password.DelegatingPasswordEncoder import org.springframework.security.crypto.password.PasswordEncoder +import org.springframework.security.web.context.HttpSessionSecurityContextRepository import spock.lang.Specification import grails.core.GrailsApplication @@ -39,7 +45,9 @@ import grails.web.CamelCaseUrlConverter /** * The handshake a browser makes, against what the plugin creates with {@code useDigestAuth}: the challenge from its - * entry point, and the response sent through its whole filter chain, which is what grants the request. + * entry point, and the response sent through its whole filter chain, which is what grants the request. And what the + * rest of the application still does with Digest authentication on: a form sign-in, a Basic one, and the user that + * {@code spring.security.user.*} describes. */ abstract class AbstractDigestAuthenticationSpec extends Specification implements GrailsWebUnitTest { @@ -62,11 +70,16 @@ abstract class AbstractDigestAuthenticationSpec extends Specification implements config.grails.plugin.springsecurity.useDigestAuth = true config.grails.plugin.springsecurity.userDetailsServiceBeanClass = StoredPasswordUserDetailsService config.grails.plugin.springsecurity.digest = digestConfig() + config.spring.security.user.name = 'admin' + config.spring.security.user.password = 'admin-secret' } } protected abstract Map digestConfig() + /** What the application stores for a user with this password. */ + protected abstract String storedFor(String password) + void cleanup() { SecurityContextHolder.clearContext() } @@ -77,6 +90,70 @@ abstract class AbstractDigestAuthenticationSpec extends Specification implements SpringSecurityUtils.application = null } + void 'a browser signs a user in with their password, and not with another'() { + given: + store(storedFor('secret')) + + expect: + signedInWith('secret') == 'user' + signedInWith('wrong') == null + } + + void 'an account that is disabled is refused, however right the password'() { + given: + store(storedFor('secret'), false) + + expect: + signedInWith('secret') == null + } + + void 'a form signs a user in with their password, and not with another'() { + given: + store(storedFor('secret')) + + expect: + signedInThroughForm('user', 'secret') == 'user' + signedInThroughForm('user', 'wrong') == null + } + + void 'what Basic authentication hands the authentication manager signs a user in with their password'() { + given: + store(storedFor('secret')) + + when: + Authentication signedIn = authenticationManager.authenticate( + UsernamePasswordAuthenticationToken.unauthenticated('user', 'secret')) + + then: + signedIn.authenticated + signedIn.name == 'user' + + when: + authenticationManager.authenticate(UsernamePasswordAuthenticationToken.unauthenticated('user', 'wrong')) + + then: + thrown(BadCredentialsException) + } + + void 'the password encoder stays as configured'() { + when: + PasswordEncoder encoder = applicationContext.getBean('passwordEncoder', PasswordEncoder) + + then: + encoder instanceof DelegatingPasswordEncoder + encoder.encode('secret').startsWith('{bcrypt}') + } + + void 'the user spring.security.user describes signs in through a form'() { + expect: + signedInThroughForm('admin', 'admin-secret') == 'admin' + signedInThroughForm('admin', 'wrong') == null + } + + protected AuthenticationManager getAuthenticationManager() { + applicationContext.getBean('authenticationManager', AuthenticationManager) + } + protected void store(String password, boolean enabled = true) { def users = applicationContext.getBean('userDetailsService', StoredPasswordUserDetailsService) users.password = password @@ -107,6 +184,19 @@ abstract class AbstractDigestAuthenticationSpec extends Specification implements reached } + /** Who a login form sending this username and password signs in, if anyone. */ + protected String signedInThroughForm(String username, String password) { + def request = new MockHttpServletRequest('POST', '/login/authenticate') + request.servletPath = '/login/authenticate' + request.addParameter('username', username) + request.addParameter('password', password) + SecurityContextHolder.clearContext() + applicationContext.getBean('springSecurityFilterChainProxy') + .doFilter(request, new MockHttpServletResponse(), new MockFilterChain()) + def context = request.getSession(false)?.getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY) + ((SecurityContext) context)?.authentication?.name + } + static class StoredPasswordUserDetailsService implements UserDetailsService { GrailsApplication grailsApplication @@ -115,6 +205,9 @@ abstract class AbstractDigestAuthenticationSpec extends Specification implements @Override UserDetails loadUserByUsername(String username) { + if (username != 'user') { + throw new UsernameNotFoundException(username) + } new User(username, password, enabled, true, true, true, [new SimpleGrantedAuthority('ROLE_USER')]) } } @@ -126,13 +219,8 @@ class EncodedDigestAuthenticationSpec extends AbstractDigestAuthenticationSpec { [realmName: REALM] } - void 'by default what is stored is the hash a browser computes, and not the password'() { - given: - store("user:${REALM}:secret".md5()) - - expect: - signedInWith('secret') == 'user' - signedInWith('wrong') == null + protected String storedFor(String password) { + "user:${REALM}:${password}".md5() } void 'a password stored as it was typed does not sign anyone in'() { @@ -143,21 +231,22 @@ class EncodedDigestAuthenticationSpec extends AbstractDigestAuthenticationSpec { signedInWith('secret') == null } - void 'an account that is disabled is refused, however right the password'() { + void 'the hash stored does not sign anyone in through a form'() { given: - store("user:${REALM}:secret".md5(), false) + String hash = storedFor('secret') + store(hash) expect: - signedInWith('secret') == null + signedInThroughForm('user', hash) == null } - void 'a form cannot sign in a user with the hash stored'() { + void 'the hash stored does not sign anyone in through Basic authentication'() { given: - store("user:${REALM}:secret".md5()) + String hash = storedFor('secret') + store(hash) when: - applicationContext.getBean('daoAuthenticationProvider') - .authenticate(UsernamePasswordAuthenticationToken.unauthenticated('user', 'secret')) + authenticationManager.authenticate(UsernamePasswordAuthenticationToken.unauthenticated('user', hash)) then: thrown(BadCredentialsException) @@ -170,24 +259,15 @@ class CleartextDigestAuthenticationSpec extends AbstractDigestAuthenticationSpec [realmName: REALM, useCleartextPasswords: true] } - void 'with cleartext passwords what the password encoder stores is what the filter hashes'() { - given: - store(applicationContext.getBean('passwordEncoder', PasswordEncoder).encode('secret')) - - expect: - signedInWith('secret') == 'user' - signedInWith('wrong') == null + protected String storedFor(String password) { + password } - void 'with cleartext passwords a form still signs a user in'() { + void 'a password stored by the password encoder does not sign anyone in'() { given: store(applicationContext.getBean('passwordEncoder', PasswordEncoder).encode('secret')) - when: - Authentication signedIn = applicationContext.getBean('daoAuthenticationProvider') - .authenticate(UsernamePasswordAuthenticationToken.unauthenticated('user', 'secret')) - - then: - signedIn.authenticated + expect: + signedInWith('secret') == null } } diff --git a/grails-spring-security/plugin/src/test/groovy/grails/plugin/springsecurity/PluginBeansSpec.groovy b/grails-spring-security/plugin/src/test/groovy/grails/plugin/springsecurity/PluginBeansSpec.groovy index 281fe4f43a3..b1100afae1c 100644 --- a/grails-spring-security/plugin/src/test/groovy/grails/plugin/springsecurity/PluginBeansSpec.groovy +++ b/grails-spring-security/plugin/src/test/groovy/grails/plugin/springsecurity/PluginBeansSpec.groovy @@ -21,6 +21,8 @@ package grails.plugin.springsecurity import org.springframework.boot.web.servlet.ServletListenerRegistrationBean import org.springframework.security.authentication.AuthenticationProvider import org.springframework.security.authentication.ProviderManager +import org.springframework.security.authentication.dao.DaoAuthenticationProvider +import org.springframework.security.core.userdetails.UserDetailsService import org.springframework.security.crypto.password.DelegatingPasswordEncoder import org.springframework.security.crypto.password.MessageDigestPasswordEncoder import org.springframework.security.crypto.password.PasswordEncoder @@ -32,6 +34,7 @@ import org.springframework.security.web.util.matcher.AnyRequestMatcher import spock.lang.Specification import grails.plugin.springsecurity.access.NullAfterInvocationProvider +import grails.plugin.springsecurity.authentication.DigestDaoAuthenticationProvider import grails.testing.web.GrailsWebUnitTest import grails.web.CamelCaseUrlConverter @@ -184,3 +187,73 @@ class CustomClassesPluginBeansSpec extends AbstractPluginBeansSpec { } } } + +class DigestPluginBeansSpec extends AbstractPluginBeansSpec { + + protected void configure(Object securityConfig) { + securityConfig.useDigestAuth = true + securityConfig.digest = [realmName: 'Test Realm'] + } + + void 'with Digest authentication the provider is told the realm and that what is stored is the hash'() { + given: + DigestDaoAuthenticationProvider provider = + applicationContext.getBean('daoAuthenticationProvider', DigestDaoAuthenticationProvider) + + expect: + provider.realmName == 'Test Realm' + provider.passwordAlreadyEncoded + applicationContext.getBean('passwordEncoder') instanceof DelegatingPasswordEncoder + } +} + +class CleartextDigestPluginBeansSpec extends AbstractPluginBeansSpec { + + protected void configure(Object securityConfig) { + securityConfig.useDigestAuth = true + securityConfig.digest = [realmName: 'Test Realm', useCleartextPasswords: true] + securityConfig.daoAuthenticationProviderBeanClass = CustomDigestDaoAuthenticationProvider + } + + void 'a subclass of the Digest provider configured in its place is told what it is'() { + given: + CustomDigestDaoAuthenticationProvider provider = + applicationContext.getBean('daoAuthenticationProvider', CustomDigestDaoAuthenticationProvider) + + expect: + provider.realmName == 'Test Realm' + !provider.passwordAlreadyEncoded + } + + static class CustomDigestDaoAuthenticationProvider extends DigestDaoAuthenticationProvider { + + CustomDigestDaoAuthenticationProvider(UserDetailsService userDetailsService) { + super(userDetailsService) + } + } +} + +class CustomProviderDigestPluginBeansSpec extends AbstractPluginBeansSpec { + + protected void configure(Object securityConfig) { + securityConfig.useDigestAuth = true + securityConfig.daoAuthenticationProviderBeanClass = CustomDaoAuthenticationProvider + } + + void 'a provider class of the application is given the password encoder with Digest authentication too'() { + expect: + applicationContext.getBean('daoAuthenticationProvider', CustomDaoAuthenticationProvider).encoder + .is(applicationContext.getBean('passwordEncoder')) + } + + static class CustomDaoAuthenticationProvider extends DaoAuthenticationProvider { + + CustomDaoAuthenticationProvider(UserDetailsService userDetailsService) { + super(userDetailsService) + } + + PasswordEncoder getEncoder() { + getPasswordEncoder() + } + } +} From 909c6ed6bde748e20493ebf27a88beb47eb043f8 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Mon, 9 Nov 2026 08:27:13 -0800 Subject: [PATCH 70/78] Leave a signed-in user whose credentials were erased to the access decision fii.alwaysReauthenticate sent every authenticated Authentication back through the authentication manager. The one a form login keeps in the session has had its credentials erased by then, as providerManager.eraseCredentialsAfterAuthentication does by default, so the provider refused it and the first secured request after signing in was sent back to the login form. An authenticated Authentication without credentials is now returned as it is. One that still holds its credentials is authenticated again, and what a filter leaves unauthenticated, as DigestAuthenticationFilter does, is authenticated whatever the setting. The Javadoc now says so, and that a request without security attributes authenticates nothing. FilterSecurityInterceptorSpec signs a user in through a real ProviderManager and DaoAuthenticationProvider and sends a secured request through the interceptor, which fails without the change. --- .../springSecurity/core/urlProperties.adoc | 2 +- .../src/en/guide/upgrading/upgrading90x.adoc | 4 +- .../FilterSecurityInterceptor.groovy | 14 +- ...itional-spring-configuration-metadata.json | 2 +- .../FilterSecurityInterceptorSpec.groovy | 133 ++++++++++++++++++ 5 files changed, 148 insertions(+), 7 deletions(-) diff --git a/grails-doc/src/en/guide/security/securityPlugins/springSecurity/core/urlProperties.adoc b/grails-doc/src/en/guide/security/securityPlugins/springSecurity/core/urlProperties.adoc index fdbde23d67b..0d41168a6a9 100644 --- a/grails-doc/src/en/guide/security/securityPlugins/springSecurity/core/urlProperties.adoc +++ b/grails-doc/src/en/guide/security/securityPlugins/springSecurity/core/urlProperties.adoc @@ -177,7 +177,7 @@ The table shows configurable URL-related properties. |fii.alwaysReauthenticate |`false` -|If `true`, re-authenticates when there is a `Authentication` in the `SecurityContext` +|If `true`, re-authenticates the `Authentication` in the `SecurityContext` for every request to a secured URL, unless its credentials were erased once it was authenticated, as `providerManager.eraseCredentialsAfterAuthentication` does by default |fii.rejectPublicInvocations |`true` diff --git a/grails-doc/src/en/guide/upgrading/upgrading90x.adoc b/grails-doc/src/en/guide/upgrading/upgrading90x.adoc index e9141dbf818..3d63448c44c 100644 --- a/grails-doc/src/en/guide/upgrading/upgrading90x.adoc +++ b/grails-doc/src/en/guide/upgrading/upgrading90x.adoc @@ -148,7 +148,9 @@ With `digest.useCleartextPasswords`, nobody could sign in with Digest authentica A form or Basic authentication signs a user in with their password in either mode. * *`fii.alwaysReauthenticate` in the Spring Security plugin takes effect.* -The setting did nothing, because the plugin's security interceptor went straight to the access decision. An application that sets it now has every request authenticated again, as the setting describes. +The setting did nothing, because the plugin's security interceptor went straight to the access decision. +An application that sets it now has the `Authentication` of a request to a secured URL authenticated again, while it still holds its credentials, as it does with `providerManager.eraseCredentialsAfterAuthentication` set to `false`. +By default the credentials are erased at sign-in, so a user signed in through a form is not authenticated again. [TIP] ==== diff --git a/grails-spring-security/compat/src/main/groovy/org/springframework/security/web/access/intercept/FilterSecurityInterceptor.groovy b/grails-spring-security/compat/src/main/groovy/org/springframework/security/web/access/intercept/FilterSecurityInterceptor.groovy index 0a97429c460..e9a98ea8dcb 100644 --- a/grails-spring-security/compat/src/main/groovy/org/springframework/security/web/access/intercept/FilterSecurityInterceptor.groovy +++ b/grails-spring-security/compat/src/main/groovy/org/springframework/security/web/access/intercept/FilterSecurityInterceptor.groovy @@ -78,12 +78,18 @@ class FilterSecurityInterceptor extends AbstractSecurityInterceptor implements F } /** - * Authenticates what a filter left in the context without doing so, as {@code DigestAuthenticationFilter} does so - * that the account checks of the authentication manager still run, or everything if {@code alwaysReauthenticate} - * is set. Spring Security's own {@code AbstractSecurityInterceptor} did this before Spring Security 7 removed it. + * Authenticates, for a request that has security attributes, what a filter left in the context without doing so, + * as {@code DigestAuthenticationFilter} does so that the account checks of the authentication manager still run. + * A request without security attributes is passed on before this, so nothing is authenticated for it, as Spring + * Security's own {@code AbstractSecurityInterceptor} did for public invocations before Spring Security 7 removed it. + * + *

With {@code alwaysReauthenticate}, what is authenticated already is authenticated again too, but only while it + * still holds its credentials. The authentication manager erases them by default once it has authenticated it, as + * for a form login kept in the session, and such an authentication, with nothing left to authenticate with, is + * returned as it is.

*/ private Authentication authenticateIfRequired(Authentication authentication) { - if (authentication.authenticated && !alwaysReauthenticate) { + if (authentication.authenticated && (!alwaysReauthenticate || authentication.credentials == null)) { return authentication } Authentication authenticated = authenticationManager.authenticate(authentication) diff --git a/grails-spring-security/plugin/src/main/resources/META-INF/additional-spring-configuration-metadata.json b/grails-spring-security/plugin/src/main/resources/META-INF/additional-spring-configuration-metadata.json index 9fb9659330e..c39b0a334ac 100644 --- a/grails-spring-security/plugin/src/main/resources/META-INF/additional-spring-configuration-metadata.json +++ b/grails-spring-security/plugin/src/main/resources/META-INF/additional-spring-configuration-metadata.json @@ -729,7 +729,7 @@ { "name": "grails.plugin.springsecurity.fii.alwaysReauthenticate", "type": "java.lang.Boolean", - "description": "If true, re-authenticates when there is an Authentication in the SecurityContext.", + "description": "If true, re-authenticates the Authentication in the SecurityContext for every request to a secured URL, unless its credentials were erased once it was authenticated, as providerManager.eraseCredentialsAfterAuthentication does by default.", "group": "grails.plugin.springsecurity.authentication" }, { diff --git a/grails-spring-security/plugin/src/test/groovy/grails/plugin/springsecurity/web/access/intercept/FilterSecurityInterceptorSpec.groovy b/grails-spring-security/plugin/src/test/groovy/grails/plugin/springsecurity/web/access/intercept/FilterSecurityInterceptorSpec.groovy index b6a774ba181..6ca5215768a 100644 --- a/grails-spring-security/plugin/src/test/groovy/grails/plugin/springsecurity/web/access/intercept/FilterSecurityInterceptorSpec.groovy +++ b/grails-spring-security/plugin/src/test/groovy/grails/plugin/springsecurity/web/access/intercept/FilterSecurityInterceptorSpec.groovy @@ -23,6 +23,7 @@ import jakarta.servlet.Servlet import org.springframework.http.HttpStatus import org.springframework.mock.web.MockFilterChain +import org.springframework.mock.web.MockHttpServletRequest import org.springframework.security.access.AccessDecisionManager import org.springframework.security.access.AccessDeniedException import org.springframework.security.access.SecurityConfig @@ -30,9 +31,15 @@ import org.springframework.security.access.vote.RoleVoter import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException import org.springframework.security.authentication.AuthenticationManager import org.springframework.security.authentication.BadCredentialsException +import org.springframework.security.authentication.ProviderManager import org.springframework.security.authentication.UsernamePasswordAuthenticationToken +import org.springframework.security.authentication.dao.DaoAuthenticationProvider +import org.springframework.security.core.Authentication import org.springframework.security.core.authority.AuthorityUtils import org.springframework.security.core.context.SecurityContextHolder +import org.springframework.security.core.userdetails.User +import org.springframework.security.core.userdetails.UserDetails +import org.springframework.security.provisioning.InMemoryUserDetailsManager import org.springframework.security.web.FilterInvocation import org.springframework.security.web.access.ExceptionTranslationFilter import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource @@ -167,6 +174,116 @@ class FilterSecurityInterceptorSpec extends AbstractUnitSpec { true | 1 } + void 'with alwaysReauthenticate a user whose credentials were erased once signed in reaches a secured page'() { + given: 'a user signed in through an authentication manager that erases the credentials, as it does by default' + def provider = new DaoAuthenticationProvider(new InMemoryUserDetailsManager(user('secret'))) + ProviderManager manager = Spy(constructorArgs: [[provider]]) + Authentication signedIn = manager.authenticate(UsernamePasswordAuthenticationToken.unauthenticated('user', 'secret')) + SecurityContextHolder.context.authentication = signedIn + def interceptor = securedBy(manager) + FilterChain chain = Mock() + + when: + interceptor.doFilter(request, response, chain) + + then: 'what was signed in is used as it is, since it has nothing left to be authenticated with' + 0 * manager.authenticate(_) + 1 * chain.doFilter(request, response) + signedIn.credentials == null + SecurityContextHolder.context.authentication.is(signedIn) + } + + void 'with alwaysReauthenticate a user who still holds their password is authenticated again on every request'() { + given: 'a user signed in through an authentication manager that keeps the credentials' + def users = new InMemoryUserDetailsManager(user('secret')) + def manager = new ProviderManager([new DaoAuthenticationProvider(users)]) + manager.eraseCredentialsAfterAuthentication = false + Authentication signedIn = manager.authenticate(UsernamePasswordAuthenticationToken.unauthenticated('user', 'secret')) + SecurityContextHolder.context.authentication = signedIn + def interceptor = securedBy(manager) + FilterChain chain = Mock() + + when: + interceptor.doFilter(request, response, chain) + + then: + 1 * chain.doFilter(request, response) + !SecurityContextHolder.context.authentication.is(signedIn) + SecurityContextHolder.context.authentication.authenticated + + when: 'the password is changed before the next request' + users.updateUser(user('changed')) + def next = new MockHttpServletRequest('GET', '/secure') + interceptor.doFilter(next, response, chain) + + then: + thrown(BadCredentialsException) + 0 * chain._ + } + + void 'what a filter left unauthenticated is authenticated when alwaysReauthenticate is #always'() { + given: + def manager = new ProviderManager([new DaoAuthenticationProvider(new InMemoryUserDetailsManager(user('secret')))]) + SecurityContextHolder.context.authentication = UsernamePasswordAuthenticationToken.unauthenticated('user', 'secret') + def interceptor = securedBy(manager) + interceptor.alwaysReauthenticate = always + FilterChain chain = Mock() + + when: + interceptor.doFilter(request, response, chain) + + then: + 1 * chain.doFilter(request, response) + SecurityContextHolder.context.authentication.authenticated + SecurityContextHolder.context.authentication.name == 'user' + + where: + always << [false, true] + } + + void 'what a filter left unauthenticated without credentials is refused when alwaysReauthenticate is #always'() { + given: + def manager = new ProviderManager([new DaoAuthenticationProvider(new InMemoryUserDetailsManager(user('secret')))]) + SecurityContextHolder.context.authentication = UsernamePasswordAuthenticationToken.unauthenticated('user', null) + def interceptor = securedBy(manager) + interceptor.alwaysReauthenticate = always + FilterChain chain = Mock() + + when: + interceptor.doFilter(request, response, chain) + + then: + thrown(BadCredentialsException) + 0 * chain._ + + where: + always << [false, true] + } + + void 'a request without security attributes authenticates nothing, even with alwaysReauthenticate'() { + given: + def left = UsernamePasswordAuthenticationToken.unauthenticated('user', 'secret') + SecurityContextHolder.context.authentication = left + AuthenticationManager manager = Mock() + def interceptor = new FilterSecurityInterceptor( + authenticationManager: manager, + alwaysReauthenticate: true, + rejectPublicInvocations: false, + securityMetadataSource: Stub(FilterInvocationSecurityMetadataSource) { + getAttributes(_ as FilterInvocation) >> null + } + ) + FilterChain chain = Mock() + + when: + interceptor.doFilter(request, response, chain) + + then: + 0 * manager._ + 1 * chain.doFilter(request, response) + SecurityContextHolder.context.authentication.is(left) + } + private FilterSecurityInterceptor interceptorFor(AuthenticationManager manager, AccessDecisionManager decisions) { new FilterSecurityInterceptor( authenticationManager: manager, @@ -177,6 +294,22 @@ class FilterSecurityInterceptorSpec extends AbstractUnitSpec { ) } + /** An interceptor that re-authenticates, in front of a URL a user with {@code ROLE_USER} may reach. */ + private FilterSecurityInterceptor securedBy(AuthenticationManager manager) { + new FilterSecurityInterceptor( + authenticationManager: manager, + alwaysReauthenticate: true, + accessDecisionManager: new AuthenticatedVetoableDecisionManager([new WebExpressionVoter(), new RoleVoter()]), + securityMetadataSource: Stub(FilterInvocationSecurityMetadataSource) { + getAttributes(_ as FilterInvocation) >> [new SecurityConfig('ROLE_USER')] + } + ) + } + + private static UserDetails user(String password) { + User.withUsername('user').password("{noop}${password}").roles('USER').build() + } + void 'secured filter chain responds with #status for #scenario'() { given: if (role != null) { From ae1442e2389c3f83328ffcaf1f79a5b8c2c91cd1 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Mon, 9 Nov 2026 08:49:37 -0800 Subject: [PATCH 71/78] Run the action that a forward during an async dispatch names A forward made while the result of async processing was answered, such as the one a view from a forward: name or a Spring MVC handler makes, never ran the Grails action it named: the request answered 200 with an empty body. UrlMappingsInfoHandlerAdapter took any request carrying jakarta.servlet.async.request_uri for the dispatch that returns the async result, and a forward carries it too. UrlMappingsHandlerMapping also answered every dispatch but an error dispatch with the match it had cached on the request, so a forward that did run an action ran the one that started the async processing again. The adapter now takes only the ASYNC dispatch for that one, and the handler mapping answers only that dispatch with its cached match, as it is there for. Any other dispatch matches its own URI, which also fixes a plain forward from a Grails action's view running that action again, since only forward() and g:include cleared the cache before dispatching. UrlMappingsInfoHandlerAdapterAsyncSpec forwards during the async dispatch, UrlMappingsHandlerMappingSpec forwards and includes after one, and the example apps forward from a Grails action's async result to a failing action, answered by the error view and by an error controller, on Tomcat, Jetty and Undertow. Those rows answered 200 with nothing before. --- .../issue11102/FailingController.groovy | 20 +++++++++++ .../FailedActionObservationSpec.groovy | 34 ++++++++++--------- .../issue12688/FailingController.groovy | 20 +++++++++++ .../JettyFailedActionObservationSpec.groovy | 32 +++++++++-------- .../undertowapp/FailingController.groovy | 20 +++++++++++ ...UndertowFailedActionObservationSpec.groovy | 32 +++++++++-------- .../mvc/UrlMappingsHandlerMapping.groovy | 5 ++- .../mvc/UrlMappingsInfoHandlerAdapter.groovy | 5 ++- .../mapping/mvc/ActionReturnValuesSpec.groovy | 4 +++ .../mvc/UrlMappingsHandlerMappingSpec.groovy | 34 +++++++++++++++++++ ...MappingsInfoHandlerAdapterAsyncSpec.groovy | 28 +++++++++++++++ 11 files changed, 186 insertions(+), 48 deletions(-) diff --git a/grails-test-examples/issue-11102/grails-app/controllers/issue11102/FailingController.groovy b/grails-test-examples/issue-11102/grails-app/controllers/issue11102/FailingController.groovy index 088dc227243..ab4872b0e5b 100644 --- a/grails-test-examples/issue-11102/grails-app/controllers/issue11102/FailingController.groovy +++ b/grails-test-examples/issue-11102/grails-app/controllers/issue11102/FailingController.groovy @@ -22,6 +22,8 @@ package issue11102 import org.springframework.web.context.request.async.DeferredResult import org.springframework.web.context.request.async.WebAsyncManager import org.springframework.web.context.request.async.WebAsyncUtils +import org.springframework.web.servlet.ModelAndView +import org.springframework.web.servlet.view.InternalResourceView class FailingController { @@ -67,6 +69,14 @@ class FailingController { forward(action: 'answeredByView') } + def forwardedToViewAsynchronously() { + forwardAsynchronously('/failing/answeredByView') + } + + def forwardedToControllerAsynchronously() { + forwardAsynchronously('/failing/answeredByController') + } + def forwardedToController() { forward(action: 'answeredByController') } @@ -114,6 +124,16 @@ class FailingController { result.errorResult = failure } + /** + * Completes asynchronous processing with a view that forwards, as a view Spring MVC resolves from a + * {@code forward:} name does, so that the action the path maps to answers on the asynchronous dispatch. + */ + private void forwardAsynchronously(String path) { + DeferredResult result = new DeferredResult<>() + startAsync(result) + result.result = new ModelAndView(new InternalResourceView(path)) + } + /** * Starts asynchronous processing that nothing completes. Unless the container ends it when the action fails, as * Tomcat does when the exception is left on the request, it ends when it times out. diff --git a/grails-test-examples/issue-11102/src/integration-test/groovy/issue11102/FailedActionObservationSpec.groovy b/grails-test-examples/issue-11102/src/integration-test/groovy/issue11102/FailedActionObservationSpec.groovy index 05d6ddca417..0e14d0e212c 100644 --- a/grails-test-examples/issue-11102/src/integration-test/groovy/issue11102/FailedActionObservationSpec.groovy +++ b/grails-test-examples/issue-11102/src/integration-test/groovy/issue11102/FailedActionObservationSpec.groovy @@ -79,22 +79,24 @@ class FailedActionObservationSpec extends Specification implements HttpClientSup NOTIFIED[path] == [exception] where: - handler | path | route | page || exception - 'the error view' | '/failing/answeredByView' | '/failing/answeredByView' | 'An error has occurred' || 'IllegalStateException' - 'an error controller' | '/failing/answeredByController' | '/failing/answeredByController' | 'Answered by the error controller' || 'UnsupportedOperationException' - 'the error view, asynchronously' | '/failing/answeredByViewAsynchronously' | '/failing/answeredByViewAsynchronously' | 'An error has occurred' || 'IllegalStateException' - 'an error controller, asynchronously' | '/failing/answeredByControllerAsynchronously' | '/failing/answeredByControllerAsynchronously' | 'Answered by the error controller' || 'UnsupportedOperationException' - 'the error view, after starting async' | '/failing/answeredByViewAfterStartingAsync' | '/failing/answeredByViewAfterStartingAsync' | 'An error has occurred' || 'IllegalStateException' - 'an error controller, after starting async' | '/failing/answeredByControllerAfterStartingAsync' | '/failing/answeredByControllerAfterStartingAsync' | 'Answered by the error controller' || 'UnsupportedOperationException' - 'the error view, after a forward' | '/failing/forwardedToView' | '/failing/answeredByView' | 'An error has occurred' || 'IllegalStateException' - 'an error controller, after a forward' | '/failing/forwardedToController' | '/failing/answeredByController' | 'Answered by the error controller' || 'UnsupportedOperationException' - 'the error view, after an asynchronous forward' | '/spring/forwardedToViewAsynchronously' | '/spring/answeredByView' | 'An error has occurred' || 'IllegalStateException' - 'an error controller, after an asynchronous forward' | '/spring/forwardedToControllerAsynchronously' | '/spring/answeredByController' | 'Answered by the error controller' || 'UnsupportedOperationException' - 'the error view, for an Error' | '/failing/answeredByViewForAnError' | '/failing/answeredByViewForAnError' | 'An error has occurred' || 'AssertionError' - 'an error controller, for an Error' | '/failing/answeredByControllerForAnError' | '/failing/answeredByControllerForAnError' | 'Answered by the error controller' || 'StackOverflowError' - 'an error controller that forwards' | '/failing/answeredByForwardingController' | '/failing/answeredByForwardingController' | 'Answered by the error controller' || 'ArithmeticException' - 'the error view, after an include' | '/failing/failsAfterInclude' | '/failing/failsAfterInclude' | 'An error has occurred' || 'IllegalStateException' - 'an error controller, after an interceptor failed' | '/failing/failsInInterceptor' | '/failing/failsInInterceptor' | 'Answered by the error controller' || 'UnsupportedOperationException' + handler | path | route | page || exception + 'the error view' | '/failing/answeredByView' | '/failing/answeredByView' | 'An error has occurred' || 'IllegalStateException' + 'an error controller' | '/failing/answeredByController' | '/failing/answeredByController' | 'Answered by the error controller' || 'UnsupportedOperationException' + 'the error view, asynchronously' | '/failing/answeredByViewAsynchronously' | '/failing/answeredByViewAsynchronously' | 'An error has occurred' || 'IllegalStateException' + 'an error controller, asynchronously' | '/failing/answeredByControllerAsynchronously' | '/failing/answeredByControllerAsynchronously' | 'Answered by the error controller' || 'UnsupportedOperationException' + 'the error view, after starting async' | '/failing/answeredByViewAfterStartingAsync' | '/failing/answeredByViewAfterStartingAsync' | 'An error has occurred' || 'IllegalStateException' + 'an error controller, after starting async' | '/failing/answeredByControllerAfterStartingAsync' | '/failing/answeredByControllerAfterStartingAsync' | 'Answered by the error controller' || 'UnsupportedOperationException' + 'the error view, after a forward' | '/failing/forwardedToView' | '/failing/answeredByView' | 'An error has occurred' || 'IllegalStateException' + 'an error controller, after a forward' | '/failing/forwardedToController' | '/failing/answeredByController' | 'Answered by the error controller' || 'UnsupportedOperationException' + 'the error view, after an asynchronous forward from Spring MVC' | '/spring/forwardedToViewAsynchronously' | '/spring/answeredByView' | 'An error has occurred' || 'IllegalStateException' + 'an error controller, after an asynchronous forward from Spring MVC' | '/spring/forwardedToControllerAsynchronously' | '/spring/answeredByController' | 'Answered by the error controller' || 'UnsupportedOperationException' + 'the error view, after an asynchronous forward from an action' | '/failing/forwardedToViewAsynchronously' | '/failing/answeredByView' | 'An error has occurred' || 'IllegalStateException' + 'an error controller, after an asynchronous forward from an action' | '/failing/forwardedToControllerAsynchronously' | '/failing/answeredByController' | 'Answered by the error controller' || 'UnsupportedOperationException' + 'the error view, for an Error' | '/failing/answeredByViewForAnError' | '/failing/answeredByViewForAnError' | 'An error has occurred' || 'AssertionError' + 'an error controller, for an Error' | '/failing/answeredByControllerForAnError' | '/failing/answeredByControllerForAnError' | 'Answered by the error controller' || 'StackOverflowError' + 'an error controller that forwards' | '/failing/answeredByForwardingController' | '/failing/answeredByForwardingController' | 'Answered by the error controller' || 'ArithmeticException' + 'the error view, after an include' | '/failing/failsAfterInclude' | '/failing/failsAfterInclude' | 'An error has occurred' || 'IllegalStateException' + 'an error controller, after an interceptor failed' | '/failing/failsInInterceptor' | '/failing/failsInInterceptor' | 'Answered by the error controller' || 'UnsupportedOperationException' } void 'a failure #handler answers inside an include is not the failure of the page that included it'() { diff --git a/grails-test-examples/jetty/grails-app/controllers/issue12688/FailingController.groovy b/grails-test-examples/jetty/grails-app/controllers/issue12688/FailingController.groovy index 3e5fa7d619b..15e03975240 100644 --- a/grails-test-examples/jetty/grails-app/controllers/issue12688/FailingController.groovy +++ b/grails-test-examples/jetty/grails-app/controllers/issue12688/FailingController.groovy @@ -21,6 +21,8 @@ package issue12688 import org.springframework.web.context.request.async.DeferredResult import org.springframework.web.context.request.async.WebAsyncManager import org.springframework.web.context.request.async.WebAsyncUtils +import org.springframework.web.servlet.ModelAndView +import org.springframework.web.servlet.view.InternalResourceView class FailingController { @@ -66,6 +68,14 @@ class FailingController { forward(action: 'answeredByView') } + def forwardedToViewAsynchronously() { + forwardAsynchronously('/failing/answeredByView') + } + + def forwardedToControllerAsynchronously() { + forwardAsynchronously('/failing/answeredByController') + } + def forwardedToController() { forward(action: 'answeredByController') } @@ -101,6 +111,16 @@ class FailingController { result.errorResult = failure } + /** + * Completes asynchronous processing with a view that forwards, as a view Spring MVC resolves from a + * {@code forward:} name does, so that the action the path maps to answers on the asynchronous dispatch. + */ + private void forwardAsynchronously(String path) { + DeferredResult result = new DeferredResult<>() + startAsync(result) + result.result = new ModelAndView(new InternalResourceView(path)) + } + /** * Starts asynchronous processing that nothing completes. Unless the container ends it when the action fails, as * Tomcat does when the exception is left on the request, it ends when it times out. diff --git a/grails-test-examples/jetty/src/integration-test/groovy/issue12688/JettyFailedActionObservationSpec.groovy b/grails-test-examples/jetty/src/integration-test/groovy/issue12688/JettyFailedActionObservationSpec.groovy index 29d9afabed7..e1a11eaba7f 100644 --- a/grails-test-examples/jetty/src/integration-test/groovy/issue12688/JettyFailedActionObservationSpec.groovy +++ b/grails-test-examples/jetty/src/integration-test/groovy/issue12688/JettyFailedActionObservationSpec.groovy @@ -78,21 +78,23 @@ class JettyFailedActionObservationSpec extends Specification implements HttpClie NOTIFIED[path] == [exception] where: - handler | path | route | page || exception - 'the error view' | '/failing/answeredByView' | '/failing/answeredByView' | 'An error has occurred' || 'IllegalStateException' - 'an error controller' | '/failing/answeredByController' | '/failing/answeredByController' | 'Answered by the error controller' || 'UnsupportedOperationException' - 'the error view, asynchronously' | '/failing/answeredByViewAsynchronously' | '/failing/answeredByViewAsynchronously' | 'An error has occurred' || 'IllegalStateException' - 'an error controller, asynchronously' | '/failing/answeredByControllerAsynchronously' | '/failing/answeredByControllerAsynchronously' | 'Answered by the error controller' || 'UnsupportedOperationException' - 'the error view, after starting async' | '/failing/answeredByViewAfterStartingAsync' | '/failing/answeredByViewAfterStartingAsync' | 'An error has occurred' || 'IllegalStateException' - 'an error controller, after starting async' | '/failing/answeredByControllerAfterStartingAsync' | '/failing/answeredByControllerAfterStartingAsync' | 'Answered by the error controller' || 'UnsupportedOperationException' - 'the error view, after a forward' | '/failing/forwardedToView' | '/failing/answeredByView' | 'An error has occurred' || 'IllegalStateException' - 'an error controller, after a forward' | '/failing/forwardedToController' | '/failing/answeredByController' | 'Answered by the error controller' || 'UnsupportedOperationException' - 'the error view, after an asynchronous forward' | '/spring/forwardedToViewAsynchronously' | '/spring/answeredByView' | 'An error has occurred' || 'IllegalStateException' - 'an error controller, after an asynchronous forward' | '/spring/forwardedToControllerAsynchronously' | '/spring/answeredByController' | 'Answered by the error controller' || 'UnsupportedOperationException' - 'the error view, for an Error' | '/failing/answeredByViewForAnError' | '/failing/answeredByViewForAnError' | 'An error has occurred' || 'AssertionError' - 'an error controller, for an Error' | '/failing/answeredByControllerForAnError' | '/failing/answeredByControllerForAnError' | 'Answered by the error controller' || 'StackOverflowError' - 'an error controller that forwards' | '/failing/answeredByForwardingController' | '/failing/answeredByForwardingController' | 'Answered by the error controller' || 'ArithmeticException' - 'the error view, after an include' | '/failing/failsAfterInclude' | '/failing/failsAfterInclude' | 'An error has occurred' || 'IllegalStateException' + handler | path | route | page || exception + 'the error view' | '/failing/answeredByView' | '/failing/answeredByView' | 'An error has occurred' || 'IllegalStateException' + 'an error controller' | '/failing/answeredByController' | '/failing/answeredByController' | 'Answered by the error controller' || 'UnsupportedOperationException' + 'the error view, asynchronously' | '/failing/answeredByViewAsynchronously' | '/failing/answeredByViewAsynchronously' | 'An error has occurred' || 'IllegalStateException' + 'an error controller, asynchronously' | '/failing/answeredByControllerAsynchronously' | '/failing/answeredByControllerAsynchronously' | 'Answered by the error controller' || 'UnsupportedOperationException' + 'the error view, after starting async' | '/failing/answeredByViewAfterStartingAsync' | '/failing/answeredByViewAfterStartingAsync' | 'An error has occurred' || 'IllegalStateException' + 'an error controller, after starting async' | '/failing/answeredByControllerAfterStartingAsync' | '/failing/answeredByControllerAfterStartingAsync' | 'Answered by the error controller' || 'UnsupportedOperationException' + 'the error view, after a forward' | '/failing/forwardedToView' | '/failing/answeredByView' | 'An error has occurred' || 'IllegalStateException' + 'an error controller, after a forward' | '/failing/forwardedToController' | '/failing/answeredByController' | 'Answered by the error controller' || 'UnsupportedOperationException' + 'the error view, after an asynchronous forward from Spring MVC' | '/spring/forwardedToViewAsynchronously' | '/spring/answeredByView' | 'An error has occurred' || 'IllegalStateException' + 'an error controller, after an asynchronous forward from Spring MVC' | '/spring/forwardedToControllerAsynchronously' | '/spring/answeredByController' | 'Answered by the error controller' || 'UnsupportedOperationException' + 'the error view, after an asynchronous forward from an action' | '/failing/forwardedToViewAsynchronously' | '/failing/answeredByView' | 'An error has occurred' || 'IllegalStateException' + 'an error controller, after an asynchronous forward from an action' | '/failing/forwardedToControllerAsynchronously' | '/failing/answeredByController' | 'Answered by the error controller' || 'UnsupportedOperationException' + 'the error view, for an Error' | '/failing/answeredByViewForAnError' | '/failing/answeredByViewForAnError' | 'An error has occurred' || 'AssertionError' + 'an error controller, for an Error' | '/failing/answeredByControllerForAnError' | '/failing/answeredByControllerForAnError' | 'Answered by the error controller' || 'StackOverflowError' + 'an error controller that forwards' | '/failing/answeredByForwardingController' | '/failing/answeredByForwardingController' | 'Answered by the error controller' || 'ArithmeticException' + 'the error view, after an include' | '/failing/failsAfterInclude' | '/failing/failsAfterInclude' | 'An error has occurred' || 'IllegalStateException' } void 'a failure #handler answers inside an include is not the failure of the page that included it'() { diff --git a/grails-test-examples/undertow/grails-app/controllers/undertowapp/FailingController.groovy b/grails-test-examples/undertow/grails-app/controllers/undertowapp/FailingController.groovy index 60754fc0070..73fa7b65869 100644 --- a/grails-test-examples/undertow/grails-app/controllers/undertowapp/FailingController.groovy +++ b/grails-test-examples/undertow/grails-app/controllers/undertowapp/FailingController.groovy @@ -21,6 +21,8 @@ package undertowapp import org.springframework.web.context.request.async.DeferredResult import org.springframework.web.context.request.async.WebAsyncManager import org.springframework.web.context.request.async.WebAsyncUtils +import org.springframework.web.servlet.ModelAndView +import org.springframework.web.servlet.view.InternalResourceView class FailingController { @@ -66,6 +68,14 @@ class FailingController { forward(action: 'answeredByView') } + def forwardedToViewAsynchronously() { + forwardAsynchronously('/failing/answeredByView') + } + + def forwardedToControllerAsynchronously() { + forwardAsynchronously('/failing/answeredByController') + } + def forwardedToController() { forward(action: 'answeredByController') } @@ -101,6 +111,16 @@ class FailingController { result.errorResult = failure } + /** + * Completes asynchronous processing with a view that forwards, as a view Spring MVC resolves from a + * {@code forward:} name does, so that the action the path maps to answers on the asynchronous dispatch. + */ + private void forwardAsynchronously(String path) { + DeferredResult result = new DeferredResult<>() + startAsync(result) + result.result = new ModelAndView(new InternalResourceView(path)) + } + /** * Starts asynchronous processing that nothing completes. Unless the container ends it when the action fails, as * Tomcat does when the exception is left on the request, it ends when it times out. diff --git a/grails-test-examples/undertow/src/integration-test/groovy/undertowapp/UndertowFailedActionObservationSpec.groovy b/grails-test-examples/undertow/src/integration-test/groovy/undertowapp/UndertowFailedActionObservationSpec.groovy index e6b7e7682f8..eb11791a940 100644 --- a/grails-test-examples/undertow/src/integration-test/groovy/undertowapp/UndertowFailedActionObservationSpec.groovy +++ b/grails-test-examples/undertow/src/integration-test/groovy/undertowapp/UndertowFailedActionObservationSpec.groovy @@ -80,21 +80,23 @@ class UndertowFailedActionObservationSpec extends Specification implements HttpC NOTIFIED[path] == [exception] where: - handler | path | route | page || exception - 'the error view' | '/failing/answeredByView' | '/failing/answeredByView' | 'An error has occurred' || 'IllegalStateException' - 'an error controller' | '/failing/answeredByController' | '/failing/answeredByController' | 'Answered by the error controller' || 'UnsupportedOperationException' - 'the error view, asynchronously' | '/failing/answeredByViewAsynchronously' | '/failing/answeredByViewAsynchronously' | 'An error has occurred' || 'IllegalStateException' - 'an error controller, asynchronously' | '/failing/answeredByControllerAsynchronously' | '/failing/answeredByControllerAsynchronously' | 'Answered by the error controller' || 'UnsupportedOperationException' - 'the error view, after starting async' | '/failing/answeredByViewAfterStartingAsync' | '/failing/answeredByViewAfterStartingAsync' | 'An error has occurred' || 'IllegalStateException' - 'an error controller, after starting async' | '/failing/answeredByControllerAfterStartingAsync' | '/failing/answeredByControllerAfterStartingAsync' | 'Answered by the error controller' || 'UnsupportedOperationException' - 'the error view, after a forward' | '/failing/forwardedToView' | '/failing/answeredByView' | 'An error has occurred' || 'IllegalStateException' - 'an error controller, after a forward' | '/failing/forwardedToController' | '/failing/answeredByController' | 'Answered by the error controller' || 'UnsupportedOperationException' - 'the error view, after an asynchronous forward' | '/spring/forwardedToViewAsynchronously' | '/spring/answeredByView' | 'An error has occurred' || 'IllegalStateException' - 'an error controller, after an asynchronous forward' | '/spring/forwardedToControllerAsynchronously' | '/spring/answeredByController' | 'Answered by the error controller' || 'UnsupportedOperationException' - 'the error view, for an Error' | '/failing/answeredByViewForAnError' | '/failing/answeredByViewForAnError' | 'An error has occurred' || 'AssertionError' - 'an error controller, for an Error' | '/failing/answeredByControllerForAnError' | '/failing/answeredByControllerForAnError' | 'Answered by the error controller' || 'StackOverflowError' - 'an error controller that forwards' | '/failing/answeredByForwardingController' | '/failing/answeredByForwardingController' | 'Answered by the error controller' || 'ArithmeticException' - 'the error view, after an include' | '/failing/failsAfterInclude' | '/failing/failsAfterInclude' | 'An error has occurred' || 'IllegalStateException' + handler | path | route | page || exception + 'the error view' | '/failing/answeredByView' | '/failing/answeredByView' | 'An error has occurred' || 'IllegalStateException' + 'an error controller' | '/failing/answeredByController' | '/failing/answeredByController' | 'Answered by the error controller' || 'UnsupportedOperationException' + 'the error view, asynchronously' | '/failing/answeredByViewAsynchronously' | '/failing/answeredByViewAsynchronously' | 'An error has occurred' || 'IllegalStateException' + 'an error controller, asynchronously' | '/failing/answeredByControllerAsynchronously' | '/failing/answeredByControllerAsynchronously' | 'Answered by the error controller' || 'UnsupportedOperationException' + 'the error view, after starting async' | '/failing/answeredByViewAfterStartingAsync' | '/failing/answeredByViewAfterStartingAsync' | 'An error has occurred' || 'IllegalStateException' + 'an error controller, after starting async' | '/failing/answeredByControllerAfterStartingAsync' | '/failing/answeredByControllerAfterStartingAsync' | 'Answered by the error controller' || 'UnsupportedOperationException' + 'the error view, after a forward' | '/failing/forwardedToView' | '/failing/answeredByView' | 'An error has occurred' || 'IllegalStateException' + 'an error controller, after a forward' | '/failing/forwardedToController' | '/failing/answeredByController' | 'Answered by the error controller' || 'UnsupportedOperationException' + 'the error view, after an asynchronous forward from Spring MVC' | '/spring/forwardedToViewAsynchronously' | '/spring/answeredByView' | 'An error has occurred' || 'IllegalStateException' + 'an error controller, after an asynchronous forward from Spring MVC' | '/spring/forwardedToControllerAsynchronously' | '/spring/answeredByController' | 'Answered by the error controller' || 'UnsupportedOperationException' + 'the error view, after an asynchronous forward from an action' | '/failing/forwardedToViewAsynchronously' | '/failing/answeredByView' | 'An error has occurred' || 'IllegalStateException' + 'an error controller, after an asynchronous forward from an action' | '/failing/forwardedToControllerAsynchronously' | '/failing/answeredByController' | 'Answered by the error controller' || 'UnsupportedOperationException' + 'the error view, for an Error' | '/failing/answeredByViewForAnError' | '/failing/answeredByViewForAnError' | 'An error has occurred' || 'AssertionError' + 'an error controller, for an Error' | '/failing/answeredByControllerForAnError' | '/failing/answeredByControllerForAnError' | 'Answered by the error controller' || 'StackOverflowError' + 'an error controller that forwards' | '/failing/answeredByForwardingController' | '/failing/answeredByForwardingController' | 'Answered by the error controller' || 'ArithmeticException' + 'the error view, after an include' | '/failing/failsAfterInclude' | '/failing/failsAfterInclude' | 'An error has occurred' || 'IllegalStateException' } void 'a failure #handler answers inside an include is not the failure of the page that included it'() { diff --git a/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMapping.groovy b/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMapping.groovy index 32485cdea50..24fd39c247a 100644 --- a/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMapping.groovy +++ b/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMapping.groovy @@ -20,6 +20,7 @@ package org.grails.web.mapping.mvc import groovy.transform.CompileStatic +import jakarta.servlet.DispatcherType import jakarta.servlet.http.HttpServletRequest import jakarta.servlet.http.HttpServletResponse @@ -160,7 +161,9 @@ class UrlMappingsHandlerMapping extends AbstractHandlerMapping { def matchedInfo = request.getAttribute(MATCHED_REQUEST) def errorStatus = request.getAttribute(WebUtils.ERROR_STATUS_CODE_ATTRIBUTE) - if (matchedInfo != null && errorStatus == null) return matchedInfo + // The dispatch that returns the result of asynchronous processing answers for the action that started it. Any + // other dispatch, such as a forward a view makes, matches its own URI, whatever an earlier dispatch left here. + if (matchedInfo != null && errorStatus == null && request.dispatcherType == DispatcherType.ASYNC) return matchedInfo String uri = urlHelper.getPathWithinApplication(request) def webRequest = GrailsWebRequest.lookup(request) diff --git a/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/mvc/UrlMappingsInfoHandlerAdapter.groovy b/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/mvc/UrlMappingsInfoHandlerAdapter.groovy index 9d760c298ec..1f71a29e80c 100644 --- a/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/mvc/UrlMappingsInfoHandlerAdapter.groovy +++ b/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/mvc/UrlMappingsInfoHandlerAdapter.groovy @@ -24,6 +24,7 @@ import groovy.transform.CompileStatic import io.micrometer.observation.Observation import io.micrometer.observation.ObservationRegistry +import jakarta.servlet.DispatcherType import jakarta.servlet.http.HttpServletRequest import jakarta.servlet.http.HttpServletResponse @@ -82,7 +83,9 @@ class UrlMappingsInfoHandlerAdapter implements HandlerAdapter, ApplicationContex GrailsWebRequest webRequest = GrailsWebRequest.lookup(request) - boolean isAsyncRequest = WebUtils.isAsync(request) && !WebUtils.isError(request) + // the dispatch that returns the result of asynchronous processing, not a forward or include made during it, + // which carries the same request attributes + boolean isAsyncRequest = request.dispatcherType == DispatcherType.ASYNC && !WebUtils.isError(request) if (isAsyncRequest) { Object modelAndView = request.getAttribute(GrailsApplicationAttributes.MODEL_AND_VIEW) if (modelAndView instanceof ModelAndView resolvedModelAndView) { diff --git a/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/mvc/ActionReturnValuesSpec.groovy b/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/mvc/ActionReturnValuesSpec.groovy index 0d837264bca..31210d4fe00 100644 --- a/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/mvc/ActionReturnValuesSpec.groovy +++ b/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/mvc/ActionReturnValuesSpec.groovy @@ -21,6 +21,8 @@ package org.grails.web.mapping.mvc import java.util.concurrent.Callable import java.util.concurrent.CompletableFuture +import jakarta.servlet.DispatcherType + import com.fasterxml.jackson.annotation.JsonView import groovy.json.JsonSlurper @@ -325,6 +327,7 @@ class ActionReturnValuesSpec extends AbstractUrlMappingsSpec { new PollingConditions(timeout: 5).eventually { assert WebAsyncUtils.getAsyncManager(request).hasConcurrentResult() } + request.dispatcherType = DispatcherType.ASYNC request.setAttribute(WebUtils.ASYNC_REQUEST_URI_ATTRIBUTE, '/returnValues/later') modelAndView = handle('later') @@ -347,6 +350,7 @@ class ActionReturnValuesSpec extends AbstractUrlMappingsSpec { new PollingConditions(timeout: 5).eventually { assert WebAsyncUtils.getAsyncManager(request).hasConcurrentResult() } + request.dispatcherType = DispatcherType.ASYNC request.setAttribute(WebUtils.ASYNC_REQUEST_URI_ATTRIBUTE, '/returnValues/later') handle('later') diff --git a/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMappingSpec.groovy b/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMappingSpec.groovy index 4a6228ac825..0b86cb0ccc3 100644 --- a/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMappingSpec.groovy +++ b/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMappingSpec.groovy @@ -18,6 +18,8 @@ */ package org.grails.web.mapping.mvc +import jakarta.servlet.DispatcherType + import grails.artefact.Artefact import grails.core.DefaultGrailsApplication import grails.util.GrailsWebMockUtil @@ -367,6 +369,38 @@ class UrlMappingsHandlerMappingSpec extends AbstractUrlMappingsSpec { context.pathPattern == '/foo/bar' } + void "the match of a dispatch answers for the async dispatch that follows it, and not for a #dispatch to another action"() { + given: + def grailsApplication = new DefaultGrailsApplication(FooController) + grailsApplication.initialise() + def holder = new GrailsControllerUrlMappings(grailsApplication, getUrlMappingsHolder { + "/foo/bar"(controller: 'foo', action: 'bar') + "/other"(controller: 'foo', action: 'fooBar') + }) + def handler = new UrlMappingsHandlerMapping(holder) + def webRequest = GrailsWebMockUtil.bindMockWebRequest() + def request = webRequest.request + request.requestURI = '/foo/bar' + def started = handler.getHandler(request).handler + + when: 'the action started async processing, and its result comes back on an async dispatch' + request.dispatcherType = DispatcherType.ASYNC + + then: + handler.getHandler(request).handler.is(started) + + when: 'the view of that result sends the request to another action' + request.dispatcherType = dispatch + request.requestURI = '/other' + def info = handler.getHandler(request).handler + + then: + info.actionName == 'fooBar' + + where: + dispatch << [DispatcherType.FORWARD, DispatcherType.INCLUDE] + } + void "an action a page includes leaves the route of the page on its observation"() { given: def grailsApplication = new DefaultGrailsApplication(FooController) diff --git a/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/mvc/UrlMappingsInfoHandlerAdapterAsyncSpec.groovy b/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/mvc/UrlMappingsInfoHandlerAdapterAsyncSpec.groovy index 6de5b6e0596..ab496e9cae8 100644 --- a/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/mvc/UrlMappingsInfoHandlerAdapterAsyncSpec.groovy +++ b/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/mvc/UrlMappingsInfoHandlerAdapterAsyncSpec.groovy @@ -18,6 +18,8 @@ */ package org.grails.web.mapping.mvc +import jakarta.servlet.DispatcherType + import org.springframework.mock.web.MockHttpServletRequest import org.springframework.mock.web.MockHttpServletResponse import org.springframework.mock.web.MockServletContext @@ -27,6 +29,7 @@ import org.springframework.web.context.request.async.WebAsyncManager import org.springframework.web.context.request.async.WebAsyncUtils import org.springframework.web.servlet.ModelAndView +import grails.core.GrailsControllerClass import grails.web.mapping.UrlMappingInfo import org.grails.web.servlet.mvc.GrailsWebRequest import org.grails.web.util.WebUtils @@ -70,10 +73,35 @@ class UrlMappingsInfoHandlerAdapterAsyncSpec extends Specification { failure.message == 'bad' } + void 'runs the action a forward made during the async dispatch names, rather than answering with the async result'() { + given: 'a dispatch that returned the result of async processing, whose view forwards to another action' + completeAsyncRequest(new ModelAndView('/book/index')) + request.dispatcherType = DispatcherType.FORWARD + WebUtils.storeGrailsWebRequest(new GrailsWebRequest(request, response, request.servletContext)) + def controllerClass = Mock(GrailsControllerClass) { + getFullName() >> 'BookController' + isSingleton() >> false + newInstance() >> new Object() + getDefaultAction() >> 'show' + } + def info = Mock(GrailsControllerUrlMappingInfo) { + getControllerClass() >> controllerClass + getActionName() >> 'show' + } + + when: + adapter.handle(request, response, info) + + then: 'the action runs, and the async result is left for the dispatch it belongs to' + 1 * controllerClass.invoke(_, 'show') >> [book: 'one'] + asyncManager.hasConcurrentResult() + } + private void completeAsyncRequest(Object result) { DeferredResult deferredResult = new DeferredResult<>() asyncManager.startDeferredResultProcessing(deferredResult) deferredResult.setResult(result) + request.dispatcherType = DispatcherType.ASYNC request.setAttribute(WebUtils.ASYNC_REQUEST_URI_ATTRIBUTE, '/book/index') } } From bb900b99c1ed009ebb2beed111f526aa075ee512 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Mon, 9 Nov 2026 08:49:37 -0800 Subject: [PATCH 72/78] Include the error handler for a failure inside an include A page whose g:include named an action that failed into an error controller answered 200 with an empty body on Tomcat. The resolver forwarded to the error controller from inside the include, and a forward ends the response it is given: Tomcat 11 finishes the response underneath a wrapped one once a forward returns, which inside an include is the response of the page. Jetty and Undertow rendered the page. The resolver now includes the error handler when the request is an include, as Spring MVC includes a view rather than forwarding to it there. UrlMappingUtils.includeRequestForUrlMappingInfo prepares the request as a forward does, and the include answers with the error handler's mapping, as the forward does through the status code, rather than whatever its URI would match, since an include made while an error page renders answers for its own URI. GrailsExceptionResolverSpec now expects the error controller to be included, the Tomcat example app includes an action answered by an error controller, which failed with an empty body before, and all three apps answer a page that fails after an include with an error controller. --- .../issue11102/FailingController.groovy | 9 ++++ .../FailedActionObservationSpec.groovy | 6 ++- .../issue12688/FailingController.groovy | 5 +++ .../JettyFailedActionObservationSpec.groovy | 1 + .../undertowapp/FailingController.groovy | 5 +++ ...UndertowFailedActionObservationSpec.groovy | 1 + .../web/errors/GrailsExceptionResolver.java | 24 +++++++++- .../errors/GrailsExceptionResolverSpec.groovy | 12 ++--- .../grails/web/mapping/UrlMappingUtils.java | 44 ++++++++++++++++++- .../mvc/UrlMappingsHandlerMapping.groovy | 15 +++++++ .../mvc/UrlMappingsHandlerMappingSpec.groovy | 26 +++++++++++ 11 files changed, 137 insertions(+), 11 deletions(-) diff --git a/grails-test-examples/issue-11102/grails-app/controllers/issue11102/FailingController.groovy b/grails-test-examples/issue-11102/grails-app/controllers/issue11102/FailingController.groovy index ab4872b0e5b..67f19f3f4b1 100644 --- a/grails-test-examples/issue-11102/grails-app/controllers/issue11102/FailingController.groovy +++ b/grails-test-examples/issue-11102/grails-app/controllers/issue11102/FailingController.groovy @@ -102,10 +102,19 @@ class FailingController { throw new IllegalStateException('answered by the error view') } + def failsAfterIncludeAnsweredByController() { + g.include(action: 'included') + throw new UnsupportedOperationException('answered by the error controller') + } + def includesAnswerOfView() { render "before ${g.include(action: 'answeredByView')} after" } + def includesAnswerOfController() { + render "before ${g.include(action: 'answeredByController')} after" + } + def included() { render 'included' } diff --git a/grails-test-examples/issue-11102/src/integration-test/groovy/issue11102/FailedActionObservationSpec.groovy b/grails-test-examples/issue-11102/src/integration-test/groovy/issue11102/FailedActionObservationSpec.groovy index 0e14d0e212c..555ab29e077 100644 --- a/grails-test-examples/issue-11102/src/integration-test/groovy/issue11102/FailedActionObservationSpec.groovy +++ b/grails-test-examples/issue-11102/src/integration-test/groovy/issue11102/FailedActionObservationSpec.groovy @@ -96,6 +96,7 @@ class FailedActionObservationSpec extends Specification implements HttpClientSup 'an error controller, for an Error' | '/failing/answeredByControllerForAnError' | '/failing/answeredByControllerForAnError' | 'Answered by the error controller' || 'StackOverflowError' 'an error controller that forwards' | '/failing/answeredByForwardingController' | '/failing/answeredByForwardingController' | 'Answered by the error controller' || 'ArithmeticException' 'the error view, after an include' | '/failing/failsAfterInclude' | '/failing/failsAfterInclude' | 'An error has occurred' || 'IllegalStateException' + 'an error controller, after an include' | '/failing/failsAfterIncludeAnsweredByController' | '/failing/failsAfterIncludeAnsweredByController' | 'Answered by the error controller' || 'UnsupportedOperationException' 'an error controller, after an interceptor failed' | '/failing/failsInInterceptor' | '/failing/failsInInterceptor' | 'Answered by the error controller' || 'UnsupportedOperationException' } @@ -113,8 +114,9 @@ class FailedActionObservationSpec extends Specification implements HttpClientSup !NOTIFIED.containsKey(path) where: - handler | path - 'the error view' | '/failing/includesAnswerOfView' + handler | path + 'the error view' | '/failing/includesAnswerOfView' + 'an error controller' | '/failing/includesAnswerOfController' } void 'a request #what is reported under #reported'() { diff --git a/grails-test-examples/jetty/grails-app/controllers/issue12688/FailingController.groovy b/grails-test-examples/jetty/grails-app/controllers/issue12688/FailingController.groovy index 15e03975240..02e19c48a09 100644 --- a/grails-test-examples/jetty/grails-app/controllers/issue12688/FailingController.groovy +++ b/grails-test-examples/jetty/grails-app/controllers/issue12688/FailingController.groovy @@ -85,6 +85,11 @@ class FailingController { throw new IllegalStateException('answered by the error view') } + def failsAfterIncludeAnsweredByController() { + g.include(action: 'included') + throw new UnsupportedOperationException('answered by the error controller') + } + def includesAnswerOfView() { render "before ${g.include(action: 'answeredByView')} after" } diff --git a/grails-test-examples/jetty/src/integration-test/groovy/issue12688/JettyFailedActionObservationSpec.groovy b/grails-test-examples/jetty/src/integration-test/groovy/issue12688/JettyFailedActionObservationSpec.groovy index e1a11eaba7f..7cd714cb5a4 100644 --- a/grails-test-examples/jetty/src/integration-test/groovy/issue12688/JettyFailedActionObservationSpec.groovy +++ b/grails-test-examples/jetty/src/integration-test/groovy/issue12688/JettyFailedActionObservationSpec.groovy @@ -95,6 +95,7 @@ class JettyFailedActionObservationSpec extends Specification implements HttpClie 'an error controller, for an Error' | '/failing/answeredByControllerForAnError' | '/failing/answeredByControllerForAnError' | 'Answered by the error controller' || 'StackOverflowError' 'an error controller that forwards' | '/failing/answeredByForwardingController' | '/failing/answeredByForwardingController' | 'Answered by the error controller' || 'ArithmeticException' 'the error view, after an include' | '/failing/failsAfterInclude' | '/failing/failsAfterInclude' | 'An error has occurred' || 'IllegalStateException' + 'an error controller, after an include' | '/failing/failsAfterIncludeAnsweredByController' | '/failing/failsAfterIncludeAnsweredByController' | 'Answered by the error controller' || 'UnsupportedOperationException' } void 'a failure #handler answers inside an include is not the failure of the page that included it'() { diff --git a/grails-test-examples/undertow/grails-app/controllers/undertowapp/FailingController.groovy b/grails-test-examples/undertow/grails-app/controllers/undertowapp/FailingController.groovy index 73fa7b65869..72d2025eab3 100644 --- a/grails-test-examples/undertow/grails-app/controllers/undertowapp/FailingController.groovy +++ b/grails-test-examples/undertow/grails-app/controllers/undertowapp/FailingController.groovy @@ -85,6 +85,11 @@ class FailingController { throw new IllegalStateException('answered by the error view') } + def failsAfterIncludeAnsweredByController() { + g.include(action: 'included') + throw new UnsupportedOperationException('answered by the error controller') + } + def includesAnswerOfView() { render "before ${g.include(action: 'answeredByView')} after" } diff --git a/grails-test-examples/undertow/src/integration-test/groovy/undertowapp/UndertowFailedActionObservationSpec.groovy b/grails-test-examples/undertow/src/integration-test/groovy/undertowapp/UndertowFailedActionObservationSpec.groovy index eb11791a940..39310879564 100644 --- a/grails-test-examples/undertow/src/integration-test/groovy/undertowapp/UndertowFailedActionObservationSpec.groovy +++ b/grails-test-examples/undertow/src/integration-test/groovy/undertowapp/UndertowFailedActionObservationSpec.groovy @@ -97,6 +97,7 @@ class UndertowFailedActionObservationSpec extends Specification implements HttpC 'an error controller, for an Error' | '/failing/answeredByControllerForAnError' | '/failing/answeredByControllerForAnError' | 'Answered by the error controller' || 'StackOverflowError' 'an error controller that forwards' | '/failing/answeredByForwardingController' | '/failing/answeredByForwardingController' | 'Answered by the error controller' || 'ArithmeticException' 'the error view, after an include' | '/failing/failsAfterInclude' | '/failing/failsAfterInclude' | 'An error has occurred' || 'IllegalStateException' + 'an error controller, after an include' | '/failing/failsAfterIncludeAnsweredByController' | '/failing/failsAfterIncludeAnsweredByController' | 'Answered by the error controller' || 'UnsupportedOperationException' } void 'a failure #handler answers inside an include is not the failure of the page that included it'() { diff --git a/grails-web-mvc/src/main/groovy/org/grails/web/errors/GrailsExceptionResolver.java b/grails-web-mvc/src/main/groovy/org/grails/web/errors/GrailsExceptionResolver.java index d9e970cdda3..79f61f29e50 100644 --- a/grails-web-mvc/src/main/groovy/org/grails/web/errors/GrailsExceptionResolver.java +++ b/grails-web-mvc/src/main/groovy/org/grails/web/errors/GrailsExceptionResolver.java @@ -386,7 +386,12 @@ else if (mapsToController) { } request.setAttribute(ERROR_HANDLER_FORWARD_IN_PROGRESS_ATTRIBUTE, Boolean.TRUE); try { - forwardRequest(info, request, response, mv, uri); + if (WebUtils.isInclude(request)) { + includeRequest(info, request, response, mv, uri); + } + else { + forwardRequest(info, request, response, mv, uri); + } } finally { request.removeAttribute(ERROR_HANDLER_FORWARD_IN_PROGRESS_ATTRIBUTE); @@ -433,6 +438,23 @@ protected void forwardRequest(UrlMappingInfo info, HttpServletRequest request, H uri, info, forwardUrl, response.getClass()); } + /** + * Answers an exception inside an include with its error handler, included where the failing action would have + * written, as Spring MVC includes a view rather than forwarding to it there. A forward ends the response it is + * given, which inside an include belongs to the page that included the action, so Tomcat answered that page with + * nothing. + * + * @since 8.0.1 + */ + protected void includeRequest(UrlMappingInfo info, HttpServletRequest request, HttpServletResponse response, + ModelAndView mv, String uri) throws ServletException, IOException { + info.configure(GrailsWebRequest.lookup(request)); + String includeUrl = UrlMappingUtils.includeRequestForUrlMappingInfo( + request, response, info, mv.getModel(), true); + LOG.debug("Matched URI [{}] to URL mapping [{}], including [{}] with response [{}]", + uri, info, includeUrl, response.getClass()); + } + protected String determineUri(HttpServletRequest request) { String uri = (String) request.getAttribute(WebUtils.FORWARD_REQUEST_URI_ATTRIBUTE); if (uri == null) { diff --git a/grails-web-mvc/src/test/groovy/org/grails/web/errors/GrailsExceptionResolverSpec.groovy b/grails-web-mvc/src/test/groovy/org/grails/web/errors/GrailsExceptionResolverSpec.groovy index ae4fa2cc033..bbfd9b0959e 100644 --- a/grails-web-mvc/src/test/groovy/org/grails/web/errors/GrailsExceptionResolverSpec.groovy +++ b/grails-web-mvc/src/test/groovy/org/grails/web/errors/GrailsExceptionResolverSpec.groovy @@ -301,19 +301,19 @@ class GrailsExceptionResolverSpec extends Specification { servlet.service(req, res) } as FilterChain) - then: 'the error page answered inside the page, which answered the request' + then: 'the error page answered inside the page, included rather than forwarded to, which answered the request' response.status == 200 - response.includedUrls == included - response.forwardedUrl == forwarded + response.includedUrls == [page] + response.forwardedUrl == null and: 'so the request did not fail' observed.error == null notified.empty where: - handler | mappings | controllerMappings | included | forwarded - 'the error view' | { '500'(view: '/error') } | false | ['/error'] | null - 'an error controller' | { '500'(controller: 'errors', action: 'serverError') } | true | [] | '/errors/serverError' + handler | mappings | controllerMappings | page + 'the error view' | { '500'(view: '/error') } | false | '/error' + 'an error controller' | { '500'(controller: 'errors', action: 'serverError') } | true | '/errors/serverError' } void 'an exception is resolved as usual without an observation'() { diff --git a/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/UrlMappingUtils.java b/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/UrlMappingUtils.java index e062e7d6868..cd96ff1fdbe 100644 --- a/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/UrlMappingUtils.java +++ b/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/UrlMappingUtils.java @@ -252,9 +252,44 @@ public static String forwardRequestForUrlMappingInfo(HttpServletRequest request, * @throws jakarta.servlet.ServletException Thrown when an error occurs executing the forward * @throws java.io.IOException Thrown when an error occurs executing the forward */ - @SuppressWarnings({ "unchecked", "rawtypes" }) public static String forwardRequestForUrlMappingInfo(HttpServletRequest request, HttpServletResponse response, UrlMappingInfo info, Map model, boolean includeParams) throws ServletException, IOException { + return dispatchRequestForUrlMappingInfo(request, response, info, model, includeParams, false); + } + + /** + * Includes what the given UrlMappingInfo maps to in the response, where + * {@link #forwardRequestForUrlMappingInfo(HttpServletRequest, HttpServletResponse, UrlMappingInfo, Map, boolean)} + * would forward to it. A request that is itself an include cannot forward: a forward ends the response it is given, + * which inside an include belongs to the page that included it. The include answers with the given mapping, + * whatever its URI would match. + * + * @param request The request + * @param response The response + * @param info The UrlMappingInfo object + * @param model The Model + * @param includeParams Whether to include any request parameters + * @return The URI included + * + * @throws jakarta.servlet.ServletException Thrown when an error occurs executing the include + * @throws java.io.IOException Thrown when an error occurs executing the include + * @since 8.0.1 + */ + public static String includeRequestForUrlMappingInfo(HttpServletRequest request, + HttpServletResponse response, UrlMappingInfo info, Map model, boolean includeParams) throws ServletException, IOException { + request.setAttribute(UrlMappingsHandlerMapping.INCLUDED_MAPPING_INFO, info); + try { + return dispatchRequestForUrlMappingInfo(request, response, info, model, includeParams, true); + } + finally { + request.removeAttribute(UrlMappingsHandlerMapping.INCLUDED_MAPPING_INFO); + } + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + private static String dispatchRequestForUrlMappingInfo(HttpServletRequest request, HttpServletResponse response, + UrlMappingInfo info, Map model, boolean includeParams, boolean include) + throws ServletException, IOException { String forwardUrl = buildDispatchUrlForMapping(info, includeParams); @@ -275,7 +310,12 @@ public static String forwardRequestForUrlMappingInfo(HttpServletRequest request, webRequest.removeAttribute(GrailsApplicationAttributes.GRAILS_CONTROLLER_CLASS_AVAILABLE, WebRequest.SCOPE_REQUEST); webRequest.removeAttribute(UrlMappingsHandlerMapping.MATCHED_REQUEST, WebRequest.SCOPE_REQUEST); webRequest.removeAttribute("grailsWebRequestFilter" + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX, WebRequest.SCOPE_REQUEST); - dispatcher.forward(request, response); + if (include) { + dispatcher.include(request, response); + } + else { + dispatcher.forward(request, response); + } return forwardUrl; } diff --git a/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMapping.groovy b/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMapping.groovy index 24fd39c247a..16b6262aee2 100644 --- a/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMapping.groovy +++ b/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMapping.groovy @@ -60,6 +60,14 @@ class UrlMappingsHandlerMapping extends AbstractHandlerMapping { public static final String MATCHED_REQUEST = 'org.grails.url.match.info' + /** + * The mapping an include made by {@link org.grails.web.mapping.UrlMappingUtils#includeRequestForUrlMappingInfo} answers with, whatever its + * URI would match, as a forward to a status code mapping answers with that mapping. + * + * @since 8.0.1 + */ + public static final String INCLUDED_MAPPING_INFO = 'org.grails.url.include.info' + // Both are stateless, so one shared instance each rather than two allocations per request. private static final HandlerInterceptor OBSERVATION_ROUTE_HANDLER = new ObservationRouteHandler() private static final HandlerInterceptor ERROR_HANDLING_HANDLER = new ErrorHandlingHandler() @@ -159,6 +167,13 @@ class UrlMappingsHandlerMapping extends AbstractHandlerMapping { @Override protected Object getHandlerInternal(HttpServletRequest request) throws Exception { + def includedInfo = request.getAttribute(INCLUDED_MAPPING_INFO) + if (includedInfo instanceof UrlMappingInfo && WebUtils.isInclude(request)) { + request.removeAttribute(INCLUDED_MAPPING_INFO) + request.setAttribute(MATCHED_REQUEST, includedInfo) + return includedInfo + } + def matchedInfo = request.getAttribute(MATCHED_REQUEST) def errorStatus = request.getAttribute(WebUtils.ERROR_STATUS_CODE_ATTRIBUTE) // The dispatch that returns the result of asynchronous processing answers for the action that started it. Any diff --git a/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMappingSpec.groovy b/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMappingSpec.groovy index 0b86cb0ccc3..b6306abc745 100644 --- a/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMappingSpec.groovy +++ b/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMappingSpec.groovy @@ -401,6 +401,32 @@ class UrlMappingsHandlerMappingSpec extends AbstractUrlMappingsSpec { dispatch << [DispatcherType.FORWARD, DispatcherType.INCLUDE] } + void "an include made for a mapping answers with that mapping, whatever its URI matches"() { + given: 'an error handler with no URL of its own, as a status code mapping has' + def grailsApplication = new DefaultGrailsApplication(FooController) + grailsApplication.initialise() + def holder = new GrailsControllerUrlMappings(grailsApplication, getUrlMappingsHolder { + "/foo/bar"(controller: 'foo', action: 'bar') + "500"(controller: 'foo', action: 'fooBar') + }) + def handler = new UrlMappingsHandlerMapping(holder) + def webRequest = GrailsWebMockUtil.bindMockWebRequest() + def request = webRequest.request + def errorHandler = holder.matchStatusCode(500) + + when: 'it is included while the exception is resolved, under the URI built for it' + request.setAttribute(WebUtils.ERROR_STATUS_CODE_ATTRIBUTE, 500) + request.setAttribute(WebUtils.INCLUDE_REQUEST_URI_ATTRIBUTE, '/foo/fooBar') + request.requestURI = '/foo/fooBar' + request.setAttribute(UrlMappingsHandlerMapping.INCLUDED_MAPPING_INFO, errorHandler) + def info = handler.getHandler(request).handler + + then: 'it answers with the error handler, and only that include does' + info.is(errorHandler) + request.getAttribute(UrlMappingsHandlerMapping.INCLUDED_MAPPING_INFO) == null + handler.getHandler(request) == null + } + void "an action a page includes leaves the route of the page on its observation"() { given: def grailsApplication = new DefaultGrailsApplication(FooController) From 05c49d05484f80d31f4ecd33401b8290fb97a2e1 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Mon, 9 Nov 2026 09:23:34 -0800 Subject: [PATCH 73/78] Run the error controller for a failure included in a page whose URL has a parameter A page mapped by "/page/$slug" that included an action that threw got an empty fragment, and the error controller its "500" mapping names never ran. The exception resolver wraps the error handler's mapping in a DefaultUrlMappingInfo carrying the parameters of the page's URL, which is not the controller-aware mapping, and the include answered with it as it was. A forward never saw this, because the handler mapping resolves a forward to the error handler again through the status code. An include made for the error handler is now resolved the same way. An include made for a mapping when no error is being handled still answers with that mapping, and any other include made while an error page renders still answers for its own URI. UrlMappingsHandlerMappingSpec includes the error handler with the page's parameters, and the example apps include a failing action from a page mapped by "/page/$slug" on Tomcat, Jetty and Undertow, where the fragment was empty. The include rows now check the fragment as well as the page around it. --- .../controllers/issue11102/UrlMappings.groovy | 1 + .../FailedActionObservationSpec.groovy | 11 +++--- .../controllers/issue12688/UrlMappings.groovy | 1 + .../JettyFailedActionObservationSpec.groovy | 11 +++--- .../undertowapp/UrlMappings.groovy | 1 + ...UndertowFailedActionObservationSpec.groovy | 11 +++--- .../mvc/UrlMappingsHandlerMapping.groovy | 20 ++++++---- .../mvc/UrlMappingsHandlerMappingSpec.groovy | 39 +++++++++++++++++-- 8 files changed, 70 insertions(+), 25 deletions(-) diff --git a/grails-test-examples/issue-11102/grails-app/controllers/issue11102/UrlMappings.groovy b/grails-test-examples/issue-11102/grails-app/controllers/issue11102/UrlMappings.groovy index 684d60b8aa0..1281443a446 100644 --- a/grails-test-examples/issue-11102/grails-app/controllers/issue11102/UrlMappings.groovy +++ b/grails-test-examples/issue-11102/grails-app/controllers/issue11102/UrlMappings.groovy @@ -32,6 +32,7 @@ class UrlMappings { } "/failing/$action"(controller: 'failing') + "/page/$slug"(controller: 'failing', action: 'includesAnswerOfController') "/"(view:"/index") "500"(controller: 'failing', action: 'errorHandler', exception: UnsupportedOperationException) diff --git a/grails-test-examples/issue-11102/src/integration-test/groovy/issue11102/FailedActionObservationSpec.groovy b/grails-test-examples/issue-11102/src/integration-test/groovy/issue11102/FailedActionObservationSpec.groovy index 555ab29e077..c3eed49dd59 100644 --- a/grails-test-examples/issue-11102/src/integration-test/groovy/issue11102/FailedActionObservationSpec.groovy +++ b/grails-test-examples/issue-11102/src/integration-test/groovy/issue11102/FailedActionObservationSpec.groovy @@ -105,18 +105,19 @@ class FailedActionObservationSpec extends Specification implements HttpClientSup def response = http([(REQUEST_HEADER): path], path) then: 'the page answered, with the error page inside it' - response.assertContains(200, 'before').assertContains('after') + response.assertContains(200, 'before').assertContains(fragment).assertContains('after') and: 'its observation stopped on its own route, with no error' new PollingConditions(timeout: 30).eventually { - assert STOPPED[path] == [path, 'none'] + assert STOPPED[path] == [route, 'none'] } !NOTIFIED.containsKey(path) where: - handler | path - 'the error view' | '/failing/includesAnswerOfView' - 'an error controller' | '/failing/includesAnswerOfController' + handler | path | route | fragment + 'the error view' | '/failing/includesAnswerOfView' | '/failing/includesAnswerOfView' | 'An error has occurred' + 'an error controller' | '/failing/includesAnswerOfController' | '/failing/includesAnswerOfController' | 'Answered by the error controller' + 'an error controller, on a page whose URL has a parameter' | '/page/example' | '/failing/includesAnswerOfController' | 'Answered by the error controller' } void 'a request #what is reported under #reported'() { diff --git a/grails-test-examples/jetty/grails-app/controllers/issue12688/UrlMappings.groovy b/grails-test-examples/jetty/grails-app/controllers/issue12688/UrlMappings.groovy index 0ee14cc6cb9..d249b476815 100644 --- a/grails-test-examples/jetty/grails-app/controllers/issue12688/UrlMappings.groovy +++ b/grails-test-examples/jetty/grails-app/controllers/issue12688/UrlMappings.groovy @@ -28,6 +28,7 @@ class UrlMappings { "/"(view: "/index") "/failing/$action"(controller: 'failing') + "/page/$slug"(controller: 'failing', action: 'includesAnswerOfController') "500"(view: '/error') "500"(controller: 'failing', action: 'errorHandler', exception: UnsupportedOperationException) diff --git a/grails-test-examples/jetty/src/integration-test/groovy/issue12688/JettyFailedActionObservationSpec.groovy b/grails-test-examples/jetty/src/integration-test/groovy/issue12688/JettyFailedActionObservationSpec.groovy index 7cd714cb5a4..7103d474d90 100644 --- a/grails-test-examples/jetty/src/integration-test/groovy/issue12688/JettyFailedActionObservationSpec.groovy +++ b/grails-test-examples/jetty/src/integration-test/groovy/issue12688/JettyFailedActionObservationSpec.groovy @@ -103,18 +103,19 @@ class JettyFailedActionObservationSpec extends Specification implements HttpClie def response = http([(REQUEST_HEADER): path], path) then: 'the page answered, with the error page inside it' - response.assertContains(200, 'before').assertContains('after') + response.assertContains(200, 'before').assertContains(fragment).assertContains('after') and: 'its observation stopped on its own route, with no error' new PollingConditions(timeout: 30).eventually { - assert STOPPED[path] == [path, 'none'] + assert STOPPED[path] == [route, 'none'] } !NOTIFIED.containsKey(path) where: - handler | path - 'the error view' | '/failing/includesAnswerOfView' - 'an error controller' | '/failing/includesAnswerOfController' + handler | path | route | fragment + 'the error view' | '/failing/includesAnswerOfView' | '/failing/includesAnswerOfView' | 'An error has occurred' + 'an error controller' | '/failing/includesAnswerOfController' | '/failing/includesAnswerOfController' | 'Answered by the error controller' + 'an error controller, on a page whose URL has a parameter' | '/page/example' | '/failing/includesAnswerOfController' | 'Answered by the error controller' } private List errorTags(String route) { diff --git a/grails-test-examples/undertow/grails-app/controllers/undertowapp/UrlMappings.groovy b/grails-test-examples/undertow/grails-app/controllers/undertowapp/UrlMappings.groovy index 6d76946c00e..2bfa206272f 100644 --- a/grails-test-examples/undertow/grails-app/controllers/undertowapp/UrlMappings.groovy +++ b/grails-test-examples/undertow/grails-app/controllers/undertowapp/UrlMappings.groovy @@ -29,6 +29,7 @@ class UrlMappings { "/"(view: "/index") "/failing/$action"(controller: 'failing') + "/page/$slug"(controller: 'failing', action: 'includesAnswerOfController') "500"(view: '/error') "500"(controller: 'failing', action: 'errorHandler', exception: UnsupportedOperationException) diff --git a/grails-test-examples/undertow/src/integration-test/groovy/undertowapp/UndertowFailedActionObservationSpec.groovy b/grails-test-examples/undertow/src/integration-test/groovy/undertowapp/UndertowFailedActionObservationSpec.groovy index 39310879564..7edbe1e3211 100644 --- a/grails-test-examples/undertow/src/integration-test/groovy/undertowapp/UndertowFailedActionObservationSpec.groovy +++ b/grails-test-examples/undertow/src/integration-test/groovy/undertowapp/UndertowFailedActionObservationSpec.groovy @@ -105,18 +105,19 @@ class UndertowFailedActionObservationSpec extends Specification implements HttpC def response = http([(REQUEST_HEADER): path], path) then: 'the page answered, with the error page inside it' - response.assertContains(200, 'before').assertContains('after') + response.assertContains(200, 'before').assertContains(fragment).assertContains('after') and: 'its observation stopped on its own route, with no error' new PollingConditions(timeout: 30).eventually { - assert STOPPED[path] == [path, 'none'] + assert STOPPED[path] == [route, 'none'] } !NOTIFIED.containsKey(path) where: - handler | path - 'the error view' | '/failing/includesAnswerOfView' - 'an error controller' | '/failing/includesAnswerOfController' + handler | path | route | fragment + 'the error view' | '/failing/includesAnswerOfView' | '/failing/includesAnswerOfView' | 'An error has occurred' + 'an error controller' | '/failing/includesAnswerOfController' | '/failing/includesAnswerOfController' | 'Answered by the error controller' + 'an error controller, on a page whose URL has a parameter' | '/page/example' | '/failing/includesAnswerOfController' | 'Answered by the error controller' } private List errorTags(String route) { diff --git a/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMapping.groovy b/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMapping.groovy index 16b6262aee2..f1df071fe19 100644 --- a/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMapping.groovy +++ b/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMapping.groovy @@ -61,8 +61,10 @@ class UrlMappingsHandlerMapping extends AbstractHandlerMapping { public static final String MATCHED_REQUEST = 'org.grails.url.match.info' /** - * The mapping an include made by {@link org.grails.web.mapping.UrlMappingUtils#includeRequestForUrlMappingInfo} answers with, whatever its - * URI would match, as a forward to a status code mapping answers with that mapping. + * The mapping an include made by {@link org.grails.web.mapping.UrlMappingUtils#includeRequestForUrlMappingInfo} answers + * with, whatever its URI would match. While an error is being handled, the include answers with the status code + * mapping, as a forward to it does, since the mapping it was made for can be one that carries the parameters of the + * request rather than its controller. * * @since 8.0.1 */ @@ -167,15 +169,17 @@ class UrlMappingsHandlerMapping extends AbstractHandlerMapping { @Override protected Object getHandlerInternal(HttpServletRequest request) throws Exception { - def includedInfo = request.getAttribute(INCLUDED_MAPPING_INFO) - if (includedInfo instanceof UrlMappingInfo && WebUtils.isInclude(request)) { + def includedInfo = WebUtils.isInclude(request) ? request.getAttribute(INCLUDED_MAPPING_INFO) : null + if (includedInfo != null) { request.removeAttribute(INCLUDED_MAPPING_INFO) + } + def matchedInfo = request.getAttribute(MATCHED_REQUEST) + def errorStatus = request.getAttribute(WebUtils.ERROR_STATUS_CODE_ATTRIBUTE) + if (includedInfo instanceof UrlMappingInfo && errorStatus == null) { request.setAttribute(MATCHED_REQUEST, includedInfo) return includedInfo } - def matchedInfo = request.getAttribute(MATCHED_REQUEST) - def errorStatus = request.getAttribute(WebUtils.ERROR_STATUS_CODE_ATTRIBUTE) // The dispatch that returns the result of asynchronous processing answers for the action that started it. Any // other dispatch, such as a forward a view makes, matches its own URI, whatever an earlier dispatch left here. if (matchedInfo != null && errorStatus == null && request.dispatcherType == DispatcherType.ASYNC) return matchedInfo @@ -187,7 +191,9 @@ class UrlMappingsHandlerMapping extends AbstractHandlerMapping { String version = findRequestedVersion(webRequest) - if (errorStatus && !WebUtils.isInclude(request)) { + // An include made for the error handler resolves it as a forward to it does. Any other include made while an + // error page renders answers for its own URI. + if (errorStatus && (!WebUtils.isInclude(request) || includedInfo != null)) { def exception = request.getAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE) UrlMappingInfo info if (exception instanceof Throwable) { diff --git a/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMappingSpec.groovy b/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMappingSpec.groovy index b6306abc745..31067d976bc 100644 --- a/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMappingSpec.groovy +++ b/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMappingSpec.groovy @@ -401,7 +401,7 @@ class UrlMappingsHandlerMappingSpec extends AbstractUrlMappingsSpec { dispatch << [DispatcherType.FORWARD, DispatcherType.INCLUDE] } - void "an include made for a mapping answers with that mapping, whatever its URI matches"() { + void "an include made for the error handler answers with it as a forward does, when the include was made for #made"() { given: 'an error handler with no URL of its own, as a status code mapping has' def grailsApplication = new DefaultGrailsApplication(FooController) grailsApplication.initialise() @@ -413,6 +413,10 @@ class UrlMappingsHandlerMappingSpec extends AbstractUrlMappingsSpec { def webRequest = GrailsWebMockUtil.bindMockWebRequest() def request = webRequest.request def errorHandler = holder.matchStatusCode(500) + if (pageParameters) { + // as the exception resolver passes it when the URL of the page carries parameters + errorHandler = new DefaultUrlMappingInfo(errorHandler, pageParameters, grailsApplication) + } when: 'it is included while the exception is resolved, under the URI built for it' request.setAttribute(WebUtils.ERROR_STATUS_CODE_ATTRIBUTE, 500) @@ -421,10 +425,39 @@ class UrlMappingsHandlerMappingSpec extends AbstractUrlMappingsSpec { request.setAttribute(UrlMappingsHandlerMapping.INCLUDED_MAPPING_INFO, errorHandler) def info = handler.getHandler(request).handler - then: 'it answers with the error handler, and only that include does' - info.is(errorHandler) + then: 'it answers with the controller of the error handler, and only that include does' + info instanceof GrailsControllerUrlMappingInfo + ((GrailsControllerUrlMappingInfo) info).controllerClass.clazz == FooController + info.actionName == 'fooBar' request.getAttribute(UrlMappingsHandlerMapping.INCLUDED_MAPPING_INFO) == null handler.getHandler(request) == null + + where: + made | pageParameters + 'its mapping' | [:] + 'its mapping with the parameters of the page\'s URL' | [slug: 'example'] + } + + void "an include made for a mapping answers with that mapping when no error is being handled"() { + given: + def grailsApplication = new DefaultGrailsApplication(FooController) + grailsApplication.initialise() + def holder = new GrailsControllerUrlMappings(grailsApplication, getUrlMappingsHolder { + "/foo/bar"(controller: 'foo', action: 'bar') + "/foo/other"(controller: 'foo', action: 'fooBar') + }) + def handler = new UrlMappingsHandlerMapping(holder) + def webRequest = GrailsWebMockUtil.bindMockWebRequest() + def request = webRequest.request + def mapping = holder.match('/foo/other') + + when: + request.setAttribute(WebUtils.INCLUDE_REQUEST_URI_ATTRIBUTE, '/foo/fooBar') + request.requestURI = '/foo/fooBar' + request.setAttribute(UrlMappingsHandlerMapping.INCLUDED_MAPPING_INFO, mapping) + + then: + handler.getHandler(request).handler.is(mapping) } void "an action a page includes leaves the route of the page on its observation"() { From 2bf3e10e75fe89c49840eb9d592e11b71d95e610 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Mon, 9 Nov 2026 13:23:39 -0800 Subject: [PATCH 74/78] Wait for the redirected page in RedirectWithAndWithoutParamsFunctionalSpec The spec read the page right after clicking submit, and the click can return before the browser has followed the redirect. In the SiteMesh 2 CI lane on #16871 the page source was still the form, so the check for the saved record failed, and the check that the URL has no params passed only because the URL had not changed yet. It now waits for the page the redirect leads to before asserting on it, as ForwardingSpec does, and checks the URL once that page has loaded. --- .../RedirectWithAndWithoutParamsFunctionalSpec.groovy | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/grails-test-examples/app1/src/integration-test/groovy/functionaltests/RedirectWithAndWithoutParamsFunctionalSpec.groovy b/grails-test-examples/app1/src/integration-test/groovy/functionaltests/RedirectWithAndWithoutParamsFunctionalSpec.groovy index 2f29846a658..4e50b2cf4f7 100644 --- a/grails-test-examples/app1/src/integration-test/groovy/functionaltests/RedirectWithAndWithoutParamsFunctionalSpec.groovy +++ b/grails-test-examples/app1/src/integration-test/groovy/functionaltests/RedirectWithAndWithoutParamsFunctionalSpec.groovy @@ -36,10 +36,11 @@ class RedirectWithAndWithoutParamsFunctionalSpec extends ContainerGebSpec { $('input', name:'name').value('foo') $('input', type:'submit').click() - then: 'the params are not added to the url' - !currentUrl.contains('?name=foo') - pageSource.contains('"id":') + then: 'the page the redirect leads to answers, without the params on its url' + // waitFor guards against asserting on the form before the browser has followed the redirect + waitFor { pageSource.contains('"id":') } pageSource.contains('"name":"foo"') + !currentUrl.contains('?name=foo') } @Issue('grails-core-#10622') From 9bf4e00ba6c4edf06c92503c1b1c736410632c6a Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Mon, 9 Nov 2026 16:36:13 -0800 Subject: [PATCH 75/78] Type PromiseList.then and the GPath binding sources for Groovy 6.0.1 Groovy 6.0.1 checks wildcard containment as javac does (GROOVY-12714), and two statically compiled classes no longer compile: - GPathResultCollectionDataBindingSource returned its List field as the List that getDataBindingSources() declares. The field now holds DataBindingSource elements, typed so by the closure that builds them. - PromiseList.then passed an identity closure returning List to Promises.onComplete, whose Closure parameter leaves no T to infer. onComplete makes the closure's result the List value, so the closure is passed raw, as onComplete(Closure) already does. --- .../core/src/main/groovy/grails/async/PromiseList.groovy | 4 +++- .../xml/GPathResultCollectionDataBindingSource.groovy | 6 ++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/grails-async/core/src/main/groovy/grails/async/PromiseList.groovy b/grails-async/core/src/main/groovy/grails/async/PromiseList.groovy index fcdffb9da9e..dd7b6c4c25c 100644 --- a/grails-async/core/src/main/groovy/grails/async/PromiseList.groovy +++ b/grails-async/core/src/main/groovy/grails/async/PromiseList.groovy @@ -119,7 +119,9 @@ class PromiseList implements Promise> { @Override Promise> then(Closure callable) { - return Promises.onComplete(promises, { List values -> return values }).then(callable) + // onComplete makes the closure's result the List value, which its Closure parameter does not express + Closure allValues = { List values -> return values } + return Promises.onComplete(promises, allValues).then(callable) } /** diff --git a/grails-databinding-core/src/main/groovy/org/grails/databinding/xml/GPathResultCollectionDataBindingSource.groovy b/grails-databinding-core/src/main/groovy/org/grails/databinding/xml/GPathResultCollectionDataBindingSource.groovy index b09c38ea13d..1463b0df480 100644 --- a/grails-databinding-core/src/main/groovy/org/grails/databinding/xml/GPathResultCollectionDataBindingSource.groovy +++ b/grails-databinding-core/src/main/groovy/org/grails/databinding/xml/GPathResultCollectionDataBindingSource.groovy @@ -28,13 +28,11 @@ import grails.databinding.SimpleMapDataBindingSource @CompileStatic class GPathResultCollectionDataBindingSource implements CollectionDataBindingSource { - protected List dataBindingSources + protected List dataBindingSources GPathResultCollectionDataBindingSource(GPathResult gpath) { dataBindingSources = gpath?.children()?.collect { child -> - def map = new GPathResultMap((GPathResult) child) - DataBindingSource bindingSource = new SimpleMapDataBindingSource(map) - bindingSource + (DataBindingSource) new SimpleMapDataBindingSource(new GPathResultMap((GPathResult) child)) } } From 50eadf14adf35bda34aedac329526df55040b4af Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Mon, 9 Nov 2026 16:50:48 -0800 Subject: [PATCH 76/78] Run the action an include names when no error is being handled Outside an error, an include made by UrlMappingUtils.includeRequestForUrlMappingInfo answered with the mapping it was given. A mapping built from a controller and action, such as a ForwardUrlMappingInfo, carries no controller class, so no handler adapter ran the action and the include was empty. It now answers with the mapping with its controller, as a match by URI does, and puts the controller class on the request. A mapping for a view or a URI answers as before, and any other falls back to the URI the include was made under. --- .../issue11102/FailingController.groovy | 9 ++++ .../FailedActionObservationSpec.groovy | 17 ++++++++ .../issue12688/FailingController.groovy | 9 ++++ .../JettyFailedActionObservationSpec.groovy | 17 ++++++++ .../undertowapp/FailingController.groovy | 9 ++++ ...UndertowFailedActionObservationSpec.groovy | 17 ++++++++ .../mvc/UrlMappingsHandlerMapping.groovy | 26 +++++++++--- .../mvc/UrlMappingsHandlerMappingSpec.groovy | 41 +++++++++++++++++-- 8 files changed, 136 insertions(+), 9 deletions(-) diff --git a/grails-test-examples/issue-11102/grails-app/controllers/issue11102/FailingController.groovy b/grails-test-examples/issue-11102/grails-app/controllers/issue11102/FailingController.groovy index 67f19f3f4b1..c944632ecc9 100644 --- a/grails-test-examples/issue-11102/grails-app/controllers/issue11102/FailingController.groovy +++ b/grails-test-examples/issue-11102/grails-app/controllers/issue11102/FailingController.groovy @@ -25,6 +25,9 @@ import org.springframework.web.context.request.async.WebAsyncUtils import org.springframework.web.servlet.ModelAndView import org.springframework.web.servlet.view.InternalResourceView +import org.grails.web.mapping.ForwardUrlMappingInfo +import org.grails.web.mapping.UrlMappingUtils + class FailingController { def answeredByView() { @@ -115,6 +118,12 @@ class FailingController { render "before ${g.include(action: 'answeredByController')} after" } + def includesThroughUrlMappingUtils() { + response.writer.write('before ') + UrlMappingUtils.includeRequestForUrlMappingInfo(request, response, new ForwardUrlMappingInfo(controller: 'failing', action: 'included'), [:], false) + render ' after' + } + def included() { render 'included' } diff --git a/grails-test-examples/issue-11102/src/integration-test/groovy/issue11102/FailedActionObservationSpec.groovy b/grails-test-examples/issue-11102/src/integration-test/groovy/issue11102/FailedActionObservationSpec.groovy index c3eed49dd59..0e303987468 100644 --- a/grails-test-examples/issue-11102/src/integration-test/groovy/issue11102/FailedActionObservationSpec.groovy +++ b/grails-test-examples/issue-11102/src/integration-test/groovy/issue11102/FailedActionObservationSpec.groovy @@ -120,6 +120,23 @@ class FailedActionObservationSpec extends Specification implements HttpClientSup 'an error controller, on a page whose URL has a parameter' | '/page/example' | '/failing/includesAnswerOfController' | 'Answered by the error controller' } + void 'an action a page includes through UrlMappingUtils runs, and the page keeps its route'() { + given: + def path = '/failing/includesThroughUrlMappingUtils' + + when: + def response = http([(REQUEST_HEADER): path], path) + + then: 'the included action answered inside the page' + response.assertContains(200, 'before included after') + + and: 'the observation of the page stopped on its own route, with no error' + new PollingConditions(timeout: 30).eventually { + assert STOPPED[path] == [path, 'none'] + } + !NOTIFIED.containsKey(path) + } + void 'a request #what is reported under #reported'() { when: def response = http([(REQUEST_HEADER): path], path) diff --git a/grails-test-examples/jetty/grails-app/controllers/issue12688/FailingController.groovy b/grails-test-examples/jetty/grails-app/controllers/issue12688/FailingController.groovy index 02e19c48a09..56c91c6ad38 100644 --- a/grails-test-examples/jetty/grails-app/controllers/issue12688/FailingController.groovy +++ b/grails-test-examples/jetty/grails-app/controllers/issue12688/FailingController.groovy @@ -24,6 +24,9 @@ import org.springframework.web.context.request.async.WebAsyncUtils import org.springframework.web.servlet.ModelAndView import org.springframework.web.servlet.view.InternalResourceView +import org.grails.web.mapping.ForwardUrlMappingInfo +import org.grails.web.mapping.UrlMappingUtils + class FailingController { def answeredByView() { @@ -98,6 +101,12 @@ class FailingController { render "before ${g.include(action: 'answeredByController')} after" } + def includesThroughUrlMappingUtils() { + response.writer.write('before ') + UrlMappingUtils.includeRequestForUrlMappingInfo(request, response, new ForwardUrlMappingInfo(controller: 'failing', action: 'included'), [:], false) + render ' after' + } + def included() { render 'included' } diff --git a/grails-test-examples/jetty/src/integration-test/groovy/issue12688/JettyFailedActionObservationSpec.groovy b/grails-test-examples/jetty/src/integration-test/groovy/issue12688/JettyFailedActionObservationSpec.groovy index 7103d474d90..f6ce6272f11 100644 --- a/grails-test-examples/jetty/src/integration-test/groovy/issue12688/JettyFailedActionObservationSpec.groovy +++ b/grails-test-examples/jetty/src/integration-test/groovy/issue12688/JettyFailedActionObservationSpec.groovy @@ -118,6 +118,23 @@ class JettyFailedActionObservationSpec extends Specification implements HttpClie 'an error controller, on a page whose URL has a parameter' | '/page/example' | '/failing/includesAnswerOfController' | 'Answered by the error controller' } + void 'an action a page includes through UrlMappingUtils runs, and the page keeps its route'() { + given: + def path = '/failing/includesThroughUrlMappingUtils' + + when: + def response = http([(REQUEST_HEADER): path], path) + + then: 'the included action answered inside the page' + response.assertContains(200, 'before included after') + + and: 'the observation of the page stopped on its own route, with no error' + new PollingConditions(timeout: 30).eventually { + assert STOPPED[path] == [path, 'none'] + } + !NOTIFIED.containsKey(path) + } + private List errorTags(String route) { meterRegistry.find('http.server.requests').tag('status', '500').tag('uri', route).timers()*.id*.getTag('error') } diff --git a/grails-test-examples/undertow/grails-app/controllers/undertowapp/FailingController.groovy b/grails-test-examples/undertow/grails-app/controllers/undertowapp/FailingController.groovy index 72d2025eab3..68d1870f78b 100644 --- a/grails-test-examples/undertow/grails-app/controllers/undertowapp/FailingController.groovy +++ b/grails-test-examples/undertow/grails-app/controllers/undertowapp/FailingController.groovy @@ -24,6 +24,9 @@ import org.springframework.web.context.request.async.WebAsyncUtils import org.springframework.web.servlet.ModelAndView import org.springframework.web.servlet.view.InternalResourceView +import org.grails.web.mapping.ForwardUrlMappingInfo +import org.grails.web.mapping.UrlMappingUtils + class FailingController { def answeredByView() { @@ -98,6 +101,12 @@ class FailingController { render "before ${g.include(action: 'answeredByController')} after" } + def includesThroughUrlMappingUtils() { + response.writer.write('before ') + UrlMappingUtils.includeRequestForUrlMappingInfo(request, response, new ForwardUrlMappingInfo(controller: 'failing', action: 'included'), [:], false) + render ' after' + } + def included() { render 'included' } diff --git a/grails-test-examples/undertow/src/integration-test/groovy/undertowapp/UndertowFailedActionObservationSpec.groovy b/grails-test-examples/undertow/src/integration-test/groovy/undertowapp/UndertowFailedActionObservationSpec.groovy index 7edbe1e3211..0583eb450a0 100644 --- a/grails-test-examples/undertow/src/integration-test/groovy/undertowapp/UndertowFailedActionObservationSpec.groovy +++ b/grails-test-examples/undertow/src/integration-test/groovy/undertowapp/UndertowFailedActionObservationSpec.groovy @@ -120,6 +120,23 @@ class UndertowFailedActionObservationSpec extends Specification implements HttpC 'an error controller, on a page whose URL has a parameter' | '/page/example' | '/failing/includesAnswerOfController' | 'Answered by the error controller' } + void 'an action a page includes through UrlMappingUtils runs, and the page keeps its route'() { + given: + def path = '/failing/includesThroughUrlMappingUtils' + + when: + def response = http([(REQUEST_HEADER): path], path) + + then: 'the included action answered inside the page' + response.assertContains(200, 'before included after') + + and: 'the observation of the page stopped on its own route, with no error' + new PollingConditions(timeout: 30).eventually { + assert STOPPED[path] == [path, 'none'] + } + !NOTIFIED.containsKey(path) + } + private List errorTags(String route) { meterRegistry.find('http.server.requests').tag('status', '500').tag('uri', route).timers()*.id*.getTag('error') } diff --git a/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMapping.groovy b/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMapping.groovy index f1df071fe19..cdfb896512b 100644 --- a/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMapping.groovy +++ b/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMapping.groovy @@ -62,9 +62,9 @@ class UrlMappingsHandlerMapping extends AbstractHandlerMapping { /** * The mapping an include made by {@link org.grails.web.mapping.UrlMappingUtils#includeRequestForUrlMappingInfo} answers - * with, whatever its URI would match. While an error is being handled, the include answers with the status code - * mapping, as a forward to it does, since the mapping it was made for can be one that carries the parameters of the - * request rather than its controller. + * with, whatever its URI would match, with the controller it names. While an error is being handled, the include + * answers with the status code mapping, as a forward to it does, since the mapping it was made for can be one that + * carries the parameters of the request rather than its controller. * * @since 8.0.1 */ @@ -176,8 +176,13 @@ class UrlMappingsHandlerMapping extends AbstractHandlerMapping { def matchedInfo = request.getAttribute(MATCHED_REQUEST) def errorStatus = request.getAttribute(WebUtils.ERROR_STATUS_CODE_ATTRIBUTE) if (includedInfo instanceof UrlMappingInfo && errorStatus == null) { - request.setAttribute(MATCHED_REQUEST, includedInfo) - return includedInfo + UrlMappingInfo info = withController((UrlMappingInfo) includedInfo) + if (info instanceof GrailsControllerUrlMappingInfo) { + request.setAttribute(MATCHED_REQUEST, info) + request.setAttribute(GrailsApplicationAttributes.GRAILS_CONTROLLER_CLASS, ((GrailsControllerUrlMappingInfo) info).controllerClass) + return info + } + if (info.viewName || info.URI) return info } // The dispatch that returns the result of asynchronous processing answers for the action that started it. Any @@ -239,6 +244,17 @@ class UrlMappingsHandlerMapping extends AbstractHandlerMapping { } + /** + * The mapping with the controller it names, as a match by URI answers, so that its action runs. A mapping built + * from a controller and action, rather than matched, does not carry the controller. + */ + private UrlMappingInfo withController(UrlMappingInfo info) { + if (info instanceof GrailsControllerUrlMappingInfo || !(urlMappingsHolder instanceof AbstractGrailsControllerUrlMappings)) { + return info + } + return ((AbstractGrailsControllerUrlMappings) urlMappingsHolder).collectControllerMapping(info) + } + protected String findRequestedVersion(GrailsWebRequest currentRequest) { String version = currentRequest.getHeader(HttpHeaders.ACCEPT_VERSION) if (!version && mimeTypeResolver) { diff --git a/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMappingSpec.groovy b/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMappingSpec.groovy index 31067d976bc..e7a7c8848d6 100644 --- a/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMappingSpec.groovy +++ b/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMappingSpec.groovy @@ -28,6 +28,8 @@ import grails.web.HyphenatedUrlConverter import grails.web.mapping.AbstractUrlMappingsSpec import org.grails.web.mapping.DefaultUrlMappingData import org.grails.web.mapping.DefaultUrlMappingInfo +import org.grails.web.mapping.ForwardUrlMappingInfo +import org.grails.web.util.GrailsApplicationAttributes import org.grails.web.util.WebUtils import org.springframework.http.server.observation.ServerRequestObservationContext import org.springframework.ui.ModelMap @@ -438,7 +440,7 @@ class UrlMappingsHandlerMappingSpec extends AbstractUrlMappingsSpec { 'its mapping with the parameters of the page\'s URL' | [slug: 'example'] } - void "an include made for a mapping answers with that mapping when no error is being handled"() { + void "an include made for #made answers with the action of its controller when no error is being handled"() { given: def grailsApplication = new DefaultGrailsApplication(FooController) grailsApplication.initialise() @@ -449,11 +451,42 @@ class UrlMappingsHandlerMappingSpec extends AbstractUrlMappingsSpec { def handler = new UrlMappingsHandlerMapping(holder) def webRequest = GrailsWebMockUtil.bindMockWebRequest() def request = webRequest.request - def mapping = holder.match('/foo/other') + def mapping = matched ? holder.match('/foo/other') : new ForwardUrlMappingInfo(controller: 'foo', action: action) + + when: 'it is included under a URI that maps to another action' + request.setAttribute(WebUtils.INCLUDE_REQUEST_URI_ATTRIBUTE, '/foo/bar') + request.requestURI = '/foo/bar' + request.setAttribute(UrlMappingsHandlerMapping.INCLUDED_MAPPING_INFO, mapping) + def info = handler.getHandler(request).handler + + then: 'it answers with the action it was made for, on the controller that action belongs to' + info instanceof GrailsControllerUrlMappingInfo + ((GrailsControllerUrlMappingInfo) info).controllerClass.clazz == FooController + ((GrailsControllerUrlMappingInfo) info).info.actionName == action + request.getAttribute(UrlMappingsHandlerMapping.MATCHED_REQUEST).is(info) + request.getAttribute(GrailsApplicationAttributes.GRAILS_CONTROLLER_CLASS).is(((GrailsControllerUrlMappingInfo) info).controllerClass) + + where: + made | matched | action + 'a mapping matched by its URI' | true | 'fooBar' + 'a mapping built from a controller and action' | false | 'fooBar' + 'a mapping built from a controller alone' | false | null + } + + void "an include made for a view answers with that view when no error is being handled"() { + given: + def grailsApplication = new DefaultGrailsApplication(FooController) + grailsApplication.initialise() + def holder = new GrailsControllerUrlMappings(grailsApplication, getUrlMappingsHolder { + "/foo/bar"(controller: 'foo', action: 'bar') + }) + def handler = new UrlMappingsHandlerMapping(holder) + def request = GrailsWebMockUtil.bindMockWebRequest().request + def mapping = new ForwardUrlMappingInfo(view: '/foo/page') when: - request.setAttribute(WebUtils.INCLUDE_REQUEST_URI_ATTRIBUTE, '/foo/fooBar') - request.requestURI = '/foo/fooBar' + request.setAttribute(WebUtils.INCLUDE_REQUEST_URI_ATTRIBUTE, '/foo/bar') + request.requestURI = '/foo/bar' request.setAttribute(UrlMappingsHandlerMapping.INCLUDED_MAPPING_INFO, mapping) then: From 02ef6dc0c5a1332569789a1b94334145a03d8550 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Mon, 9 Nov 2026 19:28:52 -0800 Subject: [PATCH 77/78] Give a page its state back after an include, and run what an error handler includes After UrlMappingUtils.includeRequestForUrlMappingInfo returned, the page that made the include reported the included controller and action, with the included parameters and without its model. The include now gives the page back its controller, action, id, parameters, model, template model and page attributes, through the same code includeForUrlMappingInfo uses, and restores the request attributes its dispatch clears or the included action sets. An error controller that included another action that way ran itself again, until the stack was exhausted: an include made while an error status was set was resolved through the status code. An include now runs the action of the mapping it was made for whether or not an error is being handled. The mapping the exception resolver includes names the error handler it chose, and is made controller-aware like any other, so the status code is no longer needed for it. --- .../issue11102/FailingController.groovy | 15 +- .../controllers/issue11102/UrlMappings.groovy | 1 + .../FailedActionObservationSpec.groovy | 26 ++- .../issue12688/FailingController.groovy | 15 +- .../controllers/issue12688/UrlMappings.groovy | 1 + .../JettyFailedActionObservationSpec.groovy | 26 ++- .../undertowapp/FailingController.groovy | 15 +- .../undertowapp/UrlMappings.groovy | 1 + ...UndertowFailedActionObservationSpec.groovy | 26 ++- .../grails/web/mapping/UrlMappingUtils.java | 155 +++++++++++------- .../mvc/UrlMappingsHandlerMapping.groovy | 14 +- .../web/mapping/UrlMappingUtilsSpec.groovy | 78 +++++++++ .../mvc/UrlMappingsHandlerMappingSpec.groovy | 24 +++ 13 files changed, 315 insertions(+), 82 deletions(-) diff --git a/grails-test-examples/issue-11102/grails-app/controllers/issue11102/FailingController.groovy b/grails-test-examples/issue-11102/grails-app/controllers/issue11102/FailingController.groovy index c944632ecc9..8465f65b7d0 100644 --- a/grails-test-examples/issue-11102/grails-app/controllers/issue11102/FailingController.groovy +++ b/grails-test-examples/issue-11102/grails-app/controllers/issue11102/FailingController.groovy @@ -68,6 +68,10 @@ class FailingController { throw new ArithmeticException('answered by an error controller that forwards') } + def answeredByIncludingController() { + throw new NoSuchElementException('answered by an error controller that includes an action') + } + def forwardedToView() { forward(action: 'answeredByView') } @@ -120,8 +124,8 @@ class FailingController { def includesThroughUrlMappingUtils() { response.writer.write('before ') - UrlMappingUtils.includeRequestForUrlMappingInfo(request, response, new ForwardUrlMappingInfo(controller: 'failing', action: 'included'), [:], false) - render ' after' + UrlMappingUtils.includeRequestForUrlMappingInfo(request, response, new ForwardUrlMappingInfo(controller: 'failing', action: 'included', params: [marker: 'included']), [:], false) + render " after, as ${controllerName}/${actionName} with ${params.marker}" } def included() { @@ -136,6 +140,13 @@ class FailingController { forward(action: 'errorHandler') } + def includingErrorHandler() { + response.status = 500 + response.writer.write('Answered by the error controller, with ') + UrlMappingUtils.includeRequestForUrlMappingInfo(request, response, new ForwardUrlMappingInfo(controller: 'failing', action: 'included'), [:], false) + render ' inside' + } + private void failAsynchronously(Exception failure) { DeferredResult result = new DeferredResult<>() startAsync(result) diff --git a/grails-test-examples/issue-11102/grails-app/controllers/issue11102/UrlMappings.groovy b/grails-test-examples/issue-11102/grails-app/controllers/issue11102/UrlMappings.groovy index 1281443a446..187e866e7bf 100644 --- a/grails-test-examples/issue-11102/grails-app/controllers/issue11102/UrlMappings.groovy +++ b/grails-test-examples/issue-11102/grails-app/controllers/issue11102/UrlMappings.groovy @@ -38,6 +38,7 @@ class UrlMappings { "500"(controller: 'failing', action: 'errorHandler', exception: UnsupportedOperationException) "500"(controller: 'failing', action: 'errorHandler', exception: StackOverflowError) "500"(controller: 'failing', action: 'forwardingErrorHandler', exception: ArithmeticException) + "500"(controller: 'failing', action: 'includingErrorHandler', exception: NoSuchElementException) "500"(view:'/error') "404"(controller: 'failing', action: 'notFoundHandler') } diff --git a/grails-test-examples/issue-11102/src/integration-test/groovy/issue11102/FailedActionObservationSpec.groovy b/grails-test-examples/issue-11102/src/integration-test/groovy/issue11102/FailedActionObservationSpec.groovy index 0e303987468..f48e3294257 100644 --- a/grails-test-examples/issue-11102/src/integration-test/groovy/issue11102/FailedActionObservationSpec.groovy +++ b/grails-test-examples/issue-11102/src/integration-test/groovy/issue11102/FailedActionObservationSpec.groovy @@ -120,15 +120,15 @@ class FailedActionObservationSpec extends Specification implements HttpClientSup 'an error controller, on a page whose URL has a parameter' | '/page/example' | '/failing/includesAnswerOfController' | 'Answered by the error controller' } - void 'an action a page includes through UrlMappingUtils runs, and the page keeps its route'() { + void 'an action a page includes through UrlMappingUtils runs, and the page goes on as itself with its own route'() { given: def path = '/failing/includesThroughUrlMappingUtils' when: - def response = http([(REQUEST_HEADER): path], path) + def response = http([(REQUEST_HEADER): path], "${path}?marker=page") - then: 'the included action answered inside the page' - response.assertContains(200, 'before included after') + then: 'the included action answered inside the page, and after it the page had its own action and parameters' + response.assertContains(200, 'before included after, as failing/includesThroughUrlMappingUtils with page') and: 'the observation of the page stopped on its own route, with no error' new PollingConditions(timeout: 30).eventually { @@ -159,6 +159,24 @@ class FailedActionObservationSpec extends Specification implements HttpClientSup reported = route == 'none' ? 'no route' : 'its own route' } + void 'an error controller that includes an action runs that action inside its page, and the failure is reported once'() { + given: + def path = '/failing/answeredByIncludingController' + + when: + def response = http([(REQUEST_HEADER): path], path) + + then: 'the error controller answered, with the action it included inside its page' + response.assertContains(500, 'Answered by the error controller, with included inside') + + and: 'the observation stopped on the route that failed with what failed, and the handlers heard of it once' + new PollingConditions(timeout: 30).eventually { + assert STOPPED[path] == [path, 'NoSuchElementException'] + assert 'NoSuchElementException' in errorTags(path) + } + NOTIFIED[path] == ['NoSuchElementException'] + } + private List errorTags(String route) { meterRegistry.find('http.server.requests').tag('status', '500').tag('uri', route).timers()*.id*.getTag('error') } diff --git a/grails-test-examples/jetty/grails-app/controllers/issue12688/FailingController.groovy b/grails-test-examples/jetty/grails-app/controllers/issue12688/FailingController.groovy index 56c91c6ad38..170304bd795 100644 --- a/grails-test-examples/jetty/grails-app/controllers/issue12688/FailingController.groovy +++ b/grails-test-examples/jetty/grails-app/controllers/issue12688/FailingController.groovy @@ -67,6 +67,10 @@ class FailingController { throw new ArithmeticException('answered by an error controller that forwards') } + def answeredByIncludingController() { + throw new NoSuchElementException('answered by an error controller that includes an action') + } + def forwardedToView() { forward(action: 'answeredByView') } @@ -103,8 +107,8 @@ class FailingController { def includesThroughUrlMappingUtils() { response.writer.write('before ') - UrlMappingUtils.includeRequestForUrlMappingInfo(request, response, new ForwardUrlMappingInfo(controller: 'failing', action: 'included'), [:], false) - render ' after' + UrlMappingUtils.includeRequestForUrlMappingInfo(request, response, new ForwardUrlMappingInfo(controller: 'failing', action: 'included', params: [marker: 'included']), [:], false) + render " after, as ${controllerName}/${actionName} with ${params.marker}" } def included() { @@ -119,6 +123,13 @@ class FailingController { forward(action: 'errorHandler') } + def includingErrorHandler() { + response.status = 500 + response.writer.write('Answered by the error controller, with ') + UrlMappingUtils.includeRequestForUrlMappingInfo(request, response, new ForwardUrlMappingInfo(controller: 'failing', action: 'included'), [:], false) + render ' inside' + } + private void failAsynchronously(Exception failure) { DeferredResult result = new DeferredResult<>() startAsync(result) diff --git a/grails-test-examples/jetty/grails-app/controllers/issue12688/UrlMappings.groovy b/grails-test-examples/jetty/grails-app/controllers/issue12688/UrlMappings.groovy index d249b476815..228ab844a78 100644 --- a/grails-test-examples/jetty/grails-app/controllers/issue12688/UrlMappings.groovy +++ b/grails-test-examples/jetty/grails-app/controllers/issue12688/UrlMappings.groovy @@ -34,6 +34,7 @@ class UrlMappings { "500"(controller: 'failing', action: 'errorHandler', exception: UnsupportedOperationException) "500"(controller: 'failing', action: 'errorHandler', exception: StackOverflowError) "500"(controller: 'failing', action: 'forwardingErrorHandler', exception: ArithmeticException) + "500"(controller: 'failing', action: 'includingErrorHandler', exception: NoSuchElementException) "413"(controller: 'upload', action: 'tooLarge') "404"(view: '/notFound') } diff --git a/grails-test-examples/jetty/src/integration-test/groovy/issue12688/JettyFailedActionObservationSpec.groovy b/grails-test-examples/jetty/src/integration-test/groovy/issue12688/JettyFailedActionObservationSpec.groovy index f6ce6272f11..2fa8e3e743e 100644 --- a/grails-test-examples/jetty/src/integration-test/groovy/issue12688/JettyFailedActionObservationSpec.groovy +++ b/grails-test-examples/jetty/src/integration-test/groovy/issue12688/JettyFailedActionObservationSpec.groovy @@ -118,15 +118,15 @@ class JettyFailedActionObservationSpec extends Specification implements HttpClie 'an error controller, on a page whose URL has a parameter' | '/page/example' | '/failing/includesAnswerOfController' | 'Answered by the error controller' } - void 'an action a page includes through UrlMappingUtils runs, and the page keeps its route'() { + void 'an action a page includes through UrlMappingUtils runs, and the page goes on as itself with its own route'() { given: def path = '/failing/includesThroughUrlMappingUtils' when: - def response = http([(REQUEST_HEADER): path], path) + def response = http([(REQUEST_HEADER): path], "${path}?marker=page") - then: 'the included action answered inside the page' - response.assertContains(200, 'before included after') + then: 'the included action answered inside the page, and after it the page had its own action and parameters' + response.assertContains(200, 'before included after, as failing/includesThroughUrlMappingUtils with page') and: 'the observation of the page stopped on its own route, with no error' new PollingConditions(timeout: 30).eventually { @@ -135,6 +135,24 @@ class JettyFailedActionObservationSpec extends Specification implements HttpClie !NOTIFIED.containsKey(path) } + void 'an error controller that includes an action runs that action inside its page, and the failure is reported once'() { + given: + def path = '/failing/answeredByIncludingController' + + when: + def response = http([(REQUEST_HEADER): path], path) + + then: 'the error controller answered, with the action it included inside its page' + response.assertContains(500, 'Answered by the error controller, with included inside') + + and: 'the observation stopped on the route that failed with what failed, and the handlers heard of it once' + new PollingConditions(timeout: 30).eventually { + assert STOPPED[path] == [path, 'NoSuchElementException'] + assert 'NoSuchElementException' in errorTags(path) + } + NOTIFIED[path] == ['NoSuchElementException'] + } + private List errorTags(String route) { meterRegistry.find('http.server.requests').tag('status', '500').tag('uri', route).timers()*.id*.getTag('error') } diff --git a/grails-test-examples/undertow/grails-app/controllers/undertowapp/FailingController.groovy b/grails-test-examples/undertow/grails-app/controllers/undertowapp/FailingController.groovy index 68d1870f78b..6726d134c4c 100644 --- a/grails-test-examples/undertow/grails-app/controllers/undertowapp/FailingController.groovy +++ b/grails-test-examples/undertow/grails-app/controllers/undertowapp/FailingController.groovy @@ -67,6 +67,10 @@ class FailingController { throw new ArithmeticException('answered by an error controller that forwards') } + def answeredByIncludingController() { + throw new NoSuchElementException('answered by an error controller that includes an action') + } + def forwardedToView() { forward(action: 'answeredByView') } @@ -103,8 +107,8 @@ class FailingController { def includesThroughUrlMappingUtils() { response.writer.write('before ') - UrlMappingUtils.includeRequestForUrlMappingInfo(request, response, new ForwardUrlMappingInfo(controller: 'failing', action: 'included'), [:], false) - render ' after' + UrlMappingUtils.includeRequestForUrlMappingInfo(request, response, new ForwardUrlMappingInfo(controller: 'failing', action: 'included', params: [marker: 'included']), [:], false) + render " after, as ${controllerName}/${actionName} with ${params.marker}" } def included() { @@ -119,6 +123,13 @@ class FailingController { forward(action: 'errorHandler') } + def includingErrorHandler() { + response.status = 500 + response.writer.write('Answered by the error controller, with ') + UrlMappingUtils.includeRequestForUrlMappingInfo(request, response, new ForwardUrlMappingInfo(controller: 'failing', action: 'included'), [:], false) + render ' inside' + } + private void failAsynchronously(Exception failure) { DeferredResult result = new DeferredResult<>() startAsync(result) diff --git a/grails-test-examples/undertow/grails-app/controllers/undertowapp/UrlMappings.groovy b/grails-test-examples/undertow/grails-app/controllers/undertowapp/UrlMappings.groovy index 2bfa206272f..d463a9677a3 100644 --- a/grails-test-examples/undertow/grails-app/controllers/undertowapp/UrlMappings.groovy +++ b/grails-test-examples/undertow/grails-app/controllers/undertowapp/UrlMappings.groovy @@ -35,6 +35,7 @@ class UrlMappings { "500"(controller: 'failing', action: 'errorHandler', exception: UnsupportedOperationException) "500"(controller: 'failing', action: 'errorHandler', exception: StackOverflowError) "500"(controller: 'failing', action: 'forwardingErrorHandler', exception: ArithmeticException) + "500"(controller: 'failing', action: 'includingErrorHandler', exception: NoSuchElementException) "500"(controller: 'errorPage', action: 'handle', exception: StaticInitFailure) "413"(controller: 'upload', action: 'tooLarge') "404"(view: '/notFound') diff --git a/grails-test-examples/undertow/src/integration-test/groovy/undertowapp/UndertowFailedActionObservationSpec.groovy b/grails-test-examples/undertow/src/integration-test/groovy/undertowapp/UndertowFailedActionObservationSpec.groovy index 0583eb450a0..ef8ee0567db 100644 --- a/grails-test-examples/undertow/src/integration-test/groovy/undertowapp/UndertowFailedActionObservationSpec.groovy +++ b/grails-test-examples/undertow/src/integration-test/groovy/undertowapp/UndertowFailedActionObservationSpec.groovy @@ -120,15 +120,15 @@ class UndertowFailedActionObservationSpec extends Specification implements HttpC 'an error controller, on a page whose URL has a parameter' | '/page/example' | '/failing/includesAnswerOfController' | 'Answered by the error controller' } - void 'an action a page includes through UrlMappingUtils runs, and the page keeps its route'() { + void 'an action a page includes through UrlMappingUtils runs, and the page goes on as itself with its own route'() { given: def path = '/failing/includesThroughUrlMappingUtils' when: - def response = http([(REQUEST_HEADER): path], path) + def response = http([(REQUEST_HEADER): path], "${path}?marker=page") - then: 'the included action answered inside the page' - response.assertContains(200, 'before included after') + then: 'the included action answered inside the page, and after it the page had its own action and parameters' + response.assertContains(200, 'before included after, as failing/includesThroughUrlMappingUtils with page') and: 'the observation of the page stopped on its own route, with no error' new PollingConditions(timeout: 30).eventually { @@ -137,6 +137,24 @@ class UndertowFailedActionObservationSpec extends Specification implements HttpC !NOTIFIED.containsKey(path) } + void 'an error controller that includes an action runs that action inside its page, and the failure is reported once'() { + given: + def path = '/failing/answeredByIncludingController' + + when: + def response = http([(REQUEST_HEADER): path], path) + + then: 'the error controller answered, with the action it included inside its page' + response.assertContains(500, 'Answered by the error controller, with included inside') + + and: 'the observation stopped on the route that failed with what failed, and the handlers heard of it once' + new PollingConditions(timeout: 30).eventually { + assert STOPPED[path] == [path, 'NoSuchElementException'] + assert 'NoSuchElementException' in errorTags(path) + } + NOTIFIED[path] == ['NoSuchElementException'] + } + private List errorTags(String route) { meterRegistry.find('http.server.requests').tag('status', '500').tag('uri', route).timers()*.id*.getTag('error') } diff --git a/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/UrlMappingUtils.java b/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/UrlMappingUtils.java index cd96ff1fdbe..b7fcefffb9d 100644 --- a/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/UrlMappingUtils.java +++ b/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/UrlMappingUtils.java @@ -65,6 +65,18 @@ * @since 2.4 */ public class UrlMappingUtils { + + /** + * The request attributes a dispatch for a mapping clears for what it dispatches to, and that an include sets for + * its own action, so an include restores them for the page that made it. + */ + private static final String[] INCLUDE_DISPATCH_ATTRIBUTES = { + UrlMappingsHandlerMapping.MATCHED_REQUEST, + GrailsApplicationAttributes.GRAILS_CONTROLLER_CLASS, + GrailsApplicationAttributes.GRAILS_CONTROLLER_CLASS_AVAILABLE, + "grailsWebRequestFilter" + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX + }; + private UrlMappingUtils() { } @@ -261,8 +273,9 @@ public static String forwardRequestForUrlMappingInfo(HttpServletRequest request, * Includes what the given UrlMappingInfo maps to in the response, where * {@link #forwardRequestForUrlMappingInfo(HttpServletRequest, HttpServletResponse, UrlMappingInfo, Map, boolean)} * would forward to it. A request that is itself an include cannot forward: a forward ends the response it is given, - * which inside an include belongs to the page that included it. The include answers with the given mapping, - * whatever its URI would match. + * which inside an include belongs to the page that included it. The include answers with the action of the given + * mapping, whatever its URI would match and whatever error is being handled. Once it returns, the page has its own + * controller, action, id, parameters and model again, and renders on as it was. * * @param request The request * @param response The response @@ -277,12 +290,26 @@ public static String forwardRequestForUrlMappingInfo(HttpServletRequest request, */ public static String includeRequestForUrlMappingInfo(HttpServletRequest request, HttpServletResponse response, UrlMappingInfo info, Map model, boolean includeParams) throws ServletException, IOException { + final IncludingPage page = new IncludingPage(GrailsWebRequest.lookup(request)); + final Map dispatchAttributes = new HashMap<>(); + for (String name : INCLUDE_DISPATCH_ATTRIBUTES) { + dispatchAttributes.put(name, request.getAttribute(name)); + } request.setAttribute(UrlMappingsHandlerMapping.INCLUDED_MAPPING_INFO, info); try { return dispatchRequestForUrlMappingInfo(request, response, info, model, includeParams, true); } finally { request.removeAttribute(UrlMappingsHandlerMapping.INCLUDED_MAPPING_INFO); + for (Map.Entry attribute : dispatchAttributes.entrySet()) { + if (attribute.getValue() != null) { + request.setAttribute(attribute.getKey(), attribute.getValue()); + } + else { + request.removeAttribute(attribute.getKey()); + } + } + page.restore(); } } @@ -361,35 +388,7 @@ public static IncludedContent includeForUrlMappingInfo(HttpServletRequest reques private static IncludedContent includeForUrlMappingInfoHelper(String includeUrl, HttpServletRequest request, HttpServletResponse response, UrlMappingInfo info, Map model) { final GrailsWebRequest webRequest = GrailsWebRequest.lookup(request); - - String currentController = null; - String currentAction = null; - String currentId = null; - ModelAndView currentMv = null; - Map currentTemplateModel = null; - Binding currentPageBinding = null; - Map currentParams = null; - Object currentLayoutAttribute = null; - Object currentRenderingView = null; - if (webRequest != null) { - currentPageBinding = (Binding) webRequest.getAttribute(GrailsApplicationAttributes.PAGE_SCOPE, 0); - webRequest.removeAttribute(GrailsApplicationAttributes.PAGE_SCOPE, 0); - currentLayoutAttribute = webRequest.getAttribute(WebUtils.LAYOUT_ATTRIBUTE, 0); - if (currentLayoutAttribute != null) { - webRequest.removeAttribute(WebUtils.LAYOUT_ATTRIBUTE, 0); - } - currentRenderingView = webRequest.getAttribute(WebUtils.RENDERING_VIEW, 0); - if (currentRenderingView != null) { - webRequest.removeAttribute(WebUtils.RENDERING_VIEW, 0); - } - currentController = webRequest.getControllerName(); - currentAction = webRequest.getActionName(); - currentId = webRequest.getId(); - currentParams = new HashMap(); - currentParams.putAll(webRequest.getParameterMap()); - currentMv = (ModelAndView) webRequest.getAttribute(GrailsApplicationAttributes.MODEL_AND_VIEW, 0); - currentTemplateModel = (Map) webRequest.getAttribute(GrailsApplicationAttributes.TEMPLATE_MODEL, 0); - } + final IncludingPage page = webRequest != null ? new IncludingPage(webRequest) : null; try { if (webRequest != null) { webRequest.getParameterMap().clear(); @@ -401,32 +400,76 @@ private static IncludedContent includeForUrlMappingInfoHelper(String includeUrl, return includeForUrl(includeUrl, request, response, model); } finally { - if (webRequest != null) { - if (webRequest.isActive()) { + if (page != null) { + page.restore(); + } + } + } - webRequest.setAttribute(GrailsApplicationAttributes.PAGE_SCOPE, currentPageBinding, 0); - if (currentLayoutAttribute != null) { - webRequest.setAttribute(WebUtils.LAYOUT_ATTRIBUTE, currentLayoutAttribute, 0); - } - if (currentRenderingView != null) { - webRequest.setAttribute(WebUtils.RENDERING_VIEW, currentRenderingView, 0); - } - webRequest.getParameterMap().clear(); - webRequest.getParameterMap().putAll(currentParams); - webRequest.setId(currentId); - webRequest.setControllerName(currentController); - webRequest.setActionName(currentAction); - if (currentMv != null) { - webRequest.setAttribute(GrailsApplicationAttributes.MODEL_AND_VIEW, currentMv, 0); - } - if (currentTemplateModel != null) { - webRequest.setAttribute(GrailsApplicationAttributes.TEMPLATE_MODEL, currentTemplateModel, 0); - } else { - webRequest.removeAttribute(GrailsApplicationAttributes.TEMPLATE_MODEL, 0); - } - } else { - RequestContextHolder.setRequestAttributes(null); - } + /** + * What an include changes on the request of the page that makes it: the controller, action, id and parameters the + * included mapping configures, and the model and page attributes the include must not see. Created before the + * include, which takes the page attributes away, and restored once it returns, so the page renders on as it was. + */ + @SuppressWarnings({ "unchecked", "rawtypes" }) + private static final class IncludingPage { + + private final GrailsWebRequest webRequest; + private final String controller; + private final String action; + private final String id; + private final Map params; + private final ModelAndView modelAndView; + private final Map templateModel; + private final Binding pageBinding; + private final Object layoutAttribute; + private final Object renderingView; + + IncludingPage(GrailsWebRequest webRequest) { + this.webRequest = webRequest; + pageBinding = (Binding) webRequest.getAttribute(GrailsApplicationAttributes.PAGE_SCOPE, 0); + webRequest.removeAttribute(GrailsApplicationAttributes.PAGE_SCOPE, 0); + layoutAttribute = webRequest.getAttribute(WebUtils.LAYOUT_ATTRIBUTE, 0); + if (layoutAttribute != null) { + webRequest.removeAttribute(WebUtils.LAYOUT_ATTRIBUTE, 0); + } + renderingView = webRequest.getAttribute(WebUtils.RENDERING_VIEW, 0); + if (renderingView != null) { + webRequest.removeAttribute(WebUtils.RENDERING_VIEW, 0); + } + controller = webRequest.getControllerName(); + action = webRequest.getActionName(); + id = webRequest.getId(); + params = new HashMap(); + params.putAll(webRequest.getParameterMap()); + modelAndView = (ModelAndView) webRequest.getAttribute(GrailsApplicationAttributes.MODEL_AND_VIEW, 0); + templateModel = (Map) webRequest.getAttribute(GrailsApplicationAttributes.TEMPLATE_MODEL, 0); + } + + void restore() { + if (!webRequest.isActive()) { + RequestContextHolder.setRequestAttributes(null); + return; + } + webRequest.setAttribute(GrailsApplicationAttributes.PAGE_SCOPE, pageBinding, 0); + if (layoutAttribute != null) { + webRequest.setAttribute(WebUtils.LAYOUT_ATTRIBUTE, layoutAttribute, 0); + } + if (renderingView != null) { + webRequest.setAttribute(WebUtils.RENDERING_VIEW, renderingView, 0); + } + webRequest.getParameterMap().clear(); + webRequest.getParameterMap().putAll(params); + webRequest.setId(id); + webRequest.setControllerName(controller); + webRequest.setActionName(action); + if (modelAndView != null) { + webRequest.setAttribute(GrailsApplicationAttributes.MODEL_AND_VIEW, modelAndView, 0); + } + if (templateModel != null) { + webRequest.setAttribute(GrailsApplicationAttributes.TEMPLATE_MODEL, templateModel, 0); + } else { + webRequest.removeAttribute(GrailsApplicationAttributes.TEMPLATE_MODEL, 0); } } } diff --git a/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMapping.groovy b/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMapping.groovy index cdfb896512b..b09169dfb65 100644 --- a/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMapping.groovy +++ b/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMapping.groovy @@ -61,10 +61,10 @@ class UrlMappingsHandlerMapping extends AbstractHandlerMapping { public static final String MATCHED_REQUEST = 'org.grails.url.match.info' /** - * The mapping an include made by {@link org.grails.web.mapping.UrlMappingUtils#includeRequestForUrlMappingInfo} answers - * with, whatever its URI would match, with the controller it names. While an error is being handled, the include - * answers with the status code mapping, as a forward to it does, since the mapping it was made for can be one that - * carries the parameters of the request rather than its controller. + * The mapping an include made by {@link org.grails.web.mapping.UrlMappingUtils#includeRequestForUrlMappingInfo} was + * made for. The include runs the action of that mapping, whatever its URI would match and whatever error is being + * handled: the exception resolver includes the error handler it chose, and an error handler can include another + * action. * * @since 8.0.1 */ @@ -175,7 +175,7 @@ class UrlMappingsHandlerMapping extends AbstractHandlerMapping { } def matchedInfo = request.getAttribute(MATCHED_REQUEST) def errorStatus = request.getAttribute(WebUtils.ERROR_STATUS_CODE_ATTRIBUTE) - if (includedInfo instanceof UrlMappingInfo && errorStatus == null) { + if (includedInfo instanceof UrlMappingInfo) { UrlMappingInfo info = withController((UrlMappingInfo) includedInfo) if (info instanceof GrailsControllerUrlMappingInfo) { request.setAttribute(MATCHED_REQUEST, info) @@ -196,9 +196,7 @@ class UrlMappingsHandlerMapping extends AbstractHandlerMapping { String version = findRequestedVersion(webRequest) - // An include made for the error handler resolves it as a forward to it does. Any other include made while an - // error page renders answers for its own URI. - if (errorStatus && (!WebUtils.isInclude(request) || includedInfo != null)) { + if (errorStatus && !WebUtils.isInclude(request)) { def exception = request.getAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE) UrlMappingInfo info if (exception instanceof Throwable) { diff --git a/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/UrlMappingUtilsSpec.groovy b/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/UrlMappingUtilsSpec.groovy index 245bfdab905..28ffa27e48a 100644 --- a/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/UrlMappingUtilsSpec.groovy +++ b/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/UrlMappingUtilsSpec.groovy @@ -21,6 +21,7 @@ package org.grails.web.mapping import grails.web.mapping.LinkGenerator import grails.web.mapping.UrlMappingInfo import grails.web.servlet.mvc.GrailsParameterMap +import org.grails.web.mapping.mvc.UrlMappingsHandlerMapping import org.grails.web.servlet.mvc.GrailsWebRequest import org.grails.web.util.GrailsApplicationAttributes import org.grails.web.util.IncludedContent @@ -226,4 +227,81 @@ class UrlMappingUtilsSpec extends Specification { then: "TEMPLATE_MODEL is removed after the include (not leaked back to the outer action)" capturingWebRequest.getAttribute(GrailsApplicationAttributes.TEMPLATE_MODEL, 0) == null } + + void "includeRequestForUrlMappingInfo #outcome gives the page back its controller, action, id, parameters and model"() { + given: 'a page with its own controller, action, id, parameter, model and matched mapping' + final ModelAndView pageModel = new ModelAndView('/outer/page', [greeting: 'hello']) + final Map pageTemplateModel = [templateKey: 'templateValue'] + final Object pageMatch = new ForwardUrlMappingInfo(controllerName: 'outer', actionName: 'page') + final Object pageControllerClass = new Object() + final UrlMappingInfo fragment = new ForwardUrlMappingInfo(controllerName: 'inner', actionName: 'fragment', id: '9', params: [marker: 'fragment']) + Map duringInclude = [fails: fails] + MockHttpServletRequest pageRequest = new MockHttpServletRequest() { + @Override + jakarta.servlet.RequestDispatcher getRequestDispatcher(String path) { + return new jakarta.servlet.RequestDispatcher() { + @Override + void forward(jakarta.servlet.ServletRequest req, jakarta.servlet.ServletResponse res) {} + @Override + void include(jakarta.servlet.ServletRequest req, jakarta.servlet.ServletResponse res) { + GrailsWebRequest included = GrailsWebRequest.lookup((jakarta.servlet.http.HttpServletRequest) req) + duringInclude.path = path + duringInclude.controller = included.controllerName + duringInclude.action = included.actionName + duringInclude.mapping = req.getAttribute(UrlMappingsHandlerMapping.INCLUDED_MAPPING_INFO) + duringInclude.model = req.getAttribute(GrailsApplicationAttributes.MODEL_AND_VIEW) + // as the handler mapping does for the included action + req.setAttribute(UrlMappingsHandlerMapping.MATCHED_REQUEST, fragment) + req.setAttribute(GrailsApplicationAttributes.GRAILS_CONTROLLER_CLASS, 'inner controller') + if (duringInclude.fails) { + throw new IllegalStateException('the included action failed') + } + } + } + } + } + GrailsWebRequest page = new GrailsWebRequest(pageRequest, response, attr) + pageRequest.setAttribute(GrailsApplicationAttributes.WEB_REQUEST, page) + page.controllerName = 'outer' + page.actionName = 'page' + page.id = '7' + page.params.marker = 'page' + page.setAttribute(GrailsApplicationAttributes.MODEL_AND_VIEW, pageModel, 0) + page.setAttribute(GrailsApplicationAttributes.TEMPLATE_MODEL, pageTemplateModel, 0) + pageRequest.setAttribute(UrlMappingsHandlerMapping.MATCHED_REQUEST, pageMatch) + pageRequest.setAttribute(GrailsApplicationAttributes.GRAILS_CONTROLLER_CLASS, pageControllerClass) + + when: 'the page includes another action' + Throwable failure = null + try { + UrlMappingUtils.includeRequestForUrlMappingInfo(pageRequest, response, fragment, [:], false) + } + catch (IllegalStateException e) { + failure = e + } + + then: 'the include ran for the action it was made for, without the model of the page' + duringInclude.path == '/inner/fragment' + duringInclude.controller == 'inner' + duringInclude.action == 'fragment' + duringInclude.mapping.is(fragment) + duringInclude.model == null + (failure != null) == fails + + and: 'the page is as it was' + page.controllerName == 'outer' + page.actionName == 'page' + page.id == '7' + page.params.marker == 'page' + page.getAttribute(GrailsApplicationAttributes.MODEL_AND_VIEW, 0).is(pageModel) + page.getAttribute(GrailsApplicationAttributes.TEMPLATE_MODEL, 0).is(pageTemplateModel) + pageRequest.getAttribute(UrlMappingsHandlerMapping.MATCHED_REQUEST).is(pageMatch) + pageRequest.getAttribute(GrailsApplicationAttributes.GRAILS_CONTROLLER_CLASS).is(pageControllerClass) + pageRequest.getAttribute(UrlMappingsHandlerMapping.INCLUDED_MAPPING_INFO) == null + + where: + outcome | fails + 'that returns' | false + 'whose included action throws' | true + } } diff --git a/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMappingSpec.groovy b/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMappingSpec.groovy index e7a7c8848d6..26a2cdea213 100644 --- a/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMappingSpec.groovy +++ b/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMappingSpec.groovy @@ -440,6 +440,30 @@ class UrlMappingsHandlerMappingSpec extends AbstractUrlMappingsSpec { 'its mapping with the parameters of the page\'s URL' | [slug: 'example'] } + void "an include an error handler makes answers with the action it names rather than with the error handler"() { + given: + def grailsApplication = new DefaultGrailsApplication(FooController) + grailsApplication.initialise() + def holder = new GrailsControllerUrlMappings(grailsApplication, getUrlMappingsHolder { + "/foo/bar"(controller: 'foo', action: 'bar') + "500"(controller: 'foo', action: 'fooBar') + }) + def handler = new UrlMappingsHandlerMapping(holder) + def request = GrailsWebMockUtil.bindMockWebRequest().request + + when: 'the error handler includes another action while the request still carries the error' + request.setAttribute(WebUtils.ERROR_STATUS_CODE_ATTRIBUTE, 500) + request.setAttribute(WebUtils.INCLUDE_REQUEST_URI_ATTRIBUTE, '/foo/bar') + request.requestURI = '/foo/bar' + request.setAttribute(UrlMappingsHandlerMapping.INCLUDED_MAPPING_INFO, new ForwardUrlMappingInfo(controller: 'foo', action: 'bar')) + def info = handler.getHandler(request).handler + + then: 'the include runs that action, not the error handler, which would include it again' + info instanceof GrailsControllerUrlMappingInfo + ((GrailsControllerUrlMappingInfo) info).controllerClass.clazz == FooController + ((GrailsControllerUrlMappingInfo) info).info.actionName == 'bar' + } + void "an include made for #made answers with the action of its controller when no error is being handled"() { given: def grailsApplication = new DefaultGrailsApplication(FooController) From d8f15f387069feaad6eceff6cc4434782e4c719b Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Tue, 10 Nov 2026 07:17:41 -0800 Subject: [PATCH 78/78] Give an included action its own id, and the page its namespace and attributes back An include made by UrlMappingUtils.includeRequestForUrlMappingInfo ran its action with the page's id: the include's dispatch creates the request state the action reads, and the handler mapping answered the include without configuring it with the mapping. It now resets and configures it, as a match by URI does, so the action sees the id of the mapping it was included for. After the include returned, the page had lost its controller namespace, so a page in a namespace that included an action of a controller with none went on without it, and its links named the wrong controller. The page now gets its namespace back with its controller and action, which also applies to g:include, through the code they share. Each request attribute the include's model set is also restored to the page's value, or removed when the page had none. --- .../issue11102/FailingController.groovy | 9 +++-- .../controllers/issue11102/UrlMappings.groovy | 1 + .../issue11102/admin/PagesController.groovy | 34 +++++++++++++++++++ .../FailedActionObservationSpec.groovy | 14 ++++++-- .../issue12688/FailingController.groovy | 9 +++-- .../controllers/issue12688/UrlMappings.groovy | 1 + .../issue12688/admin/PagesController.groovy | 34 +++++++++++++++++++ .../JettyFailedActionObservationSpec.groovy | 14 ++++++-- .../undertowapp/FailingController.groovy | 9 +++-- .../undertowapp/UrlMappings.groovy | 1 + .../undertowapp/admin/PagesController.groovy | 34 +++++++++++++++++++ ...UndertowFailedActionObservationSpec.groovy | 14 ++++++-- .../grails/web/mapping/UrlMappingUtils.java | 21 ++++++++---- .../mvc/UrlMappingsHandlerMapping.groovy | 6 ++++ .../web/mapping/UrlMappingUtilsSpec.groovy | 19 ++++++++--- .../mvc/UrlMappingsHandlerMappingSpec.groovy | 22 ++++++++++++ 16 files changed, 216 insertions(+), 26 deletions(-) create mode 100644 grails-test-examples/issue-11102/grails-app/controllers/issue11102/admin/PagesController.groovy create mode 100644 grails-test-examples/jetty/grails-app/controllers/issue12688/admin/PagesController.groovy create mode 100644 grails-test-examples/undertow/grails-app/controllers/undertowapp/admin/PagesController.groovy diff --git a/grails-test-examples/issue-11102/grails-app/controllers/issue11102/FailingController.groovy b/grails-test-examples/issue-11102/grails-app/controllers/issue11102/FailingController.groovy index 8465f65b7d0..16bdfbad9ba 100644 --- a/grails-test-examples/issue-11102/grails-app/controllers/issue11102/FailingController.groovy +++ b/grails-test-examples/issue-11102/grails-app/controllers/issue11102/FailingController.groovy @@ -123,9 +123,14 @@ class FailingController { } def includesThroughUrlMappingUtils() { + request.setAttribute('greeting', 'outer') response.writer.write('before ') - UrlMappingUtils.includeRequestForUrlMappingInfo(request, response, new ForwardUrlMappingInfo(controller: 'failing', action: 'included', params: [marker: 'included']), [:], false) - render " after, as ${controllerName}/${actionName} with ${params.marker}" + UrlMappingUtils.includeRequestForUrlMappingInfo(request, response, new ForwardUrlMappingInfo(controller: 'failing', action: 'includedDetails', id: '9', params: [marker: 'included']), [greeting: 'inner'], false) + render " after, as ${controllerName}/${actionName} with ${params.marker}, id ${params.id} and ${request.getAttribute('greeting')}" + } + + def includedDetails() { + render "included with id ${params.id} and ${request.getAttribute('greeting')}" } def included() { diff --git a/grails-test-examples/issue-11102/grails-app/controllers/issue11102/UrlMappings.groovy b/grails-test-examples/issue-11102/grails-app/controllers/issue11102/UrlMappings.groovy index 187e866e7bf..0be9fbeb723 100644 --- a/grails-test-examples/issue-11102/grails-app/controllers/issue11102/UrlMappings.groovy +++ b/grails-test-examples/issue-11102/grails-app/controllers/issue11102/UrlMappings.groovy @@ -32,6 +32,7 @@ class UrlMappings { } "/failing/$action"(controller: 'failing') + "/admin/pages/$action"(controller: 'pages', namespace: 'admin') "/page/$slug"(controller: 'failing', action: 'includesAnswerOfController') "/"(view:"/index") diff --git a/grails-test-examples/issue-11102/grails-app/controllers/issue11102/admin/PagesController.groovy b/grails-test-examples/issue-11102/grails-app/controllers/issue11102/admin/PagesController.groovy new file mode 100644 index 00000000000..138aa6d191d --- /dev/null +++ b/grails-test-examples/issue-11102/grails-app/controllers/issue11102/admin/PagesController.groovy @@ -0,0 +1,34 @@ +/* + * 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 issue11102.admin + +import org.grails.web.mapping.ForwardUrlMappingInfo +import org.grails.web.mapping.UrlMappingUtils + +class PagesController { + + static namespace = 'admin' + + def includesAnAction() { + response.writer.write('before ') + UrlMappingUtils.includeRequestForUrlMappingInfo(request, response, new ForwardUrlMappingInfo(controller: 'failing', action: 'included'), [:], false) + render " after, in the ${controllerNamespace} namespace" + } +} diff --git a/grails-test-examples/issue-11102/src/integration-test/groovy/issue11102/FailedActionObservationSpec.groovy b/grails-test-examples/issue-11102/src/integration-test/groovy/issue11102/FailedActionObservationSpec.groovy index f48e3294257..594544131b3 100644 --- a/grails-test-examples/issue-11102/src/integration-test/groovy/issue11102/FailedActionObservationSpec.groovy +++ b/grails-test-examples/issue-11102/src/integration-test/groovy/issue11102/FailedActionObservationSpec.groovy @@ -125,10 +125,10 @@ class FailedActionObservationSpec extends Specification implements HttpClientSup def path = '/failing/includesThroughUrlMappingUtils' when: - def response = http([(REQUEST_HEADER): path], "${path}?marker=page") + def response = http([(REQUEST_HEADER): path], "${path}?marker=page&id=7") - then: 'the included action answered inside the page, and after it the page had its own action and parameters' - response.assertContains(200, 'before included after, as failing/includesThroughUrlMappingUtils with page') + then: 'the included action saw its own id and model, and after it the page had its own action, parameters and request attributes' + response.assertContains(200, 'before included with id 9 and inner after, as failing/includesThroughUrlMappingUtils with page, id 7 and outer') and: 'the observation of the page stopped on its own route, with no error' new PollingConditions(timeout: 30).eventually { @@ -159,6 +159,14 @@ class FailedActionObservationSpec extends Specification implements HttpClientSup reported = route == 'none' ? 'no route' : 'its own route' } + void 'a namespaced controller that includes an action of another controller keeps its namespace'() { + when: + def response = http('/admin/pages/includesAnAction') + + then: + response.assertContains(200, 'before included after, in the admin namespace') + } + void 'an error controller that includes an action runs that action inside its page, and the failure is reported once'() { given: def path = '/failing/answeredByIncludingController' diff --git a/grails-test-examples/jetty/grails-app/controllers/issue12688/FailingController.groovy b/grails-test-examples/jetty/grails-app/controllers/issue12688/FailingController.groovy index 170304bd795..c070bdd99a2 100644 --- a/grails-test-examples/jetty/grails-app/controllers/issue12688/FailingController.groovy +++ b/grails-test-examples/jetty/grails-app/controllers/issue12688/FailingController.groovy @@ -106,9 +106,14 @@ class FailingController { } def includesThroughUrlMappingUtils() { + request.setAttribute('greeting', 'outer') response.writer.write('before ') - UrlMappingUtils.includeRequestForUrlMappingInfo(request, response, new ForwardUrlMappingInfo(controller: 'failing', action: 'included', params: [marker: 'included']), [:], false) - render " after, as ${controllerName}/${actionName} with ${params.marker}" + UrlMappingUtils.includeRequestForUrlMappingInfo(request, response, new ForwardUrlMappingInfo(controller: 'failing', action: 'includedDetails', id: '9', params: [marker: 'included']), [greeting: 'inner'], false) + render " after, as ${controllerName}/${actionName} with ${params.marker}, id ${params.id} and ${request.getAttribute('greeting')}" + } + + def includedDetails() { + render "included with id ${params.id} and ${request.getAttribute('greeting')}" } def included() { diff --git a/grails-test-examples/jetty/grails-app/controllers/issue12688/UrlMappings.groovy b/grails-test-examples/jetty/grails-app/controllers/issue12688/UrlMappings.groovy index 228ab844a78..0005d187989 100644 --- a/grails-test-examples/jetty/grails-app/controllers/issue12688/UrlMappings.groovy +++ b/grails-test-examples/jetty/grails-app/controllers/issue12688/UrlMappings.groovy @@ -28,6 +28,7 @@ class UrlMappings { "/"(view: "/index") "/failing/$action"(controller: 'failing') + "/admin/pages/$action"(controller: 'pages', namespace: 'admin') "/page/$slug"(controller: 'failing', action: 'includesAnswerOfController') "500"(view: '/error') diff --git a/grails-test-examples/jetty/grails-app/controllers/issue12688/admin/PagesController.groovy b/grails-test-examples/jetty/grails-app/controllers/issue12688/admin/PagesController.groovy new file mode 100644 index 00000000000..1de0ca99a29 --- /dev/null +++ b/grails-test-examples/jetty/grails-app/controllers/issue12688/admin/PagesController.groovy @@ -0,0 +1,34 @@ +/* + * 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 issue12688.admin + +import org.grails.web.mapping.ForwardUrlMappingInfo +import org.grails.web.mapping.UrlMappingUtils + +class PagesController { + + static namespace = 'admin' + + def includesAnAction() { + response.writer.write('before ') + UrlMappingUtils.includeRequestForUrlMappingInfo(request, response, new ForwardUrlMappingInfo(controller: 'failing', action: 'included'), [:], false) + render " after, in the ${controllerNamespace} namespace" + } +} diff --git a/grails-test-examples/jetty/src/integration-test/groovy/issue12688/JettyFailedActionObservationSpec.groovy b/grails-test-examples/jetty/src/integration-test/groovy/issue12688/JettyFailedActionObservationSpec.groovy index 2fa8e3e743e..c1c73d32415 100644 --- a/grails-test-examples/jetty/src/integration-test/groovy/issue12688/JettyFailedActionObservationSpec.groovy +++ b/grails-test-examples/jetty/src/integration-test/groovy/issue12688/JettyFailedActionObservationSpec.groovy @@ -123,10 +123,10 @@ class JettyFailedActionObservationSpec extends Specification implements HttpClie def path = '/failing/includesThroughUrlMappingUtils' when: - def response = http([(REQUEST_HEADER): path], "${path}?marker=page") + def response = http([(REQUEST_HEADER): path], "${path}?marker=page&id=7") - then: 'the included action answered inside the page, and after it the page had its own action and parameters' - response.assertContains(200, 'before included after, as failing/includesThroughUrlMappingUtils with page') + then: 'the included action saw its own id and model, and after it the page had its own action, parameters and request attributes' + response.assertContains(200, 'before included with id 9 and inner after, as failing/includesThroughUrlMappingUtils with page, id 7 and outer') and: 'the observation of the page stopped on its own route, with no error' new PollingConditions(timeout: 30).eventually { @@ -135,6 +135,14 @@ class JettyFailedActionObservationSpec extends Specification implements HttpClie !NOTIFIED.containsKey(path) } + void 'a namespaced controller that includes an action of another controller keeps its namespace'() { + when: + def response = http('/admin/pages/includesAnAction') + + then: + response.assertContains(200, 'before included after, in the admin namespace') + } + void 'an error controller that includes an action runs that action inside its page, and the failure is reported once'() { given: def path = '/failing/answeredByIncludingController' diff --git a/grails-test-examples/undertow/grails-app/controllers/undertowapp/FailingController.groovy b/grails-test-examples/undertow/grails-app/controllers/undertowapp/FailingController.groovy index 6726d134c4c..2f323bda308 100644 --- a/grails-test-examples/undertow/grails-app/controllers/undertowapp/FailingController.groovy +++ b/grails-test-examples/undertow/grails-app/controllers/undertowapp/FailingController.groovy @@ -106,9 +106,14 @@ class FailingController { } def includesThroughUrlMappingUtils() { + request.setAttribute('greeting', 'outer') response.writer.write('before ') - UrlMappingUtils.includeRequestForUrlMappingInfo(request, response, new ForwardUrlMappingInfo(controller: 'failing', action: 'included', params: [marker: 'included']), [:], false) - render " after, as ${controllerName}/${actionName} with ${params.marker}" + UrlMappingUtils.includeRequestForUrlMappingInfo(request, response, new ForwardUrlMappingInfo(controller: 'failing', action: 'includedDetails', id: '9', params: [marker: 'included']), [greeting: 'inner'], false) + render " after, as ${controllerName}/${actionName} with ${params.marker}, id ${params.id} and ${request.getAttribute('greeting')}" + } + + def includedDetails() { + render "included with id ${params.id} and ${request.getAttribute('greeting')}" } def included() { diff --git a/grails-test-examples/undertow/grails-app/controllers/undertowapp/UrlMappings.groovy b/grails-test-examples/undertow/grails-app/controllers/undertowapp/UrlMappings.groovy index d463a9677a3..b504b19be8d 100644 --- a/grails-test-examples/undertow/grails-app/controllers/undertowapp/UrlMappings.groovy +++ b/grails-test-examples/undertow/grails-app/controllers/undertowapp/UrlMappings.groovy @@ -29,6 +29,7 @@ class UrlMappings { "/"(view: "/index") "/failing/$action"(controller: 'failing') + "/admin/pages/$action"(controller: 'pages', namespace: 'admin') "/page/$slug"(controller: 'failing', action: 'includesAnswerOfController') "500"(view: '/error') diff --git a/grails-test-examples/undertow/grails-app/controllers/undertowapp/admin/PagesController.groovy b/grails-test-examples/undertow/grails-app/controllers/undertowapp/admin/PagesController.groovy new file mode 100644 index 00000000000..b62f4976faf --- /dev/null +++ b/grails-test-examples/undertow/grails-app/controllers/undertowapp/admin/PagesController.groovy @@ -0,0 +1,34 @@ +/* + * 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 undertowapp.admin + +import org.grails.web.mapping.ForwardUrlMappingInfo +import org.grails.web.mapping.UrlMappingUtils + +class PagesController { + + static namespace = 'admin' + + def includesAnAction() { + response.writer.write('before ') + UrlMappingUtils.includeRequestForUrlMappingInfo(request, response, new ForwardUrlMappingInfo(controller: 'failing', action: 'included'), [:], false) + render " after, in the ${controllerNamespace} namespace" + } +} diff --git a/grails-test-examples/undertow/src/integration-test/groovy/undertowapp/UndertowFailedActionObservationSpec.groovy b/grails-test-examples/undertow/src/integration-test/groovy/undertowapp/UndertowFailedActionObservationSpec.groovy index ef8ee0567db..cf3bbaf5489 100644 --- a/grails-test-examples/undertow/src/integration-test/groovy/undertowapp/UndertowFailedActionObservationSpec.groovy +++ b/grails-test-examples/undertow/src/integration-test/groovy/undertowapp/UndertowFailedActionObservationSpec.groovy @@ -125,10 +125,10 @@ class UndertowFailedActionObservationSpec extends Specification implements HttpC def path = '/failing/includesThroughUrlMappingUtils' when: - def response = http([(REQUEST_HEADER): path], "${path}?marker=page") + def response = http([(REQUEST_HEADER): path], "${path}?marker=page&id=7") - then: 'the included action answered inside the page, and after it the page had its own action and parameters' - response.assertContains(200, 'before included after, as failing/includesThroughUrlMappingUtils with page') + then: 'the included action saw its own id and model, and after it the page had its own action, parameters and request attributes' + response.assertContains(200, 'before included with id 9 and inner after, as failing/includesThroughUrlMappingUtils with page, id 7 and outer') and: 'the observation of the page stopped on its own route, with no error' new PollingConditions(timeout: 30).eventually { @@ -137,6 +137,14 @@ class UndertowFailedActionObservationSpec extends Specification implements HttpC !NOTIFIED.containsKey(path) } + void 'a namespaced controller that includes an action of another controller keeps its namespace'() { + when: + def response = http('/admin/pages/includesAnAction') + + then: + response.assertContains(200, 'before included after, in the admin namespace') + } + void 'an error controller that includes an action runs that action inside its page, and the failure is reported once'() { given: def path = '/failing/answeredByIncludingController' diff --git a/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/UrlMappingUtils.java b/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/UrlMappingUtils.java index b7fcefffb9d..5b9b22ad260 100644 --- a/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/UrlMappingUtils.java +++ b/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/UrlMappingUtils.java @@ -274,8 +274,9 @@ public static String forwardRequestForUrlMappingInfo(HttpServletRequest request, * {@link #forwardRequestForUrlMappingInfo(HttpServletRequest, HttpServletResponse, UrlMappingInfo, Map, boolean)} * would forward to it. A request that is itself an include cannot forward: a forward ends the response it is given, * which inside an include belongs to the page that included it. The include answers with the action of the given - * mapping, whatever its URI would match and whatever error is being handled. Once it returns, the page has its own - * controller, action, id, parameters and model again, and renders on as it was. + * mapping, whatever its URI would match and whatever error is being handled, and that action sees the id of + * the mapping. Once it returns, the page has its own controller namespace, controller, action, id, + * parameters, model and request attributes again, including those the given model set, and renders on as it was. * * @param request The request * @param response The response @@ -291,9 +292,12 @@ public static String forwardRequestForUrlMappingInfo(HttpServletRequest request, public static String includeRequestForUrlMappingInfo(HttpServletRequest request, HttpServletResponse response, UrlMappingInfo info, Map model, boolean includeParams) throws ServletException, IOException { final IncludingPage page = new IncludingPage(GrailsWebRequest.lookup(request)); - final Map dispatchAttributes = new HashMap<>(); + final Map pageAttributes = new HashMap<>(); for (String name : INCLUDE_DISPATCH_ATTRIBUTES) { - dispatchAttributes.put(name, request.getAttribute(name)); + pageAttributes.put(name, request.getAttribute(name)); + } + for (String name : model.keySet()) { + pageAttributes.put(name, request.getAttribute(name)); } request.setAttribute(UrlMappingsHandlerMapping.INCLUDED_MAPPING_INFO, info); try { @@ -301,7 +305,7 @@ public static String includeRequestForUrlMappingInfo(HttpServletRequest request, } finally { request.removeAttribute(UrlMappingsHandlerMapping.INCLUDED_MAPPING_INFO); - for (Map.Entry attribute : dispatchAttributes.entrySet()) { + for (Map.Entry attribute : pageAttributes.entrySet()) { if (attribute.getValue() != null) { request.setAttribute(attribute.getKey(), attribute.getValue()); } @@ -407,14 +411,15 @@ private static IncludedContent includeForUrlMappingInfoHelper(String includeUrl, } /** - * What an include changes on the request of the page that makes it: the controller, action, id and parameters the - * included mapping configures, and the model and page attributes the include must not see. Created before the + * What an include changes on the request of the page that makes it: the controller namespace, controller, action, id + * and parameters the included mapping configures, and the model and page attributes the include must not see. Created before the * include, which takes the page attributes away, and restored once it returns, so the page renders on as it was. */ @SuppressWarnings({ "unchecked", "rawtypes" }) private static final class IncludingPage { private final GrailsWebRequest webRequest; + private final String namespace; private final String controller; private final String action; private final String id; @@ -437,6 +442,7 @@ private static final class IncludingPage { if (renderingView != null) { webRequest.removeAttribute(WebUtils.RENDERING_VIEW, 0); } + namespace = webRequest.getControllerNamespace(); controller = webRequest.getControllerName(); action = webRequest.getActionName(); id = webRequest.getId(); @@ -461,6 +467,7 @@ void restore() { webRequest.getParameterMap().clear(); webRequest.getParameterMap().putAll(params); webRequest.setId(id); + webRequest.setControllerNamespace(namespace); webRequest.setControllerName(controller); webRequest.setActionName(action); if (modelAndView != null) { diff --git a/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMapping.groovy b/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMapping.groovy index b09169dfb65..cf62c7c141e 100644 --- a/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMapping.groovy +++ b/grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMapping.groovy @@ -177,6 +177,12 @@ class UrlMappingsHandlerMapping extends AbstractHandlerMapping { def errorStatus = request.getAttribute(WebUtils.ERROR_STATUS_CODE_ATTRIBUTE) if (includedInfo instanceof UrlMappingInfo) { UrlMappingInfo info = withController((UrlMappingInfo) includedInfo) + // as for a match by URI, the action sees the id of its mapping rather than the page's + GrailsWebRequest includeRequest = GrailsWebRequest.lookup(request) + if (includeRequest != null) { + includeRequest.resetParams() + info.configure(includeRequest) + } if (info instanceof GrailsControllerUrlMappingInfo) { request.setAttribute(MATCHED_REQUEST, info) request.setAttribute(GrailsApplicationAttributes.GRAILS_CONTROLLER_CLASS, ((GrailsControllerUrlMappingInfo) info).controllerClass) diff --git a/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/UrlMappingUtilsSpec.groovy b/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/UrlMappingUtilsSpec.groovy index 28ffa27e48a..e4ad7995bad 100644 --- a/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/UrlMappingUtilsSpec.groovy +++ b/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/UrlMappingUtilsSpec.groovy @@ -228,8 +228,8 @@ class UrlMappingUtilsSpec extends Specification { capturingWebRequest.getAttribute(GrailsApplicationAttributes.TEMPLATE_MODEL, 0) == null } - void "includeRequestForUrlMappingInfo #outcome gives the page back its controller, action, id, parameters and model"() { - given: 'a page with its own controller, action, id, parameter, model and matched mapping' + void "includeRequestForUrlMappingInfo #outcome gives the page back its namespace, controller, action, id, parameters, model and request attributes"() { + given: 'a page with its own namespace, controller, action, id, parameter, model, request attribute and matched mapping' final ModelAndView pageModel = new ModelAndView('/outer/page', [greeting: 'hello']) final Map pageTemplateModel = [templateKey: 'templateValue'] final Object pageMatch = new ForwardUrlMappingInfo(controllerName: 'outer', actionName: 'page') @@ -250,6 +250,10 @@ class UrlMappingUtilsSpec extends Specification { duringInclude.action = included.actionName duringInclude.mapping = req.getAttribute(UrlMappingsHandlerMapping.INCLUDED_MAPPING_INFO) duringInclude.model = req.getAttribute(GrailsApplicationAttributes.MODEL_AND_VIEW) + duringInclude.greeting = req.getAttribute('greeting') + duringInclude.only = req.getAttribute('only') + // as the included action does, with a controller of no namespace + included.controllerNamespace = null // as the handler mapping does for the included action req.setAttribute(UrlMappingsHandlerMapping.MATCHED_REQUEST, fragment) req.setAttribute(GrailsApplicationAttributes.GRAILS_CONTROLLER_CLASS, 'inner controller') @@ -262,6 +266,7 @@ class UrlMappingUtilsSpec extends Specification { } GrailsWebRequest page = new GrailsWebRequest(pageRequest, response, attr) pageRequest.setAttribute(GrailsApplicationAttributes.WEB_REQUEST, page) + page.controllerNamespace = 'admin' page.controllerName = 'outer' page.actionName = 'page' page.id = '7' @@ -270,11 +275,12 @@ class UrlMappingUtilsSpec extends Specification { page.setAttribute(GrailsApplicationAttributes.TEMPLATE_MODEL, pageTemplateModel, 0) pageRequest.setAttribute(UrlMappingsHandlerMapping.MATCHED_REQUEST, pageMatch) pageRequest.setAttribute(GrailsApplicationAttributes.GRAILS_CONTROLLER_CLASS, pageControllerClass) + pageRequest.setAttribute('greeting', 'outer') - when: 'the page includes another action' + when: 'the page includes another action, with a model of its own' Throwable failure = null try { - UrlMappingUtils.includeRequestForUrlMappingInfo(pageRequest, response, fragment, [:], false) + UrlMappingUtils.includeRequestForUrlMappingInfo(pageRequest, response, fragment, [greeting: 'inner', only: 'fragment'], false) } catch (IllegalStateException e) { failure = e @@ -286,9 +292,12 @@ class UrlMappingUtilsSpec extends Specification { duringInclude.action == 'fragment' duringInclude.mapping.is(fragment) duringInclude.model == null + duringInclude.greeting == 'inner' + duringInclude.only == 'fragment' (failure != null) == fails and: 'the page is as it was' + page.controllerNamespace == 'admin' page.controllerName == 'outer' page.actionName == 'page' page.id == '7' @@ -298,6 +307,8 @@ class UrlMappingUtilsSpec extends Specification { pageRequest.getAttribute(UrlMappingsHandlerMapping.MATCHED_REQUEST).is(pageMatch) pageRequest.getAttribute(GrailsApplicationAttributes.GRAILS_CONTROLLER_CLASS).is(pageControllerClass) pageRequest.getAttribute(UrlMappingsHandlerMapping.INCLUDED_MAPPING_INFO) == null + pageRequest.getAttribute('greeting') == 'outer' + pageRequest.getAttribute('only') == null where: outcome | fails diff --git a/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMappingSpec.groovy b/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMappingSpec.groovy index 26a2cdea213..221356893ad 100644 --- a/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMappingSpec.groovy +++ b/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMappingSpec.groovy @@ -440,6 +440,28 @@ class UrlMappingsHandlerMappingSpec extends AbstractUrlMappingsSpec { 'its mapping with the parameters of the page\'s URL' | [slug: 'example'] } + void "an action an include runs sees the id of its mapping rather than the id of the page"() { + given: + def grailsApplication = new DefaultGrailsApplication(FooController) + grailsApplication.initialise() + def holder = new GrailsControllerUrlMappings(grailsApplication, getUrlMappingsHolder { + "/foo/bar"(controller: 'foo', action: 'bar') + }) + def handler = new UrlMappingsHandlerMapping(holder) + def webRequest = GrailsWebMockUtil.bindMockWebRequest() + def request = webRequest.currentRequest + request.addParameter('id', '7') + + when: 'a page whose request has id 7 includes the action with id 9' + request.setAttribute(WebUtils.INCLUDE_REQUEST_URI_ATTRIBUTE, '/foo/bar') + request.requestURI = '/foo/bar' + request.setAttribute(UrlMappingsHandlerMapping.INCLUDED_MAPPING_INFO, new ForwardUrlMappingInfo(controller: 'foo', action: 'bar', id: '9')) + handler.getHandler(request) + + then: + webRequest.params.id == '9' + } + void "an include an error handler makes answers with the action it names rather than with the error handler"() { given: def grailsApplication = new DefaultGrailsApplication(FooController)