diff --git a/.agents/skills/gradle-developer/SKILL.md b/.agents/skills/gradle-developer/SKILL.md
index 26b27070dbe..e77854ffe73 100644
--- a/.agents/skills/gradle-developer/SKILL.md
+++ b/.agents/skills/gradle-developer/SKILL.md
@@ -367,6 +367,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 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/AGENTS.md b/AGENTS.md
index f7692dabab3..b6f8579ae56 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -122,8 +122,8 @@ These human-review concerns are intentionally not mechanized; `validateRepositor
|-----------|---------|
| JDK | 21+ (baseline 21) |
| Groovy | 6.0.x |
-| Spring Boot | 4.1.x |
-| Spring Framework | 7.0.x |
+| Spring Boot | 4.2.x |
+| Spring Framework | 7.1.x |
| Spock | 2.5-groovy-6.0 |
| Gradle | 9.9.x |
| Jakarta EE | 10 |
@@ -152,7 +152,7 @@ All managed dependency versions live in `dependencies.gradle` (the single source
- **Only libraries the Grails project also works on may use a snapshot version.** Between releases, `dependencies.gradle` often points at a `-SNAPSHOT` or release-candidate version of one of our own libraries, such as the Asset Pipeline (`cloud.wondrify`), SiteMesh 3 (`org.sitemesh`), or the Grails Publish plugin (`org.apache.grails.gradle:grails-publish`). These are switched to their published version before a Grails release (see `RELEASE.md`). Do not suggest replacing them with a released version, and do not flag them in reviews. Never use a snapshot of any other library, such as Jackson or Spring. The snapshot repositories in `GrailsRepoSettingsPlugin` only serve the `org.apache.grails*`, `org.apache.groovy*`, `cloud.wondrify*`, and `org.sitemesh*` groups, so a snapshot of any other library will not resolve (unless `GRAILS_INCLUDE_MAVEN_LOCAL` is set for a local build). Do not widen those content filters to get one.
- **No dynamic versions in any BOM-bearing configuration.** The same task fails when any dependency of a BOM-bearing configuration is requested with a version range, a `+` prefix, or a `latest.*` selector, even when a BOM constraint overrides it (Gradle's own `failOnDynamicVersions()` misses that case). A dynamic version makes every resolution list the module's versions in the repository once the listing cache expires, which is every CI build, so the build depends on the repository answering even when every artifact is cached. Fix it where the range enters the graph: a build script of this repository pins the version or uses the BOM-managed coordinate; for a published module, exclude the module from that dependency and declare the BOM-managed coordinate next to it (see the `ehcache` declaration in `grails-spring-security`); a dependency *constraint* with a range (marked `(constraint)`, as Hibernate publishes for `log4j-core`) is not removed by an exclusion and needs a component metadata rule. `allowedDynamicVersions` (per-project ext, `group:name` keys) is the last resort, with a commented reason.
- **`groovy-callsite` is never a framework dependency.** Grails 9 compiles with invokedynamic, the Groovy 6 compiler's default, and does not ship `org.apache.groovy:groovy-callsite`; an application that opts out with `grails { indy = false }` declares the module itself, at the version the BOM manages. Do not add it to `grails-common` or any other module's `api` or `implementation`: every application would ship it. CI's `-PgrailsIndy=false` lanes get it from `CompilePlugin`, on every source set. A module whose tests load a library compiled with classic call sites, such as `testcontainers-spock`, declares it as `testRuntimeOnly` next to that library.
-- **Prefer inheriting from the Spring Boot BOM.** Do not re-pin a coordinate that `spring-boot-dependencies` (4.1.x) already manages unless you are intentionally overriding it to a newer version (e.g. a security fix); note the reason inline.
+- **Prefer inheriting from the Spring Boot BOM.** Do not re-pin a coordinate that `spring-boot-dependencies` already manages unless you are intentionally overriding it to a newer version (e.g. a security fix); note the reason inline.
- **An override of a Spring Boot managed version must use Spring Boot's property name, and must change the version.** `validateBomProperties` (plugin `org.apache.grails.buildsrc.bom-property-validator`, run in its own CI job) checks the POM each Grails BOM publishes against `spring-boot-dependencies` (`parentBoms` in `dependencies.gradle`). It fails when a pin is declared under a different property than the one Boot controls it with - for a module Boot manages through an imported BOM, that is the import's property (`jackson-bom.version`, not `jackson3.version`) - and when a pin repeats Boot's version. Rename the version key (and the dependency keys that must prefix it) or drop the pin.
- **Every version key must be used.** The same task (opt out with `-PskipBomPropertyValidation`, not `skipDependencyValidation`) fails when a version property a BOM owns (`bomVersionProperties` in each BOM's build script) is used by no entry of its published POM - a key no dependency references, or one whose dependency keys do not reduce to it. Delete the key or add the dependency that should use it. The few deliberate exceptions to these rules live, each with its reason, in `bomUnusedVersionExemptions` / `bomPropertyNameExemptions` / `bomRedundantVersionExemptions` in `dependencies.gradle`.
- **No two dependencies may provide the same class.** The `buildHealth` task (the `com.autonomousapps.build-health` settings plugin, configured in `gradle/dependency-analysis.settings.gradle`, which applies it to a build only when one of its tasks is requested by full name, so a plain build never pays for it) fails when two dependencies on a classpath provide the same fully qualified class name that the module's own code references, because compile and runtime behavior then depend on classpath order. The Build Health workflow runs it on every push and pull request, alongside the code style checks. Resolve a report by removing or excluding the redundant dependency; its other categories (unused or transitive dependencies, wrong configurations) are advice only.
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..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
@@ -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,47 @@ 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
+ }
+
+ /**
+ * 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/main/groovy/org/apache/grails/buildsrc/SbomPlugin.groovy b/build-logic/plugins/src/main/groovy/org/apache/grails/buildsrc/SbomPlugin.groovy
index a1eafe93c28..e064c884773 100644
--- a/build-logic/plugins/src/main/groovy/org/apache/grails/buildsrc/SbomPlugin.groovy
+++ b/build-logic/plugins/src/main/groovy/org/apache/grails/buildsrc/SbomPlugin.groovy
@@ -136,7 +136,7 @@ class SbomPlugin implements Plugin {
'pkg:maven/org.jline/jline-terminal-jni@3.30.16?type=jar' : 'BSD-3-Clause',
'pkg:maven/org.jruby/jzlib@1.1.5?type=jar' : 'BSD-3-Clause', // https://web.archive.org/web/20240822213507/http://www.jcraft.com/jzlib/LICENSE.txt shows it's a 3 clause
'pkg:maven/org.liquibase.ext/liquibase-hibernate5@4.27.0?type=jar': 'Apache-2.0', // maps incorrectly because of https://github.com/liquibase/liquibase/issues/2445 & the base pom does not define a license
- 'pkg:maven/org.json/json@20251224?type=jar' : 'Public-Domain', // required due to jedis, https://issues.apache.org/jira/browse/LEGAL-666 approves this usage
+ 'pkg:maven/org.json/json@20260719?type=jar' : 'Public-Domain', // required due to jedis, https://issues.apache.org/jira/browse/LEGAL-666 approves this usage
// Bouncy Castle Licence is the MIT license (https://www.bouncycastle.org/licence.html); pulled in transitively by the CAS client
'pkg:maven/org.bouncycastle/bcpkix-jdk18on@1.84?type=jar' : 'MIT',
'pkg:maven/org.bouncycastle/bcprov-jdk18on@1.84?type=jar' : 'MIT',
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..ba12973d0a1
--- /dev/null
+++ b/build-logic/plugins/src/test/groovy/org/apache/grails/buildsrc/PomVersionsSpec.groovy
@@ -0,0 +1,135 @@
+/*
+ * 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
+ * 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 {
+
+ @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}
+ otherlib-other2.0
+ testlib-literal5.0tests
+
+ testfamily-bom${family-bom.version}
+ pomimport
+
+
+
+
+
+
+ testtest-maven-plugin1.0
+
+
+
+
+'''
+ 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.'
+ }
+
+ 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/build-logic/plugins/src/test/groovy/org/apache/grails/buildsrc/SbomPluginSpec.groovy b/build-logic/plugins/src/test/groovy/org/apache/grails/buildsrc/SbomPluginSpec.groovy
index fd196ba84c1..0e3b047f441 100644
--- a/build-logic/plugins/src/test/groovy/org/apache/grails/buildsrc/SbomPluginSpec.groovy
+++ b/build-logic/plugins/src/test/groovy/org/apache/grails/buildsrc/SbomPluginSpec.groovy
@@ -114,6 +114,15 @@ class SbomPluginSpec extends Specification {
'pkg:maven/org.jline/jansi@4.3.1?type=jar', bsd4Choice()).id == 'BSD-3-Clause'
}
+ void "org.json resolved through Jedis uses the public domain license approved in LEGAL-666"() {
+ given:
+ List publicDomainChoice = [[license: [name: 'Public Domain', url: 'https://github.com/stleary/JSON-java/blob/master/LICENSE']]]
+
+ expect:
+ SbomPlugin.pickLicense(LOGGER, 'grails-redis', 'grails-redis',
+ 'pkg:maven/org.json/json@20260719?type=jar', publicDomainChoice).name == 'Public Domain'
+ }
+
void "JLine 4 license correction is limited to JLine 4 Maven jars"() {
when:
SbomPlugin.pickLicense(LOGGER, 'grails-console', 'grails-console', bomRef, bsd4Choice())
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 81dfc115a43..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 ' +
@@ -96,10 +92,11 @@ class VulnerabilityScanPlugin implements Plugin {
'5.7.x through 6.5.10 as affected. The 7.x line already carries the fix for the preceding ' +
'CVE-2026-22747. Remove once Sonatype narrows its affected range'),
new VulnerabilityExclusion('CVE-2026-47842', 'org.springframework.security:spring-security-crypto',
- 'Sonatype flags 7.1.1, which https://spring.io/security/cve-2026-47842 lists as fixed. ' +
- 'Spring Boot 4.1.2 manages 7.1.2, past that fixed release. The exclusion stays until ' +
- 'Sonatype narrows its affected range past the version Boot manages. ' +
- 'Remove once Sonatype corrects its affected range; reassess on any Spring Security upgrade'),
+ '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-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'),
].asImmutable()
@Override
diff --git a/dependencies.gradle b/dependencies.gradle
index 074061841a6..452d0e4844e 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',
@@ -39,7 +39,7 @@ ext {
'jna.version' : '5.19.1',
'maven-model.version' : '3.9.16',
'objenesis.version' : '3.6',
- 'spring-boot.version' : '4.1.2',
+ '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
@@ -75,46 +75,31 @@ ext {
'bootstrap-icons.version' : '1.13.2',
'bootstrap.version' : '5.3.8',
'checker-qual.version' : '3.55.1',
- 'commons-codec.version' : '1.22.1',
'geb-spock.version' : '8.0.1',
- // Pinned as a drift tripwire even though 25.1 matches Spring Boot 4.1.2: graphql-java-
- // extended-scalars is not managed by Spring Boot. Keeping this pin makes a later Boot
- // graphql-java bump force a compatibility check of extended-scalars, not an equal-version
- // upgrade. See https://github.com/apache/grails-core/issues/15674
- 'graphql-java.version' : '25.1',
+ // Pinned deliberately as a drift tripwire even though it matches Spring Boot's
+ // managed version: graphql-java-extended-scalars (below) is NOT managed by Spring
+ // Boot and must be upgraded in lockstep with graphql-java. Keeping this pin makes
+ // the dependency validator flag any Spring Boot graphql-java bump so we re-check
+ // extended-scalars compatibility. See https://github.com/apache/grails-core/issues/15674
+ 'graphql-java.version' : '26.1',
'graphql-java-extended-scalars.version': '24.0',
'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 requires Jackson 2.22.x, and 2.22.4 also overrides the
- // 2.21.7 Spring Boot 4.1.2 manages: it adds the StreamReadConstraints length limit to
- // GregorianCalendar/Duration (CVE-2026-68497) and restricts the URI schemes
- // java.nio.file.Path deserialization accepts (CVE-2026-19032). Jackson 2 only releases
- // jackson-annotations on the minor, hence the separate 2.22 below. 2.22.3 also fixes
- // CVE-2026-89425, CVE-2026-89407, CVE-2026-91777 and CVE-2026-91776, and 2.22.4 fixes
- // CVE-2026-110879 (type id validation in jackson-databind), which 2.21.7 does not carry.
+ // 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. 2.22.4 also fixes
+ // CVE-2026-110879 (type id validation in jackson-databind).
'jackson-2-bom.version' : '2.22.4',
'jackson2-annotations.version' : '2.22',
- // Security: overrides Jackson 3.1.7 from Spring Boot 4.1.2. The 3.2.4 BOM aligns the family
- // and fixes CVE-2026-89425, CVE-2026-89407, CVE-2026-91777, CVE-2026-91776 and
- // CVE-2026-110879, which 3.1.7 does not carry, and CVE-2026-110729, which affects only
- // jackson-core 3.2.0 to 3.2.3.
+ // 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
+ // 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. 3.2.4 also fixes CVE-2026-110879, and
+ // CVE-2026-110729, which affects only jackson-core 3.2.0 to 3.2.3.
'jackson-bom.version' : '3.2.4',
'jquery.version' : '4.0.0',
- // Security: overrides the 1.5.38 Spring Boot 4.1.2 manages. 1.6.3 strips slashes from MDC
- // values before SiftingAppender uses them as discriminating keys (CVE-2026-19880), and
- // 1.6.5 completes that fix (CVE-2026-104721). The 1.6.x line keeps SLF4J 2.0.x and JDK 11.
- // Spring Boot 4.1.2 manages SLF4J 2.0.20, so SLF4J is not pinned.
- 'logback.version' : '1.6.5',
- // Security: overrides the 5.8.1 Spring Boot 4.1 manages. 5.9.2 stopped ProxySettings
- // .toString() writing the SOCKS5 proxy credentials into the application log
- // (CVE-2026-18710); 5.12.0 is the current release of that line.
- 'mongodb.version' : '5.12.0',
'nimbus-jose-jwt.version' : '10.10',
- // Overrides the 1.62.0 Spring Boot 4.1 manages, on every classpath, so the BOM manages the
- // version Selenium 4.49.0 pulls in transitively - see selenium.version. Can return to Boot's
- // version when the Selenium pin is dropped.
- 'opentelemetry.version' : '1.65.0',
// Includes the follow-up logout redirect and direct-client CSRF fixes on the 6.5.x line.
'pac4j.version' : '6.5.9',
// Security: overrides the transitive 3.5.1. 4.0.3 fixes CVE-2025-67030 flagged against plexus-utils.
@@ -128,13 +113,6 @@ ext {
'rxjava2.version' : '2.2.21',
'sitemesh.version' : '2.6.0',
'scribejava.version' : '8.3.3',
- // Overrides the 4.43.0 Spring Boot 4.1 manages. selenium/standalone-chrome, the image
- // ContainerGebSpec starts, is only published for linux/arm64 from 4.47.0, so the default
- // Geb functional test runs natively on Apple silicon. The image tag must match the
- // Selenium version on the test classpath, so stay on a version with a published image.
- // Boot's selenium-htmlunit.version (htmlunit3-driver) stays at 4.43.0: the newest
- // htmlunit3-driver needs a HtmlUnit newer than Boot manages, and nothing here uses it.
- 'selenium.version' : '4.49.0',
'spock.version' : '2.5-groovy-6.0',
// Not managed by spring-boot-dependencies. Spring AI 2.0.x is the Spring Boot 4.0 / 4.1
// line; grails-bom imports its BOM so applications and grails-spring-ai share one Spring AI version.
@@ -166,8 +144,6 @@ ext {
'asset-pipeline-bom': "cloud.wondrify:asset-pipeline-bom:${bomDependencyVersions['asset-pipeline-bom.version']}",
'groovy-bom' : "org.apache.groovy:groovy-bom:${bomDependencyVersions['groovy.version']}",
'jackson-bom' : "tools.jackson:jackson-bom:${bomDependencyVersions['jackson-bom.version']}",
- 'opentelemetry-bom' : "io.opentelemetry:opentelemetry-bom:${bomDependencyVersions['opentelemetry.version']}",
- 'selenium-bom' : "org.seleniumhq.selenium:selenium-bom:${bomDependencyVersions['selenium.version']}",
'spock-bom' : "org.spockframework:spock-bom:${bomDependencyVersions['spock.version']}",
'spring-ai-bom' : "org.springframework.ai:spring-ai-bom:${bomDependencyVersions['spring-ai-bom.version']}",
]
@@ -178,7 +154,6 @@ ext {
'bootstrap-icons' : "org.webjars.npm:bootstrap-icons:${bomDependencyVersions['bootstrap-icons.version']}",
'cas-client-core' : "org.apereo.cas.client:cas-client-core:${bomDependencyVersions['cas-client-core.version']}",
'checker-qual' : "org.checkerframework:checker-qual:${bomDependencyVersions['checker-qual.version']}",
- 'commons-codec' : "commons-codec:commons-codec:${bomDependencyVersions['commons-codec.version']}",
'geb-spock' : "org.apache.groovy.geb:geb-spock:${bomDependencyVersions['geb-spock.version']}",
'graphql-java' : "com.graphql-java:graphql-java:${bomDependencyVersions['graphql-java.version']}",
'graphql-java-extended-scalars': "com.graphql-java:graphql-java-extended-scalars:${bomDependencyVersions['graphql-java-extended-scalars.version']}",
@@ -214,7 +189,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']}",
- // Security override of 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']}",
@@ -222,22 +197,11 @@ 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']}",
- // Security 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']}",
'jquery' : "org.webjars.npm:jquery:${bomDependencyVersions['jquery.version']}",
- // Security override of the transitive 1.5.38 - see logback.version
- 'logback-classic' : "ch.qos.logback:logback-classic:${bomDependencyVersions['logback.version']}",
- 'logback-core' : "ch.qos.logback:logback-core:${bomDependencyVersions['logback.version']}",
- // Security override of the 5.8.1 spring-boot-dependencies imports through
- // org.mongodb:mongodb-driver-bom - see mongodb.version. The whole driver family is
- // pinned so a classpath cannot end up mixing driver versions.
- 'mongodb-bson' : "org.mongodb:bson:${bomDependencyVersions['mongodb.version']}",
- 'mongodb-bson-record-codec': "org.mongodb:bson-record-codec:${bomDependencyVersions['mongodb.version']}",
- 'mongodb-driver-core' : "org.mongodb:mongodb-driver-core:${bomDependencyVersions['mongodb.version']}",
- 'mongodb-driver-reactivestreams': "org.mongodb:mongodb-driver-reactivestreams:${bomDependencyVersions['mongodb.version']}",
- 'mongodb-driver-sync' : "org.mongodb:mongodb-driver-sync:${bomDependencyVersions['mongodb.version']}",
// Security override of the transitive 3.5.1 - see plexus-utils.version
'plexus-utils' : "org.codehaus.plexus:plexus-utils:${bomDependencyVersions['plexus-utils.version']}",
// Required alongside plexus-utils 4.x - see plexus-xml.version
@@ -300,8 +264,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 Boot's version so enforcedPlatform consumers
- // are forced to it; the pin matches Spring Boot 4.1.2 on purpose.
+ // The Hibernate 7 BOM strictly re-declares the version Spring Boot manages, so that
+ // enforcedPlatform consumers are forced to it - see hibernate7VersionOverride.
'hibernate.version',
]
@@ -316,7 +280,7 @@ ext {
if (project.name in ['grails-bom', 'grails-hibernate5-bom'] || project.name.startsWith('grails-data-hibernate5')) {
customBomVersions = [
'liquibase-hibernate.version': '4.27.0',
- 'liquibase.version' : '4.27.0', // liquibase-hibernate5 stops at 4.27.0, and Boot 4.1.2's Liquibase 5.0.4 is a new major.
+ 'liquibase.version' : '4.27.0', // liquibase-hibernate5 stops at 4.27.0, and Spring Boot's Liquibase 5.0.4 is a new major.
'hibernate.version' : '5.6.15.Final',
]
combinedVersions += customBomVersions
@@ -355,18 +319,29 @@ 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 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 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',
'derby.version' : '10.17.1.0',
- // Spring Boot 4.1.2 selects Hibernate ORM 7.4.13.Final. This BOM strictly re-declares
- // that version so enforcedPlatform consumers are forced to it; a platform() import
- // is not enforced. 7.4.13.Final still requires hibernate-models 1.1.2.
+ // 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. 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',
- 'hibernate.version' : '7.4.13.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 Boot 4.1.2's Liquibase 5.0.4 is a new major.
+ 'liquibase.version' : '4.27.0', // liquibase-hibernate5 stops at 4.27.0, and Spring Boot's Liquibase 5.0.4 is a new major.
'mockito-inline.version' : '5.2.0',
]
combinedVersions += customBomVersions
@@ -376,9 +351,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/end-to-end/README.md b/end-to-end/README.md
index 8a12bc8bb2b..1462cd80360 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-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-bom/hibernate7/build.gradle b/grails-bom/hibernate7/build.gradle
index ca629ae6704..9203f403387 100644
--- a/grails-bom/hibernate7/build.gradle
+++ b/grails-bom/hibernate7/build.gradle
@@ -17,6 +17,9 @@
* 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
import org.apache.grails.gradle.tasks.bom.PropertyNameCalculator
@@ -53,6 +56,84 @@ 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. 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
+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')
+}
+
+// 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:${overrideHibernateVersion}"),
+ dependencies.create("org.hibernate.orm:hibernate-core:${springBootHibernateVersion}"))
+ bothVersions.transitive = false
+ bothVersions.incoming.resolutionResult.allComponents
+ .find { it.moduleVersion.name == 'hibernate-core' }.moduleVersion.version
+}
+// hibernate-models is strictly re-declared too, so it must move with Hibernate ORM
+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
+for (String module : managedHibernateOrmModules) {
+ String coordinates = "org.hibernate.orm:${module}:${hibernateVersion}"
+ customBomDependencies[module] = coordinates
+ combinedDependencies[module] = coordinates
+}
+
dependencies {
api platform(project(':grails-base-bom'))
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..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,11 +20,14 @@
import java.security.Principal;
+import jakarta.servlet.http.HttpServletResponse;
+
import org.jspecify.annotations.Nullable;
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 +72,13 @@ 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,
+ // 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/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-controllers/src/main/groovy/org/grails/plugins/web/controllers/GrailsSecurityHeadersFilter.java b/grails-controllers/src/main/groovy/org/grails/plugins/web/controllers/GrailsSecurityHeadersFilter.java
index 2a676bed6e0..b27a0378cf1 100644
--- a/grails-controllers/src/main/groovy/org/grails/plugins/web/controllers/GrailsSecurityHeadersFilter.java
+++ b/grails-controllers/src/main/groovy/org/grails/plugins/web/controllers/GrailsSecurityHeadersFilter.java
@@ -24,6 +24,7 @@
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.function.UnaryOperator;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
@@ -39,6 +40,8 @@
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.util.ForwardedHeaderUtils;
+import grails.web.http.ContentSecurityPolicyNonce;
+
/**
* Applies baseline browser hardening response headers.
*
@@ -57,6 +60,15 @@
* adds. See {@link GrailsSecurityHeadersProperties.Defaults} for the controlling
* setting.
*
+ *
A {@code Content-Security-Policy} value may contain the {@code {nonce}} placeholder that
+ * Spring Security 7.2 introduced, for example {@code script-src 'self' 'nonce-{nonce}'}. The
+ * request then carries a {@link ContentSecurityPolicyNonce}, which a page renders into the
+ * {@code nonce} attribute of an inline script or style with the {@code cspNonce} tag, and every
+ * placeholder is replaced with that nonce when the header is written. The request attribute it is
+ * carried under is the one Spring Security's {@code ContentSecurityPolicyNonceGeneratingFilter}
+ * sets by default, so a request that already carries Spring Security's nonce keeps it, and the
+ * header and the view agree on one nonce whichever generated it.
+ *
*
When {@link GrailsSecurityHeadersProperties#isEnabled()} is {@code false} the filter
* passes every request through untouched. The auto-configuration does not register the
* filter at all in that case; the check here covers filters an application constructs
@@ -73,9 +85,12 @@ public class GrailsSecurityHeadersFilter extends OncePerRequestFilter {
static final List REVERSE_PROXY_REQUEST_HEADERS = List.of(
"Forwarded", "X-Forwarded-For", "X-Forwarded-Proto", "X-Forwarded-Host", "Via", "X-Real-IP");
+ static final String NONCE_PLACEHOLDER = "{nonce}";
+
private static final Logger logger = LoggerFactory.getLogger(GrailsSecurityHeadersFilter.class);
private static final String HTTPS = "https";
+ private static final String FORWARDED = "Forwarded";
private final GrailsSecurityHeadersProperties properties;
@@ -85,6 +100,8 @@ public class GrailsSecurityHeadersFilter extends OncePerRequestFilter {
private final Set blankValueLogged = ConcurrentHashMap.newKeySet();
+ private final AtomicBoolean unreadableNonceLogged = new AtomicBoolean();
+
public GrailsSecurityHeadersFilter(GrailsSecurityHeadersProperties properties) {
this(properties, false);
}
@@ -114,8 +131,14 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse
}
boolean applyDefaults = shouldApplyDefaults(request);
boolean secure = isEnabled(this.properties.getHsts()) && isSecure(request);
+ // Left alone when the request already has one: a nonce this filter set on an earlier
+ // dispatch of the same request, or the one Spring Security's nonce filter set when its
+ // chain runs ahead of this filter. Either is what a view of this request renders.
+ if (usesNonce() && request.getAttribute(ContentSecurityPolicyNonce.ATTRIBUTE) == null) {
+ request.setAttribute(ContentSecurityPolicyNonce.ATTRIBUTE, new ContentSecurityPolicyNonce());
+ }
SecurityHeadersResponseWrapper wrapped = new SecurityHeadersResponseWrapper(response,
- () -> writeHeaders(response, applyDefaults, secure));
+ () -> writeHeaders(request, response, applyDefaults, secure));
try {
filterChain.doFilter(request, wrapped);
}
@@ -124,7 +147,8 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse
}
}
- private void writeHeaders(HttpServletResponse response, boolean applyDefaults, boolean secure) {
+ private void writeHeaders(HttpServletRequest request, HttpServletResponse response, boolean applyDefaults,
+ boolean secure) {
applyHeader(response, "X-Content-Type-Options", "content-type-options",
this.properties.getContentTypeOptions(), applyDefaults);
applyHeader(response, "X-Frame-Options", "frame-options", this.properties.getFrameOptions(), applyDefaults);
@@ -134,7 +158,37 @@ private void writeHeaders(HttpServletResponse response, boolean applyDefaults, b
applyHeader(response, "Strict-Transport-Security", "hsts", this.properties.getHsts(), applyDefaults);
}
applyHeader(response, "Content-Security-Policy", "content-security-policy",
- this.properties.getContentSecurityPolicy(), applyDefaults);
+ this.properties.getContentSecurityPolicy(), applyDefaults, (policy) -> withNonce(policy, request));
+ }
+
+ private boolean usesNonce() {
+ GrailsSecurityHeadersProperties.Header policy = this.properties.getContentSecurityPolicy();
+ return isEnabled(policy) && policy.getValue() != null && policy.getValue().contains(NONCE_PLACEHOLDER);
+ }
+
+ /**
+ * The policy with each {@code {nonce}} replaced by the nonce the request carries when the
+ * header is written, or {@code null} when the request carries none that can be read.
+ */
+ private String withNonce(String policy, HttpServletRequest request) {
+ if (!policy.contains(NONCE_PLACEHOLDER)) {
+ return policy;
+ }
+ if (request.getAttribute(ContentSecurityPolicyNonce.ATTRIBUTE) == null) {
+ // Removed after this filter set it, so the header gets one of its own.
+ request.setAttribute(ContentSecurityPolicyNonce.ATTRIBUTE, new ContentSecurityPolicyNonce());
+ }
+ String nonce = ContentSecurityPolicyNonce.nonceOf(request);
+ if (nonce == null) {
+ if (this.unreadableNonceLogged.compareAndSet(false, true)) {
+ logger.warn("The Content-Security-Policy uses {} but the {} request attribute holds a {}, which " +
+ "is neither a Grails nor a Spring Security nonce, so the header is not sent.",
+ NONCE_PLACEHOLDER, ContentSecurityPolicyNonce.ATTRIBUTE,
+ request.getAttribute(ContentSecurityPolicyNonce.ATTRIBUTE).getClass().getName());
+ }
+ return null;
+ }
+ return policy.replace(NONCE_PLACEHOLDER, nonce);
}
private boolean shouldApplyDefaults(HttpServletRequest request) {
@@ -171,11 +225,10 @@ private static String detectReverseProxyHeader(HttpServletRequest request) {
/**
* Whether the client connection is secure. Falls back to the scheme a reverse proxy
- * forwards in the RFC 7239 {@code Forwarded} header or in {@code X-Forwarded-Proto}
- * (and {@code X-Forwarded-Ssl}), read the same way Spring's {@code ForwardedHeaderFilter}
- * reads them, when the container itself saw plain HTTP. That is the case behind a
- * TLS-terminating proxy that has not been configured through
- * {@code server.forward-headers-strategy}. Trusting the forwarded scheme is safe for
+ * forwards in the RFC 7239 {@code Forwarded} header when the request has one, otherwise in
+ * {@code X-Forwarded-Proto} (and {@code X-Forwarded-Ssl}), when the container itself saw
+ * plain HTTP. That is the case behind a TLS-terminating proxy that has not been configured
+ * through {@code server.forward-headers-strategy}. Trusting the forwarded scheme is safe for
* HSTS: user agents ignore a {@code Strict-Transport-Security} header received over a
* non-secure transport (RFC 6797, section 8.1), so a spoofed header on a plain
* connection has no effect.
@@ -190,7 +243,14 @@ private static boolean isSecure(HttpServletRequest request) {
// scheme alone rather than to its URL: java.net.URI rejects request paths the
// container may accept, such as those allowed through Tomcat's relaxedPathChars.
URI base = URI.create(request.getScheme() + "://localhost");
- String scheme = ForwardedHeaderUtils.adaptFromForwardedHeaders(base, headers).build().getScheme();
+ ForwardedHeaderUtils.ForwardedInfo forwarded;
+ if (StringUtils.hasText(headers.getFirst(FORWARDED))) {
+ forwarded = ForwardedHeaderUtils.parseStandardHeader(base, headers);
+ }
+ else {
+ forwarded = ForwardedHeaderUtils.parseXForwardedHeaders(base, headers);
+ }
+ String scheme = forwarded.uriComponentsBuilder().build().getScheme();
return HTTPS.equalsIgnoreCase(scheme);
}
catch (IllegalArgumentException malformedForwardedHeaders) {
@@ -205,6 +265,11 @@ private static boolean isEnabled(GrailsSecurityHeadersProperties.Header header)
private void applyHeader(HttpServletResponse response, String name, String propertyName,
GrailsSecurityHeadersProperties.Header header, boolean applyDefaults) {
+ applyHeader(response, name, propertyName, header, applyDefaults, UnaryOperator.identity());
+ }
+
+ private void applyHeader(HttpServletResponse response, String name, String propertyName,
+ GrailsSecurityHeadersProperties.Header header, boolean applyDefaults, UnaryOperator resolve) {
if (!isEnabled(header)) {
return;
}
@@ -220,7 +285,10 @@ private void applyHeader(HttpServletResponse response, String name, String prope
return;
}
if (!response.containsHeader(name)) {
- response.setHeader(name, header.getValue());
+ String value = resolve.apply(header.getValue());
+ if (value != null) {
+ response.setHeader(name, value);
+ }
}
}
}
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..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,11 +18,14 @@
*/
package org.apache.grails.controllers.aot
+import jakarta.servlet.http.HttpServletResponse
+
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 +55,16 @@ 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)
+ }
+
void 'the controller trait Groovy dispatches through is registered'() {
expect:
registered(grails.artefact.Controller)
diff --git a/grails-controllers/src/test/groovy/org/grails/plugins/web/controllers/GrailsSecurityHeadersAutoConfigurationSpec.groovy b/grails-controllers/src/test/groovy/org/grails/plugins/web/controllers/GrailsSecurityHeadersAutoConfigurationSpec.groovy
index a61c75152e5..e1dbb7c63fe 100644
--- a/grails-controllers/src/test/groovy/org/grails/plugins/web/controllers/GrailsSecurityHeadersAutoConfigurationSpec.groovy
+++ b/grails-controllers/src/test/groovy/org/grails/plugins/web/controllers/GrailsSecurityHeadersAutoConfigurationSpec.groovy
@@ -37,11 +37,14 @@ import org.springframework.context.annotation.Configuration
import org.springframework.mock.web.MockFilterChain
import org.springframework.mock.web.MockHttpServletRequest
import org.springframework.mock.web.MockHttpServletResponse
+import org.springframework.security.web.header.ContentSecurityPolicyNonceGeneratingFilter
import org.springframework.security.web.header.HeaderWriterFilter
+import org.springframework.security.web.header.writers.ContentSecurityPolicyHeaderWriter
import org.springframework.security.web.header.writers.ReferrerPolicyHeaderWriter
import org.springframework.security.web.header.writers.frameoptions.XFrameOptionsHeaderWriter
import org.springframework.web.filter.CharacterEncodingFilter
+import grails.web.http.ContentSecurityPolicyNonce
import org.grails.web.config.http.GrailsFilters
import spock.lang.Specification
@@ -277,6 +280,170 @@ class GrailsSecurityHeadersAutoConfigurationSpec extends Specification {
response.getHeader('Content-Security-Policy') == "default-src 'self'"
}
+ void 'each {nonce} in the Content-Security-Policy is the nonce a view of the request renders'() {
+ given:
+ def request = new MockHttpServletRequest('GET', '/')
+ def response = new MockHttpServletResponse()
+ def properties = cspProperties("script-src 'self' 'nonce-{nonce}'; style-src 'nonce-{nonce}'")
+ String rendered = null
+ FilterChain view = { viewRequest, viewResponse ->
+ rendered = ContentSecurityPolicyNonce.nonceOf(viewRequest as HttpServletRequest)
+ } as FilterChain
+
+ when:
+ new GrailsSecurityHeadersFilter(properties).doFilter(request, response, view)
+
+ then: '128 random bits, Base64 without padding, as Spring Security generates a nonce'
+ rendered ==~ /[A-Za-z0-9+\/]{22}/
+ response.getHeader('Content-Security-Policy') ==
+ "script-src 'self' 'nonce-${rendered}'; style-src 'nonce-${rendered}'"
+ }
+
+ void 'every request gets a nonce of its own'() {
+ given:
+ def filter = new GrailsSecurityHeadersFilter(cspProperties("script-src 'nonce-{nonce}'"))
+
+ when:
+ def first = new MockHttpServletResponse()
+ filter.doFilter(new MockHttpServletRequest('GET', '/'), first, new MockFilterChain())
+ def second = new MockHttpServletResponse()
+ filter.doFilter(new MockHttpServletRequest('GET', '/'), second, new MockFilterChain())
+
+ then:
+ first.getHeader('Content-Security-Policy') ==~ /script-src 'nonce-[A-Za-z0-9+\/]{22}'/
+ first.getHeader('Content-Security-Policy') != second.getHeader('Content-Security-Policy')
+ }
+
+ @Unroll
+ void 'a request carries no nonce when the Content-Security-Policy #description'() {
+ given:
+ def request = new MockHttpServletRequest('GET', '/')
+ def response = new MockHttpServletResponse()
+ def properties = cspProperties(policy)
+ properties.contentSecurityPolicy.enabled = enabled
+ Object carried = 'unset'
+ FilterChain view = { viewRequest, viewResponse ->
+ carried = viewRequest.getAttribute('_csp')
+ } as FilterChain
+
+ when:
+ new GrailsSecurityHeadersFilter(properties).doFilter(request, response, view)
+
+ then:
+ carried == null
+ response.getHeader('Content-Security-Policy') == header
+
+ where:
+ description | enabled | policy || header
+ 'has no {nonce}' | true | "default-src 'self'" || "default-src 'self'"
+ 'is not sent' | false | "script-src 'nonce-{nonce}'" || null
+ }
+
+ void 'an error dispatch of the request keeps the nonce its view rendered'() {
+ given:
+ def request = new MockHttpServletRequest('GET', '/')
+ def filter = new GrailsSecurityHeadersFilter(cspProperties("script-src 'nonce-{nonce}'"))
+ def original = new MockHttpServletResponse()
+ filter.doFilter(request, original, new MockFilterChain())
+ String rendered = ContentSecurityPolicyNonce.nonceOf(request)
+
+ when: 'the container dispatches the same request to its error page'
+ request.dispatcherType = DispatcherType.ERROR
+ def errorPage = new MockHttpServletResponse()
+ filter.doFilter(request, errorPage, new MockFilterChain())
+
+ then:
+ original.getHeader('Content-Security-Policy') == "script-src 'nonce-${rendered}'"
+ errorPage.getHeader('Content-Security-Policy') == "script-src 'nonce-${rendered}'"
+ }
+
+ void 'Spring Security writing its own nonce-based policy inside the filter wins, with the nonce the view renders'() {
+ given: 'the chain the headers DSL builds when its policy uses {nonce}: the nonce filter, then the header writer'
+ def request = new MockHttpServletRequest('GET', '/')
+ def response = new MockHttpServletResponse()
+ def springSecurityNonce = new ContentSecurityPolicyNonceGeneratingFilter()
+ def springSecurityHeaders = new HeaderWriterFilter([
+ new ContentSecurityPolicyHeaderWriter("script-src 'self' 'nonce-{nonce}'")
+ ])
+ def view = new NonceRenderingServlet()
+
+ when:
+ new GrailsSecurityHeadersFilter(cspProperties("default-src 'none'; script-src 'nonce-{nonce}'"))
+ .doFilter(request, response, new MockFilterChain(view, springSecurityNonce, springSecurityHeaders))
+
+ then:
+ response.contentAsString ==~ /[A-Za-z0-9+\/]{22}/
+ response.getHeader('Content-Security-Policy') == "script-src 'self' 'nonce-${response.contentAsString}'"
+ }
+
+ void 'the filter writes the nonce Spring Security put on the request when its chain runs ahead of the filter'() {
+ given: 'spring.security.filter.order ahead of the Grails filter, so the Grails writer is the inner one and writes first'
+ def request = new MockHttpServletRequest('GET', '/')
+ def response = new MockHttpServletResponse()
+ def springSecurityNonce = new ContentSecurityPolicyNonceGeneratingFilter()
+ def springSecurityHeaders = new HeaderWriterFilter([
+ new ContentSecurityPolicyHeaderWriter("script-src 'self' 'nonce-{nonce}'")
+ ])
+ def grails = new GrailsSecurityHeadersFilter(cspProperties("default-src 'none'; script-src 'nonce-{nonce}'"))
+ def view = new NonceRenderingServlet()
+
+ when:
+ springSecurityNonce.doFilter(request, response,
+ new MockFilterChain(view, springSecurityHeaders, grails))
+
+ then: 'the Grails policy, with the nonce Spring Security generated and the view rendered'
+ response.contentAsString ==~ /[A-Za-z0-9+\/]{22}/
+ response.getHeader('Content-Security-Policy') ==
+ "default-src 'none'; script-src 'nonce-${response.contentAsString}'"
+ }
+
+ void 'a request attribute that holds no nonce leaves the policy unsent and is warned about once'() {
+ given:
+ def logCapture = new LogCapture(GrailsSecurityHeadersFilter)
+ def filter = new GrailsSecurityHeadersFilter(cspProperties("script-src 'nonce-{nonce}'"))
+
+ when: 'two requests arrive with something else under the attribute'
+ def first = new MockHttpServletResponse()
+ def firstRequest = new MockHttpServletRequest('GET', '/')
+ firstRequest.setAttribute('_csp', 'not a nonce')
+ filter.doFilter(firstRequest, first, new MockFilterChain())
+ def second = new MockHttpServletResponse()
+ def secondRequest = new MockHttpServletRequest('GET', '/')
+ secondRequest.setAttribute('_csp', 'not a nonce')
+ filter.doFilter(secondRequest, second, new MockFilterChain())
+
+ then: 'a policy that names no nonce would block every inline script the view nonced'
+ first.getHeader('Content-Security-Policy') == null
+ second.getHeader('Content-Security-Policy') == null
+ first.getHeader('X-Content-Type-Options') == 'nosniff'
+
+ and:
+ def warnings = logCapture.events.findAll { it.level == Level.WARN }
+ warnings.size() == 1
+ warnings[0].formattedMessage.contains('{nonce}')
+ warnings[0].formattedMessage.contains('_csp')
+ warnings[0].formattedMessage.contains(String.name)
+
+ cleanup:
+ logCapture.close()
+ }
+
+ void 'a nonce-based policy binds from application configuration'() {
+ expect:
+ new WebApplicationContextRunner()
+ .withPropertyValues('grails.security.headers.content-security-policy.enabled=true',
+ "grails.security.headers.content-security-policy.value=script-src 'self' 'nonce-{nonce}'")
+ .withConfiguration(AutoConfigurations.of(GrailsSecurityHeadersAutoConfiguration))
+ .run { context ->
+ def request = new MockHttpServletRequest('GET', '/')
+ def response = new MockHttpServletResponse()
+ context.getBean(GrailsSecurityHeadersFilter).doFilter(request, response, new MockFilterChain())
+ String nonce = ContentSecurityPolicyNonce.nonceOf(request)
+ assert nonce ==~ /[A-Za-z0-9+\/]{22}/
+ assert response.getHeader('Content-Security-Policy') == "script-src 'self' 'nonce-${nonce}'"
+ }
+ }
+
void 'filter respects per-header disable switches and existing response headers'() {
given:
def request = new MockHttpServletRequest('GET', '/')
@@ -903,6 +1070,8 @@ class GrailsSecurityHeadersAutoConfigurationSpec extends Specification {
'Forwarded' | 'for=192.0.2.60; PROTO=https' || true
'Forwarded' | 'for=192.0.2.60;proto=http, proto=https' || false
'Forwarded' | 'for=192.0.2.60' || false
+ 'Forwarded' | 'for=unknown;proto=https' || true
+ 'Forwarded' | 'for="[2001:db8:cafe::17]:4711";proto=https' || true
'X-Forwarded-Ssl' | 'on' || true
'X-Forwarded-For' | '192.0.2.60' || false
}
@@ -930,6 +1099,30 @@ class GrailsSecurityHeadersAutoConfigurationSpec extends Specification {
'X-Forwarded-Port' | 'not-a-port'
'X-Forwarded-Host' | 'a:b:c'
'Forwarded' | 'host=a:b:c;proto=https'
+ 'Forwarded' | 'for=2001:db8:cafe::17;proto=https'
+ }
+
+ @Unroll
+ void 'HSTS reads only the Forwarded header when the request has one: #headerName: #headerValue'() {
+ given: 'X-Forwarded-* headers are not consulted next to a Forwarded header'
+ def request = new MockHttpServletRequest('GET', '/')
+ request.secure = false
+ request.addHeader('Forwarded', 'for=192.0.2.60')
+ request.addHeader(headerName, headerValue)
+ def response = new MockHttpServletResponse()
+ def properties = new GrailsSecurityHeadersProperties()
+ properties.hsts.enabled = true
+
+ when:
+ new GrailsSecurityHeadersFilter(properties).doFilter(request, response, new MockFilterChain())
+
+ then:
+ response.getHeader('Strict-Transport-Security') == null
+
+ where:
+ headerName | headerValue
+ 'X-Forwarded-Proto' | 'https'
+ 'X-Forwarded-Ssl' | 'on'
}
@Unroll
@@ -1211,6 +1404,22 @@ class GrailsSecurityHeadersAutoConfigurationSpec extends Specification {
outcome = defaultsSent ? 'receives' : 'does not receive'
}
+ private static GrailsSecurityHeadersProperties cspProperties(String policy) {
+ def properties = new GrailsSecurityHeadersProperties()
+ properties.contentSecurityPolicy.enabled = true
+ properties.contentSecurityPolicy.value = policy
+ properties
+ }
+
+ /** Renders the nonce of the request as its body, as a view renders it into a script's nonce attribute. */
+ static class NonceRenderingServlet extends HttpServlet {
+
+ @Override
+ protected void doGet(HttpServletRequest request, HttpServletResponse response) {
+ response.writer.write(ContentSecurityPolicyNonce.nonceOf(request))
+ }
+ }
+
@Configuration(proxyBeanMethods = false)
static class UserFilterAndRegistration {
diff --git a/grails-core/src/main/groovy/grails/config/Settings.groovy b/grails-core/src/main/groovy/grails/config/Settings.groovy
index c5f7bf615f9..ed946a6ccb9 100644
--- a/grails-core/src/main/groovy/grails/config/Settings.groovy
+++ b/grails-core/src/main/groovy/grails/config/Settings.groovy
@@ -412,6 +412,18 @@ 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. 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.0
+ */
+ 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..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
@@ -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. It turns on grails.exceptionresolver.springHandlers unless the application sets that.",
+ "defaultValue": false
+ },
{
"name": "grails.controllers.responseBody",
"type": "java.lang.Boolean",
diff --git a/grails-core/src/test/groovy/grails/boot/config/GeneratedArtifactsInjectionSpec.groovy b/grails-core/src/test/groovy/grails/boot/config/GeneratedArtifactsInjectionSpec.groovy
index f981bd7cd84..16889bb1d8d 100644
--- a/grails-core/src/test/groovy/grails/boot/config/GeneratedArtifactsInjectionSpec.groovy
+++ b/grails-core/src/test/groovy/grails/boot/config/GeneratedArtifactsInjectionSpec.groovy
@@ -29,10 +29,10 @@ import jakarta.annotation.PostConstruct
import jakarta.annotation.PreDestroy
import jakarta.annotation.Resource
-import org.springframework.aot.generate.ClassNameGenerator
import org.springframework.aot.generate.DefaultGenerationContext
import org.springframework.aot.generate.GeneratedFiles
import org.springframework.aot.generate.InMemoryGeneratedFiles
+import org.springframework.aot.generate.NameGenerator
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.config.AutowireCapableBeanFactory
import org.springframework.beans.factory.config.BeanDefinition
@@ -303,7 +303,7 @@ class GeneratedArtifactsInjectionSpec extends Specification {
InMemoryGeneratedFiles generatedFiles = new InMemoryGeneratedFiles()
DefaultGenerationContext generationContext = new DefaultGenerationContext(
- new ClassNameGenerator(ClassName.get(getClass().packageName, 'Injection')), generatedFiles)
+ new NameGenerator(ClassName.get(getClass().packageName, 'Injection')), generatedFiles)
ClassName initializer = new ApplicationContextAotGenerator().processAheadOfTime(generating, generationContext)
generationContext.writeGeneratedContent()
generating.close()
diff --git a/grails-core/src/test/groovy/org/apache/grails/core/aot/ApplicationBytecodeBeanFactoryInitializationAotProcessorSpec.groovy b/grails-core/src/test/groovy/org/apache/grails/core/aot/ApplicationBytecodeBeanFactoryInitializationAotProcessorSpec.groovy
index 22b343029f4..c9bdf411b89 100644
--- a/grails-core/src/test/groovy/org/apache/grails/core/aot/ApplicationBytecodeBeanFactoryInitializationAotProcessorSpec.groovy
+++ b/grails-core/src/test/groovy/org/apache/grails/core/aot/ApplicationBytecodeBeanFactoryInitializationAotProcessorSpec.groovy
@@ -20,7 +20,6 @@ package org.apache.grails.core.aot
import java.util.function.LongBinaryOperator
-import org.springframework.aot.generate.ClassNameGenerator
import org.springframework.aot.generate.DefaultGenerationContext
import org.springframework.aot.generate.InMemoryGeneratedFiles
import org.springframework.aot.hint.MemberCategory
@@ -37,6 +36,7 @@ import com.example.nativeapp.AuditedOrderFixture
import com.example.nativeapp.NativeApplicationFixture
import com.example.nativeapp.OrderStatusFixture
import com.example.nativeapp.TotalsFixture
+import org.springframework.aot.generate.NameGenerator
/**
* Covers what Groovy does reflectively on behalf of an application's own classes being possible in an image.
@@ -56,7 +56,7 @@ class ApplicationBytecodeBeanFactoryInitializationAotProcessorSpec extends Speci
def contribution = new ApplicationBytecodeBeanFactoryInitializationAotProcessor()
.processAheadOfTime(context.beanFactory)
def generation = new DefaultGenerationContext(
- new ClassNameGenerator(ClassName.get('com.example', 'Hints')), new InMemoryGeneratedFiles())
+ new NameGenerator(ClassName.get('com.example', 'Hints')), new InMemoryGeneratedFiles())
contribution.applyTo(generation, Mock(BeanFactoryInitializationCode))
generation.runtimeHints
}
diff --git a/grails-core/src/test/groovy/org/apache/grails/core/aot/ArtefactClassesBeanFactoryInitializationAotProcessorSpec.groovy b/grails-core/src/test/groovy/org/apache/grails/core/aot/ArtefactClassesBeanFactoryInitializationAotProcessorSpec.groovy
index 2dc463e03f2..039286af4ff 100644
--- a/grails-core/src/test/groovy/org/apache/grails/core/aot/ArtefactClassesBeanFactoryInitializationAotProcessorSpec.groovy
+++ b/grails-core/src/test/groovy/org/apache/grails/core/aot/ArtefactClassesBeanFactoryInitializationAotProcessorSpec.groovy
@@ -18,10 +18,10 @@
*/
package org.apache.grails.core.aot
-import org.springframework.aot.generate.ClassNameGenerator
import org.springframework.aot.generate.DefaultGenerationContext
import org.springframework.aot.generate.GeneratedFiles
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
@@ -56,7 +56,7 @@ class ArtefactClassesBeanFactoryInitializationAotProcessorSpec extends Specifica
InMemoryGeneratedFiles generatedFiles = new InMemoryGeneratedFiles()
DefaultGenerationContext generationContext = new DefaultGenerationContext(
- new ClassNameGenerator(ClassName.get('com.example', 'Subject')), generatedFiles)
+ new NameGenerator(ClassName.get('com.example', 'Subject')), generatedFiles)
new ApplicationContextAotGenerator().processAheadOfTime(context, generationContext)
generationContext.writeGeneratedContent()
@@ -146,7 +146,7 @@ class ArtefactClassesBeanFactoryInitializationAotProcessorSpec extends Specifica
private List writtenBy(contribution) {
InMemoryGeneratedFiles files = new InMemoryGeneratedFiles()
DefaultGenerationContext generation = new DefaultGenerationContext(
- new ClassNameGenerator(ClassName.get('com.example', 'Written')), files)
+ new NameGenerator(ClassName.get('com.example', 'Written')), files)
new ApplicationContextAotGenerator().processAheadOfTime(context, generation)
generation.writeGeneratedContent()
String source = files.getGeneratedFiles(GeneratedFiles.Kind.SOURCE)
diff --git a/grails-core/src/test/groovy/org/apache/grails/core/aot/ArtefactReflectionBeanFactoryInitializationAotProcessorSpec.groovy b/grails-core/src/test/groovy/org/apache/grails/core/aot/ArtefactReflectionBeanFactoryInitializationAotProcessorSpec.groovy
index 494abbd6e72..0ff759d6d7e 100644
--- a/grails-core/src/test/groovy/org/apache/grails/core/aot/ArtefactReflectionBeanFactoryInitializationAotProcessorSpec.groovy
+++ b/grails-core/src/test/groovy/org/apache/grails/core/aot/ArtefactReflectionBeanFactoryInitializationAotProcessorSpec.groovy
@@ -18,7 +18,6 @@
*/
package org.apache.grails.core.aot
-import org.springframework.aot.generate.ClassNameGenerator
import org.springframework.aot.generate.DefaultGenerationContext
import org.springframework.aot.generate.InMemoryGeneratedFiles
import org.springframework.aot.hint.MemberCategory
@@ -36,6 +35,7 @@ import grails.plugins.GrailsPlugin
import grails.plugins.GrailsPluginManager
import org.grails.core.DefaultGrailsServiceClass
import org.grails.core.DefaultGrailsUrlMappingsClass
+import org.springframework.aot.generate.NameGenerator
/**
* Covers what the framework creates reflectively as it registers artefacts being creatable in an image:
@@ -64,7 +64,7 @@ class ArtefactReflectionBeanFactoryInitializationAotProcessorSpec extends Specif
def contribution = new ArtefactReflectionBeanFactoryInitializationAotProcessor()
.processAheadOfTime(context.beanFactory)
def generation = new DefaultGenerationContext(
- new ClassNameGenerator(ClassName.get('com.example', 'Hints')), new InMemoryGeneratedFiles())
+ new NameGenerator(ClassName.get('com.example', 'Hints')), new InMemoryGeneratedFiles())
contribution.applyTo(generation, Mock(BeanFactoryInitializationCode))
generation.runtimeHints
}
diff --git a/grails-core/src/test/groovy/org/apache/grails/core/aot/BeanReflectionBeanFactoryInitializationAotProcessorSpec.groovy b/grails-core/src/test/groovy/org/apache/grails/core/aot/BeanReflectionBeanFactoryInitializationAotProcessorSpec.groovy
index bd4384f9eb0..367e14b4972 100644
--- a/grails-core/src/test/groovy/org/apache/grails/core/aot/BeanReflectionBeanFactoryInitializationAotProcessorSpec.groovy
+++ b/grails-core/src/test/groovy/org/apache/grails/core/aot/BeanReflectionBeanFactoryInitializationAotProcessorSpec.groovy
@@ -18,9 +18,9 @@
*/
package org.apache.grails.core.aot
-import org.springframework.aot.generate.ClassNameGenerator
import org.springframework.aot.generate.DefaultGenerationContext
import org.springframework.aot.generate.InMemoryGeneratedFiles
+import org.springframework.aot.generate.NameGenerator
import org.springframework.aot.hint.MemberCategory
import org.springframework.aot.hint.RuntimeHints
import org.springframework.aot.hint.predicate.RuntimeHintsPredicates
@@ -62,7 +62,7 @@ class BeanReflectionBeanFactoryInitializationAotProcessorSpec extends Specificat
private RuntimeHints hints() {
def contribution = new BeanReflectionBeanFactoryInitializationAotProcessor().processAheadOfTime(context.beanFactory)
def generation = new DefaultGenerationContext(
- new ClassNameGenerator(ClassName.get('com.example', 'Hints')), new InMemoryGeneratedFiles())
+ new NameGenerator(ClassName.get('com.example', 'Hints')), new InMemoryGeneratedFiles())
contribution.applyTo(generation, Mock(BeanFactoryInitializationCode))
generation.runtimeHints
}
diff --git a/grails-core/src/test/groovy/org/apache/grails/core/aot/GeneratedInjectionBeanRegistrationAotProcessorSpec.groovy b/grails-core/src/test/groovy/org/apache/grails/core/aot/GeneratedInjectionBeanRegistrationAotProcessorSpec.groovy
index e59632f6e0a..acf10f43d6a 100644
--- a/grails-core/src/test/groovy/org/apache/grails/core/aot/GeneratedInjectionBeanRegistrationAotProcessorSpec.groovy
+++ b/grails-core/src/test/groovy/org/apache/grails/core/aot/GeneratedInjectionBeanRegistrationAotProcessorSpec.groovy
@@ -18,10 +18,10 @@
*/
package org.apache.grails.core.aot
-import org.springframework.aot.generate.ClassNameGenerator
import org.springframework.aot.generate.DefaultGenerationContext
import org.springframework.aot.generate.GeneratedFiles
import org.springframework.aot.generate.InMemoryGeneratedFiles
+import org.springframework.aot.generate.NameGenerator
import org.springframework.beans.factory.support.RootBeanDefinition
import org.springframework.context.aot.ApplicationContextAotGenerator
import org.springframework.context.support.GenericApplicationContext
@@ -45,7 +45,7 @@ class GeneratedInjectionBeanRegistrationAotProcessorSpec extends Specification {
private String generatedSource() {
InMemoryGeneratedFiles generatedFiles = new InMemoryGeneratedFiles()
DefaultGenerationContext generationContext = new DefaultGenerationContext(
- new ClassNameGenerator(ClassName.get('com.example', 'Subject')), generatedFiles)
+ new NameGenerator(ClassName.get('com.example', 'Subject')), generatedFiles)
new ApplicationContextAotGenerator().processAheadOfTime(context, generationContext)
generationContext.writeGeneratedContent()
diff --git a/grails-core/src/test/groovy/org/apache/grails/core/aot/PluginConfigurationBeanFactoryInitializationAotProcessorSpec.groovy b/grails-core/src/test/groovy/org/apache/grails/core/aot/PluginConfigurationBeanFactoryInitializationAotProcessorSpec.groovy
index f9b42c5f510..43be8986a6f 100644
--- a/grails-core/src/test/groovy/org/apache/grails/core/aot/PluginConfigurationBeanFactoryInitializationAotProcessorSpec.groovy
+++ b/grails-core/src/test/groovy/org/apache/grails/core/aot/PluginConfigurationBeanFactoryInitializationAotProcessorSpec.groovy
@@ -20,7 +20,6 @@ package org.apache.grails.core.aot
import java.nio.file.Path
-import org.springframework.aot.generate.ClassNameGenerator
import org.springframework.aot.generate.DefaultGenerationContext
import org.springframework.aot.generate.GeneratedFiles.Kind
import org.springframework.aot.generate.InMemoryGeneratedFiles
@@ -35,6 +34,7 @@ import grails.plugins.GrailsPlugin
import grails.plugins.GrailsPluginManager
import org.apache.grails.core.plugins.PluginClassFixtures
import org.apache.grails.core.plugins.PluginUtils
+import org.springframework.aot.generate.NameGenerator
/**
* Covers each plugin's configuration reaching an application running on generated code, where every class is
@@ -81,7 +81,7 @@ class PluginConfigurationBeanFactoryInitializationAotProcessorSpec extends Speci
private DefaultGenerationContext generate() {
def generation = new DefaultGenerationContext(
- new ClassNameGenerator(ClassName.get('com.example', 'Configuration')), new InMemoryGeneratedFiles())
+ new NameGenerator(ClassName.get('com.example', 'Configuration')), new InMemoryGeneratedFiles())
new PluginConfigurationBeanFactoryInitializationAotProcessor().processAheadOfTime(context.beanFactory)
.applyTo(generation, Mock(BeanFactoryInitializationCode))
generation
diff --git a/grails-core/src/test/groovy/org/apache/grails/core/aot/VarargsBeanRegistrationAotProcessorSpec.groovy b/grails-core/src/test/groovy/org/apache/grails/core/aot/VarargsBeanRegistrationAotProcessorSpec.groovy
index 734335ad381..80d917cd79e 100644
--- a/grails-core/src/test/groovy/org/apache/grails/core/aot/VarargsBeanRegistrationAotProcessorSpec.groovy
+++ b/grails-core/src/test/groovy/org/apache/grails/core/aot/VarargsBeanRegistrationAotProcessorSpec.groovy
@@ -18,10 +18,10 @@
*/
package org.apache.grails.core.aot
-import org.springframework.aot.generate.ClassNameGenerator
import org.springframework.aot.generate.DefaultGenerationContext
import org.springframework.aot.generate.GeneratedFiles
import org.springframework.aot.generate.InMemoryGeneratedFiles
+import org.springframework.aot.generate.NameGenerator
import org.springframework.beans.factory.config.RuntimeBeanReference
import org.springframework.beans.factory.support.AbstractBeanDefinition
import org.springframework.beans.factory.support.RootBeanDefinition
@@ -59,7 +59,7 @@ class VarargsBeanRegistrationAotProcessorSpec extends Specification {
InMemoryGeneratedFiles generatedFiles = new InMemoryGeneratedFiles()
DefaultGenerationContext generationContext = new DefaultGenerationContext(
- new ClassNameGenerator(ClassName.get('com.example', 'Subject')), generatedFiles)
+ new NameGenerator(ClassName.get('com.example', 'Subject')), generatedFiles)
new ApplicationContextAotGenerator().processAheadOfTime(context, generationContext)
generationContext.writeGeneratedContent()
diff --git a/grails-core/src/test/groovy/org/grails/plugins/CoreGrailsPluginAotSpec.groovy b/grails-core/src/test/groovy/org/grails/plugins/CoreGrailsPluginAotSpec.groovy
index 6d8fef80df6..9d11e3306a2 100644
--- a/grails-core/src/test/groovy/org/grails/plugins/CoreGrailsPluginAotSpec.groovy
+++ b/grails-core/src/test/groovy/org/grails/plugins/CoreGrailsPluginAotSpec.groovy
@@ -19,9 +19,9 @@
package org.grails.plugins
import org.springframework.aot.AotDetector
-import org.springframework.aot.generate.ClassNameGenerator
import org.springframework.aot.generate.DefaultGenerationContext
import org.springframework.aot.generate.InMemoryGeneratedFiles
+import org.springframework.aot.generate.NameGenerator
import org.springframework.beans.factory.BeanRegistrar
import org.springframework.beans.factory.support.BeanRegistryAdapter
import org.springframework.beans.factory.support.GenericBeanDefinition
@@ -149,7 +149,7 @@ class CoreGrailsPluginAotSpec extends Specification {
and:
def generationContext = new DefaultGenerationContext(
- new ClassNameGenerator(ClassName.get('org.apache.grails.common.aot.test', 'CoreAotTest')),
+ new NameGenerator(ClassName.get('org.apache.grails.common.aot.test', 'CoreAotTest')),
new InMemoryGeneratedFiles())
when: 'the context is processed exactly as the processAot build task processes it'
@@ -173,7 +173,7 @@ class CoreGrailsPluginAotSpec extends Specification {
and:
def generationContext = new DefaultGenerationContext(
- new ClassNameGenerator(ClassName.get('org.apache.grails.common.aot.test', 'LiveInstanceAotTest')),
+ new NameGenerator(ClassName.get('org.apache.grails.common.aot.test', 'LiveInstanceAotTest')),
new InMemoryGeneratedFiles())
when:
diff --git a/grails-data-graphql/core/src/main/groovy/org/grails/gorm/graphql/Schema.groovy b/grails-data-graphql/core/src/main/groovy/org/grails/gorm/graphql/Schema.groovy
index d0af2bd49de..d873110f301 100644
--- a/grails-data-graphql/core/src/main/groovy/org/grails/gorm/graphql/Schema.groovy
+++ b/grails-data-graphql/core/src/main/groovy/org/grails/gorm/graphql/Schema.groovy
@@ -23,10 +23,12 @@ import graphql.schema.DataFetcher
import graphql.schema.GraphQLCodeRegistry
import graphql.schema.GraphQLFieldDefinition
import graphql.schema.GraphQLInputType
+import graphql.schema.GraphQLNamedType
import graphql.schema.GraphQLObjectType
import graphql.schema.GraphQLOutputType
import graphql.schema.GraphQLSchema
import graphql.schema.GraphQLType
+import graphql.schema.GraphQLTypeUtil
import groovy.transform.CompileStatic
import javassist.Modifier
import org.grails.datastore.mapping.model.MappingContext
@@ -531,9 +533,16 @@ class Schema {
schemaInterceptor.interceptSchema(queryType, mutationType, additionalTypes)
}
+ // graphql-java only accepts named types as additional types. Unwrapping list and
+ // non-null wrappers adds the type they wrap, which is what a wrapped type
+ // contributed to the schema before graphql-java 26 narrowed the signature.
+ Set namedAdditionalTypes = additionalTypes.collect(new LinkedHashSet()) { GraphQLType type ->
+ GraphQLTypeUtil.unwrapAll(type)
+ }
+
GraphQLSchema.Builder schema = GraphQLSchema.newSchema()
.codeRegistry(codeRegistry.build())
- .additionalTypes(additionalTypes)
+ .additionalTypes(namedAdditionalTypes)
GraphQLObjectType mutation = mutationType.build()
if (mutation.fieldDefinitions) {
diff --git a/grails-data-graphql/core/src/test/groovy/org/grails/gorm/graphql/QueryComplexityLimitsSpec.groovy b/grails-data-graphql/core/src/test/groovy/org/grails/gorm/graphql/QueryComplexityLimitsSpec.groovy
new file mode 100644
index 00000000000..2d90b624843
--- /dev/null
+++ b/grails-data-graphql/core/src/test/groovy/org/grails/gorm/graphql/QueryComplexityLimitsSpec.groovy
@@ -0,0 +1,105 @@
+/*
+ * 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.gorm.graphql
+
+import graphql.ExecutionInput
+import graphql.ParseAndValidate
+import graphql.schema.GraphQLSchema
+import graphql.validation.QueryComplexityLimits
+import graphql.validation.ValidationError
+import graphql.validation.ValidationErrorType
+import org.grails.datastore.mapping.config.Settings
+import org.grails.datastore.mapping.core.DatastoreUtils
+import org.grails.gorm.graphql.domain.general.GeneralPackage
+import org.grails.gorm.graphql.domain.hibernate.HibernatePackage
+import org.grails.orm.hibernate.HibernateDatastore
+import spock.lang.AutoCleanup
+import spock.lang.Shared
+import spock.lang.Specification
+
+/**
+ * graphql-java 26 enforces query complexity limits by default; the upgrade guide tells
+ * applications to adjust them with {@link QueryComplexityLimits#setDefaultLimits}.
+ */
+class QueryComplexityLimitsSpec extends Specification {
+
+ @Shared @AutoCleanup HibernateDatastore hibernateDatastore
+ @Shared GraphQLSchema schema
+
+ void setupSpec() {
+ hibernateDatastore = new HibernateDatastore(
+ DatastoreUtils.createPropertyResolver(Collections.singletonMap(Settings.SETTING_DB_CREATE, 'create-drop')),
+ GeneralPackage.getPackage(), HibernatePackage.getPackage())
+ schema = new Schema(hibernateDatastore.mappingContext).generate()
+ }
+
+ void cleanup() {
+ QueryComplexityLimits.setDefaultLimits(QueryComplexityLimits.DEFAULT)
+ }
+
+ void 'a query nested 100 levels deep passes the default limits'() {
+ expect:
+ errors(nestedQuery(100)).empty
+ }
+
+ void 'a query nested more than 100 levels deep fails the default limits'() {
+ expect:
+ errors(nestedQuery(101)) == [ValidationErrorType.MaxQueryDepthExceeded.name()]
+ }
+
+ void 'raised default limits let a deeper query pass'() {
+ given:
+ QueryComplexityLimits.setDefaultLimits(QueryComplexityLimits.newLimits()
+ .maxDepth(150)
+ .maxFieldsCount(200_000)
+ .build())
+
+ expect:
+ errors(nestedQuery(150)).empty
+ errors(nestedQuery(151)) == [ValidationErrorType.MaxQueryDepthExceeded.name()]
+ }
+
+ void 'the limits can be turned off'() {
+ given:
+ QueryComplexityLimits.setDefaultLimits(QueryComplexityLimits.NONE)
+
+ expect:
+ errors(nestedQuery(160)).empty
+ }
+
+ /**
+ * DebugCircular refers to itself through otherCircular, so a query can nest as deep as
+ * needed: debugBarList and circular are the first two levels, every otherCircular adds one
+ * and id is the last.
+ */
+ private static String nestedQuery(int depth) {
+ int nested = depth - 3
+ '{ debugBarList { circular { ' + 'otherCircular { ' * nested + 'id' + ' }' * nested + ' } } }'
+ }
+
+ /**
+ * The validation error types, or the class of any other error, so a query the parser
+ * rejects (graphql-java stops parsing past about 165 levels) cannot pass as valid.
+ */
+ private List errors(String query) {
+ ParseAndValidate.parseAndValidate(schema, ExecutionInput.newExecutionInput(query).build()).errors.collect {
+ it instanceof ValidationError ? ((ValidationError) it).validationErrorType.name() : it.getClass().simpleName
+ }
+ }
+}
diff --git a/grails-data-graphql/core/src/test/groovy/org/grails/gorm/graphql/SchemaInterceptorSpec.groovy b/grails-data-graphql/core/src/test/groovy/org/grails/gorm/graphql/SchemaInterceptorSpec.groovy
new file mode 100644
index 00000000000..62dfb81a9d6
--- /dev/null
+++ b/grails-data-graphql/core/src/test/groovy/org/grails/gorm/graphql/SchemaInterceptorSpec.groovy
@@ -0,0 +1,87 @@
+/*
+ * 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.gorm.graphql
+
+import graphql.Scalars
+import graphql.schema.GraphQLFieldDefinition
+import graphql.schema.GraphQLList
+import graphql.schema.GraphQLNonNull
+import graphql.schema.GraphQLObjectType
+import graphql.schema.GraphQLSchema
+import graphql.schema.GraphQLType
+import org.grails.datastore.mapping.config.Settings
+import org.grails.datastore.mapping.core.DatastoreUtils
+import org.grails.datastore.mapping.model.PersistentEntity
+import org.grails.gorm.graphql.domain.general.GeneralPackage
+import org.grails.gorm.graphql.domain.hibernate.HibernatePackage
+import org.grails.gorm.graphql.interceptor.GraphQLSchemaInterceptor
+import org.grails.gorm.graphql.interceptor.manager.DefaultGraphQLInterceptorManager
+import org.grails.orm.hibernate.HibernateDatastore
+import spock.lang.AutoCleanup
+import spock.lang.Shared
+import spock.lang.Specification
+
+class SchemaInterceptorSpec extends Specification {
+
+ @Shared @AutoCleanup HibernateDatastore hibernateDatastore
+
+ void setupSpec() {
+ hibernateDatastore = new HibernateDatastore(
+ DatastoreUtils.createPropertyResolver(Collections.singletonMap(Settings.SETTING_DB_CREATE, 'create-drop')),
+ GeneralPackage.getPackage(), HibernatePackage.getPackage())
+ }
+
+ void 'additional types from a schema interceptor are added to the schema, unwrapped from list and non-null'() {
+ given:
+ GraphQLObjectType standalone = objectType('Standalone')
+ GraphQLObjectType wrapped = objectType('Wrapped')
+ def interceptorManager = new DefaultGraphQLInterceptorManager()
+ interceptorManager.registerInterceptor(new GraphQLSchemaInterceptor() {
+ @Override
+ void interceptEntity(PersistentEntity entity,
+ List queryFields,
+ List mutationFields) {
+ }
+
+ @Override
+ void interceptSchema(GraphQLObjectType.Builder queryType,
+ GraphQLObjectType.Builder mutationType,
+ Set additionalTypes) {
+ additionalTypes << standalone
+ additionalTypes << GraphQLNonNull.nonNull(GraphQLList.list(wrapped))
+ }
+ })
+ def schema = new Schema(hibernateDatastore.mappingContext)
+ schema.interceptorManager = interceptorManager
+
+ when:
+ GraphQLSchema graphQLSchema = schema.generate()
+
+ then:
+ graphQLSchema.getType('Standalone') == standalone
+ graphQLSchema.getType('Wrapped') == wrapped
+ }
+
+ private static GraphQLObjectType objectType(String name) {
+ GraphQLObjectType.newObject()
+ .name(name)
+ .field(GraphQLFieldDefinition.newFieldDefinition().name('value').type(Scalars.GraphQLString))
+ .build()
+ }
+}
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 6c79126db94..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,19 @@
*/
package org.grails.datastore.gorm.mongodb.embedded;
+import java.io.DataInputStream;
+import java.io.IOException;
+import java.net.InetSocketAddress;
+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;
+import io.netty.buffer.ByteBufAllocator;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import org.springframework.util.ClassUtils;
@@ -41,6 +52,19 @@ 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;
+
+ /** 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;
+
+ private static final byte BSON_INT32 = 0x10;
+
+ private static final Logger log = LoggerFactory.getLogger(InMemoryMongoBackend.class);
+
@Override
public String getName() {
return NAME;
@@ -70,9 +94,82 @@ public RunningEmbeddedMongo start(EmbeddedMongoSettings settings) {
MemoryBackend backend = new RetainingMemoryBackend();
MongoServer server = new MongoServer(backend);
server.bind("localhost", 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(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++) {
+ 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.
+ *
+ *
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 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(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
+ DataInputStream reply = new DataInputStream(client.getInputStream());
+ int length = Integer.reverseBytes(reply.readInt());
+ reply.skipNBytes(length - (long) Integer.BYTES);
+ }
+ catch (IOException ex) {
+ log.debug("The embedded MongoDB at {} did not answer the request it serves as it starts", address, ex);
+ }
+ }
+
+ /** 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/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[]
+ }
+ }
}
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..0ab288955b2
--- /dev/null
+++ b/grails-data-mongodb/embedded/src/test/java/org/grails/datastore/gorm/mongodb/embedded/ClearedJarsServerApplication.java
@@ -0,0 +1,135 @@
+/*
+ * 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.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+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 io.netty.buffer.ByteBufAllocator;
+
+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);
+ 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;
+
+ stop.run();
+ }
+ }
+
+ /** Created by the class loader above, so that what it loads is loaded through it. */
+ 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(
+ 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]);
+ }
+ }
+}
diff --git a/grails-doc/src/en/guide/REST/openApi.adoc b/grails-doc/src/en/guide/REST/openApi.adoc
index 53d30e13c0d..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 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/conf/config/builtInOptions.adoc b/grails-doc/src/en/guide/conf/config/builtInOptions.adoc
index 64ffb941a45..e75cb409351 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. 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/conf/config/logging.adoc b/grails-doc/src/en/guide/conf/config/logging.adoc
index f471d4216ce..56908ec16ce 100644
--- a/grails-doc/src/en/guide/conf/config/logging.adoc
+++ b/grails-doc/src/en/guide/conf/config/logging.adoc
@@ -96,7 +96,7 @@ More information can be found in the official https://logback.qos.ch/documentati
=== Structured Logging
Grails does not enable structured logging. Existing Logback configuration and plain-text output remain unchanged
-unless an application explicitly selects a Spring Boot structured format. Spring Boot 4.1 provides the JSON format
+unless an application explicitly selects a Spring Boot structured format. Spring Boot provides the JSON format
IDs `ecs` (Elastic Common Schema), `gelf` (Graylog Extended Log Format), and `logstash` for console and file output.
For the complete reference, see the https://docs.spring.io/spring-boot/reference/features/logging.html#features.logging.structured[Spring Boot structured logging documentation].
diff --git a/grails-doc/src/en/guide/deployment/deploymentAot.adoc b/grails-doc/src/en/guide/deployment/deploymentAot.adoc
index 94f2d79af28..d46b3531b35 100644
--- a/grails-doc/src/en/guide/deployment/deploymentAot.adoc
+++ b/grails-doc/src/en/guide/deployment/deploymentAot.adoc
@@ -143,10 +143,30 @@ 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.
+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 or a link on `example.com` for an email or URL field, and recognisable text for a text field, each no longer than the field's `maxlength`. `example.com` is kept for examples and accepts no mail, so a save that sends mail sends none. A form with an email field too short for `1@example.com`, or a URL field too short for `ftp://example.com`, is not submitted, because whatever fits is text the field rejects or an address on someone else's domain. The trace fails, naming the field, until it is given a value in `forms`. 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
+
+`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 before the application is started, and one that answers with an error fails it too.
+
==== 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.
@@ -163,6 +183,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 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
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:
@@ -190,3 +224,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 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/deployment/deploymentAotCache.adoc b/grails-doc/src/en/guide/deployment/deploymentAotCache.adoc
index e30532c8ce8..fdbdaf84ec2 100644
--- a/grails-doc/src/en/guide/deployment/deploymentAotCache.adoc
+++ b/grails-doc/src/en/guide/deployment/deploymentAotCache.adoc
@@ -41,7 +41,7 @@ grails {
}
----
-That adds two tasks. `extractAotCacheApplication` unpacks the executable jar into `build/aot-cache/application`, and `trainAotCache` runs what it unpacked, asks for each path, stops it, and leaves the cache beside the extracted application:
+That adds two tasks. `extractAotCacheApplication` unpacks the executable archive into `build/aot-cache/application`, and `trainAotCache` runs what it unpacked, asks for each path, stops it, and leaves the cache beside the extracted application:
[source,bash]
----
@@ -53,7 +53,11 @@ That adds two tasks. `extractAotCacheApplication` unpacks the executable jar int
Trained myapp.aot (167 MB) over 4 paths
----
-The application is unpacked first because a cache is read against the layout it was trained on. An executable jar loads its dependencies through a nested-jar classloader; the extracted form loads them as ordinary jars on the classpath, and only the second is a layout a cache can be reused against.
+The application is unpacked first because a cache is read against the layout it was trained on. An executable archive loads its dependencies through a nested-jar classloader; the extracted form loads them as ordinary jars on the classpath, and only the second is a layout a cache can be reused against.
+
+The archive unpacked is the one the application ships. An application that applies the `war` plugin, as a generated application does, ships the executable war that `bootWar` builds, and that is what is unpacked. Any other application, or one that switches `bootWar` off, ships the executable jar that `bootJar` builds.
+
+A war is unpacked as a jar of the same name, `myapp.jar` for `myapp.war`. The libraries in `WEB-INF/lib` and `WEB-INF/lib-provided` go to `lib/` beside it, and the files the war holds outside `WEB-INF`, such as the contents of `src/main/webapp`, go to the jar's `META-INF/resources`. The application serves those files as it serves them from the war. The executable jar leaves `src/main/webapp` out, which is why an application that ships its war is trained against the war.
=== Running with the cache
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 ba55112e531..37c102fbab6 100644
--- a/grails-doc/src/en/guide/deployment/deploymentTasks.adoc
+++ b/grails-doc/src/en/guide/deployment/deploymentTasks.adoc
@@ -232,6 +232,8 @@ See the link:{springBootReference}actuator/endpoints.html#actuator.endpoints.kub
Many deployments terminate TLS at a reverse proxy or ingress. Keep certificate renewal there and restrict direct access to the application port.
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/introduction/whatsNew.adoc b/grails-doc/src/en/guide/introduction/whatsNew.adoc
index f74ffae4ba4..7918c538eaa 100644
--- a/grails-doc/src/en/guide/introduction/whatsNew.adoc
+++ b/grails-doc/src/en/guide/introduction/whatsNew.adoc
@@ -24,7 +24,7 @@ This section covers all the new features introduced in Grails {grailsMajorVersio
Grails {grailsMajorVersion} is a major release that includes new features, improvements, and dependency upgrades.
This release focuses on enhancing the developer experience, improving performance, and ensuring compatibility with the latest technologies.
-For detailed information on how to upgrade to Grails {grailsMajorVersion}, including major dependency changes, please see the xref:upgrading#upgrading80x[Upgrading from Grails 7 to Grails {grailsMajorVersion}] section.
+For detailed information on how to upgrade to Grails {grailsMajorVersion}, including major dependency changes, please see the xref:upgrading#upgrading90x[Upgrading from Grails 8 to Grails {grailsMajorVersion}] section.
Notable new features are included below.
==== Platform Baseline
@@ -70,12 +70,40 @@ dependencies {
An application that keeps the default never ships the module. The same dependency is needed, whatever the application's own setting, for a library that was compiled with classic call sites, because Groovy 6 can load such a class only with the module: `org.testcontainers:testcontainers-spock` is one, so declare the module as `testRuntimeOnly` next to it.
-==== Spring Boot 4.1 and Spring Framework 7
+==== Spring Boot 4.2 and Spring Framework 7.1
Grails {grailsMajorVersion} is built on Spring Boot {springBootVersion} and Spring Framework {springVersion}.
-This brings the Spring Boot 4 modular artifact layout, Spring Framework 7 API removals, Jackson 3, Tomcat 11 and Jakarta Servlet 6.1, plus Spring Boot 4.1 dependency management for Spring Security 7.1, Spring Data 2026.0 and Micrometer 1.17.
+This brings the Spring Boot 4 modular artifact layout, Spring Framework 7 API removals, Jackson 3, Tomcat 11 and Jakarta Servlet 6.1, plus Spring Boot 4.2 dependency management for Spring Security 7.2, Spring Data 2026.1 and Micrometer 1.18.
The Grails 8 upgrade guide calls out the major application-impacting changes and links to the Spring Boot 4.0 migration guide, Spring Boot 4.1 release notes and Spring Framework 7.0 release notes.
+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:
+
+[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
@@ -126,6 +154,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 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
adapter, the `ResponseBodyAdvice` beans that apply to the controller, and the action's `@JsonView` and
@@ -578,6 +611,37 @@ deployment whose reverse proxy already sends these headers can set `grails.secur
only explicitly configured headers on proxied requests. See the xref:security[Security] section of the user guide and
the xref:upgrading#upgrading80x[upgrade guide] for details.
+==== Nonce-based Content Security Policy
+
+`grails.security.headers.content-security-policy.value` can name a per-request nonce with the `+{nonce}+` placeholder
+that Spring Security 7.2 introduced, so a policy can allow an inline script or style by nonce rather than with
+`'unsafe-inline'`:
+
+[source,yaml]
+.grails-app/conf/application.yml
+----
+grails:
+ security:
+ headers:
+ content-security-policy:
+ enabled: true
+ value: "script-src 'self' 'nonce-{nonce}'"
+----
+
+A view renders the request's nonce with the new `` tag, as in `
+
+----
+
+The link:{gspTagsRef}javascript.html[javascript] tag adds the nonce to the inline script it writes.
+Code outside a view, such as a controller or a service, reads the nonce with `ContentSecurityPolicyNonce.nonceOf(request)` from the `grails.web.http` package, which returns `null` when the request carries none.
+It compiles under `@GrailsCompileStatic` as well as in dynamic code, and it reads the nonce whichever of Grails or Spring Security generated it.
+A script or stylesheet loaded from the application's own origin, such as an asset, is allowed by `'self'` and needs no nonce.
+
+`_csp` is also the attribute Spring Security's `ContentSecurityPolicyNonceGeneratingFilter` sets by default, so a view renders the right nonce whichever of the two generated it, and the header carries the same nonce:
+
+* When Spring Security's header configuration also writes a nonce-based policy, at Spring Boot's default filter order, Spring Security's nonce replaces the Grails one on the request.
+Spring Security's header is written first, and the Grails policy is not sent.
+* When the Spring Security filter chain is ordered ahead of `GrailsFilters.FIRST`, Grails keeps the nonce Spring Security put on the request and writes the Grails policy with it.
+
+The `cspNonce` and `javascript` tags read the nonce from `_csp`.
+If Spring Security's header configuration names another attribute with `nonceAttributeName`, render the nonce from that attribute instead.
+
+If the `_csp` attribute holds anything other than a Grails or Spring Security nonce, the policy is not sent, since a policy without the nonce would block every inline script the view gave one.
+Grails logs a warning the first time that happens.
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..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
@@ -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,7 @@ 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
+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.
-[source,groovy]
-----
-password = springSecurityService.encodePassword(password)
-----
-
-to
-
-[source,groovy]
-----
-password = springSecurityService.encodePassword(password, username)
-----
+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/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-doc/src/en/guide/security/securityPlugins/springSecurity/core/miscProperties.adoc b/grails-doc/src/en/guide/security/securityPlugins/springSecurity/core/miscProperties.adoc
index fa466791d27..1d95ee8d883 100644
--- a/grails-doc/src/en/guide/security/securityPlugins/springSecurity/core/miscProperties.adoc
+++ b/grails-doc/src/en/guide/security/securityPlugins/springSecurity/core/miscProperties.adoc
@@ -73,6 +73,10 @@ under the License.
|`true`
|Whether caching `SavedRequest` can trigger the creation of a session
+|requestCache.ignoredPatterns
+|`['/favicon.*', '/apple-touch-icon*.png', '/manifest.json', '/manifest.webmanifest', '/browserconfig.xml', '/.well-known/appspecific/com.chrome.devtools.json']`
+|Path patterns, relative to the context path, of requests that are never saved as the page to redirect to after a login. Browsers and their tools request these on their own, so a denied one would otherwise replace the page the user asked for. Set to `[]` to save every request
+
|roleHierarchy
|_none_
|Hierarchical role definition. See <>
diff --git a/grails-doc/src/en/guide/security/securityPlugins/springSecurity/core/passwords/locking.adoc b/grails-doc/src/en/guide/security/securityPlugins/springSecurity/core/passwords/locking.adoc
index 3f5a9d122b3..4a71685fc4d 100644
--- a/grails-doc/src/en/guide/security/securityPlugins/springSecurity/core/passwords/locking.adoc
+++ b/grails-doc/src/en/guide/security/securityPlugins/springSecurity/core/passwords/locking.adoc
@@ -197,6 +197,8 @@ If the `cacheUsers` configuration property is set to `true`, Spring Security cac
If you enable this feature, you must remove any cached instances after making a change that affects login. If you do not remove cached instances, even though a user's account is locked or disabled, logins succeed because the database is bypassed. By removing the cached data, you force at trip to the database to retrieve the latest updates.
+The cache stores users by value: each lookup is given a copy, made by serializing the user, so erasing the password of the user that is signed in, which the authentication manager does by default, leaves the cached user with the password it is checked against. A user with a field that cannot be serialized is not cached and is loaded on every sign-in, with a warning; mark such a field `transient`. Changing a user read from the cache changes only that copy, so put it back with `userCache.putUserInCache` to change what is cached. In a native image the plugin registers its own user classes for this. A user class or id type of your own needs serialization metadata, which `traceNativeMetadata` records when the login form is listed in `forms`.
+
Here is a sample Quartz job that demonstrates how to find and disable users with passwords that are too old:
[source,groovy]
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/theWebLayer/controllers/controllerExceptionHandling.adoc b/grails-doc/src/en/guide/theWebLayer/controllers/controllerExceptionHandling.adoc
index c4b0eb39ba8..014f3dc6b9c 100644
--- a/grails-doc/src/en/guide/theWebLayer/controllers/controllerExceptionHandling.adoc
+++ b/grails-doc/src/en/guide/theWebLayer/controllers/controllerExceptionHandling.adoc
@@ -148,3 +148,36 @@ 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. 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
+----
+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 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. 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, 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-doc/src/en/guide/theWebLayer/urlmappings/mappingHTTP.adoc b/grails-doc/src/en/guide/theWebLayer/urlmappings/mappingHTTP.adoc
index a3fa27a86ae..149cdc8c34d 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,35 @@ 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`:
+
+* A browser cannot send it from an HTML form. Call it from JavaScript or another HTTP client.
+* 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-doc/src/en/guide/upgrading/upgrading90x.adoc b/grails-doc/src/en/guide/upgrading/upgrading90x.adoc
index 9b4cb68887c..8a769c10e22 100644
--- a/grails-doc/src/en/guide/upgrading/upgrading90x.adoc
+++ b/grails-doc/src/en/guide/upgrading/upgrading90x.adoc
@@ -17,10 +17,9 @@ specific language governing permissions and limitations
under the License.
////
-=== Upgrade Instructions for Grails and Related Dependencies
+=== Upgrade Instructions for Grails 8 to Grails 9
-To ensure compatibility with Grails {version}, please review the following upgrade instructions carefully.
-This guide outlines the necessary steps and warnings to upgrade your Grails project from Grails 8.x to Grails 9.
+This guide outlines the changes introduced in Grails 9 and the steps required to upgrade your application.
[TIP]
====
@@ -38,10 +37,171 @@ skill 'org.apache.grails.skills:grails-9-upgrade:{version}'
==== 1. Groovy 6
-Grails 9 builds on Groovy {groovyVersion} and the matching Spock {spockVersion}; Java 21, Spring Boot {springBootVersion} and Spring Framework are unchanged from Grails 8.
+Grails 9 builds on Groovy {groovyVersion} and the matching Spock {spockVersion}; Java 21 is unchanged from Grails 8.
The Grails BOM manages Groovy and Spock, so remove any version an application pins for them and review the https://groovy-lang.org/releasenotes/groovy-6.0.html[Groovy 6 release notes] for language changes that affect application code.
-==== 2. GPars Integration Deprecated in Favour of Groovy Concurrency
+==== 2. Spring Boot 4.2 and Spring Framework 7.1
+
+Grails 9 moves from Spring Boot 4.1 and Spring Framework 7.0, which Grails 8 uses, to Spring Boot {springBootVersion} and Spring Framework {springVersion}.
+The managed versions that change include Spring Security 7.2, Spring Data 2026.1, Micrometer 1.18 and Reactor 2026.0.
+Review 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] for the changes that affect your application.
+The ones most likely to affect a Grails application are:
+
+* *`server.forward-headers-strategy: framework` reads only the `+X-Forwarded-*+` headers by default.*
+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.*
+`server.tomcat.servlet.use-relative-redirects`, renamed from `server.tomcat.use-relative-redirects`, now defaults to `true`, Tomcat's own default.
+A redirect sent through `HttpServletResponse.sendRedirect` with a path, such as a controller `chain` call, a Spring Security redirect or a `redirect:` view name, now has a relative `Location` header instead of an absolute URL.
+A controller `redirect` sets the `Location` header itself and still sends an absolute URL unless you pass `absolute: false`.
+Browsers resolve relative locations; set the property to `false` if a client or test expects an absolute URL.
+
+* *`TestRestTemplate` is deprecated for removal.*
+Spring Framework 7.1 deprecates `RestTemplate`, and Spring Boot 4.2 deprecates `TestRestTemplate` and `@AutoConfigureTestRestTemplate` with it.
+Move `@SpringBootTest` tests to `RestTestClient`, which `@AutoConfigureRestTestClient` injects:
++
+[source,groovy]
+----
+// Before
+import org.springframework.boot.resttestclient.TestRestTemplate
+import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureTestRestTemplate
+
+@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
+@AutoConfigureTestRestTemplate
+class BookApiSpec extends Specification {
+ @Autowired TestRestTemplate rest
+}
+
+// After
+import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureRestTestClient
+import org.springframework.test.web.servlet.client.RestTestClient
+
+@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
+@AutoConfigureRestTestClient
+class BookApiSpec extends Specification {
+ @Autowired RestTestClient client
+}
+----
+
+* *A problem detail no longer gets the request path as its `instance`.*
+RFC 9457 defines `instance` as a URI that identifies the specific occurrence of a problem, so Spring Framework 7.1 no longer sets it to the request path when a handler method returns a `ProblemDetail` or an `ErrorResponse`.
+`respond` follows it: a `ProblemDetail` or `ErrorResponse` it writes, and the problem it writes for validation errors, no longer get one either.
+A client that reads `instance` gets it only where the application sets it: in a `ResponseEntityExceptionHandler` for Spring MVC controllers, and on the problem an action responds with, including one `validationProblemDetailFactory.create(errors)` makes for validation errors:
++
+[source,groovy]
+----
+ProblemDetail problem = validationProblemDetailFactory.create(book.errors)
+problem.instance = URI.create("urn:uuid:${UUID.randomUUID()}")
+respond problem
+----
+
+* *Spring MVC no longer detects the JAXB XML converter.*
+Spring Framework 7.1 stops auto-detecting the JAXB message converter for server applications.
+Grails `render` and `respond` write XML through Grails' own converters and are unaffected.
+A Spring MVC `@RestController` that returns JAXB-annotated objects needs the converter registered explicitly, as the Spring Framework 7.1 release notes show.
+
+* *Tests load static nested `@Configuration` classes from their superclasses and enclosing classes.*
+The Spring TestContext Framework used to ignore such a class unless its class hierarchy declared `@ContextConfiguration`, and now adds it to the test's application context.
+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.
+
+* *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.
+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, and neither is a failure inside `g:include`, whose error page is rendered inside a page that goes on to answer the request.
+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.
+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`.
+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`.
+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 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 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]
+====
+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`.
+Spring Boot 4.2 can also make the application fail to start while such a property is left: set `spring.properties.migrator.fail` to `on-warning` to fail on renamed and removed properties, or to `on-error` to fail on removed ones only.
+The default, `never`, only logs them.
+====
+
+==== 3. graphql-java 26 for GraphQL Applications
+
+Spring Boot 4.2 manages graphql-java 26, so applications using the GraphQL plugin (`grails-data-graphql`) move from graphql-java 25 to graphql-java 26.1.
+graphql-java 26.0 contains breaking changes, listed in its https://github.com/graphql-java/graphql-java/releases/tag/v26.0[release notes].
+The ones that can affect a Grails application are:
+
+* *Query complexity limits are enforced by default.*
+A query nested more than 100 levels deep, or selecting more than 100,000 fields, now fails validation with a `MaxQueryDepthExceeded` or `MaxQueryFieldsExceeded` error.
+To raise the limits, or to turn them off, set new defaults when the application starts, for example in `BootStrap.groovy`:
++
+[source,groovy]
+----
+import graphql.validation.QueryComplexityLimits
+
+class BootStrap {
+
+ def init = {
+ QueryComplexityLimits.setDefaultLimits(QueryComplexityLimits.newLimits()
+ .maxDepth(150)
+ .maxFieldsCount(200_000)
+ .build())
+ // or, to turn the limits off:
+ // QueryComplexityLimits.setDefaultLimits(QueryComplexityLimits.NONE)
+ }
+}
+----
++
+graphql-java's parser separately rejects a query nested more than about 165 levels deep, so a `maxDepth` above that has no effect.
+
+* *Schemas built in code are validated like schemas built from SDL.*
+A required argument or input field (non-null with no default value) can no longer be deprecated.
+The schema the plugin generates never deprecates an argument or an input field, but arguments and input types an application adds through a `GraphQLSchemaInterceptor` must follow the rule.
+
+* *Additional schema types must be named types.*
+`GraphQLSchemaInterceptor.interceptSchema` still receives the additional types as a `Set`, and the plugin unwraps list and non-null wrappers before it builds the schema, so existing interceptors need no change.
+Code that builds a `GraphQLSchema` directly must pass `GraphQLNamedType` instances to `GraphQLSchema.Builder.additionalTypes`.
+
+The other breaking changes (the validation rule filter, the removal of `DirectiveInfo`, and the JSpecify nullability annotations) only affect code that uses graphql-java directly.
+The nullability annotations document existing behavior and do not change what graphql-java returns at runtime.
+
+The plugin continues to use graphql-java-extended-scalars 24.0, its latest release, which works with graphql-java 26.1.
+
+==== 4. GPars Integration Deprecated in Favour of Groovy Concurrency
Groovy 6 brings a unified concurrency and parallel-processing toolkit into core under https://groovy-lang.org/releasenotes/groovy-6.0.html#concurrency-toolkit[GEP-18: Integrated Concurrency and Parallel Processing]. The `groovy.concurrent` package provides `Awaitable`, `DataflowVariable`, `Actor`, `Agent`, `Pool`, `ParallelScope` and the parallel collection methods such as `eachParallel` and `collectParallel`. The Groovy release notes describe the toolkit as modernising the patterns from GPars around virtual threads, structured concurrency and Groovy 6's `async`/`await`, and state that previous users of GPars will find much of its functionality there.
@@ -66,7 +226,7 @@ Applications that use GPars directly, for example `GParsPool.withPool { list.eac
NOTE: Groovy 6 marks the concurrency toolkit as incubating. The Grails modules that build on it expose only the Grails `Promise` and `EventBus` contracts, so changes to the Groovy API in later Groovy releases are absorbed by Grails rather than by application code.
-==== 3. Groovy Code Is Compiled with invokedynamic
+==== 5. Groovy Code Is Compiled with invokedynamic
Grails 8 compiles every Groovy source set of an application without invokedynamic (`grails { indy = false }` was the default). Grails 9 leaves the setting unset, so the Groovy compiler's own default applies, and on Groovy 6 that is invokedynamic. An application that set `grails { indy = true }` can remove the line. Build logic that read the property, for example `grails.indy.get()`, must allow for it having no value now: use `grails.indy.getOrElse(true)` or check `grails.indy.present`.
@@ -86,7 +246,7 @@ Classic call sites on Groovy 6 need `org.apache.groovy:groovy-callsite` on the c
A library compiled with classic call sites needs the module too, whatever the application's own setting, because Groovy 6 loads such a class only with it; the failure is a `NoClassDefFoundError` naming `org.codehaus.groovy.runtime.callsite.CallSiteArray`. Spock 2.5, Geb 8 and the Asset Pipeline 5.2 are compiled with invokedynamic, but `org.testcontainers:testcontainers-spock` is not, so an application that uses it declares `testRuntimeOnly 'org.apache.groovy:groovy-callsite'` next to it.
-==== 4. XML Web Support Moves to a Separate Module
+==== 6. XML Web Support Moves to a Separate Module
XML conversion, request-body binding, and REST renderers now live in the optional
`grails-xml` module. In Grails 9 the web starter still brings it, and so does `grails-web-boot`, which the
@@ -142,14 +302,14 @@ several, so their `groovyPageLocator` and `rendererRegistry` properties are no l
application sets them.
Without the module, nothing renders XML except what the application provides, such as markup views, and `respond`
-treats XML as any format nothing renders (see section 13): it answers in the next type the client accepts that the
+treats XML as any format nothing renders (see section 15): it answers in the next type the client accepts that the
action responds in, and a client that accepts any type, by sending `*/*` or no `Accept` header, or a browser, in the
first format the action lists that it can render the value in, so an action that lists `['xml', 'json']` answers those
clients in JSON. A markup view renders XML for an action that has one; for an action without one, the client's next
type is tried. Where no type the client accepts can be rendered, `respond` sends a `406 Not Acceptable` error, or a
`404` one for validation errors where the client accepts one of the action's formats, so that the application's error
pages apply, and writes a `ProblemDetail` as
-`application/problem+json` (see section 11). An XML request body is not read and raises no error, while the
+`application/problem+json` (see section 13). An XML request body is not read and raises no error, while the
request parameters bind as they do for a request without a body, except that binding it to a collection with `bindData`
fails, as for any body of a type nothing binds; and `request.XML` throws an
`IllegalStateException` that names the module, while a class compiled with `@CompileStatic` or `@GrailsCompileStatic`
@@ -193,11 +353,11 @@ APIs.
This change does not affect Grails plugin descriptors. Plugin metadata continues to be generated and
published in its existing descriptor format; `grails-xml` concerns application HTTP payloads only.
-==== 5. Opt Into Spring JSON Conversion
+==== 7. Opt Into Spring JSON Conversion
Each JSON and XML path keeps its Grails 8 output by default in Grails 9, and has a setting that opts into the
Jackson-based one. A `ProblemDetail` is the exception: `respond` writes it as Spring MVC writes it, whatever the
-settings, with the exceptions section 11 lists. The smaller changes that apply whatever the settings, such as `Accept`
+settings, with the exceptions section 13 lists. The smaller changes that apply whatever the settings, such as `Accept`
headers matched whatever their case, are in sections 4, 7, 9, 11, 13, 14 and 16, and in this section, where `grails-converters`
now brings Boot's `JsonMapper`, which Spring MVC's JSON converter then writes with.
@@ -235,12 +395,12 @@ now brings Boot's `JsonMapper`, which Spring MVC's JSON converter then writes wi
| unchanged until legacy XML conversion is removed in Grails 11
| `grails.exceptionresolver.springHandlers`
-| Exceptions actions throw, resolved by Spring MVC's `@ExceptionHandler` methods (see section 15)
+| Exceptions actions throw, resolved by Spring MVC's `@ExceptionHandler` methods (see section 17)
| `false`
| `true` in Grails 10
| `grails.controllers.responseBody`
-| Values of actions annotated `@ResponseBody`, written by Spring MVC as the body (see section 16)
+| Values of actions annotated `@ResponseBody`, written by Spring MVC as the body (see section 18)
| `false`
| `true` in Grails 10
|===
@@ -310,7 +470,7 @@ for the type, or a converter of another library, it is labelled with a JSON type
`JsonMapper` too, and Spring MVC's JSON converter writes with it rather than with a mapper of its own.
The standard Jackson converter uses an isolated mapper derived from Boot's configured `JsonMapper` for every value but
-a `ProblemDetail`, which Spring's converter writes with Boot's mapper itself (see section 11).
+a `ProblemDetail`, which Spring's converter writes with Boot's mapper itself (see section 13).
It renders domain classes with the same Jackson serializer as the `JsonMapper` itself does when
`grails.converters.json.domain.jackson.enabled` is set, and as `render ... as JSON` does with
`grails.converters.json.legacy` set to `false` (see the section on domain classes below): the
@@ -361,10 +521,10 @@ Controller unit tests use Boot's Jackson configuration and the same setting. Sup
`JsonMapperBuilderCustomizer` from a nested Spring `@Configuration` class, so Boot can see it before
evaluating its conditional beans. A mapper registered by the deprecated `doWithSpring` callback or by
`beanRegistrar()` is too late to make Boot back off. Named JSON
-configurations work through `render` and `respond` in `ControllerUnitTest`. Section 14 covers the
+configurations work through `render` and `respond` in `ControllerUnitTest`. Section 16 covers the
other changes to web unit tests.
-==== 6. JSON Converter Customization Moves to Jackson
+==== 8. JSON Converter Customization Moves to Jackson
The `grails.converters.JSON.registerObjectMarshaller(...)` API remains supported for
`render ... as JSON` and converter-based rendering. Registering a marshaller does not change the
@@ -453,7 +613,7 @@ property of `JsonRenderer` and `JsonCollectionRenderer` beans, which selects one
the `renderJson(JSON, RenderContext)` method their subclasses override to render with the legacy converter. This
timetable does not deprecate `JSON.registerObjectMarshaller(...)`.
-==== 7. `grails.converters.JSON` Can Write JSON With Spring Boot's JsonMapper
+==== 9. `grails.converters.JSON` Can Write JSON With Spring Boot's JsonMapper
In Grails 9, `render ... as JSON`, `respond` for a JSON request and every other use of `grails.converters.JSON` still
render JSON as Grails 8 did, by default (see <>). Setting
@@ -730,7 +890,7 @@ JSON.registerObjectMarshaller(Locale) { Locale locale -> locale.toString() }
JSON.registerObjectMarshaller(byte[]) { byte[] bytes -> bytes as List }
----
-==== 8. Domain Classes Render as Jackson Beans of Their Persistent Properties
+==== 10. Domain Classes Render as Jackson Beans of Their Persistent Properties
With `grails.converters.json.legacy` set to `false`, the JSON converter renders a domain class instance with Jackson's own
bean serializer, which Grails shapes to the domain class, as `DomainClassMarshaller` rendered it in Grails 8, with these
@@ -788,7 +948,7 @@ The mapper renders associated instances as references of their id, such as `{"id
or in full with `grails.converters.json.default.deep`, and proxies as the instances they proxy, and names the id of a
reference as the referenced class names it.
-==== 9. Rendering Single Values as JSON
+==== 11. Rendering Single Values as JSON
In Grails 8, rendering a single enum value with `render(Role.HEAD as JSON)` threw a `ConverterException`.
It now produces the JSON string `"HEAD"`. The default enum marshaller uses the enum name, including when the
@@ -803,7 +963,7 @@ no longer throws a `ConverterException` merely because the root is a scalar.
`JSONWriter` accepts a single value outside any object or array whatever the `grails.converters.json.legacy`
setting, as the section on writing JSON with Spring Boot's `JsonMapper` describes.
-==== 10. Opt Into Jackson JSON Request Binding
+==== 12. Opt Into Jackson JSON Request Binding
Grails 9 retains `JsonSlurper` request binding by default and logs a startup deprecation notice. As
in Grails 8, an application `JsonSlurper` bean, for example one using `JsonParserType.LAX`, replaces
@@ -848,7 +1008,7 @@ as `BigDecimal` rather than `Double`, so binding a request value such as `1.15`
retains exactly the digits the request sent. Whole numbers bind as `Integer`, `Long`, or `BigInteger`
when too large for a `Long`, as with the legacy parser.
-==== 11. REST Validation Errors Use RFC 9457 Problems
+==== 13. REST Validation Errors Use RFC 9457 Problems
With `grails.web.rendering.json.spring: true`, `respond()` renders Spring `Errors` as
`application/problem+json` instead of the legacy `{"errors": [...]}` body. Grails 9 retains the legacy
@@ -894,9 +1054,10 @@ Applications can also inject the factory when they need to create or customize t
When `respond` receives a `ProblemDetail`, it hands it to the handler Spring MVC's handler adapter writes a
`ResponseEntity` with, so the problem is written as a Spring MVC controller method that returns it is written: the
application's `ResponseBodyAdvice` beans apply to it as to a method of the controller, and its
-`ErrorResponse.Interceptor` beans see it. The response has the status the problem carries, and an absent `instance` is
-set to the current resource path. A `status` argument decides the status instead, as the status of a `ResponseEntity`
-does in Spring MVC: a problem that carries another keeps its own, and Spring MVC logs a warning. A Spring
+`ErrorResponse.Interceptor` beans see it. The response has the status the problem carries, and a problem without an
+`instance` is written without one, as Spring MVC writes it. A `status` argument decides the status instead, as the
+status of a `ResponseEntity` does in Spring MVC: a problem that carries another keeps its own, and Spring MVC logs a
+warning. A Spring
`ErrorResponse`, such as an `ErrorResponseException`, is answered with its problem, whose message codes are resolved with
the application's messages as Spring MVC's `ResponseEntityExceptionHandler` resolves them, and with its status and
headers, where Grails 8 wrote it as a bean with a 200. Spring MVC's content
@@ -951,14 +1112,14 @@ ValidationProblemDetailFactory includingRejectedValues(MessageSource messageSour
}
----
-==== 12. HAL Rendering
+==== 14. HAL Rendering
Existing Grails HAL JSON renderers remain available through explicit renderer registration.
Adding `spring-boot-starter-hateoas` alone does not register a Grails renderer for Spring HATEOAS
`EntityModel` values. Return those models from a Spring MVC controller or provide an explicit Grails
renderer for the desired media type.
-==== 13. Grails Format Resolution and Spring MVC Content Negotiation
+==== 15. Grails Format Resolution and Spring MVC Content Negotiation
Grails format resolution -- `withFormat`, `respond`, and `response.format` -- applies the `grails.mime.*`
rules. Spring MVC keeps its own content negotiation: an `@RestController`, an actuator endpoint or any other
@@ -982,7 +1143,7 @@ target implements now handles its bodies in a content type no creator for `Objec
interface of `java.lang.Class`, such as `Serializable`, no longer matches every class, nor does a renderer registered for
one stand in as the fallback renderer of JSON and markup views. A value Spring
rejects, such as a quality value above 1, is still read as Grails 8 read it, except where `respond` writes a
-`ProblemDetail` as without a view, which is answered as Spring MVC answers such a client (see section 11). Parameter names are read ignoring case,
+`ProblemDetail` as without a view, which is answered as Spring MVC answers such a client (see section 13). Parameter names are read ignoring case,
as Spring reads them, so `text/html;Q=0.1` has the quality 0.1, where Grails 8 read only a lower-case `q`. The problem types of RFC 9457,
`application/problem+json` and `application/problem+xml`, are the `json` and `xml` formats unless `grails.mime.types`,
or a `MimeTypeProvider` bean, such as a renderer or binding source creator, provides a type of that name. A binding
@@ -1000,7 +1161,7 @@ to `all`, so an action answered with its first format;
action responds in XML. A client that sends only a problem type is therefore answered as one that asks for that format:
`respond` sends `406 Not Acceptable` for an action that does not respond in it, where Grails 8 answered in the action's
first format, and `withFormat` runs no block where it has neither one for that format nor a `*` one, where Grails 8 ran
-its first block. `respond` writes a `ProblemDetail` in the type section 11 describes, whatever format this selects,
+its first block. `respond` writes a `ProblemDetail` in the type section 13 describes, whatever format this selects,
in XML only where the action responds in XML, and any other value as the format's own type, such as `application/xml`. In `Content-Type`, Grails 8 gave `null`: a body a client
sends as `application/problem+json` is now the `json` format, which `withFormat` selects and the JSON binding source
binds, and one sent as `application/problem+xml` the `xml` format, which the XML binding source of `grails-xml` binds.
@@ -1038,7 +1199,7 @@ Spring MVC asks for its formats while it starts. Spring MVC negotiates
with them only when the application enables parameter negotiation with
`spring.mvc.contentnegotiation.favor-parameter: true`. Spring Boot leaves it disabled, so after the
upgrade `?format=json` still does not change what a Spring MVC endpoint returns. Where it is enabled, it also decides the type `respond`
-writes a `ProblemDetail` in, as for a Spring MVC controller (see section 11). Browser formats such
+writes a `ProblemDetail` in, as for a Spring MVC controller (see section 13). Browser formats such
as `html` and `js` are not registered, preserving Spring's reflected-file-download protection.
Where a format has several media types, an `application/*` one is preferred over a `text/*` one, and Boot's
`spring.mvc.contentnegotiation.media-types.*` overrides these defaults. Invalid names are skipped.
@@ -1052,7 +1213,7 @@ method of `DefaultAcceptHeaderParser` takes the requested `MimeType`, where it t
that overrode the Grails 8 method no longer overrides it. The settings are read once for each application context, which a unit test keeps for all the features of
its spec, so a spec sets them in `doWithConfig` rather than in a feature.
-==== 14. Web Unit Tests Set Up More of the Web Layer
+==== 16. Web Unit Tests Set Up More of the Web Layer
Web test traits such as `ControllerUnitTest` and `TagLibUnitTest` now always include the
`restResponder` plugin, even when a spec overrides `getIncludePlugins()`. They also provide JSON
@@ -1067,7 +1228,7 @@ on the test classpath, without loading the XML plugin's dependency graph. A spec
asserts on the beans in its application context sees these additions. The manager is built as Spring MVC builds it, from
`spring.mvc.contentnegotiation.*`, which a spec sets in `application.yml` or `doWithConfig`, and the spec's
`WebMvcConfigurer` beans, so `respond` writes a `ProblemDetail` in a unit test in the type it writes it in for the
-application (see section 11). The `format` parameter that `favor-parameter` reads is one the spec adds to the request,
+application (see section 13). The `format` parameter that `favor-parameter` reads is one the spec adds to the request,
with `request.addParameter`, as a query parameter is added, not `params.format`, which stands for the format a URL
mapping gives and which Spring MVC does not read either. A spec for an application that declares `@EnableWebMvc`, which
turns off Spring Boot's Spring MVC auto-configuration and with it those properties, declares the manager the
@@ -1102,7 +1263,7 @@ own, a session locale resolver among them. Without `grails-xml` on the test clas
rather than to a `String` of XML, or reading `request.XML` fails with an `IllegalStateException` that names the module. `GrailsUnitTest` and `ServiceUnitTest` do
not load XML or the web plugins just because those modules are on the classpath. See <>.
-==== 15. Opt Into Spring MVC Exception Handlers
+==== 17. Opt Into Spring MVC Exception Handlers
Spring MVC resolves an exception with the `@ExceptionHandler` methods of the controller and of the `@ControllerAdvice`
beans only for a handler method, which a Grails action is not, so such methods, and Spring Boot's handler of
@@ -1121,7 +1282,14 @@ grails:
springHandlers: true
----
-==== 16. Actions Can Return Spring MVC Responses
+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`,
`HttpHeaders`, a `StreamingResponseBody` or a `ResponseBodyEmitter` has it written as Spring MVC writes what a handler
@@ -1144,7 +1312,7 @@ grails:
responseBody: true
----
-==== 17. Generated GORM Identity and Version Properties Stay Within Domain Classes
+==== 19. Generated GORM Identity and Version Properties Stay Within Domain Classes
Grails 9 no longer adds generated `id` and `version` properties to a non-domain superclass of a domain class.
Previously, these properties could be added to a shared abstract base class, causing command objects extending that same base class to inherit persistence properties and fail validation for `id` and `version`.
@@ -1171,7 +1339,7 @@ When upgrading an affected application:
See xref:theWebLayer#commandObjects[Command Objects] for a trait-based alternative to sharing a non-domain superclass with a domain class.
-==== 18. RxGORM Runs on RxJava 3
+==== 20. RxGORM Runs on RxJava 3
RxGORM, the reactive variant of GORM in `org.apache.grails.data:grails-datamapping-rx`, is built on RxJava 3 instead of RxJava 1.
Its dependency is now `io.reactivex.rxjava3:rxjava`, and the RxJava 1 artifact `io.reactivex:rxjava` is no longer on the classpath of an application that only uses RxGORM.
@@ -1220,7 +1388,7 @@ A datastore implementation of RxGORM built for Grails 8 or earlier, such as the
The `RxEntity` domain model has had no datastore implementation for several releases and its removal is under discussion for Grails 9, so an application that implements `RxEntity` should plan to move to `GormEntity` with the RxJava data services, which work on every GORM datastore. The import and blocking-call changes above apply to both.
The `rx-mongodb` profile feature is removed, because the `org.grails.plugins:rx-mongodb` plugin it added has had no release since GORM 6.1 and has never been published to Maven Central, so an application generated with it could not resolve its dependencies.
-==== 19. RxJava 1 and RxJava 2 Async and Events Modules Are Deprecated
+==== 21. RxJava 1 and RxJava 2 Async and Events Modules Are Deprecated
The RxJava 1 and RxJava 2 implementations of the Grails promise and event bus APIs, `grails-async-rxjava`, `grails-async-rxjava2`, `grails-events-rxjava` and `grails-events-rxjava2`, are deprecated for removal.
They keep working in Grails 9 and log a warning when their promise factory or event bus is created.
@@ -1230,19 +1398,19 @@ See <> and <>.
`grails-async-rxjava3` carries a `null` value as the RxJava 1 factory and every other promise factory do: `createPromise()` and `createPromise(Class)` give a promise whose `get()` returns `null`, a task that returns `null` resolves to `null`, and a `null` value keeps its place in the list that `onComplete`, `onError` and `waitAll` deliver.
`grails-async-rxjava2` does not: there `createPromise()` and `onComplete` over a list holding a bound promise of `null` fail with a `NullPointerException`, and a task that returns `null` resolves to the `java.lang.Void` class.
-==== 20. Spring Boot Registers the Character Encoding Filter
+==== 22. Spring Boot Registers the Character Encoding Filter
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.
-==== 21. A Configuration Key Below a Value That Is Not a Map Is Absent
+==== 23. A Configuration Key Below a Value That Is Not a Map Is Absent
In Grails 8, `getProperty` on `grailsApplication.config` answered a dotted key that runs past a value that is not a map with that value: `server.url.port` when `server.url` is a string, `server.ports.0` when `server.ports` is a list, or `grails.gorm.default.constraints.nullable` when `grails.gorm.default.constraints` is a closure from `application.groovy`. `containsProperty` of such a key was `true`. In Grails 9 the key is absent: `getProperty` returns `null` or the default, `containsProperty` returns `false`, and `navigate` answers `null`.
@@ -1274,3 +1442,14 @@ A property source of lower precedence that sets the deeper key now answers it. W
* Code that reads a child of a string or a closure and relied on being answered with the parent reads the parent instead.
* Code that read a whole list through a key ending in a whole number, such as `server.ports.0`, now gets the element; it reads the list as `server.ports`.
* A typed read with a default below such a value, such as `getProperty('x.y.enabled', Boolean, true)` when `x.y` is `false`, reads the parent, or the configuration sets the deeper key.
+
+==== 24. The Spring Security User Cache Stores Copies
+
+With `cacheUsers` enabled, the Spring Security plugin's user cache now stores users by value, so each lookup gets its own copy, made by serializing the user. Grails 8 stored the instance itself. The authentication manager erases the password of the user it signs in, and it erased the cached instance too: the next sign-in missed the cache and loaded the user again. A copy is erased instead, so the cached user keeps its password and the user kept in the session holds none. In a native image the plugin registers its own user classes for this. A user class or id type of your own needs serialization metadata, which `traceNativeMetadata` records when the login form is listed in `forms`.
+
+===== Required Actions
+
+* A user class of your own is serialized, as `UserDetails` is `Serializable`. A field that cannot be serialized, such as a reference to a domain instance, makes the user uncached: it is loaded on every sign-in, and a warning is logged. Mark such a field `transient`, or hold its id instead.
+* Code that changed a user it read from `userCache` and expected the cache to see the change puts the user back with `userCache.putUserInCache`.
+* To store users by reference, as Grails 8 did, set `cacheConfig` on the `userCache` bean to a `MutableConfiguration` with `setStoreByValue(false)`.
+
diff --git a/grails-doc/src/en/ref/Controllers/respond.adoc b/grails-doc/src/en/ref/Controllers/respond.adoc
index b5b33abafe7..23022689bce 100644
--- a/grails-doc/src/en/ref/Controllers/respond.adoc
+++ b/grails-doc/src/en/ref/Controllers/respond.adoc
@@ -89,7 +89,8 @@ Supported `arguments`:
A Spring `ProblemDetail` is written as Spring MVC writes one that a handler method returns: `respond` hands it to the
handler Spring MVC's handler adapter writes a `ResponseEntity` with, so the application's `ResponseBodyAdvice` beans
apply to it as to a method of the controller, and its `ErrorResponse.Interceptor` beans see it. The response has the
-status the problem carries, and an absent `instance` is set to the current resource path. A `status` argument decides
+status the problem carries, and a problem without an `instance` is written without one, as Spring MVC writes it; set the
+`instance` where the application identifies the occurrence of a problem. A `status` argument decides
the status of the response, as the status of a `ResponseEntity` does in Spring MVC: a problem that carries another keeps
its own, and Spring MVC logs a warning. Its properties are written by the mapper of Spring Boot's converter, as a Spring
MVC controller writes them: a domain class instance, validation errors or a value that leads back to itself among them is
diff --git a/grails-doc/src/en/ref/Tags - GSP/cspNonce.adoc b/grails-doc/src/en/ref/Tags - GSP/cspNonce.adoc
new file mode 100644
index 00000000000..38671591d0b
--- /dev/null
+++ b/grails-doc/src/en/ref/Tags - GSP/cspNonce.adoc
@@ -0,0 +1,57 @@
+////
+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.
+////
+
+
+== cspNonce
+
+
+
+=== Purpose
+
+
+Renders the nonce of the request's nonce-based Content Security Policy, for the `nonce` attribute of an inline script or style.
+
+
+=== Examples
+
+
+[source,xml]
+----
+
+
+
+----
+
+
+=== Description
+
+
+A policy configured with `grails.security.headers.content-security-policy.value` names the nonce with the `+{nonce}+` placeholder, for example `script-src 'self' 'nonce-+{nonce}+'`.
+Each request then carries a nonce of its own, which this tag renders, and the policy the response carries names the same nonce.
+See link:{guidePath}/security.html[Security] for configuring the policy.
+
+The tag renders the nonce Spring Security's `ContentSecurityPolicyNonceGeneratingFilter` generated when that filter put one on the request, so it can be used with a policy Spring Security writes as well.
+
+It renders nothing when the request carries no nonce.
+
+The tag works in a statically compiled page as well as a dynamic one. Code outside a view, such as a controller, reads the nonce with `ContentSecurityPolicyNonce.nonceOf(request)` from the `grails.web.http` package.
diff --git a/grails-doc/src/en/ref/Tags - GSP/javascript.adoc b/grails-doc/src/en/ref/Tags - GSP/javascript.adoc
index 1a97be1fe71..2dab073a2b4 100644
--- a/grails-doc/src/en/ref/Tags - GSP/javascript.adoc
+++ b/grails-doc/src/en/ref/Tags - GSP/javascript.adoc
@@ -44,6 +44,7 @@ Includes JavaScript libraries and scripts as well as providing a shorthand for i
If you do not include a "src" attribute but instead provide a body, the result is an inline script.
+When the request carries the nonce of a nonce-based Content Security Policy, the inline script carries it in its `nonce` attribute, so the policy allows it to run.
If you are doing more advanced JavaScript and asset management we recommend checking out the Asset Pipeline plugin.
diff --git a/grails-gradle/plugins/build.gradle b/grails-gradle/plugins/build.gradle
index 25b8d9a7388..87e84e748ee 100644
--- a/grails-gradle/plugins/build.gradle
+++ b/grails-gradle/plugins/build.gradle
@@ -79,6 +79,11 @@ dependencies {
// Testing - Gradle TestKit is auto-added by java-gradle-plugin
testImplementation('org.spockframework:spock-core') { transitive = false }
testImplementation 'org.apache.groovy:groovy-test-junit5'
+ // The validators behind Grails' email and url constraints, so what traceNativeMetadata fills an email or URL
+ // field with is checked the way an application's save checks it, at the version grails-datamapping-validation uses.
+ testImplementation("commons-validator:commons-validator:$commonsValidatorVersion") {
+ transitive = false
+ }
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine'
// The asset pipeline plugin the Grails BOM manages, so the layout this plugin gives it is tested
// against the real one
diff --git a/grails-gradle/plugins/src/main/groovy/org/apache/grails/gradle/plugin/aot/ExtractApplicationTask.groovy b/grails-gradle/plugins/src/main/groovy/org/apache/grails/gradle/plugin/aot/ExtractApplicationTask.groovy
index 467793ce12f..15d62722d9b 100644
--- a/grails-gradle/plugins/src/main/groovy/org/apache/grails/gradle/plugin/aot/ExtractApplicationTask.groovy
+++ b/grails-gradle/plugins/src/main/groovy/org/apache/grails/gradle/plugin/aot/ExtractApplicationTask.groovy
@@ -37,11 +37,15 @@ import org.gradle.jvm.toolchain.JavaLauncher
import org.gradle.process.ExecOperations
/**
- * Unpacks an executable jar into the form an AOT cache is read against.
+ * Unpacks an executable jar or war into the form an AOT cache is read against.
*
- *
An executable jar loads its dependencies through a nested-jar class loader; the extracted form
- * loads them as ordinary jars on the classpath. A cache records the class path it saw, so only the
- * second is a layout a later run can reuse one against.
+ *
An executable archive loads its dependencies through a nested-jar class loader; the extracted
+ * form loads them as ordinary jars on the classpath. A cache records the class path it saw, so only
+ * the second is a layout a later run can reuse one against.
+ *
+ *
A war is extracted as a jar, with the libraries it provides beside its own and what it holds
+ * outside {@code WEB-INF} in the jar's {@code META-INF/resources}, which needs Spring Boot 4.2 or
+ * later in the war.
*
*
The work is done through injected services rather than through the project, so that nothing is
* reached at execution time that the configuration cache forbids.
@@ -52,7 +56,7 @@ import org.gradle.process.ExecOperations
@CompileStatic
abstract class ExtractApplicationTask extends DefaultTask {
- /** The archive to unpack, which has to be the one the cache will be trained against. */
+ /** The executable jar or war to unpack, which has to be the one the cache will be trained against. */
@InputFile
@PathSensitive(PathSensitivity.RELATIVE)
abstract RegularFileProperty getArchiveFile()
@@ -79,6 +83,16 @@ abstract class ExtractApplicationTask extends DefaultTask {
@Inject
abstract ExecOperations getExecOperations()
+ /**
+ * The name of the application the extraction writes for an archive of the given name: a jar
+ * keeps its name, and a war is written as a jar of the same name.
+ */
+ static String applicationFileName(String archiveFileName) {
+ archiveFileName.toLowerCase(Locale.ROOT).endsWith('.war') ?
+ archiveFileName.substring(0, archiveFileName.length() - 4) + '.jar' :
+ archiveFileName
+ }
+
@TaskAction
void extract() {
File target = destination.get().asFile
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..5a1f654e4d1 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,16 @@ 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}. One that does not, or that names anything else, fails
+ * the trace before the application is started.
+ *
+ * @since 9.0
+ */
+ abstract ListProperty
*
+ *
A request neither of those can make, with another method or with a body that is not a form, is
+ * declared whole. An action restricted to QUERY answers nothing else, and what writes a JSON response
+ * runs only for a client that asks for one:
Written to the application's sources rather than to the build directory: what an image was
* built from should be reviewable, and a trace is only as good as the paths someone thought of.
*
@@ -94,6 +111,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'
@@ -105,10 +125,22 @@ abstract class TraceNativeMetadataTask extends DefaultTask {
private static final Pattern FORM = Pattern.compile(/(?is)
+ *
+ *
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()
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 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. " +
"What it printed is in ${output}")
}
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 778831b87a8..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
@@ -115,6 +115,8 @@ class GrailsGradlePlugin implements Plugin {
private static final String ASSET_PIPELINE_PLUGIN = 'cloud.wondrify.asset-pipeline'
+ private static final String WAR_PLUGIN = 'war'
+
private static final int TRAINING_PORT = 18080
/** Not the training port: a trace and a training run are both a started application. */
@@ -1232,11 +1234,15 @@ ${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)
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')
@@ -1254,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)
@@ -1261,6 +1268,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
@@ -1530,6 +1568,9 @@ ${importStatements}
* archive is extracted, the extracted application is run and asked for its pages, and what the
* run recorded is left beside it. An application asks for this with
* {@code grails.aotCache.enabled}, and says which of its pages matter.
+ *
+ *
The archive is the executable war where the application applies the war plugin, as a
+ * generated application does, and the executable jar otherwise.
*/
protected void configureAotCache(Project project) {
AotCacheExtension extension = ((ExtensionAware) project.extensions.getByName('grails'))
@@ -1541,7 +1582,6 @@ ${importStatements}
extension.startTimeoutSeconds.convention(TRAINING_START_TIMEOUT_SECONDS)
project.pluginManager.withPlugin(SPRING_BOOT_PLUGIN) {
- TaskProvider> bootJar = project.tasks.named('bootJar')
Provider application = project.layout.buildDirectory.dir('aot-cache/application')
Provider launcher = trainingLauncher(project)
@@ -1550,7 +1590,7 @@ ${importStatements}
task.group = BasePlugin.BUILD_GROUP
task.description = 'Extracts the application, which is the form the cache is read against'
task.onlyIf { extension.enabled.get() }
- task.archiveFile.set(archiveFileOf(bootJar))
+ task.archiveFile.set(archiveFileOf(executableArchive(project)))
// The launcher rather than its path: this task is cacheable, and a path is where a
// JDK happens to live on the machine that ran the build. Set as the provider it is,
// so the toolchain is not resolved -- and a JDK not provisioned -- by every build
@@ -1565,7 +1605,8 @@ ${importStatements}
task.onlyIf { extension.enabled.get() }
task.dependsOn(extract)
task.applicationDirectory.set(application)
- task.archiveFileName.set(archiveFileOf(bootJar).map { RegularFile file -> file.asFile.name })
+ task.archiveFileName.set(archiveFileNameOf(executableArchive(project))
+ .map { String name -> ExtractApplicationTask.applicationFileName(name) })
// Beside the extracted application rather than inside it. Inside, the cache and its
// metadata land in the directory this task declares as its input, so writing them
// changes that input and the task can never be up to date -- every build would run
@@ -1599,8 +1640,37 @@ ${importStatements}
* task resolved while the build is configured is one every build pays for whether or not it
* asked for an archive.
*/
- private static Provider archiveFileOf(TaskProvider> bootJar) {
- bootJar.flatMap { Task task -> (Provider) task.property('archiveFile') }
+ private static Provider archiveFileOf(TaskProvider> archive) {
+ archive.flatMap { Task task -> (Provider) task.property('archiveFile') }
+ }
+
+ /** The name of the archive a task builds, which is known before the task has run, unlike its file. */
+ private static Provider archiveFileNameOf(TaskProvider> archive) {
+ archive.flatMap { Task task -> (Provider) task.property('archiveFileName') }
+ }
+
+ /**
+ * The executable archive the application ships: the war where it applies the war plugin, as a
+ * generated application does, and the jar otherwise.
+ *
+ *
Spring Boot extracts a war as of 4.2: its provided libraries, the embedded container among
+ * them, beside its own, and what sits outside {@code WEB-INF}, {@code src/main/webapp} included,
+ * in the extracted jar's {@code META-INF/resources}. The jar leaves {@code src/main/webapp} out,
+ * so a cache trained against the jar of an application that ships its war was trained against
+ * an application missing what the war serves. An application that switches its war off ships
+ * the jar.
+ *
+ *
Read as a task that consumes the archive is configured, by which time the build has applied
+ * its plugins and configured its archives.
+ */
+ private static TaskProvider> executableArchive(Project project) {
+ if (project.pluginManager.hasPlugin(WAR_PLUGIN)) {
+ TaskProvider> bootWar = project.tasks.named('bootWar')
+ if (bootWar.get().enabled) {
+ return bootWar
+ }
+ }
+ project.tasks.named('bootJar')
}
/**
diff --git a/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/ExtractApplicationTaskSpec.groovy b/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/ExtractApplicationTaskSpec.groovy
index 4c20f391ea9..63d744a2ba6 100644
--- a/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/ExtractApplicationTaskSpec.groovy
+++ b/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/ExtractApplicationTaskSpec.groovy
@@ -51,4 +51,16 @@ class ExtractApplicationTaskSpec extends Specification {
expect:
declared.isEmpty()
}
+
+ void 'the application extracted from #archive is #application'() {
+ expect: 'a jar keeps its name, and a war is written as a jar of the same name'
+ ExtractApplicationTask.applicationFileName(archive) == application
+
+ where:
+ archive | application
+ 'myapp-0.1.jar' | 'myapp-0.1.jar'
+ 'myapp-0.1.war' | 'myapp-0.1.jar'
+ 'MYAPP.WAR' | 'MYAPP.jar'
+ 'myapp.war.jar' | 'myapp.war.jar'
+ }
}
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..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
@@ -18,14 +18,55 @@
*/
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 ->
+ if (retryAfter) {
+ exchange.responseHeaders.add('Retry-After', '1')
+ }
+ exchange.sendResponseHeaders(status, -1)
+ exchange.close()
+ }
+ server.start()
+
+ expect:
+ RunPort.answersNotReady(server.address.port) == notReady
+
+ cleanup:
+ server?.stop(0)
+
+ where:
+ 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'() {
+ 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 1c27fb1687d..64317bb3d0e 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,7 +20,15 @@ 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
+import java.time.YearMonth
+
+import org.apache.commons.validator.routines.EmailValidator
+import org.apache.commons.validator.routines.RegexValidator
+import org.apache.commons.validator.routines.UrlValidator
import org.gradle.api.GradleException
import org.gradle.api.Project
import org.gradle.testfixtures.ProjectBuilder
@@ -35,6 +43,10 @@ import spock.lang.TempDir
*/
class TraceNativeMetadataTaskSpec extends Specification {
+ /** The validator Grails' {@code url} constraint builds, which accepts any scheme. */
+ private static final UrlValidator URL_CONSTRAINT = new UrlValidator((RegexValidator) null,
+ UrlValidator.ALLOW_ALL_SCHEMES + UrlValidator.ALLOW_2_SLASHES)
+
@TempDir
File temporaryFolder
@@ -159,6 +171,103 @@ 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 '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?tinyContact=a@b.example&tinyHomepage=ftp://e.example'])
+
+ 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
+ edgeContact ==~ /\d@example\.com/
+ tinyContact == 'a@b.example'
+ new URI(homepage).scheme == 'https' && new URI(homepage).host
+ (shortHomepage ==~ /https:\/\/example\.com\/\d+/) && shortHomepage.size() <= 24
+ siteHomepage == 'https://example.com'
+ plainHomepage == 'http://example.com'
+ ftpHomepage == 'ftp://example.com'
+ tinyHomepage == 'ftp://e.example'
+ phone ==~ /\d+/
+ colour ==~ /#[0-9a-f]{6}/
+ }
+
+ and: 'each address and link passes the check the email and url constraints make, and stays on example.com'
+ [sent.contact, sent.shortContact, sent.edgeContact].every { String email ->
+ EmailValidator.instance.isValid(email) && email.endsWith('@example.com')
+ }
+ [sent.homepage, sent.shortHomepage, sent.siteHomepage, sent.plainHomepage, sent.ftpHomepage].every { String url ->
+ URL_CONSTRAINT.isValid(url) && new UrlValidator().isValid(url) && new URI(url).host == 'example.com'
+ }
+
+ and: 'a hidden field is the page\'s own, so one that says nothing is sent saying nothing'
+ 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'])
@@ -252,6 +361,23 @@ exec '${new File(System.getProperty('java.home'), 'bin/java').absolutePath}' \\
requested.any { it.startsWith('POST /protected-save') && it.contains('secretTitle=') }
}
+ void 'a form with a field too short for an address or link on example.com is not submitted, and fails the trace'() {
+ given: 'whatever fits is text the field rejects, answered with the form again and a 200, or another host'
+ TraceNativeMetadataTask task = task([], ['/typed?tinyContact=a@b.example'])
+
+ when:
+ task.trace()
+
+ then: 'the field without a value is named, with how to give it one'
+ GradleException e = thrown()
+ e.message.contains('FORM /typed -> not submitted: tinyHomepage too short')
+ e.message.contains('/typed?tinyHomepage=...')
+ !e.message.contains('tinyContact')
+
+ and:
+ !requested.any { it.startsWith('POST /typed-save') }
+ }
+
void 'a form on a page that has none fails the trace'() {
given:
TraceNativeMetadataTask task = task([], ['/'])
@@ -264,6 +390,46 @@ 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 and Retry-After 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 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(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()
+
+ 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'], [])
@@ -289,6 +455,83 @@ 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: '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: 'the one that cannot be made is named'
+ GradleException e = thrown()
+ e.message.contains('a request names its method and path')
+ !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: '{}']]
+ }
+
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()
@@ -322,6 +565,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 7785db385bb..2977c65dbef 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,17 +61,117 @@ class TracedRunFixture {