From 75aced6e9638e21d2162d43ed9b2fba4681650ff Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Fri, 25 Sep 2026 20:22:06 -0600 Subject: [PATCH 001/131] Upgrade to Spring Boot 4.2.0-M2 --- dependencies.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dependencies.gradle b/dependencies.gradle index 59acfc8ce7b..0531f898ac7 100644 --- a/dependencies.gradle +++ b/dependencies.gradle @@ -40,7 +40,7 @@ ext { 'jquery.version' : '4.0.0', 'maven-model.version' : '3.9.16', 'objenesis.version' : '3.6', - 'spring-boot.version' : '4.1.1', + 'spring-boot.version' : '4.2.0-M2', ] // Note: the name of the dependency must be the prefix of the property name so properties in the pom are resolved correctly From 9e98d99c5eef38b9df89321112c1be793625dcce Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Fri, 25 Sep 2026 20:22:06 -0600 Subject: [PATCH 002/131] Use NameGenerator, Spring Framework 7.1's name for ClassNameGenerator Spring Framework 7.1 renamed org.springframework.aot.generate.ClassNameGenerator to NameGenerator (it now also generates resource paths). The constructors are unchanged, so the AOT specs only need the new type name. --- ...tClassesBeanFactoryInitializationAotProcessorSpec.groovy | 6 +++--- .../core/aot/VarargsBeanRegistrationAotProcessorSpec.groovy | 4 ++-- .../org/grails/plugins/CoreGrailsPluginAotSpec.groovy | 6 +++--- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/grails-core/src/test/groovy/org/apache/grails/core/aot/ArtefactClassesBeanFactoryInitializationAotProcessorSpec.groovy b/grails-core/src/test/groovy/org/apache/grails/core/aot/ArtefactClassesBeanFactoryInitializationAotProcessorSpec.groovy index 861746179e8..7386318d1ca 100644 --- a/grails-core/src/test/groovy/org/apache/grails/core/aot/ArtefactClassesBeanFactoryInitializationAotProcessorSpec.groovy +++ b/grails-core/src/test/groovy/org/apache/grails/core/aot/ArtefactClassesBeanFactoryInitializationAotProcessorSpec.groovy @@ -18,10 +18,10 @@ */ package org.apache.grails.core.aot -import org.springframework.aot.generate.ClassNameGenerator import org.springframework.aot.generate.DefaultGenerationContext import org.springframework.aot.generate.GeneratedFiles import org.springframework.aot.generate.InMemoryGeneratedFiles +import org.springframework.aot.generate.NameGenerator import org.springframework.context.aot.ApplicationContextAotGenerator import org.springframework.context.support.GenericApplicationContext import org.springframework.javapoet.ClassName @@ -56,7 +56,7 @@ class ArtefactClassesBeanFactoryInitializationAotProcessorSpec extends Specifica InMemoryGeneratedFiles generatedFiles = new InMemoryGeneratedFiles() DefaultGenerationContext generationContext = new DefaultGenerationContext( - new ClassNameGenerator(ClassName.get('com.example', 'Subject')), generatedFiles) + new NameGenerator(ClassName.get('com.example', 'Subject')), generatedFiles) new ApplicationContextAotGenerator().processAheadOfTime(context, generationContext) generationContext.writeGeneratedContent() @@ -145,7 +145,7 @@ class ArtefactClassesBeanFactoryInitializationAotProcessorSpec extends Specifica private List writtenBy(contribution) { InMemoryGeneratedFiles files = new InMemoryGeneratedFiles() DefaultGenerationContext generation = new DefaultGenerationContext( - new ClassNameGenerator(ClassName.get('com.example', 'Written')), files) + new NameGenerator(ClassName.get('com.example', 'Written')), files) new ApplicationContextAotGenerator().processAheadOfTime(context, generation) generation.writeGeneratedContent() String source = files.getGeneratedFiles(GeneratedFiles.Kind.SOURCE) diff --git a/grails-core/src/test/groovy/org/apache/grails/core/aot/VarargsBeanRegistrationAotProcessorSpec.groovy b/grails-core/src/test/groovy/org/apache/grails/core/aot/VarargsBeanRegistrationAotProcessorSpec.groovy index 734335ad381..80d917cd79e 100644 --- a/grails-core/src/test/groovy/org/apache/grails/core/aot/VarargsBeanRegistrationAotProcessorSpec.groovy +++ b/grails-core/src/test/groovy/org/apache/grails/core/aot/VarargsBeanRegistrationAotProcessorSpec.groovy @@ -18,10 +18,10 @@ */ package org.apache.grails.core.aot -import org.springframework.aot.generate.ClassNameGenerator import org.springframework.aot.generate.DefaultGenerationContext import org.springframework.aot.generate.GeneratedFiles import org.springframework.aot.generate.InMemoryGeneratedFiles +import org.springframework.aot.generate.NameGenerator import org.springframework.beans.factory.config.RuntimeBeanReference import org.springframework.beans.factory.support.AbstractBeanDefinition import org.springframework.beans.factory.support.RootBeanDefinition @@ -59,7 +59,7 @@ class VarargsBeanRegistrationAotProcessorSpec extends Specification { InMemoryGeneratedFiles generatedFiles = new InMemoryGeneratedFiles() DefaultGenerationContext generationContext = new DefaultGenerationContext( - new ClassNameGenerator(ClassName.get('com.example', 'Subject')), generatedFiles) + new NameGenerator(ClassName.get('com.example', 'Subject')), generatedFiles) new ApplicationContextAotGenerator().processAheadOfTime(context, generationContext) generationContext.writeGeneratedContent() diff --git a/grails-core/src/test/groovy/org/grails/plugins/CoreGrailsPluginAotSpec.groovy b/grails-core/src/test/groovy/org/grails/plugins/CoreGrailsPluginAotSpec.groovy index 6d8fef80df6..9d11e3306a2 100644 --- a/grails-core/src/test/groovy/org/grails/plugins/CoreGrailsPluginAotSpec.groovy +++ b/grails-core/src/test/groovy/org/grails/plugins/CoreGrailsPluginAotSpec.groovy @@ -19,9 +19,9 @@ package org.grails.plugins import org.springframework.aot.AotDetector -import org.springframework.aot.generate.ClassNameGenerator import org.springframework.aot.generate.DefaultGenerationContext import org.springframework.aot.generate.InMemoryGeneratedFiles +import org.springframework.aot.generate.NameGenerator import org.springframework.beans.factory.BeanRegistrar import org.springframework.beans.factory.support.BeanRegistryAdapter import org.springframework.beans.factory.support.GenericBeanDefinition @@ -149,7 +149,7 @@ class CoreGrailsPluginAotSpec extends Specification { and: def generationContext = new DefaultGenerationContext( - new ClassNameGenerator(ClassName.get('org.apache.grails.common.aot.test', 'CoreAotTest')), + new NameGenerator(ClassName.get('org.apache.grails.common.aot.test', 'CoreAotTest')), new InMemoryGeneratedFiles()) when: 'the context is processed exactly as the processAot build task processes it' @@ -173,7 +173,7 @@ class CoreGrailsPluginAotSpec extends Specification { and: def generationContext = new DefaultGenerationContext( - new ClassNameGenerator(ClassName.get('org.apache.grails.common.aot.test', 'LiveInstanceAotTest')), + new NameGenerator(ClassName.get('org.apache.grails.common.aot.test', 'LiveInstanceAotTest')), new InMemoryGeneratedFiles()) when: From 35e64e41fcb37955010718d4d280f6c71ac2a75b Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Fri, 25 Sep 2026 20:24:47 -0600 Subject: [PATCH 003/131] Implement getBean(String, ParameterizedTypeReference) in MockApplicationContext Spring Framework 7.1 adds it to BeanFactory as an abstract method. The mock resolves the reference to its raw class and applies the same name and type checks as getBean(String, Class). --- .../support/MockApplicationContext.java | 6 ++ .../support/MockApplicationContextSpec.groovy | 62 +++++++++++++++++++ 2 files changed, 68 insertions(+) create mode 100644 grails-test-suite-uber/src/test/groovy/org/grails/support/MockApplicationContextSpec.groovy diff --git a/grails-test-suite-base/src/main/groovy/org/grails/support/MockApplicationContext.java b/grails-test-suite-base/src/main/groovy/org/grails/support/MockApplicationContext.java index d0e7ce29dff..c694697dcb8 100644 --- a/grails-test-suite-base/src/main/groovy/org/grails/support/MockApplicationContext.java +++ b/grails-test-suite-base/src/main/groovy/org/grails/support/MockApplicationContext.java @@ -281,6 +281,12 @@ public T getBean(String name, Class requiredType) throws BeansException { return (T) beans.get(name); } + @Override + @SuppressWarnings("unchecked") + public T getBean(String name, org.springframework.core.ParameterizedTypeReference requiredType) throws BeansException { + return (T) getBean(name, ResolvableType.forType(requiredType.getType()).toClass()); + } + public T getBean(Class tClass) throws BeansException { final Map map = getBeansOfType(tClass); if (map.isEmpty()) { diff --git a/grails-test-suite-uber/src/test/groovy/org/grails/support/MockApplicationContextSpec.groovy b/grails-test-suite-uber/src/test/groovy/org/grails/support/MockApplicationContextSpec.groovy new file mode 100644 index 00000000000..9cb1532a000 --- /dev/null +++ b/grails-test-suite-uber/src/test/groovy/org/grails/support/MockApplicationContextSpec.groovy @@ -0,0 +1,62 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.grails.support + +import org.springframework.beans.factory.NoSuchBeanDefinitionException +import org.springframework.core.ParameterizedTypeReference +import spock.lang.Specification + +class MockApplicationContextSpec extends Specification { + + void 'getBean with a ParameterizedTypeReference returns the named bean'() { + given: + def context = new MockApplicationContext() + def names = ['one', 'two'] + context.registerMockBean('names', names) + + when: + List bean = context.getBean('names', new ParameterizedTypeReference>() {}) + + then: + bean.is(names) + } + + void 'getBean with a ParameterizedTypeReference rejects a bean of another type'() { + given: + def context = new MockApplicationContext() + context.registerMockBean('names', 'not a list') + + when: + context.getBean('names', new ParameterizedTypeReference>() {}) + + then: + thrown(NoSuchBeanDefinitionException) + } + + void 'getBean with a ParameterizedTypeReference rejects an unknown bean name'() { + given: + def context = new MockApplicationContext() + + when: + context.getBean('missing', new ParameterizedTypeReference>() {}) + + then: + thrown(NoSuchBeanDefinitionException) + } +} From 31edfada064cce5c1efa2db0147f930bb8d38bf5 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Fri, 25 Sep 2026 20:30:06 -0600 Subject: [PATCH 004/131] Pass only named types to graphql-java 26 as additional schema types graphql-java 26 (selected by Spring Boot 4.2) narrowed GraphQLSchema.Builder.additionalTypes to Set. GraphQLSchemaInterceptor.interceptSchema keeps handing interceptors a Set, so existing implementations still override it; Schema unwraps list and non-null wrappers before building, which adds the same named type graphql-java 25 reached by traversing the wrapper. --- .../org/grails/gorm/graphql/Schema.groovy | 11 ++- .../gorm/graphql/SchemaInterceptorSpec.groovy | 87 +++++++++++++++++++ 2 files changed, 97 insertions(+), 1 deletion(-) create mode 100644 grails-data-graphql/core/src/test/groovy/org/grails/gorm/graphql/SchemaInterceptorSpec.groovy diff --git a/grails-data-graphql/core/src/main/groovy/org/grails/gorm/graphql/Schema.groovy b/grails-data-graphql/core/src/main/groovy/org/grails/gorm/graphql/Schema.groovy index 14d702a6fdd..59baa6cb1fe 100644 --- a/grails-data-graphql/core/src/main/groovy/org/grails/gorm/graphql/Schema.groovy +++ b/grails-data-graphql/core/src/main/groovy/org/grails/gorm/graphql/Schema.groovy @@ -23,10 +23,12 @@ import graphql.schema.DataFetcher import graphql.schema.GraphQLCodeRegistry import graphql.schema.GraphQLFieldDefinition import graphql.schema.GraphQLInputType +import graphql.schema.GraphQLNamedType import graphql.schema.GraphQLObjectType import graphql.schema.GraphQLOutputType import graphql.schema.GraphQLSchema import graphql.schema.GraphQLType +import graphql.schema.GraphQLTypeUtil import groovy.transform.CompileStatic import javassist.Modifier import org.grails.datastore.mapping.model.MappingContext @@ -531,9 +533,16 @@ class Schema { schemaInterceptor.interceptSchema(queryType, mutationType, additionalTypes) } + // graphql-java only accepts named types as additional types. Unwrapping list and + // non-null wrappers adds the type they wrap, which is what a wrapped type + // contributed to the schema before graphql-java 26 narrowed the signature. + Set namedAdditionalTypes = additionalTypes.collect(new LinkedHashSet()) { GraphQLType type -> + GraphQLTypeUtil.unwrapAll(type) + } + GraphQLSchema.Builder schema = GraphQLSchema.newSchema() .codeRegistry(codeRegistry.build()) - .additionalTypes(additionalTypes) + .additionalTypes(namedAdditionalTypes) GraphQLObjectType mutation = mutationType.build() if (mutation.fieldDefinitions) { diff --git a/grails-data-graphql/core/src/test/groovy/org/grails/gorm/graphql/SchemaInterceptorSpec.groovy b/grails-data-graphql/core/src/test/groovy/org/grails/gorm/graphql/SchemaInterceptorSpec.groovy new file mode 100644 index 00000000000..62dfb81a9d6 --- /dev/null +++ b/grails-data-graphql/core/src/test/groovy/org/grails/gorm/graphql/SchemaInterceptorSpec.groovy @@ -0,0 +1,87 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.grails.gorm.graphql + +import graphql.Scalars +import graphql.schema.GraphQLFieldDefinition +import graphql.schema.GraphQLList +import graphql.schema.GraphQLNonNull +import graphql.schema.GraphQLObjectType +import graphql.schema.GraphQLSchema +import graphql.schema.GraphQLType +import org.grails.datastore.mapping.config.Settings +import org.grails.datastore.mapping.core.DatastoreUtils +import org.grails.datastore.mapping.model.PersistentEntity +import org.grails.gorm.graphql.domain.general.GeneralPackage +import org.grails.gorm.graphql.domain.hibernate.HibernatePackage +import org.grails.gorm.graphql.interceptor.GraphQLSchemaInterceptor +import org.grails.gorm.graphql.interceptor.manager.DefaultGraphQLInterceptorManager +import org.grails.orm.hibernate.HibernateDatastore +import spock.lang.AutoCleanup +import spock.lang.Shared +import spock.lang.Specification + +class SchemaInterceptorSpec extends Specification { + + @Shared @AutoCleanup HibernateDatastore hibernateDatastore + + void setupSpec() { + hibernateDatastore = new HibernateDatastore( + DatastoreUtils.createPropertyResolver(Collections.singletonMap(Settings.SETTING_DB_CREATE, 'create-drop')), + GeneralPackage.getPackage(), HibernatePackage.getPackage()) + } + + void 'additional types from a schema interceptor are added to the schema, unwrapped from list and non-null'() { + given: + GraphQLObjectType standalone = objectType('Standalone') + GraphQLObjectType wrapped = objectType('Wrapped') + def interceptorManager = new DefaultGraphQLInterceptorManager() + interceptorManager.registerInterceptor(new GraphQLSchemaInterceptor() { + @Override + void interceptEntity(PersistentEntity entity, + List queryFields, + List mutationFields) { + } + + @Override + void interceptSchema(GraphQLObjectType.Builder queryType, + GraphQLObjectType.Builder mutationType, + Set additionalTypes) { + additionalTypes << standalone + additionalTypes << GraphQLNonNull.nonNull(GraphQLList.list(wrapped)) + } + }) + def schema = new Schema(hibernateDatastore.mappingContext) + schema.interceptorManager = interceptorManager + + when: + GraphQLSchema graphQLSchema = schema.generate() + + then: + graphQLSchema.getType('Standalone') == standalone + graphQLSchema.getType('Wrapped') == wrapped + } + + private static GraphQLObjectType objectType(String name) { + GraphQLObjectType.newObject() + .name(name) + .field(GraphQLFieldDefinition.newFieldDefinition().name('value').type(Scalars.GraphQLString)) + .build() + } +} From ef48d42e7c2904f42846572970c4af8a067ea557 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Fri, 25 Sep 2026 20:30:06 -0600 Subject: [PATCH 005/131] Manage graphql-java 26.1, the version Spring Boot 4.2 selects graphql-java-extended-scalars has no release newer than 24.0; the grails-data-graphql core and plugin test suites pass with 24.0 against graphql-java 26.1. --- dependencies.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dependencies.gradle b/dependencies.gradle index 0531f898ac7..d5f1eae5726 100644 --- a/dependencies.gradle +++ b/dependencies.gradle @@ -83,7 +83,7 @@ ext { // Boot and must be upgraded in lockstep with graphql-java. Keeping this pin makes // the dependency validator flag any Spring Boot graphql-java bump so we re-check // extended-scalars compatibility. See https://github.com/apache/grails-core/issues/15674 - 'graphql-java.version' : '25.0', + 'graphql-java.version' : '26.1', 'graphql-java-extended-scalars.version': '24.0', 'groovy.version' : '6.0.0-RC-3', 'guava.version' : '33.7.1-jre', From e80fe405182c23c8b30e22aafae9742aa38ecfb4 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Fri, 25 Sep 2026 20:34:33 -0600 Subject: [PATCH 006/131] Map the org.json version Jedis 8 uses to its LEGAL-666 license Spring Boot 4.2 manages Jedis 8, which depends on org.json:json:20260719 instead of 20251224. The SBOM license override is keyed by version, so grails-redis failed cyclonedxDirectBom until the entry moved with it. --- .../groovy/org/apache/grails/buildsrc/SbomPlugin.groovy | 2 +- .../org/apache/grails/buildsrc/SbomPluginSpec.groovy | 9 +++++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/build-logic/plugins/src/main/groovy/org/apache/grails/buildsrc/SbomPlugin.groovy b/build-logic/plugins/src/main/groovy/org/apache/grails/buildsrc/SbomPlugin.groovy index 0cc8d5f8e34..e796c450902 100644 --- a/build-logic/plugins/src/main/groovy/org/apache/grails/buildsrc/SbomPlugin.groovy +++ b/build-logic/plugins/src/main/groovy/org/apache/grails/buildsrc/SbomPlugin.groovy @@ -130,7 +130,7 @@ class SbomPlugin implements Plugin { 'pkg:maven/org.jline/jline-terminal-jni@3.30.16?type=jar' : 'BSD-3-Clause', 'pkg:maven/org.jruby/jzlib@1.1.5?type=jar' : 'BSD-3-Clause', // https://web.archive.org/web/20240822213507/http://www.jcraft.com/jzlib/LICENSE.txt shows it's a 3 clause 'pkg:maven/org.liquibase.ext/liquibase-hibernate5@4.27.0?type=jar': 'Apache-2.0', // maps incorrectly because of https://github.com/liquibase/liquibase/issues/2445 & the base pom does not define a license - 'pkg:maven/org.json/json@20251224?type=jar' : 'Public-Domain', // required due to jedis, https://issues.apache.org/jira/browse/LEGAL-666 approves this usage + 'pkg:maven/org.json/json@20260719?type=jar' : 'Public-Domain', // required due to jedis, https://issues.apache.org/jira/browse/LEGAL-666 approves this usage // Bouncy Castle Licence is the MIT license (https://www.bouncycastle.org/licence.html); pulled in transitively by the CAS client 'pkg:maven/org.bouncycastle/bcpkix-jdk18on@1.84?type=jar' : 'MIT', 'pkg:maven/org.bouncycastle/bcprov-jdk18on@1.84?type=jar' : 'MIT', diff --git a/build-logic/plugins/src/test/groovy/org/apache/grails/buildsrc/SbomPluginSpec.groovy b/build-logic/plugins/src/test/groovy/org/apache/grails/buildsrc/SbomPluginSpec.groovy index 658459dc4b4..5180c081454 100644 --- a/build-logic/plugins/src/test/groovy/org/apache/grails/buildsrc/SbomPluginSpec.groovy +++ b/build-logic/plugins/src/test/groovy/org/apache/grails/buildsrc/SbomPluginSpec.groovy @@ -108,6 +108,15 @@ class SbomPluginSpec extends Specification { 'pkg:maven/org.jline/jansi@4.3.1?type=jar', bsd4Choice()).id == 'BSD-3-Clause' } + void "org.json resolved through Jedis uses the public domain license approved in LEGAL-666"() { + given: + List publicDomainChoice = [[license: [name: 'Public Domain', url: 'https://github.com/stleary/JSON-java/blob/master/LICENSE']]] + + expect: + SbomPlugin.pickLicense(LOGGER, 'grails-redis', 'grails-redis', + 'pkg:maven/org.json/json@20260719?type=jar', publicDomainChoice).name == 'Public Domain' + } + void "JLine 4 license correction is limited to JLine 4 Maven jars"() { when: SbomPlugin.pickLicense(LOGGER, 'grails-console', 'grails-console', bomRef, bsd4Choice()) From 3cfe2c23017c1a24079dd5c138dc3db8fbd61f1f Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Fri, 25 Sep 2026 20:40:17 -0600 Subject: [PATCH 007/131] Inherit Jackson 3, Logback and Commons Codec from Spring Boot 4.2 Spring Boot 4.2.0-M2 manages the versions these pins overrode Spring Boot 4.1 with - Jackson 3.1.6, Logback 1.6.3 and Commons Codec 1.22.1 - so grails-bom no longer needs to redeclare them. The Spring Dependency Management end-to-end fixture only mirrors the logback and jackson3 overrides when they are present. --- dependencies.gradle | 18 ------------------ 1 file changed, 18 deletions(-) diff --git a/dependencies.gradle b/dependencies.gradle index d5f1eae5726..a10abcc892f 100644 --- a/dependencies.gradle +++ b/dependencies.gradle @@ -76,7 +76,6 @@ ext { 'bootstrap-icons.version' : '1.13.1', 'bootstrap.version' : '5.3.8', 'checker-qual.version' : '3.55.1', - 'commons-codec.version' : '1.22.1', 'geb-spock.version' : '8.0.1', // Pinned deliberately as a drift tripwire even though it matches Spring Boot's // managed version: graphql-java-extended-scalars (below) is NOT managed by Spring @@ -96,18 +95,9 @@ ext { // jackson-annotations on the minor, hence the separate 2.22 below. 'jackson2.version' : '2.22.2', 'jackson2-annotations.version' : '2.22', - // Security: overrides the Jackson 3 line Spring Boot 4.1 manages (3.1.5). 3.1.6 adds the - // StreamReadConstraints length limit to GregorianCalendar/Duration (CVE-2026-68497) and - // restricts the URI schemes java.nio.file.Path deserialization accepts (CVE-2026-19032). - // Stays on Spring Boot's 3.1.x line so its Jackson 3 integration keeps a supported version. - 'jackson3.version' : '3.1.6', 'jquery.version' : '4.0.0', 'kotlin.version' : '2.2.21', 'liquibase-hibernate5.version' : '4.27.0', - // Security: overrides the 1.5.38 Spring Boot 4.1 manages. 1.6.3 strips slashes from MDC - // values before SiftingAppender uses them as discriminating keys (CVE-2026-19880). The - // 1.6.x line keeps SLF4J 2.0.x and a JDK 11 baseline, so it is a drop-in replacement. - 'logback.version' : '1.6.3', 'mockito.version' : '5.23.0', // Security: overrides the 5.8.1 Spring Boot 4.1 manages. 5.9.2 stopped ProxySettings // .toString() writing the SOCKS5 proxy credentials into the application log @@ -155,7 +145,6 @@ ext { 'bootstrap-icons' : "org.webjars.npm:bootstrap-icons:${bomDependencyVersions['bootstrap-icons.version']}", 'cas-client-core' : "org.apereo.cas.client:cas-client-core:${bomDependencyVersions['cas-client-core.version']}", 'checker-qual' : "org.checkerframework:checker-qual:${bomDependencyVersions['checker-qual.version']}", - 'commons-codec' : "commons-codec:commons-codec:${bomDependencyVersions['commons-codec.version']}", 'geb-spock' : "org.apache.groovy.geb:geb-spock:${bomDependencyVersions['geb-spock.version']}", 'graphql-java' : "com.graphql-java:graphql-java:${bomDependencyVersions['graphql-java.version']}", 'graphql-java-extended-scalars': "com.graphql-java:graphql-java-extended-scalars:${bomDependencyVersions['graphql-java-extended-scalars.version']}", @@ -202,14 +191,7 @@ ext { 'jackson2-databind' : "com.fasterxml.jackson.core:jackson-databind:${bomDependencyVersions['jackson2.version']}", 'jackson2-dataformat-yaml' : "com.fasterxml.jackson.dataformat:jackson-dataformat-yaml:${bomDependencyVersions['jackson2.version']}", 'jackson2-datatype-jsr310' : "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:${bomDependencyVersions['jackson2.version']}", - // Security override of the 3.1.5 spring-boot-dependencies imports through - // tools.jackson:jackson-bom - see jackson3.version - 'jackson3-core' : "tools.jackson.core:jackson-core:${bomDependencyVersions['jackson3.version']}", - 'jackson3-databind' : "tools.jackson.core:jackson-databind:${bomDependencyVersions['jackson3.version']}", 'jquery' : "org.webjars.npm:jquery:${bomDependencyVersions['jquery.version']}", - // Security override of the transitive 1.5.38 - see logback.version - 'logback-classic' : "ch.qos.logback:logback-classic:${bomDependencyVersions['logback.version']}", - 'logback-core' : "ch.qos.logback:logback-core:${bomDependencyVersions['logback.version']}", // Security override of the 5.8.1 spring-boot-dependencies imports through // org.mongodb:mongodb-driver-bom - see mongodb.version. The whole driver family is // pinned so a classpath cannot end up mixing driver versions. From 5ee6cc09626861603538632e97a90f35faf84e0f Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Fri, 25 Sep 2026 20:40:17 -0600 Subject: [PATCH 008/131] Describe the remaining overrides against Spring Boot 4.2's versions Jackson 2.21.6, which Spring Boot 4.2 manages, already carries the CVE-2026-68497 and CVE-2026-19032 fixes, so the 2.22.2 pin is only needed for Groovy YAML. MongoDB 5.12.0 now overrides 5.11.1, which already has the CVE-2026-18710 fix; it stays so the upgrade does not downgrade the driver. --- dependencies.gradle | 20 +++++++++----------- 1 file changed, 9 insertions(+), 11 deletions(-) diff --git a/dependencies.gradle b/dependencies.gradle index a10abcc892f..1f1f3a19669 100644 --- a/dependencies.gradle +++ b/dependencies.gradle @@ -88,20 +88,18 @@ ext { 'guava.version' : '33.7.1-jre', // Security: overrides spring-boot-dependencies (5.4.2). 5.4.3 fixes CVE-2026-54399 (httpcore5) and CVE-2026-54428 (httpcore5-h2). 'httpcore5.version' : '5.4.3', - // Groovy YAML 6.0.0-RC-3 requires Jackson 2.22.x, and 2.22.2 also overrides the - // 2.21.5 Spring Boot 4.1 manages: it adds the StreamReadConstraints length limit to - // GregorianCalendar/Duration (CVE-2026-68497) and restricts the URI schemes - // java.nio.file.Path deserialization accepts (CVE-2026-19032). Jackson 2 only releases - // jackson-annotations on the minor, hence the separate 2.22 below. + // Groovy YAML 6.0.0-RC-3 requires Jackson 2.22.x, newer than the 2.21.6 Spring Boot 4.2 + // manages. Jackson 2 only releases jackson-annotations on the minor, hence the separate + // 2.22 below. 'jackson2.version' : '2.22.2', 'jackson2-annotations.version' : '2.22', 'jquery.version' : '4.0.0', 'kotlin.version' : '2.2.21', 'liquibase-hibernate5.version' : '4.27.0', 'mockito.version' : '5.23.0', - // Security: overrides the 5.8.1 Spring Boot 4.1 manages. 5.9.2 stopped ProxySettings - // .toString() writing the SOCKS5 proxy credentials into the application log - // (CVE-2026-18710); 5.12.0 is the current release of that line. + // Overrides the 5.11.1 Spring Boot 4.2 manages. Pinned first as a security override of + // Spring Boot 4.1's 5.8.1 (CVE-2026-18710, fixed in 5.9.2); kept so that moving to Spring + // Boot 4.2 does not downgrade the driver. Drop once Spring Boot manages 5.12.0 or later. 'mongodb.version' : '5.12.0', 'nimbus-jose-jwt.version' : '10.10', 'pac4j.version' : '6.5.8', @@ -183,7 +181,7 @@ ext { // Security override of spring-boot-dependencies - see httpcore5.version 'httpcore5' : "org.apache.httpcomponents.core5:httpcore5:${bomDependencyVersions['httpcore5.version']}", 'httpcore5-h2' : "org.apache.httpcomponents.core5:httpcore5-h2:${bomDependencyVersions['httpcore5.version']}", - // Security override of the 2.21.5 spring-boot-dependencies imports through + // Overrides the 2.21.6 spring-boot-dependencies imports through // com.fasterxml.jackson:jackson-bom - see jackson2.version. groovy-yaml 6.0.0-RC-3 // 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']}", @@ -192,7 +190,7 @@ ext { 'jackson2-dataformat-yaml' : "com.fasterxml.jackson.dataformat:jackson-dataformat-yaml:${bomDependencyVersions['jackson2.version']}", 'jackson2-datatype-jsr310' : "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:${bomDependencyVersions['jackson2.version']}", 'jquery' : "org.webjars.npm:jquery:${bomDependencyVersions['jquery.version']}", - // Security override of the 5.8.1 spring-boot-dependencies imports through + // Override of the 5.11.1 spring-boot-dependencies imports through // org.mongodb:mongodb-driver-bom - see mongodb.version. The whole driver family is // pinned so a classpath cannot end up mixing driver versions. 'mongodb-bson' : "org.mongodb:bson:${bomDependencyVersions['mongodb.version']}", @@ -284,7 +282,7 @@ ext { customBomVersions = [ 'cache-ri-impl.version' : '1.1.1', 'derby.version' : '10.17.1.0', - // Spring Boot 4.1 can select Hibernate ORM 7.4.x through Spring Dependency + // 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. 'hibernate-models.version' : '1.1.2', 'hibernate-tools.version' : '7.3.13.Final', From d9a9fae5d31f87c738d94d2947e84bc785225bf5 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Fri, 25 Sep 2026 20:43:10 -0600 Subject: [PATCH 009/131] Move the vulnerability scan exclusions to Spring Boot 4.2's versions Both coordinates are version-pinned. Spring Boot 4.2.0-M2 manages H2 2.5.250 (Sonatype still flags every H2 version for CVE-2018-14335) and Spring Security 7.2.0-M2 (outside the range Spring's CVE-2026-47838 advisory lists). --- .../grails/buildsrc/VulnerabilityScanPlugin.groovy | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/build-logic/plugins/src/main/groovy/org/apache/grails/buildsrc/VulnerabilityScanPlugin.groovy b/build-logic/plugins/src/main/groovy/org/apache/grails/buildsrc/VulnerabilityScanPlugin.groovy index 0a1ea797c94..873afbd710f 100644 --- a/build-logic/plugins/src/main/groovy/org/apache/grails/buildsrc/VulnerabilityScanPlugin.groovy +++ b/build-logic/plugins/src/main/groovy/org/apache/grails/buildsrc/VulnerabilityScanPlugin.groovy @@ -66,19 +66,19 @@ class VulnerabilityScanPlugin implements Plugin { extension.excludeCoordinates = [ // CVE-2018-14335: Sonatype flags this against ALL H2 versions; no fixed release exists upstream. // See https://github.com/h2database/h2database/issues/1294 - 'com.h2database:h2:2.4.240', + 'com.h2database:h2:2.5.250', // CVE-2026-14683/14684/14685/14686: pulled transitively via micrometer/actuator (LatencyUtils). // The fix is HdrHistogram 2.2.3, which is not yet published to Maven Central (2.2.2 is the latest // release). Remove once 2.2.3+ is available and resolves on the classpath. 'org.hdrhistogram:HdrHistogram:2.2.2', // CVE-2026-47838: OSS Index flags the 7.x line, but Spring's advisory // (https://spring.io/security/cve-2026-47838) lists only 5.7.x-6.5.10 as affected, fixed in - // 6.5.11 - the 7.0.x/7.1.x lines are not listed, the advisory being a continuation of - // CVE-2026-22747 which 7.x already carries. 7.1.1 is the version managed by Spring Boot 4.1.1 - // and the latest release, so there is nothing to bump to. Remove once OSS Index narrows its - // range. Note this coordinate is version-pinned: a spring-boot.version bump moves - // spring-security and orphans the entry, so update it in lockstep. - 'org.springframework.security:spring-security-web:7.1.1', + // 6.5.11 - no 7.x line is listed, the advisory being a continuation of + // CVE-2026-22747 which 7.x already carries. 7.2.0-M2 is the version managed by Spring Boot + // 4.2.0-M2, so there is nothing to bump to. Remove once OSS Index narrows its range. Note + // this coordinate is version-pinned: a spring-boot.version bump moves spring-security and + // orphans the entry, so update it in lockstep. + 'org.springframework.security:spring-security-web:7.2.0-M2', ] as Set project.tasks.named(TASK_NAME) { task -> From 3753d864e78d6189e969841e658ae0f66cf4ff8f Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Fri, 25 Sep 2026 21:01:33 -0600 Subject: [PATCH 010/131] Document Spring Boot 4.2 and Spring Framework 7.1 in What's New Names the Spring Security, Spring Data and Micrometer lines Spring Boot 4.2 manages and links its release notes and Spring Framework 7.1's. The structured logging note no longer ties the format IDs to Spring Boot 4.1. --- grails-doc/src/en/guide/conf/config/logging.adoc | 2 +- grails-doc/src/en/guide/introduction/whatsNew.adoc | 5 +++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/grails-doc/src/en/guide/conf/config/logging.adoc b/grails-doc/src/en/guide/conf/config/logging.adoc index f471d4216ce..56908ec16ce 100644 --- a/grails-doc/src/en/guide/conf/config/logging.adoc +++ b/grails-doc/src/en/guide/conf/config/logging.adoc @@ -96,7 +96,7 @@ More information can be found in the official https://logback.qos.ch/documentati === Structured Logging Grails does not enable structured logging. Existing Logback configuration and plain-text output remain unchanged -unless an application explicitly selects a Spring Boot structured format. Spring Boot 4.1 provides the JSON format +unless an application explicitly selects a Spring Boot structured format. Spring Boot provides the JSON format IDs `ecs` (Elastic Common Schema), `gelf` (Graylog Extended Log Format), and `logstash` for console and file output. For the complete reference, see the https://docs.spring.io/spring-boot/reference/features/logging.html#features.logging.structured[Spring Boot structured logging documentation]. diff --git a/grails-doc/src/en/guide/introduction/whatsNew.adoc b/grails-doc/src/en/guide/introduction/whatsNew.adoc index b7ad640f452..727708355df 100644 --- a/grails-doc/src/en/guide/introduction/whatsNew.adoc +++ b/grails-doc/src/en/guide/introduction/whatsNew.adoc @@ -36,12 +36,13 @@ The standard Grails BOM uses Groovy {groovyVersion} and Spock {spockVersion}. Grails Micronaut is maintained and released from the https://github.com/apache/grails-micronaut[Apache Grails Micronaut repository] and consumes published Grails Core artifacts. -==== Spring Boot 4.1 and Spring Framework 7 +==== Spring Boot 4.2 and Spring Framework 7.1 Grails {grailsMajorVersion} is built on Spring Boot {springBootVersion} and Spring Framework {springVersion}. -This brings the Spring Boot 4 modular artifact layout, Spring Framework 7 API removals, Jackson 3, Tomcat 11 and Jakarta Servlet 6.1, plus Spring Boot 4.1 dependency management for Spring Security 7.1, Spring Data 2026.0 and Micrometer 1.17. +This brings the Spring Boot 4 modular artifact layout, Spring Framework 7 API removals, Jackson 3, Tomcat 11 and Jakarta Servlet 6.1, plus Spring Boot 4.2 dependency management for Spring Security 7.2, Spring Data 2026.1 and Micrometer 1.18. The Grails 8 upgrade guide calls out the major application-impacting changes and links to the Spring Boot 4.0 migration guide, Spring Boot 4.1 release notes and Spring Framework 7.0 release notes. +For the changes since Spring Boot 4.1, see the https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-4.2-Release-Notes[Spring Boot 4.2 Release Notes] and the https://github.com/spring-projects/spring-framework/wiki/Spring-Framework-7.1-Release-Notes[Spring Framework 7.1 Release Notes]. ==== Hibernate 7 Application Generation From fd9c4a95992aecf0dfce020b39bdbbc200a53355 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Fri, 25 Sep 2026 21:01:44 -0600 Subject: [PATCH 011/131] Point the agent guides at Spring Boot 4.2 and Spring Framework 7.1 --- .agents/skills/grails-developer/SKILL.md | 4 ++-- AGENTS.md | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/.agents/skills/grails-developer/SKILL.md b/.agents/skills/grails-developer/SKILL.md index 8e83754866b..5ab311f3b89 100644 --- a/.agents/skills/grails-developer/SKILL.md +++ b/.agents/skills/grails-developer/SKILL.md @@ -31,8 +31,8 @@ Activate this skill when developing with current Grails, including: ## Technology Stack Current Grails is built on: -- **Spring Boot**: 4.1.x -- **Spring Framework**: 7.0.x +- **Spring Boot**: 4.2.x +- **Spring Framework**: 7.1.x - **Groovy**: 5.1.x - **Gradle**: 9.6.x - **Spock**: 2.4-groovy-5.0 diff --git a/AGENTS.md b/AGENTS.md index 6c7eaabb4e7..2e7026b30ec 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -89,8 +89,8 @@ export GRADLE_OPTS="-Dorg.gradle.jvmargs=-Xmx4G" |-----------|---------| | JDK | 21+ (baseline 21) | | Groovy | 5.1.x | -| Spring Boot | 4.1.x | -| Spring Framework | 7.0.x | +| Spring Boot | 4.2.x | +| Spring Framework | 7.1.x | | Spock | 2.4-groovy-5.0 | | Gradle | 9.7.x | | Jakarta EE | 10 | @@ -116,7 +116,7 @@ All managed dependency versions live in `dependencies.gradle` (the single source - **The BOM must manage the latest (winning) version.** Validation fails when a transitive dependency resolves to a version *newer* than the BOM manages. The fix is to **bump the version in `dependencies.gradle`** so the BOM's version is `>=` everything on the classpath and stays authoritative. This is the *purpose* of the check — keeping the BOM ahead of its transitives. - **Do not suppress validation to work around a bump.** `allowedBomOverrides` (per-project ext) and dependency exclusions are reserved for an explicit, documented conflict or an agreed-upon workaround — never as a shortcut to silence a version the BOM should simply manage. Comment the reason when you must use one. - **A dependency managed in more than one BOM must use the *same* version everywhere.** Versions appear in `gradleBomDependencyVersions` (build tooling / `grails-gradle-bom`), `bomDependencyVersions` (`grails-bom`), and per-BOM `customBomVersions` blocks (e.g. `grails-hibernate7-bom`). `grails-bom` re-declares the gradle-BOM constraints, and the Hibernate BOMs are consumed via `enforcedPlatform`. Declaring one coordinate (e.g. `org.ow2.asm:asm`) at two different versions across these maps produces irreconcilable strict constraints and breaks `enforcedPlatform` resolution. Pin it once, consistently. -- **Prefer inheriting from the Spring Boot BOM.** Do not re-pin a coordinate that `spring-boot-dependencies` (4.1.x) already manages unless you are intentionally overriding it to a newer version (e.g. a security fix); note the reason inline. +- **Prefer inheriting from the Spring Boot BOM.** Do not re-pin a coordinate that `spring-boot-dependencies` (4.2.x) already manages unless you are intentionally overriding it to a newer version (e.g. a security fix); note the reason inline. ## Key Modules From 5d7b6adc8dd4a14e7ed0f5bbd7d13713088dab7d Mon Sep 17 00:00:00 2001 From: James Fredley Date: Mon, 5 Oct 2026 11:00:09 -0400 Subject: [PATCH 012/131] Use NameGenerator in the OpenAPI ahead-of-time spec Spring Framework 7.1 renamed ClassNameGenerator to NameGenerator. The grails-core AOT specs already use the new type; grails-openapi still imported the old one, so every workflow that compiled its tests failed. Assisted-by: opencode:grok-4.7 --- .../OpenApiBeanFactoryInitializationAotProcessorSpec.groovy | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/grails-openapi/src/test/groovy/org/apache/grails/openapi/aot/OpenApiBeanFactoryInitializationAotProcessorSpec.groovy b/grails-openapi/src/test/groovy/org/apache/grails/openapi/aot/OpenApiBeanFactoryInitializationAotProcessorSpec.groovy index 58f9d2723d6..48ab8b62017 100644 --- a/grails-openapi/src/test/groovy/org/apache/grails/openapi/aot/OpenApiBeanFactoryInitializationAotProcessorSpec.groovy +++ b/grails-openapi/src/test/groovy/org/apache/grails/openapi/aot/OpenApiBeanFactoryInitializationAotProcessorSpec.groovy @@ -21,7 +21,7 @@ package org.apache.grails.openapi.aot import io.swagger.v3.oas.annotations.media.Content import io.swagger.v3.oas.annotations.media.Schema import io.swagger.v3.oas.annotations.responses.ApiResponse -import org.springframework.aot.generate.ClassNameGenerator +import org.springframework.aot.generate.NameGenerator import org.springframework.aot.generate.DefaultGenerationContext import org.springframework.aot.generate.InMemoryGeneratedFiles import org.springframework.aot.hint.MemberCategory @@ -203,7 +203,7 @@ class OpenApiBeanFactoryInitializationAotProcessorSpec extends Specification { private RuntimeHints process(DefaultListableBeanFactory beanFactory) { def contribution = new OpenApiBeanFactoryInitializationAotProcessor().processAheadOfTime(beanFactory) def generationContext = new DefaultGenerationContext( - new ClassNameGenerator(ClassName.get('com.example', 'Application')), new InMemoryGeneratedFiles()) + new NameGenerator(ClassName.get('com.example', 'Application')), new InMemoryGeneratedFiles()) contribution.applyTo(generationContext, Stub(BeanFactoryInitializationCode)) generationContext.runtimeHints } From aabcc109999d4541fefcd5d7af8eaa516475d86f Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Mon, 5 Oct 2026 16:12:57 -0700 Subject: [PATCH 013/131] Keep the grails-developer skill's "Grails is built on" heading The 9.0.x merge brought back this PR's older "Current Grails is built on" wording, which 9.x had already shortened. --- grails-skills/developer/skills/grails-developer/SKILL.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/grails-skills/developer/skills/grails-developer/SKILL.md b/grails-skills/developer/skills/grails-developer/SKILL.md index 9401a529fe0..57e22421cb8 100644 --- a/grails-skills/developer/skills/grails-developer/SKILL.md +++ b/grails-skills/developer/skills/grails-developer/SKILL.md @@ -30,7 +30,7 @@ Activate this skill when developing with Grails, including: ## Technology Stack -Current Grails is built on: +Grails is built on: - **Spring Boot**: 4.2.x - **Spring Framework**: 7.1.x - **Groovy**: 5.1.x From c3e575bbbd8e2959cb6f5aafafc410e83d263c07 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Mon, 5 Oct 2026 16:12:57 -0700 Subject: [PATCH 014/131] Drop the Spring Boot version from the BOM inheritance rule in AGENTS.md The rule holds for whichever spring-boot-dependencies version the build imports, so it no longer needs editing on every Spring Boot bump. --- AGENTS.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/AGENTS.md b/AGENTS.md index 9d6531229d9..b1ca45e956f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -144,7 +144,7 @@ All managed dependency versions live in `dependencies.gradle` (the single source - **Do not suppress validation to work around a bump.** `allowedBomOverrides` (per-project ext) and dependency exclusions are reserved for an explicit, documented conflict or an agreed-upon workaround — never as a shortcut to silence a version the BOM should simply manage. Comment the reason when you must use one. - **A dependency managed in more than one BOM must use the *same* version everywhere.** Versions appear in `gradleBomDependencyVersions` (build tooling / `grails-gradle-bom`), `bomDependencyVersions` (`grails-bom`), and per-BOM `customBomVersions` blocks (e.g. `grails-hibernate7-bom`). `grails-bom` re-declares the gradle-BOM constraints, and the Hibernate BOMs are consumed via `enforcedPlatform`. Declaring one coordinate (e.g. `org.ow2.asm:asm`) at two different versions across these maps produces irreconcilable strict constraints and breaks `enforcedPlatform` resolution. Pin it once, consistently. - **Only libraries the Grails project also works on may use a snapshot version.** Between releases, `dependencies.gradle` often points at a `-SNAPSHOT` or release-candidate version of one of our own libraries, such as the Asset Pipeline (`cloud.wondrify`), SiteMesh 3 (`org.sitemesh`), or the Grails Publish plugin (`org.apache.grails.gradle:grails-publish`). These are switched to their published version before a Grails release (see `RELEASE.md`). Do not suggest replacing them with a released version, and do not flag them in reviews. Never use a snapshot of any other library, such as Jackson or Spring. The snapshot repositories in `GrailsRepoSettingsPlugin` only serve the `org.apache.grails*`, `org.apache.groovy*`, `cloud.wondrify*`, and `org.sitemesh*` groups, so a snapshot of any other library will not resolve (unless `GRAILS_INCLUDE_MAVEN_LOCAL` is set for a local build). Do not widen those content filters to get one. -- **Prefer inheriting from the Spring Boot BOM.** Do not re-pin a coordinate that `spring-boot-dependencies` (4.2.x) already manages unless you are intentionally overriding it to a newer version (e.g. a security fix); note the reason inline. +- **Prefer inheriting from the Spring Boot BOM.** Do not re-pin a coordinate that `spring-boot-dependencies` already manages unless you are intentionally overriding it to a newer version (e.g. a security fix); note the reason inline. - **An override of a Spring Boot managed version must use Spring Boot's property name, and must change the version.** `validateBomProperties` (plugin `org.apache.grails.buildsrc.bom-property-validator`, run in its own CI job) checks the POM each Grails BOM publishes against `spring-boot-dependencies` (`parentBoms` in `dependencies.gradle`). It fails when a pin is declared under a different property than the one Boot controls it with - for a module Boot manages through an imported BOM, that is the import's property (`jackson-bom.version`, not `jackson3.version`) - and when a pin repeats Boot's version. Rename the version key (and the dependency keys that must prefix it) or drop the pin. - **Every version key must be used.** The same task (opt out with `-PskipBomPropertyValidation`, not `skipDependencyValidation`) fails when a version property a BOM owns (`bomVersionProperties` in each BOM's build script) is used by no entry of its published POM - a key no dependency references, or one whose dependency keys do not reduce to it. Delete the key or add the dependency that should use it. The few deliberate exceptions to these rules live, each with its reason, in `bomUnusedVersionExemptions` / `bomPropertyNameExemptions` / `bomRedundantVersionExemptions` in `dependencies.gradle`. - **No two dependencies may provide the same class.** The `buildHealth` task (the `com.autonomousapps.build-health` settings plugin, configured in `gradle/dependency-analysis.settings.gradle`, which applies it to a build only when one of its tasks is requested by full name, so a plain build never pays for it) fails when two dependencies on a classpath provide the same fully qualified class name that the module's own code references, because compile and runtime behavior then depend on classpath order. The Build Health workflow runs it on every push and pull request, alongside the code style checks. Resolve a report by removing or excluding the redundant dependency; its other categories (unused or transitive dependencies, wrong configurations) are advice only. From 5d176de0da03e436e0917c2af0669a007b216c4e Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Mon, 5 Oct 2026 16:19:54 -0700 Subject: [PATCH 015/131] Document the graphql-java 26 changes that reach GraphQL applications Spring Boot 4.2 moves grails-data-graphql from graphql-java 25 to 26.1, and 26.0 has breaking changes. A new "Upgrading from Grails 9.0 to Grails 9.1" section lists the ones a Grails application can meet: query complexity limits enforced by default (100 levels, 100,000 fields) and how to change them with QueryComplexityLimits.setDefaultLimits, the deprecated non-null argument and input field validation that code-built schemas now get, and the named-type rule for additional schema types. What's New links to it. QueryComplexityLimitsSpec runs those limits against the schema the plugin generates: a 101-level query fails by default, raised and disabled limits let deeper queries through, and parse errors count as failures, since graphql-java's parser stops past about 165 levels on its own. --- .../graphql/QueryComplexityLimitsSpec.groovy | 105 ++++++++++++++++++ .../src/en/guide/introduction/whatsNew.adoc | 1 + grails-doc/src/en/guide/toc.yml | 1 + .../src/en/guide/upgrading/upgrading91x.adoc | 70 ++++++++++++ 4 files changed, 177 insertions(+) create mode 100644 grails-data-graphql/core/src/test/groovy/org/grails/gorm/graphql/QueryComplexityLimitsSpec.groovy create mode 100644 grails-doc/src/en/guide/upgrading/upgrading91x.adoc diff --git a/grails-data-graphql/core/src/test/groovy/org/grails/gorm/graphql/QueryComplexityLimitsSpec.groovy b/grails-data-graphql/core/src/test/groovy/org/grails/gorm/graphql/QueryComplexityLimitsSpec.groovy new file mode 100644 index 00000000000..2d90b624843 --- /dev/null +++ b/grails-data-graphql/core/src/test/groovy/org/grails/gorm/graphql/QueryComplexityLimitsSpec.groovy @@ -0,0 +1,105 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.grails.gorm.graphql + +import graphql.ExecutionInput +import graphql.ParseAndValidate +import graphql.schema.GraphQLSchema +import graphql.validation.QueryComplexityLimits +import graphql.validation.ValidationError +import graphql.validation.ValidationErrorType +import org.grails.datastore.mapping.config.Settings +import org.grails.datastore.mapping.core.DatastoreUtils +import org.grails.gorm.graphql.domain.general.GeneralPackage +import org.grails.gorm.graphql.domain.hibernate.HibernatePackage +import org.grails.orm.hibernate.HibernateDatastore +import spock.lang.AutoCleanup +import spock.lang.Shared +import spock.lang.Specification + +/** + * graphql-java 26 enforces query complexity limits by default; the upgrade guide tells + * applications to adjust them with {@link QueryComplexityLimits#setDefaultLimits}. + */ +class QueryComplexityLimitsSpec extends Specification { + + @Shared @AutoCleanup HibernateDatastore hibernateDatastore + @Shared GraphQLSchema schema + + void setupSpec() { + hibernateDatastore = new HibernateDatastore( + DatastoreUtils.createPropertyResolver(Collections.singletonMap(Settings.SETTING_DB_CREATE, 'create-drop')), + GeneralPackage.getPackage(), HibernatePackage.getPackage()) + schema = new Schema(hibernateDatastore.mappingContext).generate() + } + + void cleanup() { + QueryComplexityLimits.setDefaultLimits(QueryComplexityLimits.DEFAULT) + } + + void 'a query nested 100 levels deep passes the default limits'() { + expect: + errors(nestedQuery(100)).empty + } + + void 'a query nested more than 100 levels deep fails the default limits'() { + expect: + errors(nestedQuery(101)) == [ValidationErrorType.MaxQueryDepthExceeded.name()] + } + + void 'raised default limits let a deeper query pass'() { + given: + QueryComplexityLimits.setDefaultLimits(QueryComplexityLimits.newLimits() + .maxDepth(150) + .maxFieldsCount(200_000) + .build()) + + expect: + errors(nestedQuery(150)).empty + errors(nestedQuery(151)) == [ValidationErrorType.MaxQueryDepthExceeded.name()] + } + + void 'the limits can be turned off'() { + given: + QueryComplexityLimits.setDefaultLimits(QueryComplexityLimits.NONE) + + expect: + errors(nestedQuery(160)).empty + } + + /** + * DebugCircular refers to itself through otherCircular, so a query can nest as deep as + * needed: debugBarList and circular are the first two levels, every otherCircular adds one + * and id is the last. + */ + private static String nestedQuery(int depth) { + int nested = depth - 3 + '{ debugBarList { circular { ' + 'otherCircular { ' * nested + 'id' + ' }' * nested + ' } } }' + } + + /** + * The validation error types, or the class of any other error, so a query the parser + * rejects (graphql-java stops parsing past about 165 levels) cannot pass as valid. + */ + private List errors(String query) { + ParseAndValidate.parseAndValidate(schema, ExecutionInput.newExecutionInput(query).build()).errors.collect { + it instanceof ValidationError ? ((ValidationError) it).validationErrorType.name() : it.getClass().simpleName + } + } +} diff --git a/grails-doc/src/en/guide/introduction/whatsNew.adoc b/grails-doc/src/en/guide/introduction/whatsNew.adoc index 33d38a0c45c..b78b9757578 100644 --- a/grails-doc/src/en/guide/introduction/whatsNew.adoc +++ b/grails-doc/src/en/guide/introduction/whatsNew.adoc @@ -43,6 +43,7 @@ This brings the Spring Boot 4 modular artifact layout, Spring Framework 7 API re The Grails 8 upgrade guide calls out the major application-impacting changes and links to the Spring Boot 4.0 migration guide, Spring Boot 4.1 release notes and Spring Framework 7.0 release notes. For the changes since Spring Boot 4.1, see the https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-4.2-Release-Notes[Spring Boot 4.2 Release Notes] and the https://github.com/spring-projects/spring-framework/wiki/Spring-Framework-7.1-Release-Notes[Spring Framework 7.1 Release Notes]. +The xref:upgrading#upgrading91x[Upgrading from Grails 9.0 to Grails 9.1] section covers the upgrade, including the graphql-java 26 changes that affect GraphQL applications. ==== JSON Dates and Times Render as Spring Boot Renders Them diff --git a/grails-doc/src/en/guide/toc.yml b/grails-doc/src/en/guide/toc.yml index 66914193112..264738798c1 100644 --- a/grails-doc/src/en/guide/toc.yml +++ b/grails-doc/src/en/guide/toc.yml @@ -37,6 +37,7 @@ gettingStarted: developmentReloading: Development Reloading upgrading: title: Upgrading from the previous versions + upgrading91x: Upgrading from Grails 9.0 to Grails 9.1 upgrading80x: Upgrading from Grails 7 to Grails 8 upgrading72x: Upgrading from Grails 7.1 to Grails 7.2 upgrading71x: Upgrading from Grails 7.0 to Grails 7.1 diff --git a/grails-doc/src/en/guide/upgrading/upgrading91x.adoc b/grails-doc/src/en/guide/upgrading/upgrading91x.adoc new file mode 100644 index 00000000000..5a99148983f --- /dev/null +++ b/grails-doc/src/en/guide/upgrading/upgrading91x.adoc @@ -0,0 +1,70 @@ +//// +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. +//// + +=== Upgrade Instructions for Grails 9.0 to Grails 9.1 + +This guide outlines the changes introduced in Grails 9.1 and the steps required to upgrade your application. + +==== 1. Spring Boot 4.2 and Spring Framework 7.1 + +Grails 9.1 moves from Spring Boot 4.1 to Spring Boot {springBootVersion} and from Spring Framework 7.0 to Spring Framework {springVersion}. +The managed versions that change include Spring Security 7.2, Spring Data 2026.1, Micrometer 1.18 and Reactor 2026.0. +Review the https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-4.2-Release-Notes[Spring Boot 4.2 Release Notes] and the https://github.com/spring-projects/spring-framework/wiki/Spring-Framework-7.1-Release-Notes[Spring Framework 7.1 Release Notes] for the changes that affect your application. + +==== 2. graphql-java 26 for GraphQL Applications + +Spring Boot 4.2 manages graphql-java 26, so applications using the GraphQL plugin (`grails-data-graphql`) move from graphql-java 25 to graphql-java 26.1. +graphql-java 26.0 contains breaking changes, listed in its https://github.com/graphql-java/graphql-java/releases/tag/v26.0[release notes]. +The ones that can affect a Grails application are: + +* *Query complexity limits are enforced by default.* +A query nested more than 100 levels deep, or selecting more than 100,000 fields, now fails validation with a `MaxQueryDepthExceeded` or `MaxQueryFieldsExceeded` error. +To raise the limits, or to turn them off, set new defaults when the application starts, for example in `BootStrap.groovy`: ++ +[source,groovy] +---- +import graphql.validation.QueryComplexityLimits + +class BootStrap { + + def init = { + QueryComplexityLimits.setDefaultLimits(QueryComplexityLimits.newLimits() + .maxDepth(150) + .maxFieldsCount(200_000) + .build()) + // or, to turn the limits off: + // QueryComplexityLimits.setDefaultLimits(QueryComplexityLimits.NONE) + } +} +---- ++ +graphql-java's parser separately rejects a query nested more than about 165 levels deep, so a `maxDepth` above that has no effect. + +* *Schemas built in code are validated like schemas built from SDL.* +A non-null argument or input field can no longer be deprecated. +The schema the plugin generates never deprecates an argument or an input field, but arguments and input types an application adds through a `GraphQLSchemaInterceptor` must follow the rule. + +* *Additional schema types must be named types.* +`GraphQLSchemaInterceptor.interceptSchema` still receives the additional types as a `Set`, and the plugin unwraps list and non-null wrappers before it builds the schema, so existing interceptors need no change. +Code that builds a `GraphQLSchema` directly must pass `GraphQLNamedType` instances to `GraphQLSchema.Builder.additionalTypes`. + +The other breaking changes (the validation rule filter, the removal of `DirectiveInfo`, and the JSpecify nullability annotations) only affect code that uses graphql-java directly. +The nullability annotations document existing behavior and do not change what graphql-java returns at runtime. + +The plugin continues to use graphql-java-extended-scalars 24.0, its latest release, which works with graphql-java 26.1. From 7b91b998ce133ebabfea5563ab03d28d18d7cf14 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Tue, 6 Oct 2026 12:18:38 -0700 Subject: [PATCH 016/131] Limit the 9.1 upgrade note's deprecation rule to required arguments graphql-java only rejects deprecating a non-null argument or input field that has no default value (DeprecatedInputObjectAndArgumentsAreValid checks hasSetDefaultValue); a non-null one with a default can still be deprecated. --- grails-doc/src/en/guide/upgrading/upgrading91x.adoc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/grails-doc/src/en/guide/upgrading/upgrading91x.adoc b/grails-doc/src/en/guide/upgrading/upgrading91x.adoc index 5a99148983f..f47bd07a801 100644 --- a/grails-doc/src/en/guide/upgrading/upgrading91x.adoc +++ b/grails-doc/src/en/guide/upgrading/upgrading91x.adoc @@ -57,7 +57,7 @@ class BootStrap { graphql-java's parser separately rejects a query nested more than about 165 levels deep, so a `maxDepth` above that has no effect. * *Schemas built in code are validated like schemas built from SDL.* -A non-null argument or input field can no longer be deprecated. +A required argument or input field (non-null with no default value) can no longer be deprecated. The schema the plugin generates never deprecates an argument or an input field, but arguments and input types an application adds through a `GraphQLSchemaInterceptor` must follow the rule. * *Additional schema types must be named types.* From 76626c94704bba3c1ba0abe5e9414395c218072f Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Tue, 6 Oct 2026 12:21:26 -0700 Subject: [PATCH 017/131] Say Groovy YAML depends on Jackson 2.22.2 rather than requires it groovy-yaml 6.0.0 declares Jackson 2.22.2 as an ordinary dependency, which wins over the 2.21.6 Spring Boot 4.2 manages; nothing marks 2.22 as a minimum. The pin exists because the BOM must manage the winning version. --- dependencies.gradle | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/dependencies.gradle b/dependencies.gradle index 6596ada9e8c..8c9d8369492 100644 --- a/dependencies.gradle +++ b/dependencies.gradle @@ -85,9 +85,9 @@ ext { 'graphql-java-extended-scalars.version': '24.0', 'groovy.version' : '6.0.0', 'guava.version' : '33.7.1-jre', - // Groovy YAML 6.0.0 requires Jackson 2.22.x, newer than the 2.21.6 Spring Boot 4.2 - // manages. Jackson 2 only releases jackson-annotations on the minor, hence the separate - // 2.22 below. + // Groovy YAML 6.0.0 depends on Jackson 2.22.2, which wins over the 2.21.6 Spring Boot 4.2 + // manages, so the BOM must manage at least that. Jackson 2 only releases jackson-annotations + // on the minor, hence the separate 2.22 below. 'jackson-2-bom.version' : '2.22.2', 'jackson2-annotations.version' : '2.22', 'jquery.version' : '4.0.0', From ede220df40463dfd2d0fa6f0bc14893db206f321 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Mon, 12 Oct 2026 07:31:56 -0700 Subject: [PATCH 018/131] Drop the Tomcat and SLF4J pins that repeat Spring Boot 4.2.0-M2's versions 9.0.x pins Tomcat 11.0.26 as a security override of the 11.0.24 Spring Boot 4.1 manages, and SLF4J 2.0.19 above 4.1's 2.0.18 for Logback 1.6.5. Spring Boot 4.2.0-M2 manages exactly those versions, so validateBomProperties fails on the repeated pins and they and their entries go; the Tomcat CVE fixes and the SLF4J version Logback needs come from Spring Boot itself. --- dependencies.gradle | 14 -------------- 1 file changed, 14 deletions(-) diff --git a/dependencies.gradle b/dependencies.gradle index f3c46c9e9d1..4e3cf527bc8 100644 --- a/dependencies.gradle +++ b/dependencies.gradle @@ -118,8 +118,6 @@ ext { 'rxjava2.version' : '2.2.21', 'sitemesh.version' : '2.6.0', 'scribejava.version' : '8.3.3', - // Logback 1.6.5 requires 2.0.19; align the SLF4J family above Boot's managed 2.0.18. - 'slf4j.version' : '2.0.19', 'spock.version' : '2.5-groovy-6.0', // Not managed by spring-boot-dependencies. springdoc 3.x is the Spring Boot 4 / // Spring Framework 7 line; the grails-openapi module compiles against its @@ -134,9 +132,6 @@ ext { // grails-shell-cli SpringRetryCompilerAutoConfiguration's unversioned // reference resolves and consumer apps using @Retryable get a known version. 'spring-retry.version' : '2.0.13', - // Security: overrides Tomcat 11.0.24 from Spring Boot 4.1. Includes the fixes for - // CVE-2026-65905, CVE-2026-65182, CVE-2026-68525 and CVE-2026-65927 on the Servlet 6.1 line. - 'tomcat.version' : '11.0.26', // Undertow is no longer managed by spring-boot-dependencies: Spring Boot 4 // removed its Undertow support before GA. Servlet 6.1 support ships as // undertow-core 2.4.x plus the io.undertow.ee servlet/websockets artifacts, @@ -151,7 +146,6 @@ ext { 'asset-pipeline-bom': "cloud.wondrify:asset-pipeline-bom:${bomDependencyVersions['asset-pipeline-bom.version']}", 'groovy-bom' : "org.apache.groovy:groovy-bom:${bomDependencyVersions['groovy.version']}", 'jackson-bom' : "tools.jackson:jackson-bom:${bomDependencyVersions['jackson-bom.version']}", - 'slf4j-bom' : "org.slf4j:slf4j-bom:${bomDependencyVersions['slf4j.version']}", 'spock-bom' : "org.spockframework:spock-bom:${bomDependencyVersions['spock.version']}", ] @@ -245,14 +239,6 @@ ext { 'swagger-models-jakarta' : "io.swagger.core.v3:swagger-models-jakarta:${bomDependencyVersions['swagger.version']}", 'starter-sitemesh' : "org.sitemesh:spring-boot-starter-sitemesh:${bomDependencyVersions['starter-sitemesh.version']}", 'spring-webmvc-sitemesh' : "org.sitemesh:spring-webmvc-sitemesh:${bomDependencyVersions['spring-webmvc-sitemesh.version']}", - // Security override of spring-boot-dependencies - see tomcat.version - 'tomcat-annotations-api' : "org.apache.tomcat:tomcat-annotations-api:${bomDependencyVersions['tomcat.version']}", - 'tomcat-jdbc' : "org.apache.tomcat:tomcat-jdbc:${bomDependencyVersions['tomcat.version']}", - 'tomcat-jsp-api' : "org.apache.tomcat:tomcat-jsp-api:${bomDependencyVersions['tomcat.version']}", - 'tomcat-embed-core' : "org.apache.tomcat.embed:tomcat-embed-core:${bomDependencyVersions['tomcat.version']}", - 'tomcat-embed-el' : "org.apache.tomcat.embed:tomcat-embed-el:${bomDependencyVersions['tomcat.version']}", - 'tomcat-embed-jasper' : "org.apache.tomcat.embed:tomcat-embed-jasper:${bomDependencyVersions['tomcat.version']}", - 'tomcat-embed-websocket' : "org.apache.tomcat.embed:tomcat-embed-websocket:${bomDependencyVersions['tomcat.version']}", // Not managed by spring-boot-dependencies - see undertow.version 'undertow-core' : "io.undertow:undertow-core:${bomDependencyVersions['undertow.version']}", 'undertow-servlet' : "io.undertow.ee:undertow-servlet:${bomDependencyVersions['undertow-servlet.version']}", From 0180ce9410df445c5d7ffba789689e02b3fea171 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Mon, 12 Oct 2026 07:33:09 -0700 Subject: [PATCH 019/131] Describe the CVE-2026-47842 exclusion for Spring Security 7.2.0-M2 The reason still named 7.1.1 and Spring Boot 4.1.1 and asked to be reassessed on a Spring Security upgrade. Spring's advisory lists only 7.1.0 on the 7.1 line as affected; 7.2.0-M2, which Spring Boot 4.2.0-M2 manages, is not listed and contains the AesCbcBytesEncryptor and AesGcmBytesEncryptor replacements the 7.1.1 fix introduced, so the exclusion still holds. --- .../grails/buildsrc/scan/VulnerabilityScanPlugin.groovy | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/build-logic/vulnerability-scan/src/main/groovy/org/apache/grails/buildsrc/scan/VulnerabilityScanPlugin.groovy b/build-logic/vulnerability-scan/src/main/groovy/org/apache/grails/buildsrc/scan/VulnerabilityScanPlugin.groovy index 96cc34b088b..97a661ca16d 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 @@ -88,9 +88,11 @@ class VulnerabilityScanPlugin implements Plugin { '5.7.x through 6.5.10 as affected. The 7.x line already carries the fix for the preceding ' + 'CVE-2026-22747. Remove once Sonatype narrows its affected range'), new VulnerabilityExclusion('CVE-2026-47842', 'org.springframework.security:spring-security-crypto', - 'Sonatype flags 7.1.1, but https://spring.io/security/cve-2026-47842 explicitly lists 7.1.1 as ' + - 'fixed. It is the latest stable 7.1.x release and the version Spring Boot 4.1.1 manages. ' + - 'Remove once Sonatype corrects its affected range; reassess on any Spring Security upgrade'), + 'Sonatype flagged 7.1.1, but https://spring.io/security/cve-2026-47842 lists only 7.1.0 on ' + + 'the 7.1 line as affected and 7.1.1 as fixed. Spring Boot 4.2.0-M2 manages 7.2.0-M2, which ' + + 'the advisory does not list and which carries the fix (the AesCbcBytesEncryptor and ' + + 'AesGcmBytesEncryptor replacements 7.1.1 introduced). Remove once Sonatype corrects its ' + + 'affected range; reassess on any Spring Security upgrade'), ].asImmutable() @Override From 07566b4fec821b35a25f1ada0a001d389a1f99aa Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Mon, 12 Oct 2026 07:36:02 -0700 Subject: [PATCH 020/131] Make the upgrade notes the Grails 8 to Grails 9 guide With the PR on 9.0.x (9.0.0-SNAPSHOT), applications get Spring Boot 4.2 and graphql-java 26 when they upgrade from Grails 8, not from 9.0 to 9.1. The section moves to upgrading90x, "Upgrading from Grails 8 to Grails 9", above the Grails 7 to Grails 8 entry, and opens by describing the move from Grails 8 on Spring Boot 4.1. What's New points its introduction and its Spring Boot 4.2 section at it. --- grails-doc/src/en/guide/introduction/whatsNew.adoc | 4 ++-- grails-doc/src/en/guide/toc.yml | 2 +- .../upgrading/{upgrading91x.adoc => upgrading90x.adoc} | 6 +++--- 3 files changed, 6 insertions(+), 6 deletions(-) rename grails-doc/src/en/guide/upgrading/{upgrading91x.adoc => upgrading90x.adoc} (92%) diff --git a/grails-doc/src/en/guide/introduction/whatsNew.adoc b/grails-doc/src/en/guide/introduction/whatsNew.adoc index f8cd7d8542a..400af07c325 100644 --- a/grails-doc/src/en/guide/introduction/whatsNew.adoc +++ b/grails-doc/src/en/guide/introduction/whatsNew.adoc @@ -24,7 +24,7 @@ This section covers all the new features introduced in Grails {grailsMajorVersio Grails {grailsMajorVersion} is a major release that includes new features, improvements, and dependency upgrades. This release focuses on enhancing the developer experience, improving performance, and ensuring compatibility with the latest technologies. -For detailed information on how to upgrade to Grails {grailsMajorVersion}, including major dependency changes, please see the xref:upgrading#upgrading80x[Upgrading from Grails 7 to Grails {grailsMajorVersion}] section. +For detailed information on how to upgrade to Grails {grailsMajorVersion}, including major dependency changes, please see the xref:upgrading#upgrading90x[Upgrading from Grails 8 to Grails {grailsMajorVersion}] section. Notable new features are included below. ==== Platform Baseline @@ -49,7 +49,7 @@ This brings the Spring Boot 4 modular artifact layout, Spring Framework 7 API re The Grails 8 upgrade guide calls out the major application-impacting changes and links to the Spring Boot 4.0 migration guide, Spring Boot 4.1 release notes and Spring Framework 7.0 release notes. For the changes since Spring Boot 4.1, see the https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-4.2-Release-Notes[Spring Boot 4.2 Release Notes] and the https://github.com/spring-projects/spring-framework/wiki/Spring-Framework-7.1-Release-Notes[Spring Framework 7.1 Release Notes]. -The xref:upgrading#upgrading91x[Upgrading from Grails 9.0 to Grails 9.1] section covers the upgrade, including the graphql-java 26 changes that affect GraphQL applications. +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. ==== JSON Dates and Times Render as Spring Boot Renders Them diff --git a/grails-doc/src/en/guide/toc.yml b/grails-doc/src/en/guide/toc.yml index 592a0286ec8..14bfb1dc6d1 100644 --- a/grails-doc/src/en/guide/toc.yml +++ b/grails-doc/src/en/guide/toc.yml @@ -37,7 +37,7 @@ gettingStarted: developmentReloading: Development Reloading upgrading: title: Upgrading from the previous versions - upgrading91x: Upgrading from Grails 9.0 to Grails 9.1 + upgrading90x: Upgrading from Grails 8 to Grails 9 upgrading80x: Upgrading from Grails 7 to Grails 8 upgrading72x: Upgrading from Grails 7.1 to Grails 7.2 upgrading71x: Upgrading from Grails 7.0 to Grails 7.1 diff --git a/grails-doc/src/en/guide/upgrading/upgrading91x.adoc b/grails-doc/src/en/guide/upgrading/upgrading90x.adoc similarity index 92% rename from grails-doc/src/en/guide/upgrading/upgrading91x.adoc rename to grails-doc/src/en/guide/upgrading/upgrading90x.adoc index f47bd07a801..e8002e353d9 100644 --- a/grails-doc/src/en/guide/upgrading/upgrading91x.adoc +++ b/grails-doc/src/en/guide/upgrading/upgrading90x.adoc @@ -17,13 +17,13 @@ specific language governing permissions and limitations under the License. //// -=== Upgrade Instructions for Grails 9.0 to Grails 9.1 +=== Upgrade Instructions for Grails 8 to Grails 9 -This guide outlines the changes introduced in Grails 9.1 and the steps required to upgrade your application. +This guide outlines the changes introduced in Grails 9 and the steps required to upgrade your application. ==== 1. Spring Boot 4.2 and Spring Framework 7.1 -Grails 9.1 moves from Spring Boot 4.1 to Spring Boot {springBootVersion} and from Spring Framework 7.0 to Spring Framework {springVersion}. +Grails 9 moves from Spring Boot 4.1 and Spring Framework 7.0, which Grails 8 uses, to Spring Boot {springBootVersion} and Spring Framework {springVersion}. The managed versions that change include Spring Security 7.2, Spring Data 2026.1, Micrometer 1.18 and Reactor 2026.0. Review the https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-4.2-Release-Notes[Spring Boot 4.2 Release Notes] and the https://github.com/spring-projects/spring-framework/wiki/Spring-Framework-7.1-Release-Notes[Spring Framework 7.1 Release Notes] for the changes that affect your application. From fe8f6d0d9ecfc75535e2aab50f224969fb58efba Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Mon, 12 Oct 2026 07:37:27 -0700 Subject: [PATCH 021/131] Import ParameterizedTypeReference in MockApplicationContext Both getBean(String, ParameterizedTypeReference) and getBeanProvider spelled the type out in full, while ResolvableType beside it is imported. --- .../groovy/org/grails/support/MockApplicationContext.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/grails-test-suite-base/src/main/groovy/org/grails/support/MockApplicationContext.java b/grails-test-suite-base/src/main/groovy/org/grails/support/MockApplicationContext.java index c694697dcb8..4283b29d075 100644 --- a/grails-test-suite-base/src/main/groovy/org/grails/support/MockApplicationContext.java +++ b/grails-test-suite-base/src/main/groovy/org/grails/support/MockApplicationContext.java @@ -50,6 +50,7 @@ import org.springframework.context.MessageSource; import org.springframework.context.MessageSourceResolvable; import org.springframework.context.NoSuchMessageException; +import org.springframework.core.ParameterizedTypeReference; import org.springframework.core.ResolvableType; import org.springframework.core.env.Environment; import org.springframework.core.io.AbstractResource; @@ -283,7 +284,7 @@ public T getBean(String name, Class requiredType) throws BeansException { @Override @SuppressWarnings("unchecked") - public T getBean(String name, org.springframework.core.ParameterizedTypeReference requiredType) throws BeansException { + public T getBean(String name, ParameterizedTypeReference requiredType) throws BeansException { return (T) getBean(name, ResolvableType.forType(requiredType.getType()).toClass()); } @@ -519,7 +520,7 @@ public T getObject() throws BeansException { } @Override - public ObjectProvider getBeanProvider(org.springframework.core.ParameterizedTypeReference requiredType) { + public ObjectProvider getBeanProvider(ParameterizedTypeReference requiredType) { return getBeanProvider(ResolvableType.forType(requiredType.getType())); } } From 9fbf63f9f0283af04cfe2ff2acc78f65f70dfc37 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Mon, 12 Oct 2026 07:37:27 -0700 Subject: [PATCH 022/131] Sort the NameGenerator import in the OpenAPI ahead-of-time spec Renaming ClassNameGenerator in place left NameGenerator ahead of DefaultGenerationContext; the grails-core specs already list it in order. --- .../aot/OpenApiBeanFactoryInitializationAotProcessorSpec.groovy | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/grails-openapi/src/test/groovy/org/apache/grails/openapi/aot/OpenApiBeanFactoryInitializationAotProcessorSpec.groovy b/grails-openapi/src/test/groovy/org/apache/grails/openapi/aot/OpenApiBeanFactoryInitializationAotProcessorSpec.groovy index 48ab8b62017..d0f834cf73e 100644 --- a/grails-openapi/src/test/groovy/org/apache/grails/openapi/aot/OpenApiBeanFactoryInitializationAotProcessorSpec.groovy +++ b/grails-openapi/src/test/groovy/org/apache/grails/openapi/aot/OpenApiBeanFactoryInitializationAotProcessorSpec.groovy @@ -21,9 +21,9 @@ package org.apache.grails.openapi.aot import io.swagger.v3.oas.annotations.media.Content import io.swagger.v3.oas.annotations.media.Schema import io.swagger.v3.oas.annotations.responses.ApiResponse -import org.springframework.aot.generate.NameGenerator import org.springframework.aot.generate.DefaultGenerationContext import org.springframework.aot.generate.InMemoryGeneratedFiles +import org.springframework.aot.generate.NameGenerator import org.springframework.aot.hint.MemberCategory import org.springframework.aot.hint.RuntimeHints import org.springframework.aot.hint.RuntimeHintsRegistrar From e378140fde4649d53772ba12e7cc94faf476bad0 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Mon, 12 Oct 2026 07:56:41 -0700 Subject: [PATCH 023/131] Read the forwarded scheme with Spring Framework 7.1's per-format parsers Spring Framework 7.1 deprecates ForwardedHeaderUtils.adaptFromForwardedHeaders for removal in favor of parseStandardHeader and parseXForwardedHeaders, so callers choose a header format. GrailsSecurityHeadersFilter, which only needs the scheme for its HSTS decision, keeps the precedence the old method applied: the RFC 7239 Forwarded header when the request has one, otherwise X-Forwarded-Proto and X-Forwarded-Ssl. Two edge cases change, both only for HSTS, which user agents ignore on a plain connection: X-Forwarded-Ssl is no longer consulted next to a Forwarded header without proto, and a malformed for or by address in the Forwarded header now invalidates it like any other malformed forwarded value. The spec covers both, and that RFC 7239 obfuscated and quoted IPv6 for values still parse. --- .../GrailsSecurityHeadersFilter.java | 19 +++++++++----- ...ecurityHeadersAutoConfigurationSpec.groovy | 26 +++++++++++++++++++ 2 files changed, 39 insertions(+), 6 deletions(-) diff --git a/grails-controllers/src/main/groovy/org/grails/plugins/web/controllers/GrailsSecurityHeadersFilter.java b/grails-controllers/src/main/groovy/org/grails/plugins/web/controllers/GrailsSecurityHeadersFilter.java index 2a676bed6e0..3905d4b739d 100644 --- a/grails-controllers/src/main/groovy/org/grails/plugins/web/controllers/GrailsSecurityHeadersFilter.java +++ b/grails-controllers/src/main/groovy/org/grails/plugins/web/controllers/GrailsSecurityHeadersFilter.java @@ -76,6 +76,7 @@ public class GrailsSecurityHeadersFilter extends OncePerRequestFilter { private static final Logger logger = LoggerFactory.getLogger(GrailsSecurityHeadersFilter.class); private static final String HTTPS = "https"; + private static final String FORWARDED = "Forwarded"; private final GrailsSecurityHeadersProperties properties; @@ -171,11 +172,10 @@ private static String detectReverseProxyHeader(HttpServletRequest request) { /** * Whether the client connection is secure. Falls back to the scheme a reverse proxy - * forwards in the RFC 7239 {@code Forwarded} header or in {@code X-Forwarded-Proto} - * (and {@code X-Forwarded-Ssl}), read the same way Spring's {@code ForwardedHeaderFilter} - * reads them, when the container itself saw plain HTTP. That is the case behind a - * TLS-terminating proxy that has not been configured through - * {@code server.forward-headers-strategy}. Trusting the forwarded scheme is safe for + * forwards in the RFC 7239 {@code Forwarded} header when the request has one, otherwise in + * {@code X-Forwarded-Proto} (and {@code X-Forwarded-Ssl}), when the container itself saw + * plain HTTP. That is the case behind a TLS-terminating proxy that has not been configured + * through {@code server.forward-headers-strategy}. Trusting the forwarded scheme is safe for * HSTS: user agents ignore a {@code Strict-Transport-Security} header received over a * non-secure transport (RFC 6797, section 8.1), so a spoofed header on a plain * connection has no effect. @@ -190,7 +190,14 @@ private static boolean isSecure(HttpServletRequest request) { // scheme alone rather than to its URL: java.net.URI rejects request paths the // container may accept, such as those allowed through Tomcat's relaxedPathChars. URI base = URI.create(request.getScheme() + "://localhost"); - String scheme = ForwardedHeaderUtils.adaptFromForwardedHeaders(base, headers).build().getScheme(); + ForwardedHeaderUtils.ForwardedInfo forwarded; + if (StringUtils.hasText(headers.getFirst(FORWARDED))) { + forwarded = ForwardedHeaderUtils.parseStandardHeader(base, headers, null, null); + } + else { + forwarded = ForwardedHeaderUtils.parseXForwardedHeaders(base, headers, null, null); + } + String scheme = forwarded.uriComponentsBuilder().build().getScheme(); return HTTPS.equalsIgnoreCase(scheme); } catch (IllegalArgumentException malformedForwardedHeaders) { diff --git a/grails-controllers/src/test/groovy/org/grails/plugins/web/controllers/GrailsSecurityHeadersAutoConfigurationSpec.groovy b/grails-controllers/src/test/groovy/org/grails/plugins/web/controllers/GrailsSecurityHeadersAutoConfigurationSpec.groovy index a61c75152e5..01735121e31 100644 --- a/grails-controllers/src/test/groovy/org/grails/plugins/web/controllers/GrailsSecurityHeadersAutoConfigurationSpec.groovy +++ b/grails-controllers/src/test/groovy/org/grails/plugins/web/controllers/GrailsSecurityHeadersAutoConfigurationSpec.groovy @@ -903,6 +903,8 @@ class GrailsSecurityHeadersAutoConfigurationSpec extends Specification { 'Forwarded' | 'for=192.0.2.60; PROTO=https' || true 'Forwarded' | 'for=192.0.2.60;proto=http, proto=https' || false 'Forwarded' | 'for=192.0.2.60' || false + 'Forwarded' | 'for=unknown;proto=https' || true + 'Forwarded' | 'for="[2001:db8:cafe::17]:4711";proto=https' || true 'X-Forwarded-Ssl' | 'on' || true 'X-Forwarded-For' | '192.0.2.60' || false } @@ -930,6 +932,30 @@ class GrailsSecurityHeadersAutoConfigurationSpec extends Specification { 'X-Forwarded-Port' | 'not-a-port' 'X-Forwarded-Host' | 'a:b:c' 'Forwarded' | 'host=a:b:c;proto=https' + 'Forwarded' | 'for=2001:db8:cafe::17;proto=https' + } + + @Unroll + void 'HSTS reads only the Forwarded header when the request has one: #headerName: #headerValue'() { + given: 'X-Forwarded-* headers are not consulted next to a Forwarded header' + def request = new MockHttpServletRequest('GET', '/') + request.secure = false + request.addHeader('Forwarded', 'for=192.0.2.60') + request.addHeader(headerName, headerValue) + def response = new MockHttpServletResponse() + def properties = new GrailsSecurityHeadersProperties() + properties.hsts.enabled = true + + when: + new GrailsSecurityHeadersFilter(properties).doFilter(request, response, new MockFilterChain()) + + then: + response.getHeader('Strict-Transport-Security') == null + + where: + headerName | headerValue + 'X-Forwarded-Proto' | 'https' + 'X-Forwarded-Ssl' | 'on' } @Unroll From 426e7362ad4b252b0b85070913fd2e46344e13d0 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Mon, 12 Oct 2026 08:05:00 -0700 Subject: [PATCH 024/131] Document the Spring Boot 4.2 changes that affect Grails applications The upgrade guide now lists the Spring Boot 4.2 and Spring Framework 7.1 changes a Grails application is most likely to notice: - server.forward-headers-strategy=framework reads only X-Forwarded-* by default, and the filter now comes from WebMvcAutoConfiguration, so an application declaring @EnableWebMvc no longer gets it - embedded Tomcat keeps relative redirect locations relative, which changes the Location header of chain() but not of redirect() - TestRestTemplate is deprecated for removal in favor of RestTestClient - Spring MVC no longer auto-detects the JAXB converter (Grails render and respond are unaffected) - tests load static nested @Configuration classes from superclasses and enclosing classes The deployment guide's reverse-proxy section names the header-format property for proxies that send the RFC 7239 Forwarded header. --- .../en/guide/deployment/deploymentTasks.adoc | 1 + .../src/en/guide/upgrading/upgrading90x.adoc | 50 +++++++++++++++++++ 2 files changed, 51 insertions(+) diff --git a/grails-doc/src/en/guide/deployment/deploymentTasks.adoc b/grails-doc/src/en/guide/deployment/deploymentTasks.adoc index d795655aadb..df4852231dd 100644 --- a/grails-doc/src/en/guide/deployment/deploymentTasks.adoc +++ b/grails-doc/src/en/guide/deployment/deploymentTasks.adoc @@ -191,6 +191,7 @@ See the link:{springBootReference}actuator/endpoints.html#actuator.endpoints.kub Many deployments terminate TLS at a reverse proxy or ingress. Keep certificate renewal there and restrict direct access to the application port. Configure forwarded-header handling only for a trusted proxy path, and have the boundary proxy remove untrusted client-supplied `Forwarded` and `X-Forwarded-*` headers. Choose `server.forward-headers-strategy=NATIVE` for supported embedded-container handling or `FRAMEWORK` for Spring's handling, according to your proxy's headers and trust configuration. +`FRAMEWORK` reads the `+X-Forwarded-*+` headers; if your proxy sends the RFC 7239 `Forwarded` header instead, also set `spring.mvc.forwarded-headers.header-format=STANDARD`. Test redirects, absolute URLs, secure cookies, and client-address handling through that proxy. See the link:{springBootHowTo}webserver.html#howto.webserver.use-behind-a-proxy-server[Spring Boot proxy guidance]. To terminate TLS in the embedded server instead, merge settings such as these into `application.yml` and mount the keystore read-only: diff --git a/grails-doc/src/en/guide/upgrading/upgrading90x.adoc b/grails-doc/src/en/guide/upgrading/upgrading90x.adoc index e8002e353d9..e690f8ff2f3 100644 --- a/grails-doc/src/en/guide/upgrading/upgrading90x.adoc +++ b/grails-doc/src/en/guide/upgrading/upgrading90x.adoc @@ -26,6 +26,56 @@ This guide outlines the changes introduced in Grails 9 and the steps required to Grails 9 moves from Spring Boot 4.1 and Spring Framework 7.0, which Grails 8 uses, to Spring Boot {springBootVersion} and Spring Framework {springVersion}. The managed versions that change include Spring Security 7.2, Spring Data 2026.1, Micrometer 1.18 and Reactor 2026.0. Review the https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-4.2-Release-Notes[Spring Boot 4.2 Release Notes] and the https://github.com/spring-projects/spring-framework/wiki/Spring-Framework-7.1-Release-Notes[Spring Framework 7.1 Release Notes] for the changes that affect your application. +The ones most likely to affect a Grails application are: + +* *`server.forward-headers-strategy: framework` reads only the `+X-Forwarded-*+` headers by default.* +Spring Framework 7.1's `ForwardedHeaderFilter` reads either the RFC 7239 `Forwarded` header or the `+X-Forwarded-*+` headers, and Spring Boot 4.2 configures it for `+X-Forwarded-*+`. +Before, it read `Forwarded` when the request carried one and `+X-Forwarded-*+` otherwise. +If your reverse proxy sends `Forwarded`, set `spring.mvc.forwarded-headers.header-format: standard`. +Spring Boot 4.2 also registers the filter from its Spring MVC auto-configuration, which backs off when the application declares `@EnableWebMvc`; such an application must now register a `ForwardedHeaderFilter` itself. + +* *Embedded Tomcat keeps relative redirect locations relative.* +`server.tomcat.servlet.use-relative-redirects`, renamed from `server.tomcat.use-relative-redirects`, now defaults to `true`, Tomcat's own default. +A redirect sent through `HttpServletResponse.sendRedirect` with a path, such as a controller `chain` call, a Spring Security redirect or a `redirect:` view name, now has a relative `Location` header instead of an absolute URL. +A controller `redirect` sets the `Location` header itself and still sends an absolute URL unless you pass `absolute: false`. +Browsers resolve relative locations; set the property to `false` if a client or test expects an absolute URL. + +* *`TestRestTemplate` is deprecated for removal.* +Spring Framework 7.1 deprecates `RestTemplate`, and Spring Boot 4.2 deprecates `TestRestTemplate` and `@AutoConfigureTestRestTemplate` with it. +Move `@SpringBootTest` tests to `RestTestClient`, which `@AutoConfigureRestTestClient` injects: ++ +[source,groovy] +---- +// Before +import org.springframework.boot.resttestclient.TestRestTemplate +import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureTestRestTemplate + +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@AutoConfigureTestRestTemplate +class BookApiSpec extends Specification { + @Autowired TestRestTemplate rest +} + +// After +import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureRestTestClient +import org.springframework.test.web.servlet.client.RestTestClient + +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@AutoConfigureRestTestClient +class BookApiSpec extends Specification { + @Autowired RestTestClient client +} +---- + +* *Spring MVC no longer detects the JAXB XML converter.* +Spring Framework 7.1 stops auto-detecting the JAXB message converter for server applications. +Grails `render` and `respond` write XML through Grails' own converters and are unaffected. +A Spring MVC `@RestController` that returns JAXB-annotated objects needs the converter registered explicitly, as the Spring Framework 7.1 release notes show. + +* *Tests load static nested `@Configuration` classes from their superclasses and enclosing classes.* +The Spring TestContext Framework used to ignore such a class unless its class hierarchy declared `@ContextConfiguration`, and now adds it to the test's application context. +Grails 8 already logs a warning for each one it ignores, so a test run on Grails 8 shows the affected tests. +Remove the `@Configuration` annotation, or move the class to a top-level class, if the test should not load it. ==== 2. graphql-java 26 for GraphQL Applications From 829de6092e391ecd4c3c958adce0f1b90a594aea Mon Sep 17 00:00:00 2001 From: James Daugherty Date: Tue, 13 Oct 2026 11:41:03 +0100 Subject: [PATCH 025/131] Set the 9.1.x branch version to 9.1.0-SNAPSHOT and githubBranch to 9.1.x --- THREAT_MODEL.md | 2 +- gradle.properties | 8 ++++---- .../src/test/groovy/grails/util/GrailsUtilTests.java | 2 +- threat-model.yaml | 2 +- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/THREAT_MODEL.md b/THREAT_MODEL.md index 5d33d05034d..605f3ca7f92 100644 --- a/THREAT_MODEL.md +++ b/THREAT_MODEL.md @@ -19,7 +19,7 @@ limitations under the License. ## §1 Header - **Project**: Apache Grails (`apache/grails-core`) -- **Version binding**: 9.0.x branch. A report against version *N* is triaged against this document as it stood at *N*, not at HEAD. +- **Version binding**: 9.1.x branch. A report against version *N* is triaged against this document as it stood at *N*, not at HEAD. - **Date**: 2026-01 - **Author**: Apache Grails PMC and contributors (initial draft). - **Status**: **DRAFT** - not yet ratified by maintainers. Open questions in §14 must be resolved before this document is binding. diff --git a/gradle.properties b/gradle.properties index 7e1176548d8..02ac559335e 100644 --- a/gradle.properties +++ b/gradle.properties @@ -13,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. -projectVersion=9.0.0-SNAPSHOT +projectVersion=9.1.0-SNAPSHOT javaVersion=21 -githubBranch=9.0.x +githubBranch=9.1.x # Last day this release line is supported (ISO yyyy-MM-dd). Grails Forge reports it from /versions. # Each release branch sets its own value. grailsEndOfSupport=2027-12-31 githubSlug=apache/grails-core -# 9.0.0-SNAPSHOT has never been published, so the Spring Dependency Management +# 9.1.0-SNAPSHOT has never been published, so the Spring Dependency Management # example cannot resolve its grails-bom import yet. Delete this line once the first -# 9.0.0-SNAPSHOT publish succeeds - the flag is presence-based, so setting it to +# 9.1.0-SNAPSHOT publish succeeds - the flag is presence-based, so setting it to # false still excludes the example. See settings.gradle for the full explanation. bomSnapshotNotPublished=true diff --git a/grails-core/src/test/groovy/grails/util/GrailsUtilTests.java b/grails-core/src/test/groovy/grails/util/GrailsUtilTests.java index f1106bf9ada..c78f04589e2 100644 --- a/grails-core/src/test/groovy/grails/util/GrailsUtilTests.java +++ b/grails-core/src/test/groovy/grails/util/GrailsUtilTests.java @@ -33,7 +33,7 @@ public class GrailsUtilTests { @Test public void testGrailsVersion() { - assertEquals("9.0.0-SNAPSHOT", GrailsUtil.getGrailsVersion()); + assertEquals("9.1.0-SNAPSHOT", GrailsUtil.getGrailsVersion()); } @AfterEach diff --git a/threat-model.yaml b/threat-model.yaml index 49b5eb3843f..a3d52e6a065 100644 --- a/threat-model.yaml +++ b/threat-model.yaml @@ -21,7 +21,7 @@ project: name: apache/grails-core - version_binding: "9.0.x" + version_binding: "9.1.x" threat_model: THREAT_MODEL.md status: draft date: "2026-01" From 80a84cc659accb2fd3fc40f37d32f5d0f4190944 Mon Sep 17 00:00:00 2001 From: James Daugherty Date: Thu, 22 Oct 2026 10:50:32 -0400 Subject: [PATCH 026/131] [skip tests] Build the AOT generation context with NameGenerator in the injection specs Spring Framework 7.1 replaces ClassNameGenerator with NameGenerator, which the other AOT specs on this branch already use. The two specs merged up from 8.0.x follow them. --- .../grails/boot/config/GeneratedArtifactsInjectionSpec.groovy | 4 ++-- .../GeneratedInjectionBeanRegistrationAotProcessorSpec.groovy | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/grails-core/src/test/groovy/grails/boot/config/GeneratedArtifactsInjectionSpec.groovy b/grails-core/src/test/groovy/grails/boot/config/GeneratedArtifactsInjectionSpec.groovy index f981bd7cd84..16889bb1d8d 100644 --- a/grails-core/src/test/groovy/grails/boot/config/GeneratedArtifactsInjectionSpec.groovy +++ b/grails-core/src/test/groovy/grails/boot/config/GeneratedArtifactsInjectionSpec.groovy @@ -29,10 +29,10 @@ import jakarta.annotation.PostConstruct import jakarta.annotation.PreDestroy import jakarta.annotation.Resource -import org.springframework.aot.generate.ClassNameGenerator import org.springframework.aot.generate.DefaultGenerationContext import org.springframework.aot.generate.GeneratedFiles import org.springframework.aot.generate.InMemoryGeneratedFiles +import org.springframework.aot.generate.NameGenerator import org.springframework.beans.factory.annotation.Autowired import org.springframework.beans.factory.config.AutowireCapableBeanFactory import org.springframework.beans.factory.config.BeanDefinition @@ -303,7 +303,7 @@ class GeneratedArtifactsInjectionSpec extends Specification { InMemoryGeneratedFiles generatedFiles = new InMemoryGeneratedFiles() DefaultGenerationContext generationContext = new DefaultGenerationContext( - new ClassNameGenerator(ClassName.get(getClass().packageName, 'Injection')), generatedFiles) + new NameGenerator(ClassName.get(getClass().packageName, 'Injection')), generatedFiles) ClassName initializer = new ApplicationContextAotGenerator().processAheadOfTime(generating, generationContext) generationContext.writeGeneratedContent() generating.close() diff --git a/grails-core/src/test/groovy/org/apache/grails/core/aot/GeneratedInjectionBeanRegistrationAotProcessorSpec.groovy b/grails-core/src/test/groovy/org/apache/grails/core/aot/GeneratedInjectionBeanRegistrationAotProcessorSpec.groovy index e59632f6e0a..acf10f43d6a 100644 --- a/grails-core/src/test/groovy/org/apache/grails/core/aot/GeneratedInjectionBeanRegistrationAotProcessorSpec.groovy +++ b/grails-core/src/test/groovy/org/apache/grails/core/aot/GeneratedInjectionBeanRegistrationAotProcessorSpec.groovy @@ -18,10 +18,10 @@ */ package org.apache.grails.core.aot -import org.springframework.aot.generate.ClassNameGenerator import org.springframework.aot.generate.DefaultGenerationContext import org.springframework.aot.generate.GeneratedFiles import org.springframework.aot.generate.InMemoryGeneratedFiles +import org.springframework.aot.generate.NameGenerator import org.springframework.beans.factory.support.RootBeanDefinition import org.springframework.context.aot.ApplicationContextAotGenerator import org.springframework.context.support.GenericApplicationContext @@ -45,7 +45,7 @@ class GeneratedInjectionBeanRegistrationAotProcessorSpec extends Specification { private String generatedSource() { InMemoryGeneratedFiles generatedFiles = new InMemoryGeneratedFiles() DefaultGenerationContext generationContext = new DefaultGenerationContext( - new ClassNameGenerator(ClassName.get('com.example', 'Subject')), generatedFiles) + new NameGenerator(ClassName.get('com.example', 'Subject')), generatedFiles) new ApplicationContextAotGenerator().processAheadOfTime(context, generationContext) generationContext.writeGeneratedContent() From da2feb41b53fcb526888a3406917d852fd9edbdd Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Thu, 22 Oct 2026 20:03:56 -0700 Subject: [PATCH 027/131] Upgrade to Spring Boot 4.2.0-RC1 --- dependencies.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dependencies.gradle b/dependencies.gradle index 429c38bbba1..12417408cb5 100644 --- a/dependencies.gradle +++ b/dependencies.gradle @@ -39,7 +39,7 @@ ext { 'jna.version' : '5.19.1', 'maven-model.version' : '3.9.16', 'objenesis.version' : '3.6', - 'spring-boot.version' : '4.2.0-M2', + 'spring-boot.version' : '4.2.0-RC1', ] // Note: the name of the dependency must be the prefix of the property name so properties in the pom are resolved correctly From 1cecccd0f0b1ba52bf931d1f40771494c77d257a Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Thu, 22 Oct 2026 20:04:03 -0700 Subject: [PATCH 028/131] Drop the MongoDB driver pin now that Spring Boot manages 5.13.0 Spring Boot 4.2.0-RC1 manages the driver at 5.13.0, newer than the 5.12.0 the pin kept so that the move to Spring Boot 4.2 would not downgrade it. --- dependencies.gradle | 12 ------------ 1 file changed, 12 deletions(-) diff --git a/dependencies.gradle b/dependencies.gradle index 12417408cb5..c22ebf7f252 100644 --- a/dependencies.gradle +++ b/dependencies.gradle @@ -100,10 +100,6 @@ ext { // values before SiftingAppender uses them as discriminating keys (CVE-2026-19880), and // 1.6.5 completes that fix (CVE-2026-104721). The 1.6.x line keeps SLF4J 2.0.x and JDK 11. 'logback.version' : '1.6.5', - // Overrides the 5.11.1 Spring Boot 4.2 manages. Pinned first as a security override of - // Spring Boot 4.1's 5.8.1 (CVE-2026-18710, fixed in 5.9.2); kept so that moving to Spring - // Boot 4.2 does not downgrade the driver. Drop once Spring Boot manages 5.12.0 or later. - 'mongodb.version' : '5.12.0', 'nimbus-jose-jwt.version' : '10.10', // Includes the follow-up logout redirect and direct-client CSRF fixes on the 6.5.x line. 'pac4j.version' : '6.5.9', @@ -210,14 +206,6 @@ ext { // Security override of the 1.6.3 Spring Boot 4.2 manages - see logback.version 'logback-classic' : "ch.qos.logback:logback-classic:${bomDependencyVersions['logback.version']}", 'logback-core' : "ch.qos.logback:logback-core:${bomDependencyVersions['logback.version']}", - // Override of the 5.11.1 spring-boot-dependencies imports through - // org.mongodb:mongodb-driver-bom - see mongodb.version. The whole driver family is - // pinned so a classpath cannot end up mixing driver versions. - 'mongodb-bson' : "org.mongodb:bson:${bomDependencyVersions['mongodb.version']}", - 'mongodb-bson-record-codec': "org.mongodb:bson-record-codec:${bomDependencyVersions['mongodb.version']}", - 'mongodb-driver-core' : "org.mongodb:mongodb-driver-core:${bomDependencyVersions['mongodb.version']}", - 'mongodb-driver-reactivestreams': "org.mongodb:mongodb-driver-reactivestreams:${bomDependencyVersions['mongodb.version']}", - 'mongodb-driver-sync' : "org.mongodb:mongodb-driver-sync:${bomDependencyVersions['mongodb.version']}", // Security override of the transitive 3.5.1 - see plexus-utils.version 'plexus-utils' : "org.codehaus.plexus:plexus-utils:${bomDependencyVersions['plexus-utils.version']}", // Required alongside plexus-utils 4.x - see plexus-xml.version From b3eace73be286b63da2e1fee819e7cd2820e5297 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Thu, 22 Oct 2026 20:04:20 -0700 Subject: [PATCH 029/131] Describe the Jackson pins against Spring Boot 4.2.0-RC1 Spring Boot 4.2.0-RC1 manages Jackson 3.1.7 and 2.21.7, which carry the CVE-2026-89425, CVE-2026-89407, CVE-2026-91777 and CVE-2026-91776 fixes. Jackson 2 stays at 2.22.3 because Groovy YAML 6.0.0 depends on 2.22.2, and Jackson 3 stays at 3.2.3 so that moving to Spring Boot 4.2 does not take it from the 3.2 line Grails 8 and 9.0 manage back to 3.1. No dependency needs 3.2: validateDependencyVersions passes with the BOM managing 3.1.7. --- dependencies.gradle | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/dependencies.gradle b/dependencies.gradle index c22ebf7f252..3b93a8e11b7 100644 --- a/dependencies.gradle +++ b/dependencies.gradle @@ -86,14 +86,15 @@ ext { 'groovy.version' : '6.0.0', // Security: 33.7.2 addresses CVE-2026-102554 (uncontrolled resource consumption). 'guava.version' : '33.7.2-jre', - // Groovy YAML 6.0.0 depends on Jackson 2.22.2, which wins over the 2.21.6 Spring Boot 4.2 - // manages, so the BOM must manage at least that. 2.22.3 also fixes CVE-2026-89425, - // CVE-2026-89407, CVE-2026-91777 and CVE-2026-91776, which 2.21.6 does not carry. Jackson 2 - // only releases jackson-annotations on the minor, hence the separate 2.22 below. + // Groovy YAML 6.0.0 depends on Jackson 2.22.2, which wins over the 2.21.7 Spring Boot 4.2 + // manages, so the BOM must manage at least that. Jackson 2 only releases + // jackson-annotations on the minor, hence the separate 2.22 below. 'jackson-2-bom.version' : '2.22.3', 'jackson2-annotations.version' : '2.22', - // Security: overrides Jackson 3.1.6 from Spring Boot 4.2. The 3.2.3 BOM aligns the family - // and fixes CVE-2026-89425, CVE-2026-89407, CVE-2026-91777 and CVE-2026-91776. + // Overrides the 3.1.7 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. 'jackson-bom.version' : '3.2.3', 'jquery.version' : '4.0.0', // Security: overrides the 1.6.3 Spring Boot 4.2 manages. 1.6.3 strips slashes from MDC @@ -190,7 +191,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.6 spring-boot-dependencies imports through + // Overrides the 2.21.7 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']}", @@ -198,7 +199,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']}", - // Security override of the 3.1.6 spring-boot-dependencies imports through + // Override of the 3.1.7 spring-boot-dependencies imports through // tools.jackson:jackson-bom - see jackson-bom.version 'jackson-bom-core' : "tools.jackson.core:jackson-core:${bomDependencyVersions['jackson-bom.version']}", 'jackson-bom-databind' : "tools.jackson.core:jackson-databind:${bomDependencyVersions['jackson-bom.version']}", From 1e4564c96d9042da97ecc44faa4d0c6a1e7085c0 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Thu, 22 Oct 2026 20:04:41 -0700 Subject: [PATCH 030/131] Describe the CVE-2026-47842 exclusion against Spring Security 7.2.0-RC1 Spring Boot 4.2.0-RC1 manages Spring Security 7.2.0-RC1. Spring's advisory still lists only 7.1.0 on the 7.1 line as affected and does not mention 7.2, and the 7.2.0-RC1 crypto jar carries the AesCbcBytesEncryptor and AesGcmBytesEncryptor replacements 7.1.1 introduced. --- .../apache/grails/buildsrc/scan/VulnerabilityScanPlugin.groovy | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build-logic/vulnerability-scan/src/main/groovy/org/apache/grails/buildsrc/scan/VulnerabilityScanPlugin.groovy b/build-logic/vulnerability-scan/src/main/groovy/org/apache/grails/buildsrc/scan/VulnerabilityScanPlugin.groovy index 97a661ca16d..5cc60d2beb8 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 @@ -89,7 +89,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-M2 manages 7.2.0-M2, which ' + + '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 advisory does not list and which carries the fix (the AesCbcBytesEncryptor and ' + 'AesGcmBytesEncryptor replacements 7.1.1 introduced). Remove once Sonatype corrects its ' + 'affected range; reassess on any Spring Security upgrade'), From 699904f16f2d3718df1656ec89ce7f7802ece214 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Thu, 22 Oct 2026 20:08:55 -0700 Subject: [PATCH 031/131] Read the forwarded scheme with the two-argument ForwardedHeaderUtils methods Spring Framework 7.1.0-RC1 deprecates for removal the parseStandardHeader and parseXForwardedHeaders overloads that take the remote and local addresses, in favor of new parseStandardHeader(URI, HttpHeaders) and parseXForwardedHeaders(URI, HttpHeaders). GrailsSecurityHeadersFilter passed null for both addresses and reads only the forwarded scheme, which the new overloads parse the same way; they differ only in the port of a for or by address that names none. --- .../plugins/web/controllers/GrailsSecurityHeadersFilter.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/grails-controllers/src/main/groovy/org/grails/plugins/web/controllers/GrailsSecurityHeadersFilter.java b/grails-controllers/src/main/groovy/org/grails/plugins/web/controllers/GrailsSecurityHeadersFilter.java index 3905d4b739d..2aaa93876ba 100644 --- a/grails-controllers/src/main/groovy/org/grails/plugins/web/controllers/GrailsSecurityHeadersFilter.java +++ b/grails-controllers/src/main/groovy/org/grails/plugins/web/controllers/GrailsSecurityHeadersFilter.java @@ -192,10 +192,10 @@ private static boolean isSecure(HttpServletRequest request) { URI base = URI.create(request.getScheme() + "://localhost"); ForwardedHeaderUtils.ForwardedInfo forwarded; if (StringUtils.hasText(headers.getFirst(FORWARDED))) { - forwarded = ForwardedHeaderUtils.parseStandardHeader(base, headers, null, null); + forwarded = ForwardedHeaderUtils.parseStandardHeader(base, headers); } else { - forwarded = ForwardedHeaderUtils.parseXForwardedHeaders(base, headers, null, null); + forwarded = ForwardedHeaderUtils.parseXForwardedHeaders(base, headers); } String scheme = forwarded.uriComponentsBuilder().build().getScheme(); return HTTPS.equalsIgnoreCase(scheme); From 76b9be2349c03991ecc2f72f3888268c04b9a4f9 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Thu, 22 Oct 2026 20:26:20 -0700 Subject: [PATCH 032/131] Leave the instance of a problem unset, as Spring Framework 7.1 does Spring Framework 7.1.0-RC1 no longer sets the instance of a ProblemDetail a handler method returns to the request path (spring-framework#35969): RFC 9457 defines instance as a URI that identifies the specific occurrence of the problem, which the request path does not. A ProblemDetail an action returns is written by Spring MVC's return value handlers, so it lost its instance with the upgrade, while respond still gave one to the problems it writes. respond writes a problem as Spring MVC writes one a handler method returns, so it no longer sets the instance either, for a ProblemDetail, an ErrorResponse, or the problem it writes for validation errors. A problem keeps an instance the application sets. The OpenAPI problem schema still describes instance, as a member the application may set, and the upgrade notes say how to set it. --- .../src/en/guide/upgrading/upgrading90x.adoc | 19 ++++++++++++--- .../src/en/ref/Controllers/respond.adoc | 3 ++- .../openapi/ValidationErrorsContent.groovy | 3 ++- .../grails/openapi/ErrorsViewSpec.groovy | 2 +- .../rest/render/ProblemDetailResponse.groovy | 18 ++++---------- .../rest/render/html/HtmlRendererSpec.groovy | 4 +++- .../json/DefaultJsonRendererSpec.groovy | 24 +++++++++++++++++-- .../springjson/SpringJsonRespondSpec.groovy | 2 +- .../ControllerJsonSerializationSpec.groovy | 8 +++---- .../web/ControllerProblemSpringMvcSpec.groovy | 2 +- .../renderer/JsonViewJsonRendererSpec.groovy | 2 +- .../mapping/mvc/ActionReturnValuesSpec.groovy | 4 +++- 12 files changed, 60 insertions(+), 31 deletions(-) diff --git a/grails-doc/src/en/guide/upgrading/upgrading90x.adoc b/grails-doc/src/en/guide/upgrading/upgrading90x.adoc index bc82f3b3a96..8c28fe5947c 100644 --- a/grails-doc/src/en/guide/upgrading/upgrading90x.adoc +++ b/grails-doc/src/en/guide/upgrading/upgrading90x.adoc @@ -67,6 +67,18 @@ class BookApiSpec extends Specification { } ---- +* *A problem detail no longer gets the request path as its `instance`.* +RFC 9457 defines `instance` as a URI that identifies the specific occurrence of a problem, so Spring Framework 7.1 no longer sets it to the request path when a handler method returns a `ProblemDetail` or an `ErrorResponse`. +`respond` follows it: a `ProblemDetail` or `ErrorResponse` it writes, and the problem it writes for validation errors, no longer get one either. +A client that reads `instance` gets it only where the application sets it: in a `ResponseEntityExceptionHandler` for Spring MVC controllers, and on the problem an action responds with, including one `validationProblemDetailFactory.create(errors)` makes for validation errors: ++ +[source,groovy] +---- +ProblemDetail problem = validationProblemDetailFactory.create(book.errors) +problem.instance = URI.create("urn:uuid:${UUID.randomUUID()}") +respond problem +---- + * *Spring MVC no longer detects the JAXB XML converter.* Spring Framework 7.1 stops auto-detecting the JAXB message converter for server applications. Grails `render` and `respond` write XML through Grails' own converters and are unaffected. @@ -972,9 +984,10 @@ Applications can also inject the factory when they need to create or customize t When `respond` receives a `ProblemDetail`, it hands it to the handler Spring MVC's handler adapter writes a `ResponseEntity` with, so the problem is written as a Spring MVC controller method that returns it is written: the application's `ResponseBodyAdvice` beans apply to it as to a method of the controller, and its -`ErrorResponse.Interceptor` beans see it. The response has the status the problem carries, and an absent `instance` is -set to the current resource path. A `status` argument decides the status instead, as the status of a `ResponseEntity` -does in Spring MVC: a problem that carries another keeps its own, and Spring MVC logs a warning. A Spring +`ErrorResponse.Interceptor` beans see it. The response has the status the problem carries, and a problem without an +`instance` is written without one, as Spring MVC writes it. A `status` argument decides the status instead, as the +status of a `ResponseEntity` does in Spring MVC: a problem that carries another keeps its own, and Spring MVC logs a +warning. A Spring `ErrorResponse`, such as an `ErrorResponseException`, is answered with its problem, whose message codes are resolved with the application's messages as Spring MVC's `ResponseEntityExceptionHandler` resolves them, and with its status and headers, where Grails 8 wrote it as a bean with a 200. Spring MVC's content diff --git a/grails-doc/src/en/ref/Controllers/respond.adoc b/grails-doc/src/en/ref/Controllers/respond.adoc index b5b33abafe7..23022689bce 100644 --- a/grails-doc/src/en/ref/Controllers/respond.adoc +++ b/grails-doc/src/en/ref/Controllers/respond.adoc @@ -89,7 +89,8 @@ Supported `arguments`: A Spring `ProblemDetail` is written as Spring MVC writes one that a handler method returns: `respond` hands it to the handler Spring MVC's handler adapter writes a `ResponseEntity` with, so the application's `ResponseBodyAdvice` beans apply to it as to a method of the controller, and its `ErrorResponse.Interceptor` beans see it. The response has the -status the problem carries, and an absent `instance` is set to the current resource path. A `status` argument decides +status the problem carries, and a problem without an `instance` is written without one, as Spring MVC writes it; set the +`instance` where the application identifies the occurrence of a problem. A `status` argument decides the status of the response, as the status of a `ResponseEntity` does in Spring MVC: a problem that carries another keeps its own, and Spring MVC logs a warning. Its properties are written by the mapper of Spring Boot's converter, as a Spring MVC controller writes them: a domain class instance, validation errors or a value that leads back to itself among them is diff --git a/grails-openapi/src/main/groovy/org/grails/openapi/ValidationErrorsContent.groovy b/grails-openapi/src/main/groovy/org/grails/openapi/ValidationErrorsContent.groovy index 50dda100174..c6c5f1fdd58 100644 --- a/grails-openapi/src/main/groovy/org/grails/openapi/ValidationErrorsContent.groovy +++ b/grails-openapi/src/main/groovy/org/grails/openapi/ValidationErrorsContent.groovy @@ -167,7 +167,8 @@ class ValidationErrorsContent { .addProperty('title', new StringSchema().description('A summary of the problem, Validation failed')) .addProperty('status', new IntegerSchema().description('The status of the response')) .addProperty('detail', new StringSchema().description('How many errors the request has')) - .addProperty('instance', new StringSchema().format('uri-reference').description('The path the request was made to')) + .addProperty('instance', new StringSchema().format('uri-reference') + .description('Identifies the occurrence of the problem, where the application gives one')) .addProperty('errors', new ArraySchema().items(mapperError(true))) problem.setRequired(['title', 'status', 'detail', 'errors']) problem diff --git a/grails-openapi/src/test/groovy/grails/openapi/ErrorsViewSpec.groovy b/grails-openapi/src/test/groovy/grails/openapi/ErrorsViewSpec.groovy index e174b7bae67..ae2f7824720 100644 --- a/grails-openapi/src/test/groovy/grails/openapi/ErrorsViewSpec.groovy +++ b/grails-openapi/src/test/groovy/grails/openapi/ErrorsViewSpec.groovy @@ -208,7 +208,7 @@ class ErrorsViewSpec extends Specification { } void 'the problem schema describes the problem respond writes for validation errors, as Spring writes it'() { - given: 'validation errors as respond writes them, with the instance it gives them' + given: 'validation errors as respond writes them, with an instance the application gives them' def errors = new BeanPropertyBindingResult(new Kettle(name: ''), 'kettle') errors.rejectValue('name', 'blank', 'Name cannot be blank') def problem = new ValidationProblemDetailFactory().create(errors) diff --git a/grails-rest-transforms/src/main/groovy/org/grails/plugins/web/rest/render/ProblemDetailResponse.groovy b/grails-rest-transforms/src/main/groovy/org/grails/plugins/web/rest/render/ProblemDetailResponse.groovy index 47fffd8aacc..e630f9afe87 100644 --- a/grails-rest-transforms/src/main/groovy/org/grails/plugins/web/rest/render/ProblemDetailResponse.groovy +++ b/grails-rest-transforms/src/main/groovy/org/grails/plugins/web/rest/render/ProblemDetailResponse.groovy @@ -46,8 +46,8 @@ import org.grails.web.servlet.mvc.GrailsWebRequest /** * Writes the response to a {@link ProblemDetail} as Spring MVC writes one a handler method returns, and prepares it * where a view or a renderer of the application writes it: the response takes the status the problem carries, unless - * a {@code status} argument names another, as the status of a {@code ResponseEntity} does, and a problem without an - * {@code instance} is given the path of the resource. + * a {@code status} argument names another, as the status of a {@code ResponseEntity} does. A problem without an + * {@code instance} is written without one, as Spring MVC writes it since Spring Framework 7.1. * * @since 9.0 */ @@ -109,9 +109,6 @@ class ProblemDetailResponse { if (handler == null) { return false } - if (problem.instance == null && context.resourcePath) { - problem.instance = URI.create(context.resourcePath) - } HttpServletRequest request = webRequest.currentRequest // the type and encoding a renderer set for its format are not the problem's, which Spring MVC selects webRequest.currentResponse.setContentType(null) @@ -167,7 +164,7 @@ class ProblemDetailResponse { } request.setAttribute(PREPARED, problem) } - prepare(problem, context, requestedStatus(context) ?: problem.status) + setStatus(context, requestedStatus(context) ?: problem.status) } /** @@ -178,7 +175,7 @@ class ProblemDetailResponse { * @param context the context of the response */ static void prepareBuilt(ProblemDetail problem, RenderContext context) { - prepare(problem, context, problem.status) + setStatus(context, problem.status) } /** @@ -201,13 +198,6 @@ class ProblemDetailResponse { status.toString().toInteger() } - private static void prepare(ProblemDetail problem, RenderContext context, int status) { - setStatus(context, status) - if (problem.instance == null && context.resourcePath) { - problem.instance = URI.create(context.resourcePath) - } - } - /** * A problem may carry any status code, as in Spring MVC, while {@link RenderContext} takes an * {@link HttpStatus}; a code without a constant is written to the servlet response directly. diff --git a/grails-rest-transforms/src/test/groovy/org/grails/plugins/web/rest/render/html/HtmlRendererSpec.groovy b/grails-rest-transforms/src/test/groovy/org/grails/plugins/web/rest/render/html/HtmlRendererSpec.groovy index 6a799c74ce3..a7f6bffbda7 100644 --- a/grails-rest-transforms/src/test/groovy/org/grails/plugins/web/rest/render/html/HtmlRendererSpec.groovy +++ b/grails-rest-transforms/src/test/groovy/org/grails/plugins/web/rest/render/html/HtmlRendererSpec.groovy @@ -183,7 +183,9 @@ class HtmlRendererSpec extends Specification { modelAndView.viewName == 'conflict' modelAndView.model == [problemDetail: problem] webRequest.currentResponse.status == 409 - problem.instance == URI.create('/books/1') + + and: 'the problem is not given an instance' + problem.instance == null } void "the view respond names renders a problem with the status respond is given"() { diff --git a/grails-rest-transforms/src/test/groovy/org/grails/plugins/web/rest/render/json/DefaultJsonRendererSpec.groovy b/grails-rest-transforms/src/test/groovy/org/grails/plugins/web/rest/render/json/DefaultJsonRendererSpec.groovy index 0fc21e34a97..0856bbc32bd 100644 --- a/grails-rest-transforms/src/test/groovy/org/grails/plugins/web/rest/render/json/DefaultJsonRendererSpec.groovy +++ b/grails-rest-transforms/src/test/groovy/org/grails/plugins/web/rest/render/json/DefaultJsonRendererSpec.groovy @@ -88,7 +88,7 @@ import static java.nio.charset.StandardCharsets.UTF_8 class DefaultJsonRendererSpec extends Specification { - void 'an explicit ProblemDetail controls the status content type and instance for status #status'() { + void 'an explicit ProblemDetail controls the status and content type for status #status'() { given: def renderer = new DefaultJsonRenderer(Object) renderer.springHttpMessageConvertersSupplier = { [new JacksonJsonHttpMessageConverter()] } @@ -102,12 +102,32 @@ class DefaultJsonRendererSpec extends Specification { then: webRequest.response.status == status webRequest.response.contentType.startsWith('application/problem+json') - webRequest.response.contentAsString.contains('"instance":"/books"') + + and: 'a problem without an instance is written without one, as Spring MVC writes it' + !(new JsonSlurper().parseText(webRequest.response.contentAsString) as Map).containsKey('instance') where: 'a problem may carry a status that has no HttpStatus constant' status << [422, 499, 299, 599] } + void 'a ProblemDetail is written with the instance the application gives it'() { + given: + def renderer = new DefaultJsonRenderer(Object) + renderer.springHttpMessageConvertersSupplier = { [new JacksonJsonHttpMessageConverter()] } + def webRequest = GrailsWebMockUtil.bindMockWebRequest() + def context = new ServletRenderContext(webRequest) + context.resourcePath = '/books' + def problem = ProblemDetail.forStatus(409) + problem.instance = URI.create('urn:uuid:5c3e1d2a-8f4b-4e7a-9d61-0a2b3c4d5e6f') + + when: + renderer.render(problem, context) + + then: + (new JsonSlurper().parseText(webRequest.response.contentAsString) as Map).instance == + 'urn:uuid:5c3e1d2a-8f4b-4e7a-9d61-0a2b3c4d5e6f' + } + void 'a status argument of #argument decides the status of a problem response, as the status of a ResponseEntity does in Spring MVC'() { given: def renderer = new DefaultJsonRenderer(Object) diff --git a/grails-test-examples/hibernate7/spring-json-respond/src/integration-test/groovy/springjson/SpringJsonRespondSpec.groovy b/grails-test-examples/hibernate7/spring-json-respond/src/integration-test/groovy/springjson/SpringJsonRespondSpec.groovy index 1123523a0de..e9b63cd7fea 100644 --- a/grails-test-examples/hibernate7/spring-json-respond/src/integration-test/groovy/springjson/SpringJsonRespondSpec.groovy +++ b/grails-test-examples/hibernate7/spring-json-respond/src/integration-test/groovy/springjson/SpringJsonRespondSpec.groovy @@ -118,7 +118,7 @@ class SpringJsonRespondSpec extends Specification implements HttpClientSupport { response.assertStatus(409) response.contentType == 'application/problem+json' response.json().detail == 'The title is taken' - response.json().instance == '/book/conflict' + !response.json().containsKey('instance') response.json().advisedBy == 'ProblemAdvice' } diff --git a/grails-test-suite-web/src/test/groovy/grails/rest/web/ControllerJsonSerializationSpec.groovy b/grails-test-suite-web/src/test/groovy/grails/rest/web/ControllerJsonSerializationSpec.groovy index d0ad23cf58d..eae9e9edb42 100644 --- a/grails-test-suite-web/src/test/groovy/grails/rest/web/ControllerJsonSerializationSpec.groovy +++ b/grails-test-suite-web/src/test/groovy/grails/rest/web/ControllerJsonSerializationSpec.groovy @@ -315,7 +315,7 @@ class ControllerJsonSerializationSpec extends Specification implements Controlle response.status == 422 response.contentType == 'application/problem+json' response.json.status == 422 - response.json.instance == '/books' + !response.json.containsKey('instance') } void 'a status respond is given decides the status of a problem response, and the problem keeps its own'() { @@ -369,7 +369,7 @@ class ControllerJsonSerializationSpec extends Specification implements Controlle response.status == 409 response.contentType == 'application/problem+json' response.json.status == 409 - response.json.instance == '/books' + !response.json.containsKey('instance') where: format << ['html', 'csv'] @@ -786,7 +786,7 @@ class ControllerProblemDefaultsSpec extends Specification implements ControllerU response.status == 409 response.contentType == 'application/problem+json' response.json.status == 409 - response.json.instance == '/books' + !response.json.containsKey('instance') where: format << ['json', 'html', 'csv'] @@ -973,7 +973,7 @@ class ControllerProblemPageSpec extends Specification implements ControllerUnitT view == '/errors/problem' model.problem.is(problem) response.status == 409 - problem.instance == URI.create('/books') + problem.instance == null } } diff --git a/grails-test-suite-web/src/test/groovy/grails/rest/web/ControllerProblemSpringMvcSpec.groovy b/grails-test-suite-web/src/test/groovy/grails/rest/web/ControllerProblemSpringMvcSpec.groovy index c92556563c1..f28c86c3ce9 100644 --- a/grails-test-suite-web/src/test/groovy/grails/rest/web/ControllerProblemSpringMvcSpec.groovy +++ b/grails-test-suite-web/src/test/groovy/grails/rest/web/ControllerProblemSpringMvcSpec.groovy @@ -129,7 +129,7 @@ class ControllerProblemSpringMvcSpec extends Specification implements Controller response.contentType == 'application/problem+json' response.getHeader(HttpHeaders.RETRY_AFTER) == '30' response.json.status == 503 - response.json.instance == '/books/1' + !response.json.containsKey('instance') and: 'the interceptors are given the ErrorResponse' response.json.source == 'ErrorResponseException' diff --git a/grails-views-gson/src/test/groovy/grails/plugin/json/renderer/JsonViewJsonRendererSpec.groovy b/grails-views-gson/src/test/groovy/grails/plugin/json/renderer/JsonViewJsonRendererSpec.groovy index 8426b8d4f26..ed84c7fc423 100644 --- a/grails-views-gson/src/test/groovy/grails/plugin/json/renderer/JsonViewJsonRendererSpec.groovy +++ b/grails-views-gson/src/test/groovy/grails/plugin/json/renderer/JsonViewJsonRendererSpec.groovy @@ -93,7 +93,7 @@ class JsonViewJsonRendererSpec extends Specification { 0 * defaultRenderer.render(_, _) modelAndView.view.is(problemView) context.webRequest.currentResponse.status == 422 - problem.instance == URI.create('/books/1') + problem.instance == null } void 'a ProblemDetail rendered with the view respond names, for a client that accepts no JSON type, is sent as JSON'() { diff --git a/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/mvc/ActionReturnValuesSpec.groovy b/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/mvc/ActionReturnValuesSpec.groovy index 7636eda68e1..0d837264bca 100644 --- a/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/mvc/ActionReturnValuesSpec.groovy +++ b/grails-web-url-mappings/src/test/groovy/org/grails/web/mapping/mvc/ActionReturnValuesSpec.groovy @@ -143,7 +143,9 @@ class ActionReturnValuesSpec extends AbstractUrlMappingsSpec { response.status == 422 response.contentType == MediaType.APPLICATION_PROBLEM_JSON_VALUE json().detail == 'invalid' - json().instance == '/returnValues/action' + + and: 'Spring MVC does not give it an instance' + !json().containsKey('instance') } void 'a ProblemDetail an action of an error page returns is written, whatever the status of the response'() { From 96cdc44b1f238cc6ef6f1e4337827ae8cbe0bd00 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Thu, 22 Oct 2026 20:28:01 -0700 Subject: [PATCH 033/131] Point to the properties migrator's fail setting in the Grails 9 upgrade notes Spring Boot 4.2.0-RC1 adds spring.properties.migrator.fail, which makes the application fail to start while a renamed (on-warning) or removed (on-error) property is left, such as server.tomcat.use-relative-redirects, which Spring Boot 4.2 renames to server.tomcat.servlet.use-relative-redirects. --- grails-doc/src/en/guide/upgrading/upgrading90x.adoc | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/grails-doc/src/en/guide/upgrading/upgrading90x.adoc b/grails-doc/src/en/guide/upgrading/upgrading90x.adoc index 8c28fe5947c..688dc791250 100644 --- a/grails-doc/src/en/guide/upgrading/upgrading90x.adoc +++ b/grails-doc/src/en/guide/upgrading/upgrading90x.adoc @@ -89,6 +89,13 @@ 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. +[TIP] +==== +The Spring Boot properties migrator, described in the link:upgrading.html#upgrading80x[Grails 8 upgrade guide], finds the configuration properties Spring Boot 4.2 renames, such as `server.tomcat.use-relative-redirects`. +Spring Boot 4.2 can also make the application fail to start while such a property is left: set `spring.properties.migrator.fail` to `on-warning` to fail on renamed and removed properties, or to `on-error` to fail on removed ones only. +The default, `never`, only logs them. +==== + ==== 2. graphql-java 26 for GraphQL Applications Spring Boot 4.2 manages graphql-java 26, so applications using the GraphQL plugin (`grails-data-graphql`) move from graphql-java 25 to graphql-java 26.1. From 791bfcb03d9a673b1de709a0b4cb97c0a96d101c Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Thu, 22 Oct 2026 20:35:25 -0700 Subject: [PATCH 034/131] Drop the Logback pin now that Spring Boot manages 1.6.5 Spring Boot 4.2.0-RC1 manages Logback 1.6.5, the version the pin set for the CVE-2026-19880 and CVE-2026-104721 fixes, and validateBomProperties rejects a pin that repeats the version Spring Boot manages. --- dependencies.gradle | 7 ------- 1 file changed, 7 deletions(-) diff --git a/dependencies.gradle b/dependencies.gradle index 3b93a8e11b7..9165e424ef9 100644 --- a/dependencies.gradle +++ b/dependencies.gradle @@ -97,10 +97,6 @@ ext { // line Grails 8 and 9.0 manage back to 3.1. 'jackson-bom.version' : '3.2.3', 'jquery.version' : '4.0.0', - // Security: overrides the 1.6.3 Spring Boot 4.2 manages. 1.6.3 strips slashes from MDC - // values before SiftingAppender uses them as discriminating keys (CVE-2026-19880), and - // 1.6.5 completes that fix (CVE-2026-104721). The 1.6.x line keeps SLF4J 2.0.x and JDK 11. - 'logback.version' : '1.6.5', 'nimbus-jose-jwt.version' : '10.10', // Includes the follow-up logout redirect and direct-client CSRF fixes on the 6.5.x line. 'pac4j.version' : '6.5.9', @@ -204,9 +200,6 @@ ext { 'jackson-bom-core' : "tools.jackson.core:jackson-core:${bomDependencyVersions['jackson-bom.version']}", 'jackson-bom-databind' : "tools.jackson.core:jackson-databind:${bomDependencyVersions['jackson-bom.version']}", 'jquery' : "org.webjars.npm:jquery:${bomDependencyVersions['jquery.version']}", - // Security override of the 1.6.3 Spring Boot 4.2 manages - see logback.version - 'logback-classic' : "ch.qos.logback:logback-classic:${bomDependencyVersions['logback.version']}", - 'logback-core' : "ch.qos.logback:logback-core:${bomDependencyVersions['logback.version']}", // Security override of the transitive 3.5.1 - see plexus-utils.version 'plexus-utils' : "org.codehaus.plexus:plexus-utils:${bomDependencyVersions['plexus-utils.version']}", // Required alongside plexus-utils 4.x - see plexus-xml.version From b47a295c83c4fd9be5bdd9e0bd0b997be338482b Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Fri, 23 Oct 2026 09:12:58 -0700 Subject: [PATCH 035/131] Train the AOT cache against the executable war an application ships Spring Boot 4.2.0-RC1 extracts an executable war with the tools jar mode (spring-projects/spring-boot#51372): the libraries in WEB-INF/lib and WEB-INF/lib-provided go to lib/, and what the war holds outside WEB-INF goes to the extracted jar's META-INF/resources. Before it, extracting a war failed, so the cache was trained against the executable jar even for an application that applies the war plugin, as a generated application does, and that jar leaves src/main/webapp out. extractAotCacheApplication now extracts bootWar when the war plugin is applied and bootWar is enabled, and bootJar otherwise. A war is extracted as a jar of the same name, so trainAotCache runs myapp.jar for myapp.war, and the deployed command does not change. --- .../guide/deployment/deploymentAotCache.adoc | 8 +- .../src/en/guide/introduction/whatsNew.adoc | 3 + .../plugin/aot/ExtractApplicationTask.groovy | 24 +++- .../plugin/aot/TrainAotCacheTask.groovy | 1 + .../plugin/core/GrailsGradlePlugin.groovy | 44 +++++++- .../aot/ExtractApplicationTaskSpec.groovy | 12 ++ .../core/GrailsAotCacheArchiveSpec.groovy | 106 ++++++++++++++++++ 7 files changed, 186 insertions(+), 12 deletions(-) create mode 100644 grails-gradle/plugins/src/test/groovy/org/grails/gradle/plugin/core/GrailsAotCacheArchiveSpec.groovy diff --git a/grails-doc/src/en/guide/deployment/deploymentAotCache.adoc b/grails-doc/src/en/guide/deployment/deploymentAotCache.adoc index e30532c8ce8..fdbdaf84ec2 100644 --- a/grails-doc/src/en/guide/deployment/deploymentAotCache.adoc +++ b/grails-doc/src/en/guide/deployment/deploymentAotCache.adoc @@ -41,7 +41,7 @@ grails { } ---- -That adds two tasks. `extractAotCacheApplication` unpacks the executable jar into `build/aot-cache/application`, and `trainAotCache` runs what it unpacked, asks for each path, stops it, and leaves the cache beside the extracted application: +That adds two tasks. `extractAotCacheApplication` unpacks the executable archive into `build/aot-cache/application`, and `trainAotCache` runs what it unpacked, asks for each path, stops it, and leaves the cache beside the extracted application: [source,bash] ---- @@ -53,7 +53,11 @@ That adds two tasks. `extractAotCacheApplication` unpacks the executable jar int Trained myapp.aot (167 MB) over 4 paths ---- -The application is unpacked first because a cache is read against the layout it was trained on. An executable jar loads its dependencies through a nested-jar classloader; the extracted form loads them as ordinary jars on the classpath, and only the second is a layout a cache can be reused against. +The application is unpacked first because a cache is read against the layout it was trained on. An executable archive loads its dependencies through a nested-jar classloader; the extracted form loads them as ordinary jars on the classpath, and only the second is a layout a cache can be reused against. + +The archive unpacked is the one the application ships. An application that applies the `war` plugin, as a generated application does, ships the executable war that `bootWar` builds, and that is what is unpacked. Any other application, or one that switches `bootWar` off, ships the executable jar that `bootJar` builds. + +A war is unpacked as a jar of the same name, `myapp.jar` for `myapp.war`. The libraries in `WEB-INF/lib` and `WEB-INF/lib-provided` go to `lib/` beside it, and the files the war holds outside `WEB-INF`, such as the contents of `src/main/webapp`, go to the jar's `META-INF/resources`. The application serves those files as it serves them from the war. The executable jar leaves `src/main/webapp` out, which is why an application that ships its war is trained against the war. === Running with the cache diff --git a/grails-doc/src/en/guide/introduction/whatsNew.adoc b/grails-doc/src/en/guide/introduction/whatsNew.adoc index 8ca70145801..8508902502a 100644 --- a/grails-doc/src/en/guide/introduction/whatsNew.adoc +++ b/grails-doc/src/en/guide/introduction/whatsNew.adoc @@ -692,6 +692,9 @@ grails { } ---- +An application that applies the `war` plugin, as a generated application does, is trained against the executable +war it ships, `src/main/webapp` included, which Spring Boot 4.2 can extract. + See the <> section, which includes measured figures and the conditions under which a JVM will decline a cache. diff --git a/grails-gradle/plugins/src/main/groovy/org/apache/grails/gradle/plugin/aot/ExtractApplicationTask.groovy b/grails-gradle/plugins/src/main/groovy/org/apache/grails/gradle/plugin/aot/ExtractApplicationTask.groovy index 467793ce12f..15d62722d9b 100644 --- a/grails-gradle/plugins/src/main/groovy/org/apache/grails/gradle/plugin/aot/ExtractApplicationTask.groovy +++ b/grails-gradle/plugins/src/main/groovy/org/apache/grails/gradle/plugin/aot/ExtractApplicationTask.groovy @@ -37,11 +37,15 @@ import org.gradle.jvm.toolchain.JavaLauncher import org.gradle.process.ExecOperations /** - * Unpacks an executable jar into the form an AOT cache is read against. + * Unpacks an executable jar or war into the form an AOT cache is read against. * - *

