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/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/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/vulnerability-scan/src/main/groovy/org/apache/grails/buildsrc/scan/VulnerabilityScanPlugin.groovy b/build-logic/vulnerability-scan/src/main/groovy/org/apache/grails/buildsrc/scan/VulnerabilityScanPlugin.groovy
index 14134673dfc..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 ' +
@@ -97,7 +93,7 @@ class VulnerabilityScanPlugin implements Plugin {
'CVE-2026-22747. Remove once Sonatype narrows its affected range'),
new VulnerabilityExclusion('CVE-2026-47842', 'org.springframework.security:spring-security-crypto',
'Sonatype flagged 7.1.1, but https://spring.io/security/cve-2026-47842 lists only 7.1.0 on ' +
- 'the 7.1 line as affected and 7.1.1 as fixed. Spring Boot 4.2.0-RC1 manages 7.2.0-RC1, which ' +
+ 'the 7.1 line as affected and 7.1.1 as fixed. Spring Boot 4.2.0-RC2 manages 7.2.0-RC1, which ' +
'the advisory does not list and which carries the fix (the AesCbcBytesEncryptor and ' +
'AesGcmBytesEncryptor replacements 7.1.1 introduced). Remove once Sonatype corrects its ' +
'affected range; reassess on any Spring Security upgrade'),
diff --git a/dependencies.gradle b/dependencies.gradle
index 35eba03f8fd..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.2.0-RC1',
+ 'spring-boot.version' : '4.2.0-RC2',
]
// Note: the name of the dependency must be the prefix of the property name so properties in the pom are resolved correctly
@@ -86,17 +86,17 @@ ext {
'groovy.version' : '6.0.0',
// Security: 33.7.2 addresses CVE-2026-102554 (uncontrolled resource consumption).
'guava.version' : '33.7.2-jre',
- // Groovy YAML 6.0.0 depends on Jackson 2.22.2, which wins over the 2.21.7 Spring Boot 4.2
+ // Groovy YAML 6.0.0 depends on Jackson 2.22.2, which wins over the 2.21.8 Spring Boot 4.2
// manages, so the BOM must manage at least that. Jackson 2 only releases
// jackson-annotations on the minor, hence the separate 2.22 below. 2.22.4 also fixes
- // CVE-2026-110879 (type id validation in jackson-databind), which 2.21.7 does not carry.
+ // CVE-2026-110879 (type id validation in jackson-databind).
'jackson-2-bom.version' : '2.22.4',
'jackson2-annotations.version' : '2.22',
- // Overrides the 3.1.7 Spring Boot 4.2 manages. Pinned first as a security override of
+ // Overrides the 3.1.8 Spring Boot 4.2 manages. Pinned first as a security override of
// 3.1.6 (CVE-2026-89425, CVE-2026-89407, CVE-2026-91777 and CVE-2026-91776), which 3.1.7
- // also fixes; kept so that moving to Spring Boot 4.2 does not take Jackson 3 from the 3.2
- // line Grails 8 and 9.0 manage back to 3.1. 3.2.4 also fixes 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.
+ // 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',
'nimbus-jose-jwt.version' : '10.10',
@@ -189,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']}",
- // Overrides the 2.21.7 spring-boot-dependencies imports through
+ // Overrides the 2.21.8 spring-boot-dependencies imports through
// com.fasterxml.jackson:jackson-bom - see jackson-2-bom.version. groovy-yaml 6.0.0
// also pulls jackson-dataformat-yaml, so the BOM must manage it at >= the resolved version.
'jackson2-annotations' : "com.fasterxml.jackson.core:jackson-annotations:${bomDependencyVersions['jackson2-annotations.version']}",
@@ -197,7 +197,7 @@ ext {
'jackson-2-bom-databind' : "com.fasterxml.jackson.core:jackson-databind:${bomDependencyVersions['jackson-2-bom.version']}",
'jackson-2-bom-dataformat-yaml': "com.fasterxml.jackson.dataformat:jackson-dataformat-yaml:${bomDependencyVersions['jackson-2-bom.version']}",
'jackson-2-bom-datatype-jsr310': "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:${bomDependencyVersions['jackson-2-bom.version']}",
- // Override of the 3.1.7 spring-boot-dependencies imports through
+ // Override of the 3.1.8 spring-boot-dependencies imports through
// tools.jackson:jackson-bom - see jackson-bom.version
'jackson-bom-core' : "tools.jackson.core:jackson-core:${bomDependencyVersions['jackson-bom.version']}",
'jackson-bom-databind' : "tools.jackson.core:jackson-databind:${bomDependencyVersions['jackson-bom.version']}",
@@ -264,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 the version so enforcedPlatform consumers are
- // forced to it, so the pin stays even when it matches the version Spring Boot manages.
+ // The Hibernate 7 BOM strictly re-declares the version Spring Boot manages, so that
+ // enforcedPlatform consumers are forced to it - see hibernate7VersionOverride.
'hibernate.version',
]
@@ -319,16 +319,26 @@ 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.2 can select Hibernate ORM 7.4.x through Spring Dependency
// Management, and Hibernate ORM 7.4.x requires hibernate-models 1.1.x. This BOM
// strictly re-declares the version so enforcedPlatform consumers are forced to it; a
- // platform() import is not enforced.
+ // platform() import is not enforced. 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 Spring Boot's Liquibase 5.0.4 is a new major.
@@ -341,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/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-core/src/main/groovy/grails/config/Settings.groovy b/grails-core/src/main/groovy/grails/config/Settings.groovy
index c5f7bf615f9..d6b9d6ec767 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.1
+ */
+ String SETTING_EXCEPTION_RESOLVER_PROBLEM_DETAILS = 'grails.exceptionresolver.problemDetails'
+
/**
* The class to use for stacktrace filtering. Should be an instanceof {@link org.grails.exceptions.reporting.StackTraceFilterer}
*/
diff --git a/grails-core/src/main/resources/META-INF/additional-spring-configuration-metadata.json b/grails-core/src/main/resources/META-INF/additional-spring-configuration-metadata.json
index fdffe19f262..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-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-databinding-core/src/main/groovy/org/grails/databinding/xml/GPathResultCollectionDataBindingSource.groovy b/grails-databinding-core/src/main/groovy/org/grails/databinding/xml/GPathResultCollectionDataBindingSource.groovy
index b09c38ea13d..1463b0df480 100644
--- a/grails-databinding-core/src/main/groovy/org/grails/databinding/xml/GPathResultCollectionDataBindingSource.groovy
+++ b/grails-databinding-core/src/main/groovy/org/grails/databinding/xml/GPathResultCollectionDataBindingSource.groovy
@@ -28,13 +28,11 @@ import grails.databinding.SimpleMapDataBindingSource
@CompileStatic
class GPathResultCollectionDataBindingSource implements CollectionDataBindingSource {
- protected List extends DataBindingSource> dataBindingSources
+ protected List dataBindingSources
GPathResultCollectionDataBindingSource(GPathResult gpath) {
dataBindingSources = gpath?.children()?.collect { child ->
- def map = new GPathResultMap((GPathResult) child)
- DataBindingSource bindingSource = new SimpleMapDataBindingSource(map)
- bindingSource
+ (DataBindingSource) new SimpleMapDataBindingSource(new GPathResultMap((GPathResult) child))
}
}
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/deployment/deploymentAot.adoc b/grails-doc/src/en/guide/deployment/deploymentAot.adoc
index 94f2d79af28..710b3d211e1 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 for an email field, and recognisable text, no longer than the field's `maxlength`, for a text field. A select, which is how an enum, an association and each part of a date picker are rendered, sends the option a browser would: the one selected, or the first that can be chosen. A value its type does not accept would fail to bind, and the page would answer with the form again, which looks to the trace like a save that succeeded.
+
+==== Other methods and bodies
+
+`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/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 9655431bd2d..37c102fbab6 100644
--- a/grails-doc/src/en/guide/deployment/deploymentTasks.adoc
+++ b/grails-doc/src/en/guide/deployment/deploymentTasks.adoc
@@ -233,6 +233,7 @@ Many deployments terminate TLS at a reverse proxy or ingress. Keep certificate r
Configure forwarded-header handling only for a trusted proxy path, and have the boundary proxy remove untrusted client-supplied `Forwarded` and `X-Forwarded-*` headers.
Choose `server.forward-headers-strategy=NATIVE` for supported embedded-container handling or `FRAMEWORK` for Spring's handling, according to your proxy's headers and trust configuration.
`FRAMEWORK` reads the `+X-Forwarded-*+` headers; if your proxy sends the RFC 7239 `Forwarded` header instead, also set `spring.mvc.forwarded-headers.header-format=STANDARD`.
+It ignores `X-Forwarded-Prefix`; if your proxy strips a path prefix and sends that header, also set `spring.mvc.forwarded-headers.use-forwarded-prefix=true`.
Test redirects, absolute URLs, secure cookies, and client-address handling through that proxy. See the link:{springBootHowTo}webserver.html#howto.webserver.use-behind-a-proxy-server[Spring Boot proxy guidance].
To terminate TLS in the embedded server instead, merge settings such as these into `application.yml` and mount the keystore read-only:
diff --git a/grails-doc/src/en/guide/introduction/whatsNew.adoc b/grails-doc/src/en/guide/introduction/whatsNew.adoc
index ff83f9dff1d..7918c538eaa 100644
--- a/grails-doc/src/en/guide/introduction/whatsNew.adoc
+++ b/grails-doc/src/en/guide/introduction/whatsNew.adoc
@@ -79,6 +79,32 @@ The Grails 8 upgrade guide calls out the major application-impacting changes and
For the changes since Spring Boot 4.1, see the https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-4.2-Release-Notes[Spring Boot 4.2 Release Notes] and the https://github.com/spring-projects/spring-framework/wiki/Spring-Framework-7.1-Release-Notes[Spring Framework 7.1 Release Notes].
The xref:upgrading#upgrading90x[Upgrading from Grails 8 to Grails {grailsMajorVersion}] section covers the upgrade, including the graphql-java 26 changes that affect GraphQL applications.
+Spring Boot 4.2 can switch metrics and spans to OpenTelemetry's semantic conventions:
+
+[source,yaml]
+----
+management:
+ observations:
+ conventions: open-telemetry
+----
+
+`http.server.requests` then becomes `http.server.request.duration`, tagged with `http.route` and `error.type` in place of `uri` and `exception`.
+In a Grails application `http.route` is `/controller/action`, not the pattern of the URL mapping, which keeps it low in cardinality.
+Spring Boot's https://docs.spring.io/spring-boot/reference/actuator/observability.html#actuator.observability.semantic-conventions[documentation] lists what else changes, such as the properties that customize meter names no longer taking effect.
+
+==== The HTTP QUERY Method
+
+Spring Framework 7.1 supports the `QUERY` method of https://www.rfc-editor.org/info/rfc10008/[RFC 10008], a safe, idempotent request with a body. URL mappings gain a `query` prefix for it, next to `get`, `post` and the others, and a command object is bound to the body of a `QUERY`, which is JSON or form-encoded:
+
+[source,groovy]
+----
+static mappings = {
+ query "/books/search"(controller: 'book', action: 'search')
+}
+----
+
+See xref:theWebLayer#mappingHTTP[Mapping to HTTP methods].
+
==== JSON Dates and Times Render as Spring Boot Renders Them
`render ... as JSON`, `respond` and JSON views now write `Date`, `Calendar`, `TimeZone`, the `java.sql` date types,
@@ -128,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
@@ -603,6 +634,14 @@ A view renders the request's nonce with the new `` tag, as in `>
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 1326b29bd46..13426192ab3 100644
--- a/grails-doc/src/en/guide/upgrading/upgrading90x.adoc
+++ b/grails-doc/src/en/guide/upgrading/upgrading90x.adoc
@@ -51,6 +51,7 @@ The ones most likely to affect a Grails application are:
Spring Framework 7.1's `ForwardedHeaderFilter` reads either the RFC 7239 `Forwarded` header or the `+X-Forwarded-*+` headers, and Spring Boot 4.2 configures it for `+X-Forwarded-*+`.
Before, it read `Forwarded` when the request carried one and `+X-Forwarded-*+` otherwise.
If your reverse proxy sends `Forwarded`, set `spring.mvc.forwarded-headers.header-format: standard`.
+The filter also ignores `X-Forwarded-Prefix` now, where it used to add it to the context path, so if your proxy strips a path prefix and sends that header, absolute links and redirects lose the prefix until you set `spring.mvc.forwarded-headers.use-forwarded-prefix: true`.
Spring Boot 4.2 also registers the filter from its Spring MVC auto-configuration, which backs off when the application declares `@EnableWebMvc`; such an application must now register a `ForwardedHeaderFilter` itself.
* *Embedded Tomcat keeps relative redirect locations relative.*
@@ -108,6 +109,49 @@ The Spring TestContext Framework used to ignore such a class unless its class hi
Grails 8 already logs a warning for each one it ignores, so a test run on Grails 8 shows the affected tests.
Remove the `@Configuration` annotation, or move the class to a top-level class, if the test should not load it.
+* *`bootBuildImage` builds on Ubuntu 26.04.*
+The default builder is `paketobuildpacks/ubuntu-resolute-builder`, in place of `paketobuildpacks/builder-noble-java-tiny`, and images are based on Ubuntu 26.04 instead of 24.04.
+With no `builder` configured, the run image is `paketobuildpacks/ubuntu-resolute-run-tiny:latest`, which still has no shell; with one configured, it is the run image of the builder, which for `ubuntu-resolute-builder` has a shell.
+The builder no longer pins the version of the run image, so set both `builder` and `runImage` to specific versions for repeatable images, or set `builder` to `paketobuildpacks/builder-noble-java-tiny` to keep the previous one.
+
+* *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`.
@@ -1238,6 +1282,13 @@ grails:
springHandlers: true
----
+Spring Framework 7.1 adds `ProblemDetailsConfigurer.renderUnhandledExceptions`, which renders any exception no exception
+handler method handles as a problem. Turned on in a `WebMvcConfigurer`, it applies to Grails actions whatever
+`grails.exceptionresolver.springHandlers` says, and answers every exception, a browser's included, ahead of the Grails
+exception resolver, so `"500"` URL mappings no longer apply. Set `grails.exceptionresolver.problemDetails: true` instead,
+which writes the same problems and leaves the error page to the clients that prefer HTML. See
+<>.
+
==== 18. Actions Can Return Spring MVC Responses
An action that returns a `ResponseEntity` or another `HttpEntity`, a `ProblemDetail`, an `ErrorResponse`,
@@ -1351,10 +1402,10 @@ See <> and <>.
Grails no longer registers a character encoding filter of its own. It used to, and Spring Boot's backed off, so `spring.servlet.encoding` had no effect in a Grails application. Spring Boot's filter now decodes requests: it runs at `Ordered.HIGHEST_PRECEDENCE`, ahead of every other filter, and `spring.servlet.encoding` configures it.
-* The request encoding is now overridden by default, as in any Spring Boot application, so a request that declares a charset of its own is still decoded as UTF-8: its parameters, a body read through `getReader()`, `request.JSON` and `request.XML`, and a JSON or XML body bound to a command object or domain class. The parameters of a PUT, PATCH or DELETE form are the exception, as in Grails 8: the `FormContentFilter` that parses them decodes them with the declared charset, forced or not. To keep the charset a request declares, as Grails 8 did, set `spring.servlet.encoding.force-request: false`.
+* The request encoding is now overridden by default, as in any Spring Boot application, so a request that declares a charset of its own is still decoded as UTF-8: its parameters, a body read through `getReader()`, `request.JSON` and `request.XML`, and a JSON or XML body bound to a command object or domain class. The parameters of a PUT, PATCH, DELETE or QUERY form are the exception, as in Grails 8: the `FormContentFilter` that parses them decodes them with the declared charset, forced or not. To keep the charset a request declares, as Grails 8 did, set `spring.servlet.encoding.force-request: false`.
* Grails 8.1 already registers its encoding filter at `Ordered.HIGHEST_PRECEDENCE`, so an application coming from 8.1 sees no change in where the encoding filter runs. In an application coming from 8.0, filters ordered between `Ordered.HIGHEST_PRECEDENCE + 1` and -181, which used to run before Grails' encoding filter, now run after Spring Boot's, with the request encoding set, as section 5 of <> describes. asset-pipeline's filter at -190 is one: in a packaged application (a WAR or an executable jar) it copies the request's encoding to the precompiled assets it serves, so every asset response now declares a charset, for example `text/css;charset=UTF-8`, and browsers use it for stylesheets and scripts instead of detecting their encoding. A filter among them that reads a request body sent without a charset through `getReader()` now decodes it as UTF-8 instead of ISO-8859-1.
* `grails.filter.encoding` and `grails.filter.forceEncoding` are deprecated. Grails 9 translates them into `spring.servlet.encoding.charset` and `spring.servlet.encoding.force` and logs a warning, and a `spring.servlet.encoding` setting of the application wins over them. Use the Spring Boot properties instead.
-* `GrailsFilters.CHARACTER_ENCODING_FILTER` is deprecated, and its order is now `Ordered.HIGHEST_PRECEDENCE`, the order of Spring Boot's encoding filter, where Grails 8.0 had -180. A filter ordered at `GrailsFilters.CHARACTER_ENCODING_FILTER.order + 1` therefore runs right after the encoding filter, and now also ahead of `FormContentFilter` and of Grails' security headers filter at `GrailsFilters.FIRST`: it no longer sees the parameters of a PUT, PATCH or DELETE form, and a response it sends without continuing the chain gets no security headers. Order it at `Ordered.HIGHEST_PRECEDENCE + 1` instead, or at `GrailsFilters.ASSET_PIPELINE_FILTER.order + 1` to keep the place it had in Grails 8.0.
+* `GrailsFilters.CHARACTER_ENCODING_FILTER` is deprecated, and its order is now `Ordered.HIGHEST_PRECEDENCE`, the order of Spring Boot's encoding filter, where Grails 8.0 had -180. A filter ordered at `GrailsFilters.CHARACTER_ENCODING_FILTER.order + 1` therefore runs right after the encoding filter, and now also ahead of `FormContentFilter` and of Grails' security headers filter at `GrailsFilters.FIRST`: it no longer sees the parameters of a PUT, PATCH, DELETE or QUERY form, and a response it sends without continuing the chain gets no security headers. Order it at `Ordered.HIGHEST_PRECEDENCE + 1` instead, or at `GrailsFilters.ASSET_PIPELINE_FILTER.order + 1` to keep the place it had in Grails 8.0.
* `spring.servlet.encoding.enabled: false` turns the encoding filter off.
* The CAS plugin's single sign-out filter, which reads a parameter of every POST, is registered right after the encoding filter.
* A filter of your own that reads request parameters needs a later order than `Ordered.HIGHEST_PRECEDENCE`, or form input reaches controllers decoded as ISO-8859-1. One registered at exactly `Ordered.HIGHEST_PRECEDENCE` through a `FilterRegistrationBean` runs before the encoding filter.
diff --git a/grails-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..e4d31034945 100644
--- a/grails-gradle/plugins/src/main/groovy/org/apache/grails/gradle/plugin/aot/NativeMetadataExtension.groovy
+++ b/grails-gradle/plugins/src/main/groovy/org/apache/grails/gradle/plugin/aot/NativeMetadataExtension.groovy
@@ -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.1
+ */
+ abstract ListProperty
*
+ *
A request neither of those can make, with another method or with a body that is not a form, is
+ * declared whole. An action restricted to QUERY answers nothing else, and what writes a JSON response
+ * runs only for a client that asks for one:
Written to the application's sources rather than to the build directory: what an image was
* built from should be reviewable, and a trace is only as good as the paths someone thought of.
*
@@ -94,6 +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,20 @@ 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 4043bede5d1..3a5208318f4 100644
--- a/grails-gradle/plugins/src/main/groovy/org/grails/gradle/plugin/core/GrailsGradlePlugin.groovy
+++ b/grails-gradle/plugins/src/main/groovy/org/grails/gradle/plugin/core/GrailsGradlePlugin.groovy
@@ -1234,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')
@@ -1256,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)
@@ -1263,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
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..874236b6911 100644
--- a/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/TraceNativeMetadataTaskSpec.groovy
+++ b/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/TraceNativeMetadataTaskSpec.groovy
@@ -20,6 +20,11 @@ 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.gradle.api.GradleException
import org.gradle.api.Project
@@ -159,6 +164,88 @@ 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'])
+
+ when:
+ task.trace()
+
+ then:
+ Map sent = postedTo('/typed-save')
+ with(sent) {
+ available == 'on'
+ (title =~ /^traced-\d+$/) && title.size() <= 12
+ (notes =~ /^\d+$/) && notes.size() <= 5
+ query =~ /^traced-\d+$/
+ secret == 'traced-secret'
+ new BigDecimal(pages) >= 0
+ new BigDecimal(rating) >= 3 && new BigDecimal(rating) <= 5
+ new BigDecimal(price) <= 0.5
+ new BigDecimal(volume) >= 10 && new BigDecimal(volume) <= 20
+ LocalDate.parse(released)
+ launched == '2999-01-01'
+ LocalDateTime.parse(startsAt)
+ LocalTime.parse(opensAt)
+ YearMonth.parse(issue)
+ sprint ==~ /\d{4}-W\d{2}/
+ contact ==~ /traced-\d+@example\.com/
+ (shortContact ==~ /[^@]+@example\.com/) && shortContact.size() <= 16
+ new URI(homepage).scheme == 'https' && new URI(homepage).host
+ phone ==~ /\d+/
+ colour ==~ /#[0-9a-f]{6}/
+ }
+
+ and: 'a hidden field is the page\'s own, so one that says nothing is sent saying nothing'
+ sent._available == ''
+ }
+
+ void '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'])
@@ -264,6 +351,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 +416,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 +526,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..8210a65901d 100644
--- a/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/TracedRunFixture.groovy
+++ b/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/TracedRunFixture.groovy
@@ -61,17 +61,110 @@ class TracedRunFixture {