An executable jar loads its dependencies through a nested-jar class loader; the extracted form - * loads them as ordinary jars on the classpath. A cache records the class path it saw, so only the - * second is a layout a later run can reuse one against.

+ *

An executable archive loads its dependencies through a nested-jar class loader; the extracted + * form loads them as ordinary jars on the classpath. A cache records the class path it saw, so only + * the second is a layout a later run can reuse one against.

+ * + *

A war is extracted as a jar, with the libraries it provides beside its own and what it holds + * outside {@code WEB-INF} in the jar's {@code META-INF/resources}, which needs Spring Boot 4.2 or + * later in the war.

* *

The work is done through injected services rather than through the project, so that nothing is * reached at execution time that the configuration cache forbids.

@@ -52,7 +56,7 @@ import org.gradle.process.ExecOperations @CompileStatic abstract class ExtractApplicationTask extends DefaultTask { - /** The archive to unpack, which has to be the one the cache will be trained against. */ + /** The executable jar or war to unpack, which has to be the one the cache will be trained against. */ @InputFile @PathSensitive(PathSensitivity.RELATIVE) abstract RegularFileProperty getArchiveFile() @@ -79,6 +83,16 @@ abstract class ExtractApplicationTask extends DefaultTask { @Inject abstract ExecOperations getExecOperations() + /** + * The name of the application the extraction writes for an archive of the given name: a jar + * keeps its name, and a war is written as a jar of the same name. + */ + static String applicationFileName(String archiveFileName) { + archiveFileName.toLowerCase(Locale.ROOT).endsWith('.war') ? + archiveFileName.substring(0, archiveFileName.length() - 4) + '.jar' : + archiveFileName + } + @TaskAction void extract() { File target = destination.get().asFile diff --git a/grails-gradle/plugins/src/main/groovy/org/apache/grails/gradle/plugin/aot/TrainAotCacheTask.groovy b/grails-gradle/plugins/src/main/groovy/org/apache/grails/gradle/plugin/aot/TrainAotCacheTask.groovy index b4fff274c88..2ad118d7ea3 100644 --- a/grails-gradle/plugins/src/main/groovy/org/apache/grails/gradle/plugin/aot/TrainAotCacheTask.groovy +++ b/grails-gradle/plugins/src/main/groovy/org/apache/grails/gradle/plugin/aot/TrainAotCacheTask.groovy @@ -67,6 +67,7 @@ abstract class TrainAotCacheTask extends DefaultTask { @PathSensitive(PathSensitivity.RELATIVE) abstract DirectoryProperty getApplicationDirectory() + /** The name of the extracted application's jar: the archive's own, which for a war is a jar's. */ @Input abstract Property getArchiveFileName() 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 ea19e72c95e..04717819cf1 100644 --- a/grails-gradle/plugins/src/main/groovy/org/grails/gradle/plugin/core/GrailsGradlePlugin.groovy +++ b/grails-gradle/plugins/src/main/groovy/org/grails/gradle/plugin/core/GrailsGradlePlugin.groovy @@ -115,6 +115,8 @@ class GrailsGradlePlugin implements Plugin { private static final String ASSET_PIPELINE_PLUGIN = 'cloud.wondrify.asset-pipeline' + private static final String WAR_PLUGIN = 'war' + private static final int TRAINING_PORT = 18080 /** Not the training port: a trace and a training run are both a started application. */ @@ -1491,6 +1493,9 @@ ${importStatements} * archive is extracted, the extracted application is run and asked for its pages, and what the * run recorded is left beside it. An application asks for this with * {@code grails.aotCache.enabled}, and says which of its pages matter.

+ * + *

The archive is the executable war where the application applies the war plugin, as a + * generated application does, and the executable jar otherwise.

*/ protected void configureAotCache(Project project) { AotCacheExtension extension = ((ExtensionAware) project.extensions.getByName('grails')) @@ -1502,7 +1507,6 @@ ${importStatements} extension.startTimeoutSeconds.convention(TRAINING_START_TIMEOUT_SECONDS) project.pluginManager.withPlugin(SPRING_BOOT_PLUGIN) { - TaskProvider bootJar = project.tasks.named('bootJar') Provider application = project.layout.buildDirectory.dir('aot-cache/application') Provider launcher = trainingLauncher(project) @@ -1511,7 +1515,7 @@ ${importStatements} task.group = BasePlugin.BUILD_GROUP task.description = 'Extracts the application, which is the form the cache is read against' task.onlyIf { extension.enabled.get() } - task.archiveFile.set(archiveFileOf(bootJar)) + task.archiveFile.set(archiveFileOf(executableArchive(project))) // The launcher rather than its path: this task is cacheable, and a path is where a // JDK happens to live on the machine that ran the build. Set as the provider it is, // so the toolchain is not resolved -- and a JDK not provisioned -- by every build @@ -1526,7 +1530,8 @@ ${importStatements} task.onlyIf { extension.enabled.get() } task.dependsOn(extract) task.applicationDirectory.set(application) - task.archiveFileName.set(archiveFileOf(bootJar).map { RegularFile file -> file.asFile.name }) + task.archiveFileName.set(archiveFileNameOf(executableArchive(project)) + .map { String name -> ExtractApplicationTask.applicationFileName(name) }) // Beside the extracted application rather than inside it. Inside, the cache and its // metadata land in the directory this task declares as its input, so writing them // changes that input and the task can never be up to date -- every build would run @@ -1560,8 +1565,37 @@ ${importStatements} * task resolved while the build is configured is one every build pays for whether or not it * asked for an archive.

*/ - private static Provider archiveFileOf(TaskProvider bootJar) { - bootJar.flatMap { Task task -> (Provider) task.property('archiveFile') } + private static Provider archiveFileOf(TaskProvider archive) { + archive.flatMap { Task task -> (Provider) task.property('archiveFile') } + } + + /** The name of the archive a task builds, which is known before the task has run, unlike its file. */ + private static Provider archiveFileNameOf(TaskProvider archive) { + archive.flatMap { Task task -> (Provider) task.property('archiveFileName') } + } + + /** + * The executable archive the application ships: the war where it applies the war plugin, as a + * generated application does, and the jar otherwise. + * + *

Spring Boot extracts a war as of 4.2: its provided libraries, the embedded container among + * them, beside its own, and what sits outside {@code WEB-INF}, {@code src/main/webapp} included, + * in the extracted jar's {@code META-INF/resources}. The jar leaves {@code src/main/webapp} out, + * so a cache trained against the jar of an application that ships its war was trained against + * an application missing what the war serves. An application that switches its war off ships + * the jar.

+ * + *

Read as a task that consumes the archive is configured, by which time the build has applied + * its plugins and configured its archives.

+ */ + private static TaskProvider executableArchive(Project project) { + if (project.pluginManager.hasPlugin(WAR_PLUGIN)) { + TaskProvider bootWar = project.tasks.named('bootWar') + if (bootWar.get().enabled) { + return bootWar + } + } + project.tasks.named('bootJar') } /** diff --git a/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/ExtractApplicationTaskSpec.groovy b/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/ExtractApplicationTaskSpec.groovy index 4c20f391ea9..63d744a2ba6 100644 --- a/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/ExtractApplicationTaskSpec.groovy +++ b/grails-gradle/plugins/src/test/groovy/org/apache/grails/gradle/plugin/aot/ExtractApplicationTaskSpec.groovy @@ -51,4 +51,16 @@ class ExtractApplicationTaskSpec extends Specification { expect: declared.isEmpty() } + + void 'the application extracted from #archive is #application'() { + expect: 'a jar keeps its name, and a war is written as a jar of the same name' + ExtractApplicationTask.applicationFileName(archive) == application + + where: + archive | application + 'myapp-0.1.jar' | 'myapp-0.1.jar' + 'myapp-0.1.war' | 'myapp-0.1.jar' + 'MYAPP.WAR' | 'MYAPP.jar' + 'myapp.war.jar' | 'myapp.war.jar' + } } diff --git a/grails-gradle/plugins/src/test/groovy/org/grails/gradle/plugin/core/GrailsAotCacheArchiveSpec.groovy b/grails-gradle/plugins/src/test/groovy/org/grails/gradle/plugin/core/GrailsAotCacheArchiveSpec.groovy new file mode 100644 index 00000000000..11da40e5137 --- /dev/null +++ b/grails-gradle/plugins/src/test/groovy/org/grails/gradle/plugin/core/GrailsAotCacheArchiveSpec.groovy @@ -0,0 +1,106 @@ +/* + * 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.gradle.plugin.core + +import org.gradle.api.Project +import org.gradle.api.Task +import org.gradle.testfixtures.ProjectBuilder +import spock.lang.Specification +import spock.lang.TempDir + +import org.apache.grails.gradle.plugin.aot.ExtractApplicationTask +import org.apache.grails.gradle.plugin.aot.TrainAotCacheTask + +/** + * Covers which archive an AOT cache is trained against: the one the application ships. + * + *

That is the executable war where the war plugin is applied, as it is in a generated + * application, and the executable jar otherwise. The war plugin can be applied before or after the + * Grails plugin, and either order has to train against the war.

+ */ +class GrailsAotCacheArchiveSpec extends Specification { + + private static final String GRAILS_WEB_PLUGIN = 'org.apache.grails.gradle.grails-web' + + @TempDir + File projectDir + + private Project project + + void setup() { + project = ProjectBuilder.builder().withProjectDir(projectDir).withName('library').build() + project.version = '0.1' + project.extensions.extraProperties.set('grailsVersion', System.getProperty('projectVersion')) + } + + void 'an application without the war plugin is trained against its executable jar'() { + when: + project.pluginManager.apply(GRAILS_WEB_PLUGIN) + + then: + extractedArchive() == archiveOf('bootJar') + trainedApplication() == 'library-0.1.jar' + } + + void 'an application with the war plugin is trained against its executable war when #order'() { + when: + plugins.each { String id -> project.pluginManager.apply(id) } + + then: + extractedArchive() == archiveOf('bootWar') + extract().taskDependencies.getDependencies(extract())*.name.contains('bootWar') + + and: 'the war is run as the jar its extraction writes' + trainedApplication() == 'library-0.1.jar' + + where: + order | plugins + 'the Grails plugin is applied first' | [GRAILS_WEB_PLUGIN, 'war'] + 'the war plugin is applied first' | ['war', GRAILS_WEB_PLUGIN] + } + + void 'an application that switches its executable war off is trained against its executable jar'() { + given: + project.pluginManager.apply(GRAILS_WEB_PLUGIN) + project.pluginManager.apply('war') + + when: + project.tasks.named('bootWar').configure { Task task -> task.enabled = false } + + then: + extractedArchive() == archiveOf('bootJar') + trainedApplication() == 'library-0.1.jar' + } + + private ExtractApplicationTask extract() { + project.tasks.named('extractAotCacheApplication', ExtractApplicationTask).get() + } + + private File extractedArchive() { + extract().archiveFile.get().asFile + } + + private String trainedApplication() { + project.tasks.named('trainAotCache', TrainAotCacheTask).get().archiveFileName.get() + } + + private File archiveOf(String taskName) { + project.tasks.named(taskName).get().property('archiveFile').get().asFile + } +} From 9a199232a2f5d07f1c19421048defa10a61ae4b6 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Fri, 23 Oct 2026 09:32:26 -0700 Subject: [PATCH 036/131] Support a nonce-based Content-Security-Policy Spring Security 7.2.0-RC1 lets a Content-Security-Policy name a per-request nonce with the {nonce} placeholder, generates the nonce in ContentSecurityPolicyNonceGeneratingFilter and puts it on the request under the _csp attribute for views to render. grails.security.headers.content-security-policy.value takes the same placeholder. GrailsSecurityHeadersFilter then puts a lazily generated nonce, 128 bits from SecureRandom in Base64 without padding, on the request under _csp, and replaces each {nonce} with the nonce the request carries when the header is written. A request that already carries Spring Security's nonce keeps it, and the filter reads it through Spring Security's public ContentSecurityPolicyNonce interface, since grails-controllers does not depend on Spring Security, so the header and the page agree on one nonce whichever generated it. Something other than a nonce under _csp leaves the policy unsent, with a warning, rather than sending a policy that would block every inline script the page gave a nonce. The new g:cspNonce tag renders the nonce, in a statically compiled page as well as a dynamic one, where request._csp does not compile, and g:javascript adds it to the inline script it writes. Both types the nonce is read from are registered for reflection, for a native image. --- .../aot/ControllerRuntimeHints.java | 11 +- .../GrailsSecurityHeadersFilter.java | 129 ++++++++++++- .../aot/ControllerRuntimeHintsSpec.groovy | 8 + ...ecurityHeadersAutoConfigurationSpec.groovy | 182 ++++++++++++++++++ .../src/en/guide/introduction/whatsNew.adoc | 22 +++ grails-doc/src/en/guide/reference.adoc | 5 + grails-doc/src/en/guide/security.adoc | 43 +++++ .../src/en/ref/Tags - GSP/cspNonce.adoc | 57 ++++++ .../src/en/ref/Tags - GSP/javascript.adoc | 1 + .../web/taglib/ApplicationTagLib.groovy | 24 ++- .../web/taglib/JavascriptTagLib.groovy | 7 +- .../web/taglib/ApplicationTagLibTests.groovy | 45 +++++ .../web/taglib/JavascriptTagLibTests.groovy | 30 +++ 13 files changed, 556 insertions(+), 8 deletions(-) create mode 100644 grails-doc/src/en/ref/Tags - GSP/cspNonce.adoc 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..74322661dae 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 @@ -31,6 +31,7 @@ import grails.artefact.controller.support.RequestForwarder; import grails.artefact.controller.support.ResponseRedirector; import grails.artefact.controller.support.ResponseRenderer; +import org.grails.plugins.web.controllers.GrailsSecurityHeadersFilter; /** * Registers the controller API a request is dispatched through. @@ -69,7 +70,10 @@ public class ControllerRuntimeHints implements RuntimeHintsRegistrar { ResponseRenderer.class, // a view asking who is logged in reaches the request's principal, and Groovy makes that // call on the interface rather than the implementation the container supplies - Principal.class + Principal.class, + // the cspNonce tag and a controller read the nonce of a nonce-based Content-Security-Policy + // as request._csp.nonce + GrailsSecurityHeadersFilter.ContentSecurityPolicyNonce.class }; /** @@ -77,7 +81,10 @@ public class ControllerRuntimeHints implements RuntimeHintsRegistrar { * only when present, so this stays correct for an application that does not use every plugin. */ private static final String[] OPTIONAL_DISPATCHED_TYPES = { - "grails.artefact.controller.RestResponder" + "grails.artefact.controller.RestResponder", + // the nonce Spring Security's nonce filter sets, which the cspNonce tag renders and the + // security headers filter reads through this interface + "org.springframework.security.web.header.ContentSecurityPolicyNonce" }; @Override diff --git a/grails-controllers/src/main/groovy/org/grails/plugins/web/controllers/GrailsSecurityHeadersFilter.java b/grails-controllers/src/main/groovy/org/grails/plugins/web/controllers/GrailsSecurityHeadersFilter.java index 2aaa93876ba..acf537908bf 100644 --- a/grails-controllers/src/main/groovy/org/grails/plugins/web/controllers/GrailsSecurityHeadersFilter.java +++ b/grails-controllers/src/main/groovy/org/grails/plugins/web/controllers/GrailsSecurityHeadersFilter.java @@ -19,11 +19,16 @@ package org.grails.plugins.web.controllers; import java.io.IOException; +import java.lang.reflect.Method; import java.net.URI; +import java.security.SecureRandom; +import java.util.Base64; import java.util.List; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.Supplier; +import java.util.function.UnaryOperator; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; @@ -35,7 +40,10 @@ import org.springframework.http.HttpHeaders; import org.springframework.http.server.ServletServerHttpRequest; +import org.springframework.util.ClassUtils; +import org.springframework.util.ReflectionUtils; import org.springframework.util.StringUtils; +import org.springframework.util.function.SingletonSupplier; import org.springframework.web.filter.OncePerRequestFilter; import org.springframework.web.util.ForwardedHeaderUtils; @@ -57,6 +65,15 @@ * adds. See {@link GrailsSecurityHeadersProperties.Defaults} for the controlling * setting.

* + *

A {@code Content-Security-Policy} value may contain the {@code {nonce}} placeholder that + * Spring Security 7.2 introduced, for example {@code script-src 'self' 'nonce-{nonce}'}. The + * request then carries a nonce under the {@value #NONCE_ATTRIBUTE} request attribute, which a page + * renders into the {@code nonce} attribute of an inline script or style with the {@code cspNonce} + * tag, and every placeholder is replaced with that nonce when the header is written. The attribute + * is the one Spring Security's {@code ContentSecurityPolicyNonceGeneratingFilter} sets by + * default, so a request that already carries Spring Security's nonce keeps it, and the header + * and the view agree on one nonce whichever generated it.

+ * *

When {@link GrailsSecurityHeadersProperties#isEnabled()} is {@code false} the filter * passes every request through untouched. The auto-configuration does not register the * filter at all in that case; the check here covers filters an application constructs @@ -73,6 +90,15 @@ public class GrailsSecurityHeadersFilter extends OncePerRequestFilter { static final List REVERSE_PROXY_REQUEST_HEADERS = List.of( "Forwarded", "X-Forwarded-For", "X-Forwarded-Proto", "X-Forwarded-Host", "Via", "X-Real-IP"); + /** + * The request attribute that carries the nonce of a policy using the {@code {nonce}} + * placeholder: the name Spring Security's {@code ContentSecurityPolicyNonceGeneratingFilter} + * gives it by default. + */ + public static final String NONCE_ATTRIBUTE = "_csp"; + + static final String NONCE_PLACEHOLDER = "{nonce}"; + private static final Logger logger = LoggerFactory.getLogger(GrailsSecurityHeadersFilter.class); private static final String HTTPS = "https"; @@ -86,6 +112,8 @@ public class GrailsSecurityHeadersFilter extends OncePerRequestFilter { private final Set blankValueLogged = ConcurrentHashMap.newKeySet(); + private final AtomicBoolean unreadableNonceLogged = new AtomicBoolean(); + public GrailsSecurityHeadersFilter(GrailsSecurityHeadersProperties properties) { this(properties, false); } @@ -115,8 +143,14 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse } boolean applyDefaults = shouldApplyDefaults(request); boolean secure = isEnabled(this.properties.getHsts()) && isSecure(request); + // Left alone when the request already has one: a nonce this filter set on an earlier + // dispatch of the same request, or the one Spring Security's nonce filter set when its + // chain runs ahead of this filter. Either is what a view of this request renders. + if (usesNonce() && request.getAttribute(NONCE_ATTRIBUTE) == null) { + request.setAttribute(NONCE_ATTRIBUTE, new ContentSecurityPolicyNonce()); + } SecurityHeadersResponseWrapper wrapped = new SecurityHeadersResponseWrapper(response, - () -> writeHeaders(response, applyDefaults, secure)); + () -> writeHeaders(request, response, applyDefaults, secure)); try { filterChain.doFilter(request, wrapped); } @@ -125,7 +159,8 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse } } - private void writeHeaders(HttpServletResponse response, boolean applyDefaults, boolean secure) { + private void writeHeaders(HttpServletRequest request, HttpServletResponse response, boolean applyDefaults, + boolean secure) { applyHeader(response, "X-Content-Type-Options", "content-type-options", this.properties.getContentTypeOptions(), applyDefaults); applyHeader(response, "X-Frame-Options", "frame-options", this.properties.getFrameOptions(), applyDefaults); @@ -135,7 +170,57 @@ private void writeHeaders(HttpServletResponse response, boolean applyDefaults, b applyHeader(response, "Strict-Transport-Security", "hsts", this.properties.getHsts(), applyDefaults); } applyHeader(response, "Content-Security-Policy", "content-security-policy", - this.properties.getContentSecurityPolicy(), applyDefaults); + this.properties.getContentSecurityPolicy(), applyDefaults, (policy) -> withNonce(policy, request)); + } + + private boolean usesNonce() { + GrailsSecurityHeadersProperties.Header policy = this.properties.getContentSecurityPolicy(); + return isEnabled(policy) && policy.getValue() != null && policy.getValue().contains(NONCE_PLACEHOLDER); + } + + /** + * The policy with each {@code {nonce}} replaced by the nonce the request carries when the + * header is written, or {@code null} when the request carries none that can be read. + */ + private String withNonce(String policy, HttpServletRequest request) { + if (!policy.contains(NONCE_PLACEHOLDER)) { + return policy; + } + String nonce = nonceOf(request); + if (nonce == null) { + if (this.unreadableNonceLogged.compareAndSet(false, true)) { + logger.warn("The Content-Security-Policy uses {} but the {} request attribute holds a {}, which " + + "has no nonce to read, so the header is not sent.", NONCE_PLACEHOLDER, NONCE_ATTRIBUTE, + request.getAttribute(NONCE_ATTRIBUTE).getClass().getName()); + } + return null; + } + return policy.replace(NONCE_PLACEHOLDER, nonce); + } + + /** + * The nonce the request carries: the one this filter generated, or the one Spring Security's + * {@code ContentSecurityPolicyNonceGeneratingFilter} set, whose {@code getNonce()} is read + * through Spring Security's public interface since this module does not depend on it. + */ + private static String nonceOf(HttpServletRequest request) { + Object holder = request.getAttribute(NONCE_ATTRIBUTE); + if (holder == null) { + // Removed after this filter set it, so the header gets one of its own. + ContentSecurityPolicyNonce nonce = new ContentSecurityPolicyNonce(); + request.setAttribute(NONCE_ATTRIBUTE, nonce); + return nonce.getNonce(); + } + if (holder instanceof ContentSecurityPolicyNonce nonce) { + return nonce.getNonce(); + } + Method getNonce = ClassUtils.getMethodIfAvailable(holder.getClass(), "getNonce"); + if (getNonce == null || getNonce.getReturnType() != String.class) { + return null; + } + Object nonce = ReflectionUtils.invokeMethod( + ClassUtils.getPubliclyAccessibleMethodIfPossible(getNonce, holder.getClass()), holder); + return (nonce instanceof String value && StringUtils.hasText(value)) ? value : null; } private boolean shouldApplyDefaults(HttpServletRequest request) { @@ -212,6 +297,11 @@ private static boolean isEnabled(GrailsSecurityHeadersProperties.Header header) private void applyHeader(HttpServletResponse response, String name, String propertyName, GrailsSecurityHeadersProperties.Header header, boolean applyDefaults) { + applyHeader(response, name, propertyName, header, applyDefaults, UnaryOperator.identity()); + } + + private void applyHeader(HttpServletResponse response, String name, String propertyName, + GrailsSecurityHeadersProperties.Header header, boolean applyDefaults, UnaryOperator resolve) { if (!isEnabled(header)) { return; } @@ -227,7 +317,38 @@ private void applyHeader(HttpServletResponse response, String name, String prope return; } if (!response.containsHeader(name)) { - response.setHeader(name, header.getValue()); + String value = resolve.apply(header.getValue()); + if (value != null) { + response.setHeader(name, value); + } + } + } + + /** + * The nonce of one request, generated the first time it is read: 128 bits from a + * {@link SecureRandom}, Base64-encoded without padding, as Spring Security generates one. + * A page renders it with the {@code cspNonce} tag, and a controller reads it as + * {@code request._csp.nonce}. + */ + public static final class ContentSecurityPolicyNonce { + + private static final SecureRandom RANDOM = new SecureRandom(); + + private static final int NONCE_BYTES = 16; + + private final Supplier nonce = SingletonSupplier.of(ContentSecurityPolicyNonce::generate); + + ContentSecurityPolicyNonce() { + } + + public String getNonce() { + return this.nonce.get(); + } + + private static String generate() { + byte[] bytes = new byte[NONCE_BYTES]; + RANDOM.nextBytes(bytes); + return Base64.getEncoder().withoutPadding().encodeToString(bytes); } } } 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..e79e0f82b76 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 @@ -25,6 +25,8 @@ import org.springframework.aot.hint.RuntimeHints import org.springframework.aot.hint.TypeReference import spock.lang.Specification +import org.grails.plugins.web.controllers.GrailsSecurityHeadersFilter + /** * Covers the controller API surviving into an ahead-of-time image. Without these hints the methods * are stripped and dispatch fails on the request that first takes the path, which for the method @@ -64,6 +66,12 @@ class ControllerRuntimeHintsSpec extends Specification { registered(grails.artefact.controller.support.RequestForwarder) } + void 'the nonce of a nonce-based Content-Security-Policy is registered, whichever filter generated it'() { + expect: 'the cspNonce tag reads it as request._csp.nonce, and the security headers filter reads Spring Security\'s' + registered(GrailsSecurityHeadersFilter.ContentSecurityPolicyNonce) + registered(TypeReference.of('org.springframework.security.web.header.ContentSecurityPolicyNonce')) + } + void 'a type from a module that is absent is skipped rather than failing the build'() { given: RuntimeHints empty = new RuntimeHints() diff --git a/grails-controllers/src/test/groovy/org/grails/plugins/web/controllers/GrailsSecurityHeadersAutoConfigurationSpec.groovy b/grails-controllers/src/test/groovy/org/grails/plugins/web/controllers/GrailsSecurityHeadersAutoConfigurationSpec.groovy index 01735121e31..6947556a641 100644 --- a/grails-controllers/src/test/groovy/org/grails/plugins/web/controllers/GrailsSecurityHeadersAutoConfigurationSpec.groovy +++ b/grails-controllers/src/test/groovy/org/grails/plugins/web/controllers/GrailsSecurityHeadersAutoConfigurationSpec.groovy @@ -37,7 +37,9 @@ import org.springframework.context.annotation.Configuration import org.springframework.mock.web.MockFilterChain import org.springframework.mock.web.MockHttpServletRequest import org.springframework.mock.web.MockHttpServletResponse +import org.springframework.security.web.header.ContentSecurityPolicyNonceGeneratingFilter import org.springframework.security.web.header.HeaderWriterFilter +import org.springframework.security.web.header.writers.ContentSecurityPolicyHeaderWriter import org.springframework.security.web.header.writers.ReferrerPolicyHeaderWriter import org.springframework.security.web.header.writers.frameoptions.XFrameOptionsHeaderWriter import org.springframework.web.filter.CharacterEncodingFilter @@ -277,6 +279,170 @@ class GrailsSecurityHeadersAutoConfigurationSpec extends Specification { response.getHeader('Content-Security-Policy') == "default-src 'self'" } + void 'each {nonce} in the Content-Security-Policy is the nonce a view of the request renders'() { + given: + def request = new MockHttpServletRequest('GET', '/') + def response = new MockHttpServletResponse() + def properties = cspProperties("script-src 'self' 'nonce-{nonce}'; style-src 'nonce-{nonce}'") + String rendered = null + FilterChain view = { viewRequest, viewResponse -> + rendered = viewRequest.getAttribute('_csp').nonce + } as FilterChain + + when: + new GrailsSecurityHeadersFilter(properties).doFilter(request, response, view) + + then: '128 random bits, Base64 without padding, as Spring Security generates a nonce' + rendered ==~ /[A-Za-z0-9+\/]{22}/ + response.getHeader('Content-Security-Policy') == + "script-src 'self' 'nonce-${rendered}'; style-src 'nonce-${rendered}'" + } + + void 'every request gets a nonce of its own'() { + given: + def filter = new GrailsSecurityHeadersFilter(cspProperties("script-src 'nonce-{nonce}'")) + + when: + def first = new MockHttpServletResponse() + filter.doFilter(new MockHttpServletRequest('GET', '/'), first, new MockFilterChain()) + def second = new MockHttpServletResponse() + filter.doFilter(new MockHttpServletRequest('GET', '/'), second, new MockFilterChain()) + + then: + first.getHeader('Content-Security-Policy') ==~ /script-src 'nonce-[A-Za-z0-9+\/]{22}'/ + first.getHeader('Content-Security-Policy') != second.getHeader('Content-Security-Policy') + } + + @Unroll + void 'a request carries no nonce when the Content-Security-Policy #description'() { + given: + def request = new MockHttpServletRequest('GET', '/') + def response = new MockHttpServletResponse() + def properties = cspProperties(policy) + properties.contentSecurityPolicy.enabled = enabled + Object carried = 'unset' + FilterChain view = { viewRequest, viewResponse -> + carried = viewRequest.getAttribute('_csp') + } as FilterChain + + when: + new GrailsSecurityHeadersFilter(properties).doFilter(request, response, view) + + then: + carried == null + response.getHeader('Content-Security-Policy') == header + + where: + description | enabled | policy || header + 'has no {nonce}' | true | "default-src 'self'" || "default-src 'self'" + 'is not sent' | false | "script-src 'nonce-{nonce}'" || null + } + + void 'an error dispatch of the request keeps the nonce its view rendered'() { + given: + def request = new MockHttpServletRequest('GET', '/') + def filter = new GrailsSecurityHeadersFilter(cspProperties("script-src 'nonce-{nonce}'")) + def original = new MockHttpServletResponse() + filter.doFilter(request, original, new MockFilterChain()) + String rendered = request.getAttribute('_csp').nonce + + when: 'the container dispatches the same request to its error page' + request.dispatcherType = DispatcherType.ERROR + def errorPage = new MockHttpServletResponse() + filter.doFilter(request, errorPage, new MockFilterChain()) + + then: + original.getHeader('Content-Security-Policy') == "script-src 'nonce-${rendered}'" + errorPage.getHeader('Content-Security-Policy') == "script-src 'nonce-${rendered}'" + } + + void 'Spring Security writing its own nonce-based policy inside the filter wins, with the nonce the view renders'() { + given: 'the chain the headers DSL builds when its policy uses {nonce}: the nonce filter, then the header writer' + def request = new MockHttpServletRequest('GET', '/') + def response = new MockHttpServletResponse() + def springSecurityNonce = new ContentSecurityPolicyNonceGeneratingFilter() + def springSecurityHeaders = new HeaderWriterFilter([ + new ContentSecurityPolicyHeaderWriter("script-src 'self' 'nonce-{nonce}'") + ]) + def view = new NonceRenderingServlet() + + when: + new GrailsSecurityHeadersFilter(cspProperties("default-src 'none'; script-src 'nonce-{nonce}'")) + .doFilter(request, response, new MockFilterChain(view, springSecurityNonce, springSecurityHeaders)) + + then: + response.contentAsString ==~ /[A-Za-z0-9+\/]{22}/ + response.getHeader('Content-Security-Policy') == "script-src 'self' 'nonce-${response.contentAsString}'" + } + + void 'the filter writes the nonce Spring Security put on the request when its chain runs ahead of the filter'() { + given: 'spring.security.filter.order ahead of the Grails filter, so the Grails writer is the inner one and writes first' + def request = new MockHttpServletRequest('GET', '/') + def response = new MockHttpServletResponse() + def springSecurityNonce = new ContentSecurityPolicyNonceGeneratingFilter() + def springSecurityHeaders = new HeaderWriterFilter([ + new ContentSecurityPolicyHeaderWriter("script-src 'self' 'nonce-{nonce}'") + ]) + def grails = new GrailsSecurityHeadersFilter(cspProperties("default-src 'none'; script-src 'nonce-{nonce}'")) + def view = new NonceRenderingServlet() + + when: + springSecurityNonce.doFilter(request, response, + new MockFilterChain(view, springSecurityHeaders, grails)) + + then: 'the Grails policy, with the nonce Spring Security generated and the view rendered' + response.contentAsString ==~ /[A-Za-z0-9+\/]{22}/ + response.getHeader('Content-Security-Policy') == + "default-src 'none'; script-src 'nonce-${response.contentAsString}'" + } + + void 'a request attribute that holds no nonce leaves the policy unsent and is warned about once'() { + given: + def logCapture = new LogCapture(GrailsSecurityHeadersFilter) + def filter = new GrailsSecurityHeadersFilter(cspProperties("script-src 'nonce-{nonce}'")) + + when: 'two requests arrive with something else under the attribute' + def first = new MockHttpServletResponse() + def firstRequest = new MockHttpServletRequest('GET', '/') + firstRequest.setAttribute('_csp', 'not a nonce') + filter.doFilter(firstRequest, first, new MockFilterChain()) + def second = new MockHttpServletResponse() + def secondRequest = new MockHttpServletRequest('GET', '/') + secondRequest.setAttribute('_csp', 'not a nonce') + filter.doFilter(secondRequest, second, new MockFilterChain()) + + then: 'a policy that names no nonce would block every inline script the view nonced' + first.getHeader('Content-Security-Policy') == null + second.getHeader('Content-Security-Policy') == null + first.getHeader('X-Content-Type-Options') == 'nosniff' + + and: + def warnings = logCapture.events.findAll { it.level == Level.WARN } + warnings.size() == 1 + warnings[0].formattedMessage.contains('{nonce}') + warnings[0].formattedMessage.contains('_csp') + warnings[0].formattedMessage.contains(String.name) + + cleanup: + logCapture.close() + } + + void 'a nonce-based policy binds from application configuration'() { + expect: + new WebApplicationContextRunner() + .withPropertyValues('grails.security.headers.content-security-policy.enabled=true', + "grails.security.headers.content-security-policy.value=script-src 'self' 'nonce-{nonce}'") + .withConfiguration(AutoConfigurations.of(GrailsSecurityHeadersAutoConfiguration)) + .run { context -> + def request = new MockHttpServletRequest('GET', '/') + def response = new MockHttpServletResponse() + context.getBean(GrailsSecurityHeadersFilter).doFilter(request, response, new MockFilterChain()) + String nonce = request.getAttribute('_csp').nonce + assert nonce ==~ /[A-Za-z0-9+\/]{22}/ + assert response.getHeader('Content-Security-Policy') == "script-src 'self' 'nonce-${nonce}'" + } + } + void 'filter respects per-header disable switches and existing response headers'() { given: def request = new MockHttpServletRequest('GET', '/') @@ -1237,6 +1403,22 @@ class GrailsSecurityHeadersAutoConfigurationSpec extends Specification { outcome = defaultsSent ? 'receives' : 'does not receive' } + private static GrailsSecurityHeadersProperties cspProperties(String policy) { + def properties = new GrailsSecurityHeadersProperties() + properties.contentSecurityPolicy.enabled = true + properties.contentSecurityPolicy.value = policy + properties + } + + /** Renders the nonce of the request as its body, as a view renders it into a script's nonce attribute. */ + static class NonceRenderingServlet extends HttpServlet { + + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) { + response.writer.write(request.getAttribute('_csp').nonce as String) + } + } + @Configuration(proxyBeanMethods = false) static class UserFilterAndRegistration { diff --git a/grails-doc/src/en/guide/introduction/whatsNew.adoc b/grails-doc/src/en/guide/introduction/whatsNew.adoc index 8508902502a..a40f23bea8e 100644 --- a/grails-doc/src/en/guide/introduction/whatsNew.adoc +++ b/grails-doc/src/en/guide/introduction/whatsNew.adoc @@ -543,6 +543,28 @@ deployment whose reverse proxy already sends these headers can set `grails.secur only explicitly configured headers on proxied requests. See the xref:security[Security] section of the user guide and the xref:upgrading#upgrading80x[upgrade guide] for details. +==== Nonce-based Content Security Policy + +`grails.security.headers.content-security-policy.value` can name a per-request nonce with the `+{nonce}+` placeholder +that Spring Security 7.2 introduced, so a policy can allow an inline script or style by nonce rather than with +`'unsafe-inline'`: + +[source,yaml] +.grails-app/conf/application.yml +---- +grails: + security: + headers: + content-security-policy: + enabled: true + value: "script-src 'self' 'nonce-{nonce}'" +---- + +A view renders the request's nonce with the new `` tag, as in ` + +---- + +The link:{gspTagsRef}javascript.html[javascript] tag adds the nonce to the inline script it writes. +A controller can read the nonce as `request._csp?.nonce`. +A script or stylesheet loaded from the application's own origin, such as an asset, is allowed by `'self'` and needs no nonce. + +`_csp` is also the attribute Spring Security's `ContentSecurityPolicyNonceGeneratingFilter` sets by default, so a view renders the right nonce whichever of the two generated it, and the header carries the same nonce: + +* When Spring Security's header configuration also writes a nonce-based policy, at Spring Boot's default filter order, Spring Security's nonce replaces the Grails one on the request. +Spring Security's header is written first, and the Grails policy is not sent. +* When the Spring Security filter chain is ordered ahead of `GrailsFilters.FIRST`, Grails keeps the nonce Spring Security put on the request and writes the Grails policy with it. + +If the `_csp` attribute holds something that has no nonce, the policy is not sent, since a policy without the nonce would block every inline script the view gave one. +Grails logs a warning the first time that happens. diff --git a/grails-doc/src/en/ref/Tags - GSP/cspNonce.adoc b/grails-doc/src/en/ref/Tags - GSP/cspNonce.adoc new file mode 100644 index 00000000000..79a3035db7f --- /dev/null +++ b/grails-doc/src/en/ref/Tags - GSP/cspNonce.adoc @@ -0,0 +1,57 @@ +//// +Licensed to the Apache Software Foundation (ASF) under one +or more contributor license agreements. See the NOTICE file +distributed with this work for additional information +regarding copyright ownership. The ASF licenses this file +to you under the Apache License, Version 2.0 (the +"License"); you may not use this file except in compliance +with the License. You may obtain a copy of the License at + +https://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, +software distributed under the License is distributed on an +"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, either express or implied. See the License for the +specific language governing permissions and limitations +under the License. +//// + + +== cspNonce + + + +=== Purpose + + +Renders the nonce of the request's nonce-based Content Security Policy, for the `nonce` attribute of an inline script or style. + + +=== Examples + + +[source,xml] +---- + + + +---- + + +=== Description + + +A policy configured with `grails.security.headers.content-security-policy.value` names the nonce with the `+{nonce}+` placeholder, for example `script-src 'self' 'nonce-+{nonce}+'`. +Each request then carries a nonce of its own, which this tag renders, and the policy the response carries names the same nonce. +See link:{guidePath}/security.html[Security] for configuring the policy. + +The tag renders the nonce Spring Security's `ContentSecurityPolicyNonceGeneratingFilter` generated when that filter put one on the request, so it can be used with a policy Spring Security writes as well. + +It renders nothing when the request carries no nonce. + +The tag works in a statically compiled page as well as a dynamic one. A controller, or a dynamically compiled page, can read the nonce as `request._csp?.nonce`. diff --git a/grails-doc/src/en/ref/Tags - GSP/javascript.adoc b/grails-doc/src/en/ref/Tags - GSP/javascript.adoc index 1a97be1fe71..2dab073a2b4 100644 --- a/grails-doc/src/en/ref/Tags - GSP/javascript.adoc +++ b/grails-doc/src/en/ref/Tags - GSP/javascript.adoc @@ -44,6 +44,7 @@ Includes JavaScript libraries and scripts as well as providing a shorthand for i If you do not include a "src" attribute but instead provide a body, the result is an inline script. +When the request carries the nonce of a nonce-based Content Security Policy, the inline script carries it in its `nonce` attribute, so the policy allows it to run. If you are doing more advanced JavaScript and asset management we recommend checking out the Asset Pipeline plugin. diff --git a/grails-gsp/plugin/src/main/groovy/org/grails/plugins/web/taglib/ApplicationTagLib.groovy b/grails-gsp/plugin/src/main/groovy/org/grails/plugins/web/taglib/ApplicationTagLib.groovy index 1922579b7f2..6f73c317114 100644 --- a/grails-gsp/plugin/src/main/groovy/org/grails/plugins/web/taglib/ApplicationTagLib.groovy +++ b/grails-gsp/plugin/src/main/groovy/org/grails/plugins/web/taglib/ApplicationTagLib.groovy @@ -51,7 +51,13 @@ import org.grails.web.servlet.mvc.GrailsWebRequest @TagLib class ApplicationTagLib implements ApplicationContextAware, InitializingBean, GrailsApplicationAware, TagLibrary { - static returnObjectForTags = ['createLink', 'resource', 'createLinkTo', 'cookie', 'header', 'img', 'join', 'meta', 'set', 'applyCodec'] + static returnObjectForTags = ['createLink', 'resource', 'createLinkTo', 'cookie', 'header', 'cspNonce', 'img', 'join', 'meta', 'set', 'applyCodec'] + + /** + * The request attribute that carries the nonce of a nonce-based Content-Security-Policy, which the Grails + * security headers filter and Spring Security's nonce filter both set. + */ + private static final String CSP_NONCE_ATTRIBUTE = '_csp' ApplicationContext applicationContext GrailsPluginManager pluginManager @@ -123,6 +129,22 @@ class ApplicationTagLib implements ApplicationContextAware, InitializingBean, Gr attrs.name ? request.getHeader(attrs.name) : null } + /** + * Renders the nonce of the request's Content-Security-Policy, for the nonce attribute of an inline script or + * style, or nothing when the request carries none. + * + * @emptyTag + */ + def cspNonce(Map attrs) { + Object holder = request.getAttribute(CSP_NONCE_ATTRIBUTE) + try { + holder?.nonce + } catch (MissingPropertyException ignored) { + // something other than a nonce under that name leaves the page without one rather than failing it + null + } + } + /** * Sets a variable in the pageContext or the specified scope. * The value can be specified directly or can be a bean retrieved from the applicationContext. diff --git a/grails-gsp/plugin/src/main/groovy/org/grails/plugins/web/taglib/JavascriptTagLib.groovy b/grails-gsp/plugin/src/main/groovy/org/grails/plugins/web/taglib/JavascriptTagLib.groovy index db20ab98eef..65813a4336c 100644 --- a/grails-gsp/plugin/src/main/groovy/org/grails/plugins/web/taglib/JavascriptTagLib.groovy +++ b/grails-gsp/plugin/src/main/groovy/org/grails/plugins/web/taglib/JavascriptTagLib.groovy @@ -65,6 +65,9 @@ class JavascriptTagLib implements ApplicationContextAware, TagLibrary { * * <g:javascript src="myscript.js" /> // actually imports '/app/js/myscript.js' * + * An inline script carries the nonce of the request's Content-Security-Policy when the request has one, + * so a policy that allows scripts by nonce runs it. + * * @attr src The name of the javascript file to import. Will look in web-app/js dir * @attr library The name of the library to include. e.g. "jquery", "prototype", "scriptaculous", "yahoo" or "dojo" * @attr plugin The plugin to look for the javascript in @@ -78,7 +81,9 @@ class JavascriptTagLib implements ApplicationContextAware, TagLibrary { if (hasResourceProcessor) { out << r.script(Collections.EMPTY_MAP, body) } else { - out.println('') diff --git a/grails-gsp/plugin/src/test/groovy/org/grails/web/taglib/ApplicationTagLibTests.groovy b/grails-gsp/plugin/src/test/groovy/org/grails/web/taglib/ApplicationTagLibTests.groovy index 7305d50fd7c..1f073ca25e9 100644 --- a/grails-gsp/plugin/src/test/groovy/org/grails/web/taglib/ApplicationTagLibTests.groovy +++ b/grails-gsp/plugin/src/test/groovy/org/grails/web/taglib/ApplicationTagLibTests.groovy @@ -26,13 +26,17 @@ import grails.util.Metadata import grails.util.MockRequestDataValueProcessor import groovy.test.NotYetImplemented import org.grails.gsp.GroovyPageBinding +import org.grails.plugins.web.controllers.GrailsSecurityHeadersFilter +import org.grails.plugins.web.controllers.GrailsSecurityHeadersProperties import org.grails.plugins.web.taglib.ApplicationTagLib import org.grails.plugins.web.taglib.FormTagLib import org.grails.taglib.GrailsTagException import org.grails.web.util.GrailsApplicationAttributes import org.grails.web.util.WebUtils +import org.springframework.mock.web.MockHttpServletResponse import spock.lang.Specification +import jakarta.servlet.FilterChain import jakarta.servlet.http.Cookie class ApplicationTagLibTests extends Specification implements TagLibUnitTest { @@ -238,6 +242,47 @@ class ApplicationTagLibTests extends Specification implements TagLibUnitTest + page = applyTemplate(directive + '') + } as FilterChain) + String nonce = request.getAttribute('_csp').nonce + + then: 'the page and the policy name the same nonce' + nonce ==~ /[A-Za-z0-9+\/]{22}/ + page == "" + response.getHeader('Content-Security-Policy') == "script-src 'nonce-${nonce}'; style-src 'nonce-${nonce}'" + + where: + compilation | directive + 'dynamic' | '' + 'static' | '<%@ page compileStatic="true" %>' + } + + void 'no nonce renders when the request carries none: #description'() { + given: + if (holder != null) { + request.setAttribute('_csp', holder) + } + + expect: + applyTemplate('') == '' + applyTemplate('') == '' + + where: + description | holder + 'no policy names one' | null + 'the attribute holds something else' | 'not a nonce' + } + void testClonedUrlFromVariable() { given: unRegisterRequestDataValueProcessor() diff --git a/grails-gsp/plugin/src/test/groovy/org/grails/web/taglib/JavascriptTagLibTests.groovy b/grails-gsp/plugin/src/test/groovy/org/grails/web/taglib/JavascriptTagLibTests.groovy index 958447bc104..bc9c44a3103 100644 --- a/grails-gsp/plugin/src/test/groovy/org/grails/web/taglib/JavascriptTagLibTests.groovy +++ b/grails-gsp/plugin/src/test/groovy/org/grails/web/taglib/JavascriptTagLibTests.groovy @@ -19,12 +19,17 @@ package org.grails.web.taglib +import jakarta.servlet.FilterChain + import grails.util.GrailsUtil import org.grails.core.artefact.UrlMappingsArtefactHandler import org.grails.gsp.GroovyPageBinding +import org.grails.plugins.web.controllers.GrailsSecurityHeadersFilter +import org.grails.plugins.web.controllers.GrailsSecurityHeadersProperties import org.grails.web.util.GrailsApplicationAttributes import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test +import org.springframework.mock.web.MockHttpServletResponse import static org.junit.jupiter.api.Assertions.assertEquals @@ -160,6 +165,31 @@ class TestUrlMappings { assertEquals("" + EOL, sw.toString()) } + @Test + void testInlineScriptCarriesTheNonceOfTheContentSecurityPolicy() { + def properties = new GrailsSecurityHeadersProperties() + properties.contentSecurityPolicy.enabled = true + properties.contentSecurityPolicy.value = "script-src 'nonce-{nonce}'" + def response = new MockHttpServletResponse() + String output = null + + new GrailsSecurityHeadersFilter(properties).doFilter(request, response, { viewRequest, viewResponse -> + output = applyTemplate('do.this();') + } as FilterChain) + + String nonce = request.getAttribute('_csp').nonce + assertEquals("${EOL}".toString(), + output) + assertEquals("script-src 'nonce-${nonce}'".toString(), response.getHeader('Content-Security-Policy')) + } + + @Test + void testInlineScriptCarriesNoNonceWhenTheAttributeHoldsNone() { + request.setAttribute('_csp', 'not a nonce') + assertOutputEquals('' + EOL, + 'do.this();') + } + @Test void testJSSrcWithBase() { StringWriter sw = new StringWriter() From 9dc7ea74d7e95d66652294eaec48171489193da8 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Fri, 23 Oct 2026 09:33:07 -0700 Subject: [PATCH 037/131] Say which attribute the nonce tags read when Spring Security renames its own --- grails-doc/src/en/guide/security.adoc | 3 +++ 1 file changed, 3 insertions(+) diff --git a/grails-doc/src/en/guide/security.adoc b/grails-doc/src/en/guide/security.adoc index bb7303414a8..caaeca520b4 100644 --- a/grails-doc/src/en/guide/security.adoc +++ b/grails-doc/src/en/guide/security.adoc @@ -193,5 +193,8 @@ A script or stylesheet loaded from the application's own origin, such as an asse Spring Security's header is written first, and the Grails policy is not sent. * When the Spring Security filter chain is ordered ahead of `GrailsFilters.FIRST`, Grails keeps the nonce Spring Security put on the request and writes the Grails policy with it. +The `cspNonce` and `javascript` tags read the nonce from `_csp`. +If Spring Security's header configuration names another attribute with `nonceAttributeName`, render the nonce from that attribute instead. + If the `_csp` attribute holds something that has no nonce, the policy is not sent, since a policy without the nonce would block every inline script the view gave one. Grails logs a warning the first time that happens. From 3bafab600282341cc0abe94c5caedc660d3a143f Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Fri, 23 Oct 2026 13:47:02 -0700 Subject: [PATCH 038/131] Read Spring Security's CSP nonce through its registered interface The security headers filter read the nonce Spring Security puts on the request by looking up getNonce() on the holder's own class. That class is ContentSecurityPolicyNonceGeneratingFilter.DeferredContentSecurityPolicyNonce, a private nested class with no reflection metadata in a native image. In an image built without exact reachability metadata, or with it scoped to the Grails and Spring modules, the lookup missed the method and the Grails policy was silently not sent. The nonce and its reader move to grails.web.http.ContentSecurityPolicyNonce in grails-web-common. nonceOf(request) returns the Grails nonce directly and reads Spring Security's through its public ContentSecurityPolicyNonce interface, resolved with the holder's class loader, which is the only type it reflects on. ContentSecurityPolicyRuntimeHints registers that interface and the Grails nonce next to the reader, in place of the two entries ControllerRuntimeHints carried. The class is Java so that reading the nonce never reaches the Groovy runtime: a Groovy version's `as String` went through the metaclass registry, which an image built with --exact-reachability-metadata refuses. An object under _csp that is neither nonce is no longer read for a getNonce() of its own; the policy is not sent and the warning says so. --- .../aot/ControllerRuntimeHints.java | 11 +- .../GrailsSecurityHeadersFilter.java | 96 +++------------ .../aot/ControllerRuntimeHintsSpec.groovy | 8 -- ...ecurityHeadersAutoConfigurationSpec.groovy | 9 +- grails-doc/src/en/guide/security.adoc | 2 +- grails-web-common/build.gradle | 4 + .../web/http/ContentSecurityPolicyNonce.java | 113 ++++++++++++++++++ .../ContentSecurityPolicyRuntimeHints.java | 62 ++++++++++ .../resources/META-INF/spring/aot.factories | 2 + .../ContentSecurityPolicyNonceSpec.groovy | 106 ++++++++++++++++ ...ntentSecurityPolicyRuntimeHintsSpec.groovy | 71 +++++++++++ 11 files changed, 384 insertions(+), 100 deletions(-) create mode 100644 grails-web-common/src/main/groovy/grails/web/http/ContentSecurityPolicyNonce.java create mode 100644 grails-web-common/src/main/groovy/org/apache/grails/web/http/aot/ContentSecurityPolicyRuntimeHints.java create mode 100644 grails-web-common/src/main/resources/META-INF/spring/aot.factories create mode 100644 grails-web-common/src/test/groovy/grails/web/http/ContentSecurityPolicyNonceSpec.groovy create mode 100644 grails-web-common/src/test/groovy/org/apache/grails/web/http/aot/ContentSecurityPolicyRuntimeHintsSpec.groovy 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 74322661dae..d8aacb80b36 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 @@ -31,7 +31,6 @@ import grails.artefact.controller.support.RequestForwarder; import grails.artefact.controller.support.ResponseRedirector; import grails.artefact.controller.support.ResponseRenderer; -import org.grails.plugins.web.controllers.GrailsSecurityHeadersFilter; /** * Registers the controller API a request is dispatched through. @@ -70,10 +69,7 @@ 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, - // the cspNonce tag and a controller read the nonce of a nonce-based Content-Security-Policy - // as request._csp.nonce - GrailsSecurityHeadersFilter.ContentSecurityPolicyNonce.class + Principal.class }; /** @@ -81,10 +77,7 @@ public class ControllerRuntimeHints implements RuntimeHintsRegistrar { * only when present, so this stays correct for an application that does not use every plugin. */ private static final String[] OPTIONAL_DISPATCHED_TYPES = { - "grails.artefact.controller.RestResponder", - // the nonce Spring Security's nonce filter sets, which the cspNonce tag renders and the - // security headers filter reads through this interface - "org.springframework.security.web.header.ContentSecurityPolicyNonce" + "grails.artefact.controller.RestResponder" }; @Override diff --git a/grails-controllers/src/main/groovy/org/grails/plugins/web/controllers/GrailsSecurityHeadersFilter.java b/grails-controllers/src/main/groovy/org/grails/plugins/web/controllers/GrailsSecurityHeadersFilter.java index acf537908bf..b27a0378cf1 100644 --- a/grails-controllers/src/main/groovy/org/grails/plugins/web/controllers/GrailsSecurityHeadersFilter.java +++ b/grails-controllers/src/main/groovy/org/grails/plugins/web/controllers/GrailsSecurityHeadersFilter.java @@ -19,15 +19,11 @@ package org.grails.plugins.web.controllers; import java.io.IOException; -import java.lang.reflect.Method; import java.net.URI; -import java.security.SecureRandom; -import java.util.Base64; import java.util.List; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicBoolean; -import java.util.function.Supplier; import java.util.function.UnaryOperator; import jakarta.servlet.FilterChain; @@ -40,13 +36,12 @@ import org.springframework.http.HttpHeaders; import org.springframework.http.server.ServletServerHttpRequest; -import org.springframework.util.ClassUtils; -import org.springframework.util.ReflectionUtils; import org.springframework.util.StringUtils; -import org.springframework.util.function.SingletonSupplier; import org.springframework.web.filter.OncePerRequestFilter; import org.springframework.web.util.ForwardedHeaderUtils; +import grails.web.http.ContentSecurityPolicyNonce; + /** * Applies baseline browser hardening response headers. * @@ -67,12 +62,12 @@ * *

A {@code Content-Security-Policy} value may contain the {@code {nonce}} placeholder that * Spring Security 7.2 introduced, for example {@code script-src 'self' 'nonce-{nonce}'}. The - * request then carries a nonce under the {@value #NONCE_ATTRIBUTE} request attribute, which a page - * renders into the {@code nonce} attribute of an inline script or style with the {@code cspNonce} - * tag, and every placeholder is replaced with that nonce when the header is written. The attribute - * is the one Spring Security's {@code ContentSecurityPolicyNonceGeneratingFilter} sets by - * default, so a request that already carries Spring Security's nonce keeps it, and the header - * and the view agree on one nonce whichever generated it.

+ * request then carries a {@link ContentSecurityPolicyNonce}, which a page renders into the + * {@code nonce} attribute of an inline script or style with the {@code cspNonce} tag, and every + * placeholder is replaced with that nonce when the header is written. The request attribute it is + * carried under is the one Spring Security's {@code ContentSecurityPolicyNonceGeneratingFilter} + * sets by default, so a request that already carries Spring Security's nonce keeps it, and the + * header and the view agree on one nonce whichever generated it.

* *

When {@link GrailsSecurityHeadersProperties#isEnabled()} is {@code false} the filter * passes every request through untouched. The auto-configuration does not register the @@ -90,13 +85,6 @@ public class GrailsSecurityHeadersFilter extends OncePerRequestFilter { static final List REVERSE_PROXY_REQUEST_HEADERS = List.of( "Forwarded", "X-Forwarded-For", "X-Forwarded-Proto", "X-Forwarded-Host", "Via", "X-Real-IP"); - /** - * The request attribute that carries the nonce of a policy using the {@code {nonce}} - * placeholder: the name Spring Security's {@code ContentSecurityPolicyNonceGeneratingFilter} - * gives it by default. - */ - public static final String NONCE_ATTRIBUTE = "_csp"; - static final String NONCE_PLACEHOLDER = "{nonce}"; private static final Logger logger = LoggerFactory.getLogger(GrailsSecurityHeadersFilter.class); @@ -146,8 +134,8 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse // Left alone when the request already has one: a nonce this filter set on an earlier // dispatch of the same request, or the one Spring Security's nonce filter set when its // chain runs ahead of this filter. Either is what a view of this request renders. - if (usesNonce() && request.getAttribute(NONCE_ATTRIBUTE) == null) { - request.setAttribute(NONCE_ATTRIBUTE, new ContentSecurityPolicyNonce()); + if (usesNonce() && request.getAttribute(ContentSecurityPolicyNonce.ATTRIBUTE) == null) { + request.setAttribute(ContentSecurityPolicyNonce.ATTRIBUTE, new ContentSecurityPolicyNonce()); } SecurityHeadersResponseWrapper wrapped = new SecurityHeadersResponseWrapper(response, () -> writeHeaders(request, response, applyDefaults, secure)); @@ -186,43 +174,23 @@ private String withNonce(String policy, HttpServletRequest request) { if (!policy.contains(NONCE_PLACEHOLDER)) { return policy; } - String nonce = nonceOf(request); + if (request.getAttribute(ContentSecurityPolicyNonce.ATTRIBUTE) == null) { + // Removed after this filter set it, so the header gets one of its own. + request.setAttribute(ContentSecurityPolicyNonce.ATTRIBUTE, new ContentSecurityPolicyNonce()); + } + String nonce = ContentSecurityPolicyNonce.nonceOf(request); if (nonce == null) { if (this.unreadableNonceLogged.compareAndSet(false, true)) { logger.warn("The Content-Security-Policy uses {} but the {} request attribute holds a {}, which " + - "has no nonce to read, so the header is not sent.", NONCE_PLACEHOLDER, NONCE_ATTRIBUTE, - request.getAttribute(NONCE_ATTRIBUTE).getClass().getName()); + "is neither a Grails nor a Spring Security nonce, so the header is not sent.", + NONCE_PLACEHOLDER, ContentSecurityPolicyNonce.ATTRIBUTE, + request.getAttribute(ContentSecurityPolicyNonce.ATTRIBUTE).getClass().getName()); } return null; } return policy.replace(NONCE_PLACEHOLDER, nonce); } - /** - * The nonce the request carries: the one this filter generated, or the one Spring Security's - * {@code ContentSecurityPolicyNonceGeneratingFilter} set, whose {@code getNonce()} is read - * through Spring Security's public interface since this module does not depend on it. - */ - private static String nonceOf(HttpServletRequest request) { - Object holder = request.getAttribute(NONCE_ATTRIBUTE); - if (holder == null) { - // Removed after this filter set it, so the header gets one of its own. - ContentSecurityPolicyNonce nonce = new ContentSecurityPolicyNonce(); - request.setAttribute(NONCE_ATTRIBUTE, nonce); - return nonce.getNonce(); - } - if (holder instanceof ContentSecurityPolicyNonce nonce) { - return nonce.getNonce(); - } - Method getNonce = ClassUtils.getMethodIfAvailable(holder.getClass(), "getNonce"); - if (getNonce == null || getNonce.getReturnType() != String.class) { - return null; - } - Object nonce = ReflectionUtils.invokeMethod( - ClassUtils.getPubliclyAccessibleMethodIfPossible(getNonce, holder.getClass()), holder); - return (nonce instanceof String value && StringUtils.hasText(value)) ? value : null; - } - private boolean shouldApplyDefaults(HttpServletRequest request) { return switch (this.properties.getDefaults()) { case ALWAYS -> true; @@ -323,32 +291,4 @@ private void applyHeader(HttpServletResponse response, String name, String prope } } } - - /** - * The nonce of one request, generated the first time it is read: 128 bits from a - * {@link SecureRandom}, Base64-encoded without padding, as Spring Security generates one. - * A page renders it with the {@code cspNonce} tag, and a controller reads it as - * {@code request._csp.nonce}. - */ - public static final class ContentSecurityPolicyNonce { - - private static final SecureRandom RANDOM = new SecureRandom(); - - private static final int NONCE_BYTES = 16; - - private final Supplier nonce = SingletonSupplier.of(ContentSecurityPolicyNonce::generate); - - ContentSecurityPolicyNonce() { - } - - public String getNonce() { - return this.nonce.get(); - } - - private static String generate() { - byte[] bytes = new byte[NONCE_BYTES]; - RANDOM.nextBytes(bytes); - return Base64.getEncoder().withoutPadding().encodeToString(bytes); - } - } } 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 e79e0f82b76..32bf2ccba48 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 @@ -25,8 +25,6 @@ import org.springframework.aot.hint.RuntimeHints import org.springframework.aot.hint.TypeReference import spock.lang.Specification -import org.grails.plugins.web.controllers.GrailsSecurityHeadersFilter - /** * Covers the controller API surviving into an ahead-of-time image. Without these hints the methods * are stripped and dispatch fails on the request that first takes the path, which for the method @@ -66,12 +64,6 @@ class ControllerRuntimeHintsSpec extends Specification { registered(grails.artefact.controller.support.RequestForwarder) } - void 'the nonce of a nonce-based Content-Security-Policy is registered, whichever filter generated it'() { - expect: 'the cspNonce tag reads it as request._csp.nonce, and the security headers filter reads Spring Security\'s' - registered(GrailsSecurityHeadersFilter.ContentSecurityPolicyNonce) - registered(TypeReference.of('org.springframework.security.web.header.ContentSecurityPolicyNonce')) - } - void 'a type from a module that is absent is skipped rather than failing the build'() { given: RuntimeHints empty = new RuntimeHints() diff --git a/grails-controllers/src/test/groovy/org/grails/plugins/web/controllers/GrailsSecurityHeadersAutoConfigurationSpec.groovy b/grails-controllers/src/test/groovy/org/grails/plugins/web/controllers/GrailsSecurityHeadersAutoConfigurationSpec.groovy index 6947556a641..e1dbb7c63fe 100644 --- a/grails-controllers/src/test/groovy/org/grails/plugins/web/controllers/GrailsSecurityHeadersAutoConfigurationSpec.groovy +++ b/grails-controllers/src/test/groovy/org/grails/plugins/web/controllers/GrailsSecurityHeadersAutoConfigurationSpec.groovy @@ -44,6 +44,7 @@ import org.springframework.security.web.header.writers.ReferrerPolicyHeaderWrite import org.springframework.security.web.header.writers.frameoptions.XFrameOptionsHeaderWriter import org.springframework.web.filter.CharacterEncodingFilter +import grails.web.http.ContentSecurityPolicyNonce import org.grails.web.config.http.GrailsFilters import spock.lang.Specification @@ -286,7 +287,7 @@ class GrailsSecurityHeadersAutoConfigurationSpec extends Specification { def properties = cspProperties("script-src 'self' 'nonce-{nonce}'; style-src 'nonce-{nonce}'") String rendered = null FilterChain view = { viewRequest, viewResponse -> - rendered = viewRequest.getAttribute('_csp').nonce + rendered = ContentSecurityPolicyNonce.nonceOf(viewRequest as HttpServletRequest) } as FilterChain when: @@ -344,7 +345,7 @@ class GrailsSecurityHeadersAutoConfigurationSpec extends Specification { def filter = new GrailsSecurityHeadersFilter(cspProperties("script-src 'nonce-{nonce}'")) def original = new MockHttpServletResponse() filter.doFilter(request, original, new MockFilterChain()) - String rendered = request.getAttribute('_csp').nonce + String rendered = ContentSecurityPolicyNonce.nonceOf(request) when: 'the container dispatches the same request to its error page' request.dispatcherType = DispatcherType.ERROR @@ -437,7 +438,7 @@ class GrailsSecurityHeadersAutoConfigurationSpec extends Specification { def request = new MockHttpServletRequest('GET', '/') def response = new MockHttpServletResponse() context.getBean(GrailsSecurityHeadersFilter).doFilter(request, response, new MockFilterChain()) - String nonce = request.getAttribute('_csp').nonce + String nonce = ContentSecurityPolicyNonce.nonceOf(request) assert nonce ==~ /[A-Za-z0-9+\/]{22}/ assert response.getHeader('Content-Security-Policy') == "script-src 'self' 'nonce-${nonce}'" } @@ -1415,7 +1416,7 @@ class GrailsSecurityHeadersAutoConfigurationSpec extends Specification { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) { - response.writer.write(request.getAttribute('_csp').nonce as String) + response.writer.write(ContentSecurityPolicyNonce.nonceOf(request)) } } diff --git a/grails-doc/src/en/guide/security.adoc b/grails-doc/src/en/guide/security.adoc index caaeca520b4..8ec39499570 100644 --- a/grails-doc/src/en/guide/security.adoc +++ b/grails-doc/src/en/guide/security.adoc @@ -196,5 +196,5 @@ Spring Security's header is written first, and the Grails policy is not sent. The `cspNonce` and `javascript` tags read the nonce from `_csp`. If Spring Security's header configuration names another attribute with `nonceAttributeName`, render the nonce from that attribute instead. -If the `_csp` attribute holds something that has no nonce, the policy is not sent, since a policy without the nonce would block every inline script the view gave one. +If the `_csp` attribute holds anything other than a Grails or Spring Security nonce, the policy is not sent, since a policy without the nonce would block every inline script the view gave one. Grails logs a warning the first time that happens. diff --git a/grails-web-common/build.gradle b/grails-web-common/build.gradle index cb166e24fb4..30e72b7ed17 100644 --- a/grails-web-common/build.gradle +++ b/grails-web-common/build.gradle @@ -62,6 +62,10 @@ dependencies { testImplementation 'jakarta.servlet:jakarta.servlet-api' testImplementation 'org.springframework:spring-test' + // Test-only: ContentSecurityPolicyNonceSpec reads the nonce Spring Security's own nonce filter + // generates. Not a main/runtime dependency - the nonce is read through Spring Security's public + // interface without depending on it. + testImplementation 'org.springframework.security:spring-security-web' testImplementation 'org.apache.groovy:groovy-test-junit5' testImplementation 'org.junit.jupiter:junit-jupiter-api' diff --git a/grails-web-common/src/main/groovy/grails/web/http/ContentSecurityPolicyNonce.java b/grails-web-common/src/main/groovy/grails/web/http/ContentSecurityPolicyNonce.java new file mode 100644 index 00000000000..7355a58b14d --- /dev/null +++ b/grails-web-common/src/main/groovy/grails/web/http/ContentSecurityPolicyNonce.java @@ -0,0 +1,113 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package grails.web.http; + +import java.lang.reflect.Method; +import java.security.SecureRandom; +import java.util.Base64; +import java.util.function.Supplier; + +import jakarta.servlet.http.HttpServletRequest; + +import org.jspecify.annotations.Nullable; + +import org.springframework.util.ClassUtils; +import org.springframework.util.ReflectionUtils; +import org.springframework.util.StringUtils; +import org.springframework.util.function.SingletonSupplier; + +/** + * The nonce of a nonce-based Content-Security-Policy, which a request carries under the + * {@value #ATTRIBUTE} attribute. + * + *

The Grails security headers filter puts one on each request when + * {@code grails.security.headers.content-security-policy.value} names the nonce with the + * {@code {nonce}} placeholder. {@value #ATTRIBUTE} is also the attribute Spring Security's + * {@code ContentSecurityPolicyNonceGeneratingFilter} sets by default, so + * {@link #nonceOf(HttpServletRequest)} reads the nonce whichever of the two generated it.

+ * + * @since 9.1 + */ +public final class ContentSecurityPolicyNonce { + + /** + * The request attribute that carries the nonce. + */ + public static final String ATTRIBUTE = "_csp"; + + /** + * The public type of the nonce Spring Security generates, whose implementation is a private + * class. It is read through this type, the one registered for reflection, since this module + * does not depend on Spring Security. + */ + private static final String SPRING_SECURITY_NONCE = + "org.springframework.security.web.header.ContentSecurityPolicyNonce"; + + private static final SecureRandom RANDOM = new SecureRandom(); + + private static final int NONCE_BYTES = 16; + + private final Supplier generated = SingletonSupplier.of(ContentSecurityPolicyNonce::generate); + + /** + * The nonce, generated the first time it is read: 128 bits from a {@link SecureRandom}, + * Base64-encoded without padding, as Spring Security generates one. + * + * @return the nonce + */ + public String getNonce() { + return this.generated.get(); + } + + /** + * The nonce the request carries: one the Grails security headers filter generated, or one + * Spring Security's {@code ContentSecurityPolicyNonceGeneratingFilter} generated. + * + * @param request the request + * @return the nonce, or {@code null} when the request carries neither + */ + public static @Nullable String nonceOf(HttpServletRequest request) { + Object holder = request.getAttribute(ATTRIBUTE); + if (holder instanceof ContentSecurityPolicyNonce nonce) { + return nonce.getNonce(); + } + Method getNonce = springSecurityGetNonce(holder); + Object nonce = (getNonce != null) ? ReflectionUtils.invokeMethod(getNonce, holder) : null; + return (nonce instanceof String value && StringUtils.hasText(value)) ? value : null; + } + + private static @Nullable Method springSecurityGetNonce(@Nullable Object holder) { + if (holder == null) { + return null; + } + // the loader of the holder's own class, which loaded the interface it implements + ClassLoader classLoader = holder.getClass().getClassLoader(); + if (!ClassUtils.isPresent(SPRING_SECURITY_NONCE, classLoader)) { + return null; + } + Class nonceType = ClassUtils.resolveClassName(SPRING_SECURITY_NONCE, classLoader); + return nonceType.isInstance(holder) ? ClassUtils.getMethodIfAvailable(nonceType, "getNonce") : null; + } + + private static String generate() { + byte[] bytes = new byte[NONCE_BYTES]; + RANDOM.nextBytes(bytes); + return Base64.getEncoder().withoutPadding().encodeToString(bytes); + } +} diff --git a/grails-web-common/src/main/groovy/org/apache/grails/web/http/aot/ContentSecurityPolicyRuntimeHints.java b/grails-web-common/src/main/groovy/org/apache/grails/web/http/aot/ContentSecurityPolicyRuntimeHints.java new file mode 100644 index 00000000000..f36b81282e7 --- /dev/null +++ b/grails-web-common/src/main/groovy/org/apache/grails/web/http/aot/ContentSecurityPolicyRuntimeHints.java @@ -0,0 +1,62 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.grails.web.http.aot; + +import org.jspecify.annotations.Nullable; + +import org.springframework.aot.hint.MemberCategory; +import org.springframework.aot.hint.RuntimeHints; +import org.springframework.aot.hint.RuntimeHintsRegistrar; + +import grails.web.http.ContentSecurityPolicyNonce; + +/** + * Registers what reading the nonce of a nonce-based Content-Security-Policy reflects on. + * + *

Spring Security's nonce is a private class behind a public interface, and + * {@link ContentSecurityPolicyNonce#nonceOf} reads it through that interface. An image has no + * metadata for the private class, so only the interface can be registered, and the read must not + * reflect on anything else.

+ * + * @since 9.1 + */ +public class ContentSecurityPolicyRuntimeHints implements RuntimeHintsRegistrar { + + /** What a hinted type is registered for: the members Groovy reads to choose an overload. */ + private static final MemberCategory[] DISPATCHED_MEMBERS = { + MemberCategory.INVOKE_DECLARED_METHODS, + MemberCategory.INVOKE_PUBLIC_METHODS, + MemberCategory.INVOKE_DECLARED_CONSTRUCTORS + }; + + /** + * The nonce Spring Security's nonce filter sets. Named as a string and registered only when + * present, since an application need not use Spring Security. + */ + private static final String SPRING_SECURITY_NONCE = + "org.springframework.security.web.header.ContentSecurityPolicyNonce"; + + @Override + public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) { + // a controller, a service or a dynamically compiled page reads the nonce through Groovy's + // dynamic dispatch + hints.reflection().registerType(ContentSecurityPolicyNonce.class, DISPATCHED_MEMBERS); + hints.reflection().registerTypeIfPresent(classLoader, SPRING_SECURITY_NONCE, DISPATCHED_MEMBERS); + } +} diff --git a/grails-web-common/src/main/resources/META-INF/spring/aot.factories b/grails-web-common/src/main/resources/META-INF/spring/aot.factories new file mode 100644 index 00000000000..b9798aad4da --- /dev/null +++ b/grails-web-common/src/main/resources/META-INF/spring/aot.factories @@ -0,0 +1,2 @@ +org.springframework.aot.hint.RuntimeHintsRegistrar=\ +org.apache.grails.web.http.aot.ContentSecurityPolicyRuntimeHints diff --git a/grails-web-common/src/test/groovy/grails/web/http/ContentSecurityPolicyNonceSpec.groovy b/grails-web-common/src/test/groovy/grails/web/http/ContentSecurityPolicyNonceSpec.groovy new file mode 100644 index 00000000000..6af059f7fa4 --- /dev/null +++ b/grails-web-common/src/test/groovy/grails/web/http/ContentSecurityPolicyNonceSpec.groovy @@ -0,0 +1,106 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package grails.web.http + +import java.lang.reflect.Modifier + +import jakarta.servlet.FilterChain +import jakarta.servlet.http.HttpServletRequest + +import org.springframework.mock.web.MockHttpServletRequest +import org.springframework.mock.web.MockHttpServletResponse +import org.springframework.security.web.header.ContentSecurityPolicyNonceGeneratingFilter +import spock.lang.Specification +import spock.lang.Unroll + +class ContentSecurityPolicyNonceSpec extends Specification { + + MockHttpServletRequest request = new MockHttpServletRequest('GET', '/') + + void 'a nonce is 128 random bits in Base64 without padding, generated once'() { + given: + def nonce = new ContentSecurityPolicyNonce() + + expect: + nonce.nonce ==~ /[A-Za-z0-9+\/]{22}/ + nonce.nonce == nonce.nonce + nonce.nonce != new ContentSecurityPolicyNonce().nonce + } + + void 'the nonce the Grails security headers filter put on the request is read'() { + given: + def nonce = new ContentSecurityPolicyNonce() + request.setAttribute('_csp', nonce) + + expect: + ContentSecurityPolicyNonce.ATTRIBUTE == '_csp' + ContentSecurityPolicyNonce.nonceOf(request) == nonce.nonce + } + + void 'the nonce Spring Security generated is read through its public interface'() { + given: 'a view behind Spring Security\'s own nonce filter' + String read = null + Object carried = null + FilterChain view = { viewRequest, viewResponse -> + read = ContentSecurityPolicyNonce.nonceOf(viewRequest as HttpServletRequest) + carried = viewRequest.getAttribute('_csp') + } as FilterChain + + when: + new ContentSecurityPolicyNonceGeneratingFilter().doFilter(request, new MockHttpServletResponse(), view) + + then: 'the filter carries it in a class that is not public, behind the interface' + !Modifier.isPublic(carried.getClass().modifiers) + carried instanceof org.springframework.security.web.header.ContentSecurityPolicyNonce + + and: + read ==~ /[A-Za-z0-9+\/]{22}/ + read == (carried as org.springframework.security.web.header.ContentSecurityPolicyNonce).nonce + } + + @Unroll + void 'a request carries no nonce when #description'() { + given: + if (holder != null) { + request.setAttribute('_csp', holder) + } + + expect: + ContentSecurityPolicyNonce.nonceOf(request) == null + + where: + description | holder + 'nothing is under the attribute' | null + 'something else is under the attribute' | 'not a nonce' + 'Spring Security\'s nonce is blank' | blankSpringSecurityNonce() + 'another type with a nonce getter is under the attribute' | new LookalikeNonce() + } + + private static org.springframework.security.web.header.ContentSecurityPolicyNonce blankSpringSecurityNonce() { + { -> ' ' } as org.springframework.security.web.header.ContentSecurityPolicyNonce + } + + /** Has a public nonce getter, but is neither the Grails nonce nor Spring Security's. */ + static class LookalikeNonce { + + String getNonce() { + 'abc' + } + } +} diff --git a/grails-web-common/src/test/groovy/org/apache/grails/web/http/aot/ContentSecurityPolicyRuntimeHintsSpec.groovy b/grails-web-common/src/test/groovy/org/apache/grails/web/http/aot/ContentSecurityPolicyRuntimeHintsSpec.groovy new file mode 100644 index 00000000000..ff82bdf6e72 --- /dev/null +++ b/grails-web-common/src/test/groovy/org/apache/grails/web/http/aot/ContentSecurityPolicyRuntimeHintsSpec.groovy @@ -0,0 +1,71 @@ +/* + * 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.web.http.aot + +import org.springframework.aot.hint.RuntimeHints +import org.springframework.aot.hint.RuntimeHintsRegistrar +import org.springframework.aot.hint.TypeReference +import org.springframework.aot.hint.predicate.RuntimeHintsPredicates +import org.springframework.core.io.support.SpringFactoriesLoader +import spock.lang.Specification + +import grails.web.http.ContentSecurityPolicyNonce + +/** + * Covers reading the nonce of a nonce-based Content-Security-Policy in an ahead-of-time image, where + * only registered types can be reflected on. + */ +class ContentSecurityPolicyRuntimeHintsSpec extends Specification { + + private static final String SPRING_SECURITY_NONCE = 'org.springframework.security.web.header.ContentSecurityPolicyNonce' + + RuntimeHints hints = new RuntimeHints() + + void 'Spring Security\'s nonce can be read through its public interface'() { + when: + new ContentSecurityPolicyRuntimeHints().registerHints(hints, getClass().classLoader) + + then: + RuntimeHintsPredicates.reflection().onMethodInvocation(SPRING_SECURITY_NONCE, 'getNonce').test(hints) + } + + void 'the Grails nonce can be read by Groovy\'s dynamic dispatch'() { + when: + new ContentSecurityPolicyRuntimeHints().registerHints(hints, getClass().classLoader) + + then: 'a controller or a dynamically compiled page calling the reader, or the getter' + RuntimeHintsPredicates.reflection().onMethodInvocation(ContentSecurityPolicyNonce, 'nonceOf').test(hints) + RuntimeHintsPredicates.reflection().onMethodInvocation(ContentSecurityPolicyNonce, 'getNonce').test(hints) + } + + void 'an application without Spring Security still registers the Grails nonce'() { + when: 'a class loader that resolves nothing, as an application without Spring Security has' + new ContentSecurityPolicyRuntimeHints().registerHints(hints, new URLClassLoader(new URL[0], null)) + + then: + hints.reflection().getTypeHint(TypeReference.of(SPRING_SECURITY_NONCE)) == null + hints.reflection().getTypeHint(TypeReference.of(ContentSecurityPolicyNonce)) != null + } + + void 'the hints are registered for an ahead-of-time build'() { + expect: + SpringFactoriesLoader.forResourceLocation('META-INF/spring/aot.factories') + .load(RuntimeHintsRegistrar)*.class.contains(ContentSecurityPolicyRuntimeHints) + } +} From 5f76fe9db8e65f811116eac528539d808ae66795 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Fri, 23 Oct 2026 13:47:02 -0700 Subject: [PATCH 039/131] Render the nonce in the cspNonce tag through the same reader The tag read the nonce as holder?.nonce, leaving the getter to Groovy's dynamic dispatch on whatever sits under _csp, while the security headers filter now reads only a Grails or a Spring Security nonce. The tag calls ContentSecurityPolicyNonce.nonceOf(request) instead, so the page and the header read the nonce one way and agree on what counts as one. The reader lives in grails-web-common because a plain Spring Boot application using GSP has this tag but not grails-controllers. ApplicationTagLibTests renders a dynamic and a statically compiled page behind Spring Security's own ContentSecurityPolicyNonceGeneratingFilter, ahead of the Grails filter, and checks the page and the Grails policy name the nonce Spring Security carries in its non-public class. --- grails-gsp/plugin/build.gradle | 2 ++ .../web/taglib/ApplicationTagLib.groovy | 15 ++------- .../web/taglib/ApplicationTagLibTests.groovy | 31 +++++++++++++++++++ 3 files changed, 35 insertions(+), 13 deletions(-) diff --git a/grails-gsp/plugin/build.gradle b/grails-gsp/plugin/build.gradle index a80f40fd1f8..6e4b6ed2048 100644 --- a/grails-gsp/plugin/build.gradle +++ b/grails-gsp/plugin/build.gradle @@ -175,6 +175,8 @@ dependencies { testImplementation "jakarta.servlet.jsp:jakarta.servlet.jsp-api:$jspApiVersion" testImplementation 'org.junit.jupiter:junit-jupiter-api' testImplementation 'org.springframework:spring-test' + // Test-only: ApplicationTagLibTests renders the nonce Spring Security's own nonce filter generates + testImplementation 'org.springframework.security:spring-security-web' testImplementation 'org.spockframework:spock-core' testImplementation 'org.apache.grails:grails-testing-support-datamapping' testImplementation project(':grails-testing-support-core') diff --git a/grails-gsp/plugin/src/main/groovy/org/grails/plugins/web/taglib/ApplicationTagLib.groovy b/grails-gsp/plugin/src/main/groovy/org/grails/plugins/web/taglib/ApplicationTagLib.groovy index 6f73c317114..df1c971a33a 100644 --- a/grails-gsp/plugin/src/main/groovy/org/grails/plugins/web/taglib/ApplicationTagLib.groovy +++ b/grails-gsp/plugin/src/main/groovy/org/grails/plugins/web/taglib/ApplicationTagLib.groovy @@ -38,6 +38,7 @@ import grails.gsp.TagLib import grails.plugins.GrailsPluginManager import grails.util.GrailsStringUtils import grails.util.Metadata +import grails.web.http.ContentSecurityPolicyNonce import grails.web.mapping.LinkGenerator import grails.web.mapping.UrlMappingsHolder import org.grails.web.servlet.mvc.GrailsWebRequest @@ -53,12 +54,6 @@ class ApplicationTagLib implements ApplicationContextAware, InitializingBean, Gr static returnObjectForTags = ['createLink', 'resource', 'createLinkTo', 'cookie', 'header', 'cspNonce', 'img', 'join', 'meta', 'set', 'applyCodec'] - /** - * The request attribute that carries the nonce of a nonce-based Content-Security-Policy, which the Grails - * security headers filter and Spring Security's nonce filter both set. - */ - private static final String CSP_NONCE_ATTRIBUTE = '_csp' - ApplicationContext applicationContext GrailsPluginManager pluginManager GrailsApplication grailsApplication @@ -136,13 +131,7 @@ class ApplicationTagLib implements ApplicationContextAware, InitializingBean, Gr * @emptyTag */ def cspNonce(Map attrs) { - Object holder = request.getAttribute(CSP_NONCE_ATTRIBUTE) - try { - holder?.nonce - } catch (MissingPropertyException ignored) { - // something other than a nonce under that name leaves the page without one rather than failing it - null - } + ContentSecurityPolicyNonce.nonceOf(request) } /** diff --git a/grails-gsp/plugin/src/test/groovy/org/grails/web/taglib/ApplicationTagLibTests.groovy b/grails-gsp/plugin/src/test/groovy/org/grails/web/taglib/ApplicationTagLibTests.groovy index 1f073ca25e9..170deda23ee 100644 --- a/grails-gsp/plugin/src/test/groovy/org/grails/web/taglib/ApplicationTagLibTests.groovy +++ b/grails-gsp/plugin/src/test/groovy/org/grails/web/taglib/ApplicationTagLibTests.groovy @@ -34,6 +34,7 @@ import org.grails.taglib.GrailsTagException import org.grails.web.util.GrailsApplicationAttributes import org.grails.web.util.WebUtils import org.springframework.mock.web.MockHttpServletResponse +import org.springframework.security.web.header.ContentSecurityPolicyNonceGeneratingFilter import spock.lang.Specification import jakarta.servlet.FilterChain @@ -267,6 +268,36 @@ class ApplicationTagLibTests extends Specification implements TagLibUnitTest' } + void 'the nonce Spring Security generated renders in a #compilation page, and the policy names it'() { + given: 'Spring Security\'s nonce filter ahead of the security headers filter, as with its chain ordered ahead of GrailsFilters.FIRST' + def properties = new GrailsSecurityHeadersProperties() + properties.contentSecurityPolicy.enabled = true + properties.contentSecurityPolicy.value = "script-src 'nonce-{nonce}'; style-src 'nonce-{nonce}'" + def response = new MockHttpServletResponse() + String page = null + FilterChain view = { viewRequest, viewResponse -> + page = applyTemplate(directive + '') + } as FilterChain + + when: + new ContentSecurityPolicyNonceGeneratingFilter().doFilter(request, response, { securedRequest, securedResponse -> + new GrailsSecurityHeadersFilter(properties).doFilter(securedRequest, securedResponse, view) + } as FilterChain) + def carried = request.getAttribute('_csp') as org.springframework.security.web.header.ContentSecurityPolicyNonce + + then: 'the page renders the nonce Spring Security carries in its own non-public class' + carried.nonce ==~ /[A-Za-z0-9+\/]{22}/ + page == "" + + and: 'the policy names the same nonce' + response.getHeader('Content-Security-Policy') == "script-src 'nonce-${carried.nonce}'; style-src 'nonce-${carried.nonce}'" + + where: + compilation | directive + 'dynamic' | '' + 'static' | '<%@ page compileStatic="true" %>' + } + void 'no nonce renders when the request carries none: #description'() { given: if (holder != null) { From 07f1a52dec1bcadeb3187c0a70768d6219ca88ec Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Fri, 23 Oct 2026 13:47:02 -0700 Subject: [PATCH 040/131] Document ContentSecurityPolicyNonce.nonceOf for code outside a view request._csp?.nonce compiles only in dynamic code: under @GrailsCompileStatic there is no typed read that works for both producers. The security guide, the cspNonce reference and What's New now point controllers and services at grails.web.http.ContentSecurityPolicyNonce.nonceOf(request), which compiles either way and returns null when the request carries no nonce. --- grails-doc/src/en/guide/introduction/whatsNew.adoc | 3 ++- grails-doc/src/en/guide/security.adoc | 3 ++- grails-doc/src/en/ref/Tags - GSP/cspNonce.adoc | 2 +- 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/grails-doc/src/en/guide/introduction/whatsNew.adoc b/grails-doc/src/en/guide/introduction/whatsNew.adoc index db282934691..d14a6ef6b16 100644 --- a/grails-doc/src/en/guide/introduction/whatsNew.adoc +++ b/grails-doc/src/en/guide/introduction/whatsNew.adoc @@ -588,7 +588,8 @@ grails: ---- A view renders the request's nonce with the new `` tag, as in `