From d82e66c7feea85e5caa0acc766ec0ffc4af48662 Mon Sep 17 00:00:00 2001 From: James Fredley Date: Wed, 21 Oct 2026 21:46:30 -0400 Subject: [PATCH 1/7] Resolve every column of an enum unique-group member An enum unique group that includes a multi-column association no longer asks for a single column name and fails datastore startup. Each configured column of the group member is added to the unique key. A property with no explicit columns keeps the previous fallback. Fixes #16713 Assisted-by: Sisyphus:grok-4.7 --- .../domainbinding/util/CreateKeyForProps.java | 14 ++- .../EnumUniqueGroupAssociationSpec.groovy | 86 +++++++++++++++++++ .../CreateKeyForPropsSpec.groovy | 26 +++--- 3 files changed, 113 insertions(+), 13 deletions(-) create mode 100644 grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/EnumUniqueGroupAssociationSpec.groovy diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/util/CreateKeyForProps.java b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/util/CreateKeyForProps.java index 1c04ba6c1d5c..19a9d096c445 100644 --- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/util/CreateKeyForProps.java +++ b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/util/CreateKeyForProps.java @@ -19,12 +19,14 @@ package org.grails.orm.hibernate.cfg.domainbinding.util; import java.util.ArrayList; +import java.util.Collections; import java.util.List; import org.hibernate.MappingException; import org.hibernate.mapping.Column; import org.hibernate.mapping.Table; +import org.grails.orm.hibernate.cfg.ColumnConfig; import org.grails.orm.hibernate.cfg.PropertyConfig; import org.grails.orm.hibernate.cfg.domainbinding.hibernate.GrailsHibernatePersistentEntity; import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernatePersistentProperty; @@ -70,9 +72,15 @@ public void createKeyForProps(HibernatePersistentProperty grailsProp, String pat throw new MappingException( owner.getJavaClass().getName() + " references an unknown property " + propertyName); } - String otherColumnName = - columnNameForPropertyAndPathFetcher.getColumnNameForPropertyAndPath(otherProp, path, null); - keyList.add(new Column(otherColumnName)); + List columns = otherProp.getHibernateMappedForm().getColumns(); + if (columns.isEmpty()) { + columns = Collections.singletonList(null); + } + for (ColumnConfig column : columns) { + String otherColumnName = + columnNameForPropertyAndPathFetcher.getColumnNameForPropertyAndPath(otherProp, path, column); + keyList.add(new Column(otherColumnName)); + } } uniqueKeyForColumnsCreator.createUniqueKeyForColumns(table, keyList); diff --git a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/EnumUniqueGroupAssociationSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/EnumUniqueGroupAssociationSpec.groovy new file mode 100644 index 000000000000..61651d7421a5 --- /dev/null +++ b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/EnumUniqueGroupAssociationSpec.groovy @@ -0,0 +1,86 @@ +/* + * 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.gorm.tests + +import grails.gorm.annotation.Entity +import grails.gorm.hibernate.HibernateEntity +import groovy.transform.EqualsAndHashCode +import spock.lang.Issue + +@Issue('https://github.com/apache/grails-core/issues/16713') +class EnumUniqueGroupAssociationSpec extends HibernateGormDatastoreSpec { + + void setupSpec() { + manager.registerDomainClasses(EnumUniqueCompositeParent, EnumUniqueCompositeChild) + } + + void "an enum unique group includes every mapped column of a composite parent"() { + given: + def table = datastore.metadata.getEntityBinding(EnumUniqueCompositeChild.name).table + + expect: + table.uniqueKeys.values().collect { it.columns*.name.toSet() } == + [['child_state', 'parent_code', 'parent_revision'] as Set] + table.getForeignKeys().values().any { it.columns*.name.toSet() == ['parent_code', 'parent_revision'] as Set } + } + + void "the same enum can be saved for parents differing in either identifier column"() { + when: + [['a', 1], ['a', 2], ['b', 1]].each { code, revision -> + def parent = new EnumUniqueCompositeParent(code: code, revision: revision).save(failOnError: true) + new EnumUniqueCompositeChild(parent: parent, state: EnumUniqueCompositeState.ON).save(failOnError: true) + } + manager.session.flush() + manager.session.clear() + + then: + EnumUniqueCompositeChild.count() == 3 + EnumUniqueCompositeChild.list()*.parent.collect { [it.code, it.revision] }.toSet() == + [['a', 1], ['a', 2], ['b', 1]] as Set + } +} + +enum EnumUniqueCompositeState { + ON, OFF +} + +@Entity +@EqualsAndHashCode(includes = ['code', 'revision']) +class EnumUniqueCompositeParent implements HibernateEntity, Serializable { + String code + Integer revision + + static mapping = { + id composite: ['code', 'revision'] + } +} + +@Entity +class EnumUniqueCompositeChild implements HibernateEntity { + EnumUniqueCompositeParent parent + EnumUniqueCompositeState state + + static mapping = { + state column: 'child_state', unique: 'parent' + parent { + column name: 'parent_code' + column name: 'parent_revision' + } + } +} diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/CreateKeyForPropsSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/CreateKeyForPropsSpec.groovy index 260ffaadda5f..73acf1f9cb58 100644 --- a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/CreateKeyForPropsSpec.groovy +++ b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/CreateKeyForPropsSpec.groovy @@ -19,6 +19,7 @@ package org.grails.orm.hibernate.cfg.domainbinding +import org.grails.orm.hibernate.cfg.PropertyConfig import org.grails.orm.hibernate.cfg.domainbinding.hibernate.GrailsHibernatePersistentEntity import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernatePersistentProperty import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateToManyProperty @@ -50,8 +51,12 @@ class CreateKeyForPropsSpec extends Specification { } grailsProp.getMappedForm() >> mappedForm - def otherProp1 = Mock(HibernatePersistentProperty) - def otherProp2 = Mock(HibernatePersistentProperty) + def otherProp1 = Mock(HibernatePersistentProperty) { + getHibernateMappedForm() >> new PropertyConfig() + } + def otherProp2 = Mock(HibernatePersistentProperty) { + getHibernateMappedForm() >> new PropertyConfig() + } owner.getHibernatePropertyByName("p1") >> otherProp1 owner.getHibernatePropertyByName("p2") >> otherProp2 @@ -59,9 +64,6 @@ class CreateKeyForPropsSpec extends Specification { def table = new Table("t") String baseColumnName = "base_col" - columnNameFetcher.getColumnNameForPropertyAndPath(otherProp1, path, null) >> "col1" - columnNameFetcher.getColumnNameForPropertyAndPath(otherProp2, path, null) >> "col2" - when: subject.createKeyForProps(grailsProp, path, table, baseColumnName) @@ -73,9 +75,9 @@ class CreateKeyForPropsSpec extends Specification { 1 * mappedForm.getUniquenessGroup() >> ["p1", "p2"] 1 * owner.getHibernatePropertyByName("p1") >> otherProp1 1 * owner.getHibernatePropertyByName("p2") >> otherProp2 - 1 * columnNameFetcher.getColumnNameForPropertyAndPath(otherProp1, path, null) - 1 * columnNameFetcher.getColumnNameForPropertyAndPath(otherProp2, path, null) - 1 * uniqueKeyCreator.createUniqueKeyForColumns(table, _ as List) + 1 * columnNameFetcher.getColumnNameForPropertyAndPath(otherProp1, path, null) >> "col1" + 1 * columnNameFetcher.getColumnNameForPropertyAndPath(otherProp2, path, null) >> "col2" + 1 * uniqueKeyCreator.createUniqueKeyForColumns(table, { List cols -> cols*.name == ["base_col", "col1", "col2"] }) } def "does nothing when property is not unique within group"() { @@ -165,7 +167,9 @@ class CreateKeyForPropsSpec extends Specification { def uniqueKeyCreator = Mock(UniqueKeyForColumnsCreator) def subject = new CreateKeyForProps(columnNameFetcher, uniqueKeyCreator) def owner = Mock(GrailsHibernatePersistentEntity) - def otherProp = Mock(HibernatePersistentProperty) + def otherProp = Mock(HibernatePersistentProperty) { + getHibernateMappedForm() >> new PropertyConfig() + } def mappedForm = Mock(org.grails.orm.hibernate.cfg.PropertyConfig) { isUnique() >> true isUniqueWithinGroup() >> true @@ -193,7 +197,9 @@ class CreateKeyForPropsSpec extends Specification { def uniqueKeyCreator = Mock(UniqueKeyForColumnsCreator) def subject = new CreateKeyForProps(columnNameFetcher, uniqueKeyCreator) def owner = Mock(GrailsHibernatePersistentEntity) - def otherProp = Mock(HibernatePersistentProperty) + def otherProp = Mock(HibernatePersistentProperty) { + getHibernateMappedForm() >> new PropertyConfig() + } def mappedForm = Mock(org.grails.orm.hibernate.cfg.PropertyConfig) { isUnique() >> true isUniqueWithinGroup() >> true From baae3cdc73268a1513961d054954c7bdd8785a97 Mon Sep 17 00:00:00 2001 From: James Fredley Date: Wed, 28 Oct 2026 18:57:14 -0400 Subject: [PATCH 2/7] Create unique-group keys after composite association columns are bound A unique group declared before a composite association was keyed on parent_id, because those association columns did not exist yet. Resolve the group once Hibernate's second pass has populated them. Assisted-by: sisyphus-cursor-grok:grok-4.7 --- .../domainbinding/binder/ColumnBinder.java | 7 +- .../domainbinding/binder/EnumTypeBinder.java | 2 +- .../binder/SimpleValueBinder.java | 2 +- .../domainbinding/util/CreateKeyForProps.java | 64 ++++---- .../EnumUniqueGroupAssociationSpec.groovy | 94 +++++++++++- .../CreateKeyForPropsSpec.groovy | 138 ++++++++++++++++-- 6 files changed, 266 insertions(+), 41 deletions(-) diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/ColumnBinder.java b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/ColumnBinder.java index 2c93ddb616f6..68fc675ac3d9 100644 --- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/ColumnBinder.java +++ b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/ColumnBinder.java @@ -18,6 +18,7 @@ */ package org.grails.orm.hibernate.cfg.domainbinding.binder; +import org.hibernate.boot.spi.MetadataBuildingContext; import org.hibernate.dialect.Dialect; import org.hibernate.mapping.Column; import org.hibernate.mapping.Table; @@ -65,14 +66,16 @@ public ColumnBinder( this.indexBinder = indexBinder; } - public ColumnBinder(PersistentEntityNamingStrategy namingStrategy, Dialect dialect) { + public ColumnBinder( + PersistentEntityNamingStrategy namingStrategy, Dialect dialect, MetadataBuildingContext metadataBuildingContext) { this( new ColumnNameForPropertyAndPathFetcher( namingStrategy, new DefaultColumnNameFetcher(namingStrategy), new BackticksRemover()), new StringColumnConstraintsBinder(), new NumericColumnConstraintsBinder(dialect), new CreateKeyForProps(new ColumnNameForPropertyAndPathFetcher( - namingStrategy, new DefaultColumnNameFetcher(namingStrategy), new BackticksRemover())), + namingStrategy, new DefaultColumnNameFetcher(namingStrategy), new BackticksRemover()), + metadataBuildingContext.getMetadataCollector()), new IndexBinder()); } diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/EnumTypeBinder.java b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/EnumTypeBinder.java index 0c14d5c8b24c..07ed2a1cbef6 100644 --- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/EnumTypeBinder.java +++ b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/EnumTypeBinder.java @@ -74,7 +74,7 @@ protected EnumTypeBinder( indexBinder, columnConfigToColumnBinder, namingStrategy, - new CreateKeyForProps(columnNameForPropertyAndPathFetcher)); + new CreateKeyForProps(columnNameForPropertyAndPathFetcher, metadataBuildingContext.getMetadataCollector())); } protected EnumTypeBinder( diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/SimpleValueBinder.java b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/SimpleValueBinder.java index 576f2f874e49..8e43faa727e5 100644 --- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/SimpleValueBinder.java +++ b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/SimpleValueBinder.java @@ -64,7 +64,7 @@ public SimpleValueBinder( this( metadataBuildingContext, new ColumnConfigToColumnBinder(), - new ColumnBinder(namingStrategy, jdbcEnvironment.getDialect()), + new ColumnBinder(namingStrategy, jdbcEnvironment.getDialect(), metadataBuildingContext), new BasicValueCreator(metadataBuildingContext, jdbcEnvironment, namingStrategy)); } diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/util/CreateKeyForProps.java b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/util/CreateKeyForProps.java index 19a9d096c445..1394da05b9fb 100644 --- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/util/CreateKeyForProps.java +++ b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/util/CreateKeyForProps.java @@ -23,6 +23,7 @@ import java.util.List; import org.hibernate.MappingException; +import org.hibernate.boot.spi.InFlightMetadataCollector; import org.hibernate.mapping.Column; import org.hibernate.mapping.Table; @@ -37,17 +38,21 @@ public class CreateKeyForProps { private final ColumnNameForPropertyAndPathFetcher columnNameForPropertyAndPathFetcher; private final UniqueKeyForColumnsCreator uniqueKeyForColumnsCreator; + private final InFlightMetadataCollector metadataCollector; - public CreateKeyForProps(ColumnNameForPropertyAndPathFetcher columnNameForPropertyAndPathFetcher) { - this.columnNameForPropertyAndPathFetcher = columnNameForPropertyAndPathFetcher; - this.uniqueKeyForColumnsCreator = new UniqueKeyForColumnsCreator(); + public CreateKeyForProps( + ColumnNameForPropertyAndPathFetcher columnNameForPropertyAndPathFetcher, + InFlightMetadataCollector metadataCollector) { + this(columnNameForPropertyAndPathFetcher, new UniqueKeyForColumnsCreator(), metadataCollector); } protected CreateKeyForProps( ColumnNameForPropertyAndPathFetcher columnNameForPropertyAndPathFetcher, - UniqueKeyForColumnsCreator uniqueKeyForColumnsCreator) { + UniqueKeyForColumnsCreator uniqueKeyForColumnsCreator, + InFlightMetadataCollector metadataCollector) { this.columnNameForPropertyAndPathFetcher = columnNameForPropertyAndPathFetcher; this.uniqueKeyForColumnsCreator = uniqueKeyForColumnsCreator; + this.metadataCollector = metadataCollector; } public void createKeyForProps(HibernatePersistentProperty grailsProp, String path, Table table, String columnName) { @@ -61,29 +66,38 @@ public void createKeyForProps(HibernatePersistentProperty grailsProp, String pat PropertyConfig mappedForm = grailsProp.getMappedForm(); if (mappedForm.isUnique() && mappedForm.isUniqueWithinGroup()) { - - List keyList = new ArrayList<>(); - keyList.add(new Column(columnName)); - List propertyNames = mappedForm.getUniquenessGroup(); - GrailsHibernatePersistentEntity owner = grailsProp.getHibernateOwner(); - for (String propertyName : propertyNames) { - HibernatePersistentProperty otherProp = owner.getHibernatePropertyByName(propertyName); - if (otherProp == null) { - throw new MappingException( - owner.getJavaClass().getName() + " references an unknown property " + propertyName); - } - List columns = otherProp.getHibernateMappedForm().getColumns(); - if (columns.isEmpty()) { - columns = Collections.singletonList(null); - } - for (ColumnConfig column : columns) { - String otherColumnName = - columnNameForPropertyAndPathFetcher.getColumnNameForPropertyAndPath(otherProp, path, column); - keyList.add(new Column(otherColumnName)); - } + if (metadataCollector.isInSecondPass()) { + createKeyForGroup(grailsProp, path, table, columnName, mappedForm); + } else { + metadataCollector.addSecondPass(persistentClasses -> + createKeyForGroup(grailsProp, path, table, columnName, mappedForm)); } + } + } - uniqueKeyForColumnsCreator.createUniqueKeyForColumns(table, keyList); + private void createKeyForGroup( + HibernatePersistentProperty grailsProp, String path, Table table, String columnName, PropertyConfig mappedForm) { + List keyList = new ArrayList<>(); + keyList.add(new Column(columnName)); + List propertyNames = mappedForm.getUniquenessGroup(); + GrailsHibernatePersistentEntity owner = grailsProp.getHibernateOwner(); + for (String propertyName : propertyNames) { + HibernatePersistentProperty otherProp = owner.getHibernatePropertyByName(propertyName); + if (otherProp == null) { + throw new MappingException( + owner.getJavaClass().getName() + " references an unknown property " + propertyName); + } + List columns = otherProp.getHibernateMappedForm().getColumns(); + if (columns.isEmpty()) { + columns = Collections.singletonList(null); + } + for (ColumnConfig column : columns) { + String otherColumnName = + columnNameForPropertyAndPathFetcher.getColumnNameForPropertyAndPath(otherProp, path, column); + keyList.add(new Column(otherColumnName)); + } } + + uniqueKeyForColumnsCreator.createUniqueKeyForColumns(table, keyList); } } diff --git a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/EnumUniqueGroupAssociationSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/EnumUniqueGroupAssociationSpec.groovy index 61651d7421a5..17b50a47154e 100644 --- a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/EnumUniqueGroupAssociationSpec.groovy +++ b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/EnumUniqueGroupAssociationSpec.groovy @@ -21,13 +21,15 @@ package grails.gorm.tests import grails.gorm.annotation.Entity import grails.gorm.hibernate.HibernateEntity import groovy.transform.EqualsAndHashCode +import org.springframework.dao.DataIntegrityViolationException import spock.lang.Issue @Issue('https://github.com/apache/grails-core/issues/16713') class EnumUniqueGroupAssociationSpec extends HibernateGormDatastoreSpec { void setupSpec() { - manager.registerDomainClasses(EnumUniqueCompositeParent, EnumUniqueCompositeChild) + manager.registerDomainClasses(EnumUniqueCompositeParent, EnumUniqueCompositeChild, + StringUniqueCompositeChild, DeclaredFirstUniqueCompositeChild) } void "an enum unique group includes every mapped column of a composite parent"() { @@ -54,6 +56,70 @@ class EnumUniqueGroupAssociationSpec extends HibernateGormDatastoreSpec { EnumUniqueCompositeChild.list()*.parent.collect { [it.code, it.revision] }.toSet() == [['a', 1], ['a', 2], ['b', 1]] as Set } + + void "a duplicate enum for the same composite parent violates the unique key"() { + given: + def parent = new EnumUniqueCompositeParent(code: 'duplicate', revision: 1).save(failOnError: true) + new EnumUniqueCompositeChild(parent: parent, state: EnumUniqueCompositeState.ON).save(flush: true, failOnError: true) + + when: + new EnumUniqueCompositeChild(parent: parent, state: EnumUniqueCompositeState.ON).save(flush: true, validate: false) + + then: + thrown(DataIntegrityViolationException) + } + + void "a string unique group includes every configured column of a composite parent"() { + given: + def table = datastore.metadata.getEntityBinding(StringUniqueCompositeChild.name).table + + expect: + table.uniqueKeys.values().collect { it.columns*.name.toSet() } == + [['code', 'parent_code', 'parent_revision'] as Set] + } + + void "declared-first enum and string groups include every implicit composite-association column"() { + given: + def table = datastore.metadata.getEntityBinding(DeclaredFirstUniqueCompositeChild.name).table + def foreignKeyColumns = ['enum_unique_composite_parent_code', 'enum_unique_composite_parent_revision'] as Set + + expect: + table.uniqueKeys.values().collect { it.columns*.name.toSet() }.toSet() == + [(['code'] as Set) + foreignKeyColumns, (['kind'] as Set) + foreignKeyColumns] as Set + table.getForeignKeys().values().any { it.columns*.name.toSet() == foreignKeyColumns } + } + + void "declared-first enum and string groups accept parents differing in either identifier column"() { + when: + [['a', 1], ['a', 2], ['b', 1]].each { code, revision -> + def parent = new EnumUniqueCompositeParent(code: code, revision: revision).save(failOnError: true) + new DeclaredFirstUniqueCompositeChild(parent: parent, code: 'same', kind: EnumUniqueCompositeState.ON) + .save(failOnError: true) + } + manager.session.flush() + manager.session.clear() + + then: + DeclaredFirstUniqueCompositeChild.count() == 3 + } + + void "a duplicate declared-first #property for the same composite parent violates the unique key"() { + given: + def parent = new EnumUniqueCompositeParent(code: 'duplicate', revision: 1).save(failOnError: true) + new DeclaredFirstUniqueCompositeChild(parent: parent, code: 'same', kind: EnumUniqueCompositeState.ON) + .save(flush: true, failOnError: true) + + when: + new DeclaredFirstUniqueCompositeChild(parent: parent, code: code, kind: kind).save(flush: true, validate: false) + + then: + thrown(DataIntegrityViolationException) + + where: + property | code | kind + 'string' | 'same' | EnumUniqueCompositeState.OFF + 'enum' | 'other' | EnumUniqueCompositeState.ON + } } enum EnumUniqueCompositeState { @@ -84,3 +150,29 @@ class EnumUniqueCompositeChild implements HibernateEntity { + String code + EnumUniqueCompositeParent parent + + static mapping = { + code unique: 'parent' + parent { + column name: 'parent_code' + column name: 'parent_revision' + } + } +} + +@Entity +class DeclaredFirstUniqueCompositeChild implements HibernateEntity { + String code + EnumUniqueCompositeState kind + EnumUniqueCompositeParent parent + + static mapping = { + code unique: 'parent' + kind unique: 'parent' + } +} diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/CreateKeyForPropsSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/CreateKeyForPropsSpec.groovy index 73acf1f9cb58..ebae102e117c 100644 --- a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/CreateKeyForPropsSpec.groovy +++ b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/CreateKeyForPropsSpec.groovy @@ -19,11 +19,14 @@ package org.grails.orm.hibernate.cfg.domainbinding +import org.grails.orm.hibernate.cfg.ColumnConfig import org.grails.orm.hibernate.cfg.PropertyConfig import org.grails.orm.hibernate.cfg.domainbinding.hibernate.GrailsHibernatePersistentEntity import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernatePersistentProperty import org.grails.orm.hibernate.cfg.domainbinding.hibernate.HibernateToManyProperty import org.hibernate.MappingException +import org.hibernate.boot.spi.InFlightMetadataCollector +import org.hibernate.boot.spi.SecondPass import org.hibernate.mapping.Table import spock.lang.Specification @@ -33,18 +36,22 @@ import org.grails.orm.hibernate.cfg.domainbinding.util.UniqueKeyForColumnsCreato class CreateKeyForPropsSpec extends Specification { + InFlightMetadataCollector metadataCollector = Stub() { + isInSecondPass() >> true + } + def "creates unique key when property is unique within group"() { given: def columnNameFetcher = Mock(ColumnNameForPropertyAndPathFetcher) def uniqueKeyCreator = Mock(UniqueKeyForColumnsCreator) - def subject = new CreateKeyForProps(columnNameFetcher, uniqueKeyCreator) + def subject = new CreateKeyForProps(columnNameFetcher, uniqueKeyCreator, metadataCollector) def owner = Mock(GrailsHibernatePersistentEntity) def grailsProp = Mock(HibernatePersistentProperty) { getHibernateOwner() >> owner } - def mappedForm = Mock(org.grails.orm.hibernate.cfg.PropertyConfig) { + def mappedForm = Mock(PropertyConfig) { isUnique() >> true isUniqueWithinGroup() >> true getUniquenessGroup() >> ["p1", "p2"] @@ -80,16 +87,125 @@ class CreateKeyForPropsSpec extends Specification { 1 * uniqueKeyCreator.createUniqueKeyForColumns(table, { List cols -> cols*.name == ["base_col", "col1", "col2"] }) } + def "expands every configured column of a unique group member in config order"() { + given: + def columnNameFetcher = Mock(ColumnNameForPropertyAndPathFetcher) + def uniqueKeyCreator = Mock(UniqueKeyForColumnsCreator) + def subject = new CreateKeyForProps(columnNameFetcher, uniqueKeyCreator, metadataCollector) + def owner = Mock(GrailsHibernatePersistentEntity) + def mappedForm = new PropertyConfig(unique: ['parent']) + def grailsProp = Mock(HibernatePersistentProperty) { + getMappedForm() >> mappedForm + getHibernateOwner() >> owner + } + def firstColumn = new ColumnConfig(name: 'parent_code') + def secondColumn = new ColumnConfig(name: 'parent_revision') + def parent = Mock(HibernatePersistentProperty) { + getHibernateMappedForm() >> new PropertyConfig(columns: [firstColumn, secondColumn]) + } + owner.getHibernatePropertyByName('parent') >> parent + def table = new Table('child') + + when: + subject.createKeyForProps(grailsProp, 'child_path', table, 'child_state') + + then: + 1 * columnNameFetcher.getColumnNameForPropertyAndPath(parent, 'child_path', firstColumn) >> 'parent_code' + 1 * columnNameFetcher.getColumnNameForPropertyAndPath(parent, 'child_path', secondColumn) >> 'parent_revision' + 0 * columnNameFetcher._ + 1 * uniqueKeyCreator.createUniqueKeyForColumns(table, { List columns -> + columns*.name == ['child_state', 'parent_code', 'parent_revision'] + }) + } + + def "keeps group order when configured columns are followed by an implicit column"() { + given: + def columnNameFetcher = Mock(ColumnNameForPropertyAndPathFetcher) + def uniqueKeyCreator = Mock(UniqueKeyForColumnsCreator) + def subject = new CreateKeyForProps(columnNameFetcher, uniqueKeyCreator, metadataCollector) + def owner = Mock(GrailsHibernatePersistentEntity) + def mappedForm = new PropertyConfig(unique: ['parent', 'kind']) + def grailsProp = Mock(HibernatePersistentProperty) { + getMappedForm() >> mappedForm + getHibernateOwner() >> owner + } + def firstColumn = new ColumnConfig(name: 'parent_code') + def secondColumn = new ColumnConfig(name: 'parent_revision') + def parent = Mock(HibernatePersistentProperty) { + getHibernateMappedForm() >> new PropertyConfig(columns: [firstColumn, secondColumn]) + } + def kind = Mock(HibernatePersistentProperty) { + getHibernateMappedForm() >> new PropertyConfig() + } + owner.getHibernatePropertyByName('parent') >> parent + owner.getHibernatePropertyByName('kind') >> kind + def table = new Table('child') + + when: + subject.createKeyForProps(grailsProp, null, table, 'child_state') + + then: + 1 * columnNameFetcher.getColumnNameForPropertyAndPath(parent, null, firstColumn) >> 'parent_code' + 1 * columnNameFetcher.getColumnNameForPropertyAndPath(parent, null, secondColumn) >> 'parent_revision' + 1 * columnNameFetcher.getColumnNameForPropertyAndPath(kind, null, null) >> 'kind' + 0 * columnNameFetcher._ + 1 * uniqueKeyCreator.createUniqueKeyForColumns(table, { List columns -> + columns*.name == ['child_state', 'parent_code', 'parent_revision', 'kind'] + }) + } + + def "resolves group columns in the second pass after association columns have been populated"() { + given: + def collector = Mock(InFlightMetadataCollector) + def columnNameFetcher = Mock(ColumnNameForPropertyAndPathFetcher) + def uniqueKeyCreator = Mock(UniqueKeyForColumnsCreator) + def subject = new CreateKeyForProps(columnNameFetcher, uniqueKeyCreator, collector) + def owner = Mock(GrailsHibernatePersistentEntity) + def mappedForm = new PropertyConfig(unique: ['parent']) + def grailsProp = Mock(HibernatePersistentProperty) { + getMappedForm() >> mappedForm + getHibernateOwner() >> owner + } + def parentConfig = new PropertyConfig() + def firstColumn = new ColumnConfig(name: 'parent_code') + def secondColumn = new ColumnConfig(name: 'parent_revision') + def parent = Mock(HibernatePersistentProperty) { + getHibernateMappedForm() >> parentConfig + } + owner.getHibernatePropertyByName('parent') >> parent + def table = new Table('child') + SecondPass secondPass + + when: + subject.createKeyForProps(grailsProp, null, table, 'child_state') + + then: + 1 * collector.addSecondPass(_) >> { SecondPass pass -> secondPass = pass } + 0 * columnNameFetcher._ + 0 * uniqueKeyCreator._ + + when: + parentConfig.columns.addAll([firstColumn, secondColumn]) + secondPass.doSecondPass([:]) + + then: + 1 * columnNameFetcher.getColumnNameForPropertyAndPath(parent, null, { it.name == 'parent_code' }) >> 'parent_code' + 1 * columnNameFetcher.getColumnNameForPropertyAndPath(parent, null, { it.name == 'parent_revision' }) >> 'parent_revision' + 1 * uniqueKeyCreator.createUniqueKeyForColumns(table, { List columns -> + columns*.name == ['child_state', 'parent_code', 'parent_revision'] + }) + } + def "does nothing when property is not unique within group"() { given: def columnNameFetcher = Mock(ColumnNameForPropertyAndPathFetcher) def uniqueKeyCreator = Mock(UniqueKeyForColumnsCreator) - def subject = new CreateKeyForProps(columnNameFetcher, uniqueKeyCreator) + def subject = new CreateKeyForProps(columnNameFetcher, uniqueKeyCreator, metadataCollector) def owner = Mock(GrailsHibernatePersistentEntity) def grailsProp = Mock(HibernatePersistentProperty) { getHibernateOwner() >> owner } - def mappedForm = Mock(org.grails.orm.hibernate.cfg.PropertyConfig) { + def mappedForm = Mock(PropertyConfig) { isUnique() >> false isUniqueWithinGroup() >> true getUniquenessGroup() >> ["p1"] @@ -111,13 +227,13 @@ class CreateKeyForPropsSpec extends Specification { given: def columnNameFetcher = Mock(ColumnNameForPropertyAndPathFetcher) def uniqueKeyCreator = Mock(UniqueKeyForColumnsCreator) - def subject = new CreateKeyForProps(columnNameFetcher, uniqueKeyCreator) + def subject = new CreateKeyForProps(columnNameFetcher, uniqueKeyCreator, metadataCollector) def owner = Mock(GrailsHibernatePersistentEntity) def grailsProp = Mock(HibernatePersistentProperty) { getHibernateOwner() >> owner } owner.getJavaClass() >> CreateKeyForPropsSpec - def mappedForm = Mock(org.grails.orm.hibernate.cfg.PropertyConfig) { + def mappedForm = Mock(PropertyConfig) { isUnique() >> true isUniqueWithinGroup() >> true getUniquenessGroup() >> ["missingProp"] @@ -146,7 +262,7 @@ class CreateKeyForPropsSpec extends Specification { given: def columnNameFetcher = Mock(ColumnNameForPropertyAndPathFetcher) def uniqueKeyCreator = Mock(UniqueKeyForColumnsCreator) - def subject = new CreateKeyForProps(columnNameFetcher, uniqueKeyCreator) + def subject = new CreateKeyForProps(columnNameFetcher, uniqueKeyCreator, metadataCollector) def collectionProp = Mock(HibernateToManyProperty) { isSerializableType() >> false isUserButNotCollectionType() >> false @@ -165,12 +281,12 @@ class CreateKeyForPropsSpec extends Specification { given: def columnNameFetcher = Mock(ColumnNameForPropertyAndPathFetcher) def uniqueKeyCreator = Mock(UniqueKeyForColumnsCreator) - def subject = new CreateKeyForProps(columnNameFetcher, uniqueKeyCreator) + def subject = new CreateKeyForProps(columnNameFetcher, uniqueKeyCreator, metadataCollector) def owner = Mock(GrailsHibernatePersistentEntity) def otherProp = Mock(HibernatePersistentProperty) { getHibernateMappedForm() >> new PropertyConfig() } - def mappedForm = Mock(org.grails.orm.hibernate.cfg.PropertyConfig) { + def mappedForm = Mock(PropertyConfig) { isUnique() >> true isUniqueWithinGroup() >> true getUniquenessGroup() >> ["x"] @@ -195,12 +311,12 @@ class CreateKeyForPropsSpec extends Specification { given: def columnNameFetcher = Mock(ColumnNameForPropertyAndPathFetcher) def uniqueKeyCreator = Mock(UniqueKeyForColumnsCreator) - def subject = new CreateKeyForProps(columnNameFetcher, uniqueKeyCreator) + def subject = new CreateKeyForProps(columnNameFetcher, uniqueKeyCreator, metadataCollector) def owner = Mock(GrailsHibernatePersistentEntity) def otherProp = Mock(HibernatePersistentProperty) { getHibernateMappedForm() >> new PropertyConfig() } - def mappedForm = Mock(org.grails.orm.hibernate.cfg.PropertyConfig) { + def mappedForm = Mock(PropertyConfig) { isUnique() >> true isUniqueWithinGroup() >> true getUniquenessGroup() >> ["x"] From 2e8c775ac3e84207d588c98d752e52b32c2f50e6 Mon Sep 17 00:00:00 2001 From: James Fredley Date: Fri, 13 Nov 2026 10:09:25 -0500 Subject: [PATCH 3/7] docs: include Grails-owned Spring Security in the threat model The in-tree grails-spring-security modules are first-party on 8.0.x. Keep upstream Spring Security and Shiro external, and treat defects in the Grails integration as in scope. Assisted-by: opencode:grok-4.7 --- THREAT_MODEL.md | 32 +++++++++++++++++--------------- threat-model.yaml | 27 ++++++++++++++++++++------- 2 files changed, 37 insertions(+), 22 deletions(-) diff --git a/THREAT_MODEL.md b/THREAT_MODEL.md index f6d0969e9ce7..1134ce97ba7e 100644 --- a/THREAT_MODEL.md +++ b/THREAT_MODEL.md @@ -23,7 +23,7 @@ limitations under the License. - **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. -- **Reporting cross-reference**: findings that may violate a property claimed in §8 should be reported privately per [`SECURITY.md`](./SECURITY.md) (which routes to the [ASF Security Team](https://www.apache.org/security/)). Findings that fall under §3 (out of scope), §9 (disclaimed properties), or §11a (known non-findings) will be closed publicly citing the relevant section of this document. +- **Reporting cross-reference**: findings that may violate a property claimed in §8, or concern security defects in the Grails-owned Spring Security integration (§2-§3), should be reported privately per [`SECURITY.md`](./SECURITY.md) (which routes to the [ASF Security Team](https://www.apache.org/security/)). Findings that fall under §3 (out of scope), §9 (disclaimed properties), or §11a (known non-findings) will be closed publicly citing the relevant section of this document. - **Provenance legend**: every non-trivial claim is tagged. - *(documented)* - stated in the project's own docs ([`grails-doc/src/en/guide/security/`](./grails-doc/src/en/guide/security/), [`SECURITY.md`](./SECURITY.md), [`README.md`](./README.md), [`AGENTS.md`](./AGENTS.md), or the public Grails Guide). - *(maintainer)* - stated by a maintainer in response to a question from this drafting process. @@ -56,6 +56,7 @@ The framework is large; not every module has the same threat profile. The model |---|---|---|---| | HTTP request ingress | [`GrailsDispatcherServlet`](./grails-web-mvc/src/main/groovy/org/grails/web/servlet/mvc/GrailsDispatcherServlet.groovy), [`UrlMappingsHandlerMapping`](./grails-web-url-mappings/src/main/groovy/org/grails/web/mapping/mvc/UrlMappingsHandlerMapping.groovy) | Yes - network (via Spring Boot embedded container) | **In** | | Interceptors / controllers | [`GrailsInterceptorHandlerInterceptorAdapter`](./grails-interceptors/src/main/groovy/org/grails/plugins/web/interceptors/GrailsInterceptorHandlerInterceptorAdapter.groovy), `grails.artefact.Controller` trait | Yes - via Spring MVC | **In** | +| Grails Spring Security integration | [`grails-spring-security/`](./grails-spring-security/): `grails-spring-security` (core), `grails-spring-security-rest`, `grails-spring-security-oauth2`, and the other in-tree `grails-spring-security-*` plugins | Yes - HTTP authentication and authorization flows | **In** - Grails-owned integration; upstream `org.springframework.security` remains external (§3). *(documented: [settings.gradle](./settings.gradle))* | | Data binding | [`GrailsWebDataBinder`](./grails-web-databinding/src/main/groovy/grails/web/databinding/GrailsWebDataBinder.groovy), `SimpleDataBinder`, [`DefaultDataBindingSourceRegistry`](./grails-web-databinding/src/main/groovy/org/grails/web/databinding/bindingsource/DefaultDataBindingSourceRegistry.groovy) | Indirectly (consumes request body) | **In** | | View rendering (GSP, JSON, Markup) | [`GroovyPageCompiler`](./grails-gsp/core/src/main/groovy/org/grails/gsp/compiler/GroovyPageCompiler.groovy), [`ResolvableGroovyTemplateEngine`](./grails-views-core/src/main/groovy/grails/views/ResolvableGroovyTemplateEngine.groovy), [`SmartViewResolver`](./grails-views-core/src/main/groovy/grails/views/mvc/SmartViewResolver.groovy) | Filesystem (template files) | **In** | | Codecs / output encoding | [`grails-encoder`](./grails-encoder/), [`HTMLCodec`](./grails-encoder/src/main/groovy/org/grails/encoder/CodecFactory.java) and siblings | No | **In** | @@ -75,7 +76,8 @@ The framework is large; not every module has the same threat profile. The model The framework **does not** attempt to defend against, and **does not** model, the following. Triagers may close findings citing this section. -- **Application-level authentication and authorization.** The framework ships no built-in user store, login flow, or session-based auth. The user is expected to integrate with the Spring Security plugin, Apache Shiro, or an equivalent. The `grails-shell-cli` `SpringSecurityCompilerAutoConfiguration` is a compile-time hook for the plugin, not an auth implementation. *(documented: [grails-doc/src/en/guide/security/authentication.adoc](./grails-doc/src/en/guide/security/authentication.adoc), [grails-doc/src/en/guide/security/securityPlugins.adoc](./grails-doc/src/en/guide/security/securityPlugins.adoc))* +- **Application-owned user store and role policy.** The application defines its user store and role policy and enables the authentication modules it needs. An application that does not enable the Grails Spring Security modules has no authentication from the framework. This does not exclude defects in the Grails-owned modules under `grails-spring-security/`: `grails-spring-security` (core), `grails-spring-security-rest`, `grails-spring-security-oauth2`, and the other in-tree `grails-spring-security-*` plugins are in scope. Defects in how those modules bind sessions, install filter rules, handle OAuth state, or link accounts are framework findings, reportable privately per [SECURITY.md](./SECURITY.md). *(documented: [settings.gradle](./settings.gradle), [authentication.adoc](./grails-doc/src/en/guide/security/authentication.adoc), [securityPlugins.adoc](./grails-doc/src/en/guide/security/securityPlugins.adoc))* +- **Upstream Spring Security (`org.springframework.security`), Apache Shiro, and other non-Grails authentication libraries.** These remain external dependencies. Defects in Spring Security itself, including its own filters, are out of scope; defects in Grails-owned integration with it are in scope as described above. *(inferred)* (§14 wave 1, question 2) - **Transport security (TLS).** Provided by the Spring Boot embedded container (Tomcat / Jetty / Undertow / Netty) or by a reverse proxy in front of the application. Out of layer. *(inferred)* - **Database engine, JDBC driver, and JVM vulnerabilities.** The framework is a consumer; bugs in these layers are upstream. *(inferred)* - **Spring Framework, Spring Boot, Hibernate, GORM datastore implementations.** Triaged in their own projects; the framework re-exposes their public APIs but does not own their threat models. *(inferred)* @@ -312,8 +314,8 @@ The model takes the position that: These properties are **disclaimed by design**. A report that depends on one of them is a `BY-DESIGN: property-disclaimed` triage outcome (see §13). -- **Authentication, authorization, session management, password storage.** The framework ships no built-in user store. Delegated to Spring Security plugin or equivalent. *(documented: [authentication.adoc](./grails-doc/src/en/guide/security/authentication.adoc), [securityPlugins.adoc](./grails-doc/src/en/guide/security/securityPlugins.adoc))* -- **CSRF protection on requests not protected by `useToken`.** `useToken` is opt-in per form. Actions that mutate state without a synchronizer token are not CSRF-protected by the framework. *(documented: [securingAgainstAttacks.adoc](./grails-doc/src/en/guide/security/securingAgainstAttacks.adoc))* +- **Automatic authentication without enabled auth modules; an application-defined user store and role policy.** The application must enable and configure the Grails Spring Security modules to obtain their authentication and authorization support. Security defects in their session binding, filter-rule installation, OAuth state handling, or account linking remain framework findings (§2-§3), reportable per [SECURITY.md](./SECURITY.md). Upstream `org.springframework.security` defects remain external and out of scope. *(documented: [settings.gradle](./settings.gradle), [authentication.adoc](./grails-doc/src/en/guide/security/authentication.adoc), [securityPlugins.adoc](./grails-doc/src/en/guide/security/securityPlugins.adoc))* +- **CSRF protection on requests not protected by `useToken` or an enabled auth module's CSRF protection.** `useToken` is opt-in per form. The application must enable protection on state-mutating requests; omitting it is application misuse, not an exclusion for defects in Grails-owned auth modules. *(documented: [securingAgainstAttacks.adoc](./grails-doc/src/en/guide/security/securingAgainstAttacks.adoc))* - **XSS protection for templates rendered with the codec disabled (`grails.views.default.codec=none`) or values explicitly passed through `raw()`.** Opt-out is the developer's stated intent. *(documented: [xssPrevention.adoc](./grails-doc/src/en/guide/security/xssPrevention.adoc), [codecs.adoc](./grails-doc/src/en/guide/security/codecs.adoc))* - **SQL/HQL injection protection for queries built by string concatenation.** Only parameterized GORM forms are safe; `Book.find("from Book where title = '${params.title}'")` is documented as unsafe. *(documented: [securingAgainstAttacks.adoc](./grails-doc/src/en/guide/security/securingAgainstAttacks.adoc))* - **Authorization for individual domain-object access ("guessable IDs").** The framework does not check that the requesting user is permitted to view the object identified by `params.id`. The developer must enforce this. *(documented: [securingAgainstAttacks.adoc](./grails-doc/src/en/guide/security/securingAgainstAttacks.adoc) "Guessable IDs")* @@ -328,7 +330,7 @@ These properties are **disclaimed by design**. A report that depends on one of t Features that **look like** a security property but are not one. Reports that confuse a false friend for the real thing are `KNOWN-NON-FINDING` (§11a) when documented and `BY-DESIGN: property-disclaimed` (§13) when not. -- **`@Secured` annotations are not a built-in framework guarantee.** `@Secured` is integration-shaped sugar for the Spring Security plugin. Without that plugin installed and correctly configured, the annotation is inert. *(inferred)* +- **`@Secured` annotations alone do not enable authorization.** The annotation is inert unless the Grails Spring Security module is installed and configured. Defects in that module's enforcement remain in scope (§2-§3). *(inferred)* (§14 wave 1, question 2) - **`bindable=false` is neither an access-control control nor a validation constraint.** It prevents a field from being set from a request-binding source (`bindData`, command-object binding, domain-class constructor binding, `properties=` assignment). It does not prevent the field from being set programmatically, by GORM, or by a service layer; it does not prevent the field from being **read** and serialized into a response; and it does not validate the value once set. *(inferred)* - **`useToken` is a synchronizer-token CSRF defense, not a transaction-integrity guarantee.** It blocks naive cross-site form submissions and accidental double-submits. It is not a replay-protection mechanism for an authenticated user against a future-token attacker. *(inferred)* - **Domain-class `constraints { }` are input-validation rules, not security boundaries.** `nullable: false` and `matches: /…/` are correctness checks. A constraint failure is a validation error, not an attack signal. *(inferred)* @@ -349,7 +351,7 @@ One sentence per class. - **Zip-bomb / archive expansion** in multipart and `grails-forge` ZIP generation. Bounded only by container size limits. *(inferred)* - **Path traversal** through `MultipartFile.originalFilename` if used as a filesystem path. *(inferred)* - **JSON / XML DoS** (deeply nested or large primitives) - the parser's responsibility, not the framework's. *(inferred)* -- **Session fixation, replay, sidejacking.** Session security is the auth plugin's responsibility. *(inferred)* +- **Session fixation, replay, sidejacking without enabled session protection.** The application must enable and configure session protection. Defects in Grails-owned session integration remain in scope; defects in upstream Spring Security itself remain external (§3). *(inferred)* (§14 wave 1, question 2) - **Cache-key / cache-poisoning attacks** in Spring Boot caching layers. *(inferred)* --- @@ -358,7 +360,7 @@ One sentence per class. For the assumptions in §5-§7 to hold, the **application developer / operator** must: -1. Use a real authentication and authorization layer (Spring Security plugin or equivalent). The framework provides no replacement. *(documented: [authentication.adoc](./grails-doc/src/en/guide/security/authentication.adoc))* +1. Enable and configure the Grails Spring Security modules or another authentication and authorization layer; define the application's user store and role policy. Grails-owned integration defects remain framework findings (§2-§3). *(documented: [authentication.adoc](./grails-doc/src/en/guide/security/authentication.adoc), [settings.gradle](./settings.gradle))* 2. Place TLS termination in front of the application (operator) or configure the embedded container's HTTPS connector. *(inferred)* 3. Never concatenate request parameters into HQL/SQL strings, Groovy `Eval`/`GroovyShell` calls, redirect targets, or shell commands. Use parameterized GORM queries, `withForm { }`, allow-lists. *(documented: [securingAgainstAttacks.adoc](./grails-doc/src/en/guide/security/securingAgainstAttacks.adoc))* 4. Bind request data through command objects or explicit allow-lists - not by passing `params` directly into a domain-class constructor or property setter. *(inferred)* @@ -408,10 +410,10 @@ The mirror of §11: patterns that scanners, fuzzers, AI analyzers, or human revi - **"`SpelExpressionParser` in `GroovyEclipseCompilationHelper`"** - SAST flags SpEL injection. The only SpEL usage in the framework is inside the Eclipse IDE compiler helper; the expression is partially-developer-controlled (Eclipse project settings) and never reachable from an HTTP request. → `OUT-OF-MODEL: unsupported-component` (compile-time, not runtime). - **"`BeforeValidateHelper` implements `Serializable` with a custom `readObject` method"** ([`BeforeValidateHelper.java`](./grails-datamapping-validation/src/main/groovy/org/grails/datastore/gorm/support/BeforeValidateHelper.java)) - SAST flags a Java-deserialization gadget candidate. Discharged by §6 (the framework never deserializes an `ObjectInputStream` from an attacker-reachable channel). **In-model only if** the application stores `BeforeValidateHelper` instances in an attacker-reachable serialized container (HTTP session, distributed cache, untrusted message bus); that is the application's responsibility. Spot-check confirms no other custom `readObject` lives in the runtime tree, and no production code path calls `ObjectInputStream.readObject(...)` directly. → `OUT-OF-MODEL: trusted-input` for the framework itself; the application's session-store choice may pull it back in. (§14 wave 3 to confirm.) - **"`SynchronizerTokensHolder` is `Serializable`"** - SAST flags the CSRF token-holder as session-store gadget. Discharged by §6 (the session store is operator-trusted infrastructure; framework does not hand out raw `ObjectInputStream` access). If the application uses a serializing session backend (e.g. Redis with JDK serialization) the integrity of `SynchronizerTokensHolder` reduces to the integrity of that store, which is the operator's responsibility. → `OUT-OF-MODEL: trusted-input`. -- **"`@Secured` annotation present but no authz logic in the annotated method body"** - false positive when the Spring Security plugin is installed (it wires the check externally to the method). Discharged by §9 (auth is delegated to Spring Security). → `KNOWN-NON-FINDING`. +- **"`@Secured` annotation present but no authz logic in the annotated method body"** - absence of an inline check alone is a false positive when the Grails Spring Security module is installed and configured: it wires the check externally to the method. Verify that enforcement occurs before suppressing. This does not discharge defects in that enforcement (§2-§3). → `KNOWN-NON-FINDING` for the missing inline check alone. - **"Framework-level logging reflects user input"** (e.g. `log.info "request: ${request}"`) - SAST flags log-injection / Log4Shell-adjacent patterns. Discharged by §6: the framework's own logging never serializes request data into a log line without explicit developer code. Application code that does so is an application-layer bug. → `OUT-OF-MODEL: unsupported-component`. - **"`new File(...)` with multipart-derived names"** - SAST flags path traversal. No production path-traversal sink was found in framework runtime code; the risk lives in user controller code calling `multipartFile.transferTo(new File(params.filename))`. Framework-internal `new File(...)` usages either use server-derived paths or are test infrastructure. Discharged by §6 (no in-framework sink reaches a request-influenced filename). → `OUT-OF-MODEL: unsupported-component` for framework code; the application's own controller code is the surface. -- **"Production `@RestController` / `@Controller` beans shipped in framework JARs"** - SAST flags the framework as exposing HTTP endpoints of its own. The framework ships **no** `@RestController` or `@Controller` beans in production JARs; every HTTP entry point is user-defined and either extends `RestfulController` or mixes in the `Controller` trait. Discharged by §2 (HTTP request ingress component family) and §6 (controllers are developer-authored). → `KNOWN-NON-FINDING`. +- **"Production `@RestController` / `@Controller` beans shipped in framework JARs"** - the presence of an HTTP handler alone is not a vulnerability. This does not discharge defects in endpoints or filters supplied by the Grails Spring Security modules (§2-§3). → `KNOWN-NON-FINDING` for the presence of a handler alone. --- @@ -421,7 +423,7 @@ Revise this document on: - A new HTTP entry-point family (e.g., introducing first-party WebSocket or gRPC handling into the framework core). - A change in default for any §5a knob - particularly any reduction in the default codec set. -- Introduction of a built-in authentication, session, or CSRF subsystem (this would move items from §9 into §8). +- A change in which authentication, session, or CSRF modules are enabled by default, or in the Grails-owned integration boundary (§2-§3); revise §9 disclaimers and any affected §8 properties. - A change in how `application.groovy` is loaded (e.g., switching `ConfigSlurper` for a non-evaluating parser would invalidate §11's "config-as-code" item and the `BY-DESIGN` disposition for §9 Groovy-config disclaimers). - Promotion of `grails-console` or any GroovyShell-backed endpoint into a default-enabled production surface (would move §3's "interactive consoles are out of scope" claim). - A new minimum JDK or Groovy baseline (might unlock new constant-time / safer APIs that change §9 disclaimers). @@ -435,13 +437,13 @@ Every report against the framework receives **exactly one** of the following dis | Disposition | Meaning | Licensed by | |---|---|---| -| `VALID` | Violates a property the framework claims, via an in-scope adversary and input. | §8, §6, §7 | +| `VALID` | Violates a property the framework claims, or demonstrates a security defect in Grails-owned Spring Security integration, via an in-scope adversary and input. | §2-§3, §8, §6, §7 | | `VALID-HARDENING` | No §8 property is violated, but the API makes a §11 misuse easy enough that the project elects to harden it. Reported privately per [SECURITY.md](./SECURITY.md); fixed at maintainer discretion; typically no CVE. | §11 | | `OUT-OF-MODEL: trusted-input` | Requires attacker control of a parameter the model marks trusted (classpath, `application.groovy`, `grails.config.locations`, domain `mapping {}` closures, AST transform inputs). | §6 | | `OUT-OF-MODEL: adversary-not-in-scope` | Requires an attacker capability the model excludes (local shell, JVM co-tenant, side channel, compromised plugin). | §7 | | `OUT-OF-MODEL: unsupported-component` | Lands in `grails-test-examples/`, scaffold output, `grails-console`, `grails-forge` HTTP service, or third-party plugins. | §3 | | `OUT-OF-MODEL: non-default-build` | Only manifests under a discouraged or non-default §5a configuration (e.g., codec disabled, dev environment deployed to production, raised collection-growth limit). | §5a | -| `BY-DESIGN: property-disclaimed` | Concerns a property the framework explicitly does not provide (auth, CSRF without `useToken`, rate limiting, constant-time crypto, sandboxing of Groovy on classpath). | §9 | +| `BY-DESIGN: property-disclaimed` | Concerns a property the framework explicitly does not provide (automatic auth without enabled modules, application-defined user store or role policy, CSRF without enabled protection, rate limiting, constant-time crypto, sandboxing of Groovy on classpath). Does not exclude Grails-owned auth integration defects. | §9 | | `KNOWN-NON-FINDING` | Matches a documented recurring false positive. | §11a | | `MODEL-GAP` | Cannot be cleanly routed to any of the above. | triggers §12 | @@ -454,7 +456,7 @@ The model is **draft-first**. The questions below are grouped in waves of 3-7 pe ### Wave 1 - scope and intended use (most-load-bearing answers; §2-§3 depend on these) 1. **Caller-role split.** *Proposed*: the three roles in §2 (untrusted end user, trusted developer/operator, trusted-by-association plugin author) are the correct primitives. Correct or extend? *Lands in §2.* -2. **Spring Security as the only intended auth path.** *Proposed*: the framework explicitly defers all authentication, authorization, and session management to Spring Security plugin (or equivalent third-party). There is no in-framework auth roadmap. Confirm or correct. *Lands in §3 and §9.* +2. **Grails Spring Security ownership boundary.** *Proposed*: the in-tree `grails-spring-security` (core), `grails-spring-security-rest`, `grails-spring-security-oauth2`, and other `grails-spring-security-*` plugins are in scope, including session binding, filter-rule installation, OAuth state handling, account linking, and `@Secured` enforcement. Upstream `org.springframework.security`, Shiro, and other non-Grails auth libraries remain external. Applications supply their user store and role policy and must enable and configure auth modules. Confirm or correct. *Lands in §2, §3, §9, and §13.* 3. **`grails-forge` HTTP service is out of model.** *Proposed*: start.grails.org is operated separately and its own operators carry its threat model. Confirm. *Lands in §3.* 4. **`grails-console` (`GrailsShell` / `GroovyConsole`) is a developer-only tool, never enabled by default in production.** *Proposed*: these modules are not autoconfigured into a production `bootJar`. Confirm. *Lands in §3 and §11a.* 5. **`grails.views.default.codec=html` is the supported production posture.** *Proposed*: a deployment with codec disabled is `OUT-OF-MODEL: non-default-build`, not a `VALID` XSS finding. Confirm. *Lands in §5a and §13.* @@ -508,8 +510,8 @@ This back-map proves §3.1a coverage. Every threat-model-shaped claim already in | [`grails-doc/.../securingAgainstAttacks.adoc`](./grails-doc/src/en/guide/security/securingAgainstAttacks.adoc) "Guessable IDs" | Authorize each domain-object access; "every unprotected URL is publicly accessible." | §7 adversary statement, §9 disclaimer, §10 #5 | | [`grails-doc/.../xssPrevention.adoc`](./grails-doc/src/en/guide/security/xssPrevention.adoc) | Default codecs; `${raw()}` is opt-out. | §8 P2, §5a codec knob, §9 false friend, §11 misuse | | [`grails-doc/.../codecs.adoc`](./grails-doc/src/en/guide/security/codecs.adoc) | `HTMLCodec`, `URLCodec`, `JavaScriptCodec`, etc. | §8 P4, §5a codec defaults | -| [`grails-doc/.../authentication.adoc`](./grails-doc/src/en/guide/security/authentication.adoc) | Interceptor-based auth example; defers to Spring Security/Shiro. | §3 (auth out of scope), §9 disclaimer, §10 #1 | -| [`grails-doc/.../securityPlugins.adoc`](./grails-doc/src/en/guide/security/securityPlugins.adoc) | Use the Spring Security Core plugin for authorization/roles. | §3, §9, §10 #1 | +| [`grails-doc/.../authentication.adoc`](./grails-doc/src/en/guide/security/authentication.adoc) | No default auth mechanism; interceptor example; recommends enabling Spring Security. | §2-§3 (Grails-owned integration in scope; upstream external), §9 (no automatic auth), §10 #1 | +| [`grails-doc/.../securityPlugins.adoc`](./grails-doc/src/en/guide/security/securityPlugins.adoc) | Use the Grails Spring Security Core plugin for authorization/roles. | §2-§3 (in-tree modules in scope), §9 (application user store and role policy), §10 #1 | | [`SECURITY.md`](./SECURITY.md) | Disclosure routes through the ASF Security Team. | §1 reporting cross-reference | | [`AGENTS.md`](./AGENTS.md) | JDK 21, Groovy 4.0.x, Spring Boot 4.0.x, Jakarta EE 10, Spock 2.3. | §5 runtime assumptions | | [`README.md`](./README.md) | The framework is embedded in a user web application; not a service. | §1 description, §2 deployment context | diff --git a/threat-model.yaml b/threat-model.yaml index 841adfbe9ac2..9f85719c552f 100644 --- a/threat-model.yaml +++ b/threat-model.yaml @@ -39,6 +39,18 @@ components: representative_files: - grails-interceptors/src/main/groovy/org/grails/plugins/web/interceptors/GrailsInterceptorHandlerInterceptorAdapter.groovy - grails-controllers/src/main/groovy/grails/artefact/Controller.groovy + - name: grails_spring_security_integration + in_model: true + notes: "Grails-owned grails-spring-security (core), rest, oauth2, and all other in-tree grails-spring-security-* plugins are in scope. Defects in session binding, filter-rule installation, OAuth state handling, or account linking are framework findings, reportable privately per SECURITY.md. Applications supply their user store and role policy and must enable and configure the modules." + provenance: documented + source: settings.gradle + representative_files: + - grails-spring-security/ + - name: upstream_auth_libraries + in_model: false + out_of_model_reason: "Upstream org.springframework.security (including its own filters), Apache Shiro, and other non-Grails auth libraries remain external; defects in Grails-owned integration remain in scope (§3)." + provenance: inferred + open_question: "§14 wave 1, question 2" - name: data_binding in_model: true representative_files: @@ -316,11 +328,12 @@ properties_provided: # §9 - properties the framework does NOT provide. properties_disclaimed: - id: auth - description: "Authentication, authorization, session management, password storage." - delegate_to: spring_security_plugin_or_equivalent + description: "Automatic authentication without enabled auth modules; an application-defined user store and role policy." + notes: "Grails-owned Spring Security integration defects remain in scope, including session binding, filter-rule installation, OAuth state handling, and account linking; report privately per SECURITY.md. Upstream org.springframework.security defects remain external and out of scope (§2-§3, §9)." provenance: documented - id: csrf_without_useToken - description: "CSRF protection on requests not protected by useToken." + description: "CSRF protection on requests not protected by useToken or an enabled auth module's CSRF protection." + notes: "Omitting protection is application misuse; defects in Grails-owned auth modules remain in scope." provenance: documented - id: xss_with_codec_disabled description: "XSS protection when codec is disabled or raw() is used." @@ -354,7 +367,7 @@ properties_disclaimed: false_friends: - id: secured_annotation looks_like: "Authorization decoration on a method." - actually_is: "Integration hint for the Spring Security plugin. Inert without the plugin." + actually_is: "Inert unless the Grails Spring Security module is installed and configured. Defects in that module's enforcement remain in scope (§2-§3)." - id: bindable_false looks_like: "Field-level access control." actually_is: "Data-binding allow-list only; does not prevent code from setting the field or response from including it." @@ -420,7 +433,7 @@ known_non_findings: discharged_by: "§6 trust assumption on session-store infrastructure" disposition: "OUT-OF-MODEL: trusted-input" - pattern: "@Secured present but no in-method authz logic" - discharged_by: "§9 (auth delegated to Spring Security plugin)" + discharged_by: "Absence of an inline check alone is not a defect when the Grails Spring Security module is installed and configured; verify external enforcement before suppressing. Does not discharge enforcement defects (§2-§3, §9)." disposition: "KNOWN-NON-FINDING" - pattern: "Framework-level logging reflects user input" discharged_by: "§6 (framework's own logging never serializes request data without explicit developer code)" @@ -429,13 +442,13 @@ known_non_findings: discharged_by: "§6 (no in-framework sink reaches a request-influenced filename; the risk lives in user controller code)" disposition: "OUT-OF-MODEL: unsupported-component" - pattern: "Production @RestController / @Controller beans shipped in framework JARs" - discharged_by: "§2 (framework ships no Spring HTTP-handler beans; every endpoint is user-defined)" + discharged_by: "Presence of a handler alone is not a vulnerability; does not discharge defects in Grails Spring Security endpoints or filters (§2-§3)." disposition: "KNOWN-NON-FINDING" # §13 - closed set of triage dispositions. dispositions: - label: VALID - licensed_by: ["§8", "§6", "§7"] + licensed_by: ["§2-§3", "§8", "§6", "§7"] - label: VALID-HARDENING licensed_by: ["§11"] - label: "OUT-OF-MODEL: trusted-input" From a2707c6aa1c80ce06dd79ec58ec63c10995106c2 Mon Sep 17 00:00:00 2001 From: Gustavo Harff Date: Thu, 3 Dec 2026 12:19:06 -0300 Subject: [PATCH 4/7] test(hibernate7): cover the joins of nested association blocks in criteria queries (#16559) Tests for the joins of association blocks in Hibernate 7 criteria queries: nested left joins, a nested block without a join type, blocks of the same name at two levels, an outer left join of the same name, detached criteria, subqueries, and an order on a projection alias with the name of an association block. --- .../PredicateGeneratorSpec.groovy | 170 +++++++ ...teCriteriaBuilderNestedJoinTypeSpec.groovy | 416 ++++++++++++++++++ .../query/ExpressionResolverSpec.groovy | 21 + 3 files changed, 607 insertions(+) create mode 100644 grails-data-hibernate7/core/src/test/groovy/grails/orm/HibernateCriteriaBuilderNestedJoinTypeSpec.groovy diff --git a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/hibernatequery/PredicateGeneratorSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/hibernatequery/PredicateGeneratorSpec.groovy index f09b8d817a01..2a6da3f9ecea 100644 --- a/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/hibernatequery/PredicateGeneratorSpec.groovy +++ b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/hibernatequery/PredicateGeneratorSpec.groovy @@ -24,12 +24,20 @@ import grails.gorm.DetachedCriteria import grails.gorm.tests.HibernateGormDatastoreSpec import jakarta.persistence.criteria.CriteriaQuery import jakarta.persistence.criteria.Expression +import jakarta.persistence.criteria.From +import jakarta.persistence.criteria.JoinType import jakarta.persistence.criteria.Root import jakarta.persistence.criteria.Predicate import org.hibernate.query.criteria.JpaExpression +import org.hibernate.query.sqm.tree.domain.SqmPath +import org.hibernate.query.sqm.tree.predicate.SqmComparisonPredicate +import org.hibernate.query.sqm.tree.predicate.SqmInListPredicate +import org.hibernate.query.sqm.tree.predicate.SqmJunctionPredicate +import org.hibernate.query.sqm.tree.select.SqmSubQuery import org.grails.datastore.mapping.model.PersistentEntity import org.grails.datastore.mapping.query.Query import org.grails.orm.hibernate.cfg.domainbinding.hibernate.GrailsHibernatePersistentEntity +import org.grails.orm.hibernate.query.HibernateAlias import org.grails.orm.hibernate.query.JpaQueryContext import org.grails.orm.hibernate.query.PredicateGenerator import org.grails.orm.hibernate.query.PropertyArithmetic @@ -571,6 +579,168 @@ class PredicateGeneratorSpec extends HibernateGormDatastoreSpec { then: predicates.length == 1 } + + def "test getPredicates joins an association block with the join type of its alias definition"() { + given: "the join type JpaCriteriaQueryCreator registers for an association block of the queried entity" + fromProvider.registerAlias("pets", new HibernateAlias("pets", "pets", JoinType.LEFT)) + List criteria = new DetachedCriteria(PredicateGeneratorSpecPerson).build { + pets { + eq("name", "Lucky") + } + }.criteria + + when: + def predicates = predicateGenerator.getPredicates(query, root, criteria, fromProvider, personEntity) + + then: + predicates.length == 1 + root.joins*.attribute*.name == ["pets"] + root.joins*.joinType == [JoinType.LEFT] + } + + def "test getPredicates joins a nested association block with the join type recorded on the enclosing block"() { + given: + List criteria = new DetachedCriteria(PredicateGeneratorSpecPerson).build { + pets { + join("face", JoinType.LEFT) + face { + eq("name", "Funny") + } + } + }.criteria + + when: + def predicates = predicateGenerator.getPredicates(query, root, criteria, fromProvider, personEntity) + From petsJoin = root.joins.find { it.attribute.name == "pets" } + + then: + predicates.length == 1 + petsJoin.joinType == JoinType.INNER + petsJoin.joins*.attribute*.name == ["face"] + petsJoin.joins*.joinType == [JoinType.LEFT] + } + + def "test getPredicates joins a nested association block without a recorded join type with an inner join"() { + given: + List criteria = new DetachedCriteria(PredicateGeneratorSpecPerson).build { + pets { + face { + eq("name", "Funny") + } + } + }.criteria + + when: + def predicates = predicateGenerator.getPredicates(query, root, criteria, fromProvider, personEntity) + From petsJoin = root.joins.find { it.attribute.name == "pets" } + + then: + predicates.length == 1 + petsJoin.joins*.attribute*.name == ["face"] + petsJoin.joins*.joinType == [JoinType.INNER] + } + + def "test getPredicates reuses the join its context made for an association block"() { + given: + From petsJoin = root.join("pets", JoinType.LEFT) + fromProvider.addFrom("pets", petsJoin) + List criteria = new DetachedCriteria(PredicateGeneratorSpecPerson).build { + pets { + eq("name", "Lucky") + } + }.criteria + + when: + def predicates = predicateGenerator.getPredicates(query, root, criteria, fromProvider, personEntity) + + then: + predicates.length == 1 + root.joins.size() == 1 + root.joins.first().is(petsJoin) + } + + def "test getPredicates does not reuse the join of an outer association block of the same name"() { + given: "a block for the face of the person and one for the face of its pets" + List criteria = new DetachedCriteria(PredicateGeneratorSpecPerson).build { + face { + eq("name", "Funny") + } + pets { + face { + eq("name", "Happy") + } + } + }.criteria + + when: + def predicates = predicateGenerator.getPredicates(query, root, criteria, fromProvider, personEntity) + From petsJoin = root.joins.find { it.attribute.name == "pets" } + + then: "the face of the pets is joined from the pets" + predicates.length == 2 + root.joins*.attribute*.name.sort() == ["face", "pets"] + petsJoin.joins*.attribute*.name == ["face"] + } + + def "test getPredicates joins an association block of a subquery from the root of the subquery"() { + given: "the outer query already joined pets" + fromProvider.addFrom("pets", root.join("pets")) + def subCriteria = new DetachedCriteria(PredicateGeneratorSpecPerson).build { + pets { + eq("name", "Lucky") + } + projections { + property("id") + } + } + List criteria = [new Query.In("id", subCriteria)] + + when: + def predicates = predicateGenerator.getPredicates(query, root, criteria, fromProvider, personEntity) + SqmSubQuery subquery = (predicates[0] as SqmInListPredicate).listExpressions.first() as SqmSubQuery + Root subqueryRoot = subquery.roots.first() + + then: + predicates.length == 1 + root.joins.size() == 1 + subqueryRoot.joins*.attribute*.name == ["pets"] + } + + def "test getPredicates takes a path of a subquery from the root of the subquery when an outer association block joined the same name"() { + given: "an association block of the outer query for face, then a subquery projecting the name of its own face" + def subCriteria = new DetachedCriteria(PredicateGeneratorSpecPerson).build { + projections { + property("face.name") + } + } + List criteria = new DetachedCriteria(PredicateGeneratorSpecPerson).build { + face { + eq("name", "Funny") + } + }.criteria + [new Query.In("firstName", subCriteria)] + + when: + def predicates = predicateGenerator.getPredicates(query, root, criteria, fromProvider, personEntity) + From outerFace = root.joins.find { it.attribute.name == "face" } + SqmSubQuery subquery = (predicates[1] as SqmInListPredicate).listExpressions.first() as SqmSubQuery + SqmPath selection = subquery.selection as SqmPath + + then: "the projected name is the name of the face of the root of the subquery, not of the outer join" + predicates.length == 2 + outerFace != null + !selection.lhs.is(outerFace) + selection.lhs.lhs.is(subquery.roots.first()) + } + + /** + * Returns the path on the left of each comparison in the predicate. + */ + private static List comparedPaths(Predicate predicate) { + if (predicate instanceof SqmJunctionPredicate) { + return predicate.predicates.collectMany { comparedPaths(it) } + } + predicate instanceof SqmComparisonPredicate ? [predicate.leftHandExpression as SqmPath] : [] + } } @Entity diff --git a/grails-data-hibernate7/core/src/test/groovy/grails/orm/HibernateCriteriaBuilderNestedJoinTypeSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/grails/orm/HibernateCriteriaBuilderNestedJoinTypeSpec.groovy new file mode 100644 index 000000000000..51486c70d9d7 --- /dev/null +++ b/grails-data-hibernate7/core/src/test/groovy/grails/orm/HibernateCriteriaBuilderNestedJoinTypeSpec.groovy @@ -0,0 +1,416 @@ +/* + * 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.orm + +import jakarta.persistence.criteria.JoinType +import org.hibernate.resource.jdbc.spi.StatementInspector +import org.springframework.transaction.PlatformTransactionManager +import spock.lang.AutoCleanup +import spock.lang.Shared +import spock.lang.Specification + +import grails.gorm.DetachedCriteria +import grails.gorm.transactions.Rollback +import org.apache.grails.data.testing.tck.domains.Face +import org.apache.grails.data.testing.tck.domains.Nose +import org.apache.grails.data.testing.tck.domains.Person +import org.apache.grails.data.testing.tck.domains.Pet +import org.apache.grails.data.testing.tck.domains.PetType +import org.grails.datastore.mapping.core.DatastoreUtils +import org.grails.orm.hibernate.HibernateDatastore +import org.grails.orm.hibernate.cfg.Settings + +class HibernateCriteriaBuilderNestedJoinTypeSpec extends Specification { + + // The join type an association block takes, as HibernateCriteriaBuilder#convertFromInt reads it + static final int LEFT_JOIN = 1 + + @Shared + NestedJoinCapture sqlCapture = new NestedJoinCapture() + + @Shared + @AutoCleanup + HibernateDatastore hibernateDatastore = new HibernateDatastore( + DatastoreUtils.createPropertyResolver( + (Settings.SETTING_DB_CREATE): 'create-drop', + 'hibernate.session_factory.statement_inspector': sqlCapture + ), + Person, Pet, PetType, Face, Nose + ) + + @Shared + PlatformTransactionManager transactionManager = hibernateDatastore.transactionManager + + void setup() { + sqlCapture.statements.clear() + } + + @Rollback + void 'a nested association block keeps the left join it asks for'() { + given: + savePets() + + when: + List pets = Pet.createCriteria().list { + owner(LEFT_JOIN) { + face(LEFT_JOIN) { + or { + isNull('id') + eq('name', 'Homer') + } + } + } + order('name') + } + String sql = sqlCapture.statements.last() + + then: 'the pet of an owner without a face and the pet without an owner are still there' + pets*.name == ['Lucky', 'Rex', 'Whiskers'] + ownerFaceJoins(sql) == ['left'] + !(sql =~ /(?i)(? pets = Pet.createCriteria().list { + owner(LEFT_JOIN) { + face { + eq('name', 'Homer') + } + } + } + String sql = sqlCapture.statements.last() + + then: + pets*.name == ['Lucky'] + ownerFaceJoins(sql) == ['inner'] + } + + @Rollback + void 'a projection counts the rows a nested left join keeps'() { + given: + savePets() + + expect: + Pet.createCriteria().get { + owner(LEFT_JOIN) { + face(LEFT_JOIN) { + or { + isNull('id') + eq('name', 'Homer') + } + } + } + projections { + rowCount() + } + } == 3L + } + + @Rollback + void 'the nested block and a block of the queried class for an association of the same name do not mix'() { + given: + savePets() + + expect: 'the face of the owner is left joined, the face of the pet inner joined, in either order' + Pet.createCriteria().list { + owner(LEFT_JOIN) { + face(LEFT_JOIN) { + or { + isNull('id') + eq('name', 'Homer') + } + } + } + face { + eq('name', 'Santa') + } + }*.name == ['Lucky'] + Pet.createCriteria().list { + face { + eq('name', 'Santa') + } + owner(LEFT_JOIN) { + face(LEFT_JOIN) { + or { + isNull('id') + eq('name', 'Homer') + } + } + } + }*.name == ['Lucky'] + } + + @Rollback + void 'a nested block without a recorded join type does not reuse the join of an outer block of the same name'() { + given: + savePets() + + expect: 'the face of the owner is joined from the owner, not taken from the face of the pet' + new DetachedCriteria(Pet).build { + face { + eq('name', 'Santa') + } + owner { + face { + eq('name', 'Homer') + } + } + }.list()*.name == ['Lucky'] + } + + @Rollback + void 'a nested block without a join type does not take the left join of an outer join of the same name in a detached criteria'() { + given: + savePets() + + when: 'the face of the pet is left joined and the block of the face of the owner asks for no join type' + List pets = new DetachedCriteria(Pet).build { + join('face', JoinType.LEFT) + owner { + face { + isNull('id') + } + } + }.list() + String sql = sqlCapture.statements.last() + + then: 'the owner without a face is dropped by the inner join' + pets.empty + ownerFaceJoins(sql) == ['inner'] + } + + @Rollback + void 'a nested block without a join type does not take the left join of an outer block of the same name'() { + given: + savePets() + + when: 'the block of the face of the pet is left joined and the block of the face of the owner asks for no join type' + List pets = Pet.createCriteria().list { + face(LEFT_JOIN) { + isNotNull('id') + } + owner { + face { + isNull('id') + } + } + } + String sql = sqlCapture.statements.last() + + then: 'the owner without a face is dropped by the inner join' + pets.empty + ownerFaceJoins(sql) == ['inner'] + } + + @Rollback + void 'a path through a nested block resolves to its join when an outer criterion went through the same name'() { + given: + savePets() + + expect: 'face.name in the owner block is the name of the face of the owner, not of the face of the pet' + Pet.createCriteria().list { + eq('face.name', 'Santa') + owner { + face { + isNotNull('id') + } + eq('face.name', 'Homer') + } + }*.name == ['Lucky'] + } + + @Rollback + void 'the name of a nested block resolves to its join when an outer criterion went through the same name'() { + given: + savePets() + + expect: 'face in the owner block is the face of the owner, not the face of the pet' + Pet.createCriteria().list { + eq('face.name', 'Santa') + owner { + face { + isNotNull('id') + } + eq('face', Face.findByName('Homer')) + } + }*.name == ['Lucky'] + } + + @Rollback + void 'an association block of a subquery joins from the root of the subquery'() { + given: + savePets() + + expect: 'the subquery selects the age of every pet of Homer, not only for the pets of Homer' + Pet.createCriteria().list { + owner(LEFT_JOIN) { + or { + isNull('id') + isNotNull('id') + } + } + 'in'('age', new DetachedCriteria(Pet).build { + owner { + eq('firstName', 'Homer') + } + projections { + property('age') + } + }) + order('name') + }*.name == ['Lucky', 'Rex'] + } + + @Rollback + void 'a subquery projecting a path through an association of an outer block takes the path from its own root'() { + given: 'a pet of Homer named after Ned' + savePets() + new Pet(name: 'Ned', age: 3, owner: Person.findByFirstName('Homer')).save(flush: true) + + expect: 'the subquery selects the first name of the owner of every pet, not of the owner of the outer pet' + new DetachedCriteria(Pet).build { + owner { + eq('firstName', 'Homer') + } + 'in'('name', new DetachedCriteria(Pet).build { + projections { + property('owner.firstName') + } + }) + }.list()*.name == ['Ned'] + } + + @Rollback + void 'a subquery in a nested block projecting a path through an association of that block takes the path from its own root'() { + given: + savePets() + + expect: 'the subquery selects the name of the face of every pet (Santa), not the name of the face of the owner' + Pet.createCriteria().list { + owner { + face { + isNotNull('id') + } + notIn('firstName', new DetachedCriteria(Pet).build { + projections { + property('face.name') + } + }) + } + }*.name == ['Lucky'] + } + + @Rollback + void 'a criterion on a collection of a nested block still restricts the collection'() { + given: + savePets() + + expect: + Pet.createCriteria().list { + owner { + isNotEmpty('pets') + pets { + eq('name', 'Rex') + } + } + }*.name == ['Rex'] + } + + @Rollback + void 'an order on a projection alias with the name of an association block orders by the projection'() { + given: + savePets() + + when: + List rows = Pet.createCriteria().list { + owner { + isNotNull('id') + } + projections { + groupProperty('name') + min('owner.age', 'owner') + } + order('owner', 'desc') + } + String sql = sqlCapture.statements.last() + + then: 'the order takes the second selection, min(owner.age), rather than the owner joined by the block' + rows == [['Rex', 60], ['Lucky', 39]] + sql.endsWith('order by 2 desc') + } + + /** + * Returns, for each join of the face of a person in the SQL, whether it is a left or an inner join. + */ + private static List ownerFaceJoins(String sql) { + Set people = sql.findAll(/(?i)join person (\w+)/) { String all, String alias -> alias } as Set + sql.findAll(/(?i)(left )?join face \w+ on \w+\.id=(\w+)\.face_id/) { String all, String left, String from -> + from in people ? (left ? 'left' : 'inner') : null + }.findAll() + } + + private static void savePets() { + Person homer = new Person(firstName: 'Homer', lastName: 'Simpson', age: 39, face: face('Homer')).save() + Person ned = new Person(firstName: 'Ned', lastName: 'Flanders', age: 60).save() + new Pet(name: 'Lucky', age: 5, owner: homer, face: face('Santa')).save() + new Pet(name: 'Rex', age: 5, owner: ned).save() + new Pet(name: 'Whiskers', age: 7).save(flush: true) + } + + private static Face face(String name) { + Face face = new Face(name: name) + face.nose = new Nose(hasFreckles: true, face: face) + face + } +} + +class NestedJoinCapture implements StatementInspector { + + final List statements = Collections.synchronizedList([]) + + @Override + String inspect(String sql) { + statements << sql + sql + } +} diff --git a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/query/ExpressionResolverSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/query/ExpressionResolverSpec.groovy index d30dd40aa466..a87f513fa1b7 100644 --- a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/query/ExpressionResolverSpec.groovy +++ b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/query/ExpressionResolverSpec.groovy @@ -683,4 +683,25 @@ class ExpressionResolverSpec extends Specification { 0 * root.join(_, _) result == namePath } + + def "test resolve takes a path of a subquery from its own root when the parent joined the same name without an alias"() { + given: "the owner joined by an association block of the outer query" + def parentOwner = Mock(Join) + def parentJoinTracker = new JoinTracker(Mock(From)) + parentJoinTracker.addJoin("owner", parentOwner) + + def subRoot = Mock(From) + def ownerPath = Mock(Path) + def firstNamePath = Mock(Path) + def resolver = new ExpressionResolver(new AliasRegistry(new AliasRegistry()), new JoinTracker(parentJoinTracker, subRoot)) + + when: + def result = resolver.resolve("owner.firstName") + + then: + 0 * parentOwner.get(_) + 1 * subRoot.get("owner") >> ownerPath + 1 * ownerPath.get("firstName") >> firstNamePath + result.is(firstNamePath) + } } From ed188b5347947d0848af55864cd2224d1f8ab1ff Mon Sep 17 00:00:00 2001 From: Walter B Duque de Estrada Date: Thu, 3 Dec 2026 09:35:27 -0600 Subject: [PATCH 5/7] docs: upgrade note for the Hibernate 7 list() fetch mode join (#16940) * docs: upgrade note for the Hibernate 7 list() fetch mode join (#16898) Refs #16939 Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL * docs: show the inner join of the list() fetch join note on the criteria query, and name both restrictions (#16961) Addresses the review of #16940: list() takes no join type, so JoinType.INNER goes on the join of a criteria query, with the jakarta.persistence.criteria import; the restriction for players is isNotEmpty, as isNotNull covers club. Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL --------- Co-authored-by: James Daugherty --- .../src/en/guide/upgrading/upgrading80x.adoc | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/grails-doc/src/en/guide/upgrading/upgrading80x.adoc b/grails-doc/src/en/guide/upgrading/upgrading80x.adoc index fe205625ee5f..f09a71fcbc3e 100644 --- a/grails-doc/src/en/guide/upgrading/upgrading80x.adoc +++ b/grails-doc/src/en/guide/upgrading/upgrading80x.adoc @@ -4999,6 +4999,24 @@ As of Grails 8.0.1, an exception an action throws is recorded as an error on the See the `rlike` entry of the criteria reference for the databases that match with a regular expression. +==== `list()` With the Fetch Mode `join` Returns the Rows Without the Association (Hibernate 7) + +As of Grails 8.0.1, with Hibernate 7, a fetch mode of `join` on `list()` and on a paged list fetches the association and never filters the result. + +* In 8.0.0, `Team.list(fetch: [club: 'join'])` built an inner `join fetch`, so the teams without a club were left out, and `Team.list(fetch: [players: 'join'])` left out the teams without players. +* Now both return every team, as a where query, a dynamic finder and a criteria query with the same fetch always did. The association of a team without one is `null`, or an empty collection. +* To get the earlier rows back, use a criteria query with an inner join on the association. `list()` takes no join type, so it goes on the `join` of the criteria query, with the `JoinType` of `jakarta.persistence.criteria` and not Hibernate's own: ++ +[source,groovy] +---- +import jakarta.persistence.criteria.JoinType + +Team.createCriteria().list { join('club', JoinType.INNER) } // the teams with a club +Team.createCriteria().list { join('players', JoinType.INNER) } // the teams with players +---- ++ +A where query or a criteria query that restricts the association returns the same rows: `isNotNull('club')` for `club`, and `isNotEmpty('players')` for `players`. + ==== A Proxy Factory That a Hibernate 5 Configuration Class Registers Is Used Again Grails 8.0.0 registered GORM's Groovy-aware proxy factory for Hibernate 5 over a Hibernate `ProxyFactoryFactory` that an application registered itself, in the `createStandardServiceRegistryBuilder` method of a configuration class set with `hibernate.configClass`. The application's factory was ignored without a message, and its proxies were built by GORM's. This was a regression from Grails 7, which used the application's factory. A factory registered there, with `addInitiator` or `addService` on the builder that the method returns, builds the proxies again. From ac1181779b5911a2cef1f7074153d13ac4bca6db Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Thu, 3 Dec 2026 16:34:01 -0800 Subject: [PATCH 6/7] Make the GSP Spring Boot script example run on 8.0.x The script grabbed org.grails:grails-gsp-spring-boot:7.0.0-SNAPSHOT from repo.grails.org and pinned Groovy 4 and Spring Boot 3.5, so it ran an old 7.0 snapshot rather than this line. It now grabs the released org.apache.grails:grails-gsp-spring-boot:8.0.0 from Maven Central. Two changes make it start: Groovy is excluded from the grab, because the groovy command already supplies it and refuses a second copy at another version, and Application no longer proxies its bean methods, because a CGLIB proxy cannot be defined in the class loader of a script under Spring Framework 7. The .sdkmanrc now matches the repository: the Java of the root .sdkmanrc and the Groovy of dependencies.gradle. The unused Spring Boot CLI entry is removed. --- grails-test-examples/gsp-spring-boot/script/.sdkmanrc | 5 ++--- grails-test-examples/gsp-spring-boot/script/README.md | 2 +- grails-test-examples/gsp-spring-boot/script/app.groovy | 9 +++++---- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/grails-test-examples/gsp-spring-boot/script/.sdkmanrc b/grails-test-examples/gsp-spring-boot/script/.sdkmanrc index 37a55964a79d..9df76f25a2ff 100644 --- a/grails-test-examples/gsp-spring-boot/script/.sdkmanrc +++ b/grails-test-examples/gsp-spring-boot/script/.sdkmanrc @@ -1,3 +1,2 @@ -java=21.0.7-librca -groovy=4.0.26 -springboot=3.5.10 +java=21.0.12-librca +groovy=5.1.4 diff --git a/grails-test-examples/gsp-spring-boot/script/README.md b/grails-test-examples/gsp-spring-boot/script/README.md index 354e5591091f..4f5a01b5603d 100644 --- a/grails-test-examples/gsp-spring-boot/script/README.md +++ b/grails-test-examples/gsp-spring-boot/script/README.md @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. --> -Use the following command with Groovy CLI 4.x +Use the following command with the Groovy CLI of the version in `.sdkmanrc` ```shell sdk env diff --git a/grails-test-examples/gsp-spring-boot/script/app.groovy b/grails-test-examples/gsp-spring-boot/script/app.groovy index d5db2158390f..ca6a62834db4 100644 --- a/grails-test-examples/gsp-spring-boot/script/app.groovy +++ b/grails-test-examples/gsp-spring-boot/script/app.groovy @@ -19,9 +19,9 @@ package demo -@GrabResolver(name='grails-repo', root='https://repo.grails.org/grails/restricted/') -@Grab("org.grails:grails-gsp-spring-boot:7.0.0-SNAPSHOT") -// if you need to clear snapshots, they are saved to ~/.groovy/grapes +@Grab('org.apache.grails:grails-gsp-spring-boot:8.0.0') +// the groovy command supplies Groovy itself: grabbing it again loads a second copy, and Groovy refuses to start +@GrabExclude('org.apache.groovy:*') import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.SpringApplication @@ -52,7 +52,8 @@ class FormatTagLib { } } -@SpringBootApplication +// no bean method calls another, and a CGLIB proxy cannot be defined in the class loader of a script +@SpringBootApplication(proxyBeanMethods = false) @ImportAutoConfiguration(GspAutoConfiguration.class) class Application { @Bean GspController rspController() { new GspController() } From 9b6c7b8c5845107d8a69412285ce0377a466b2e9 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Thu, 3 Dec 2026 16:45:42 -0800 Subject: [PATCH 7/7] Run the GSP Spring Boot script example against the branch's snapshot The script now grabs 8.0.1-SNAPSHOT from the Apache snapshot repository instead of the 8.0.0 release, so it runs what is on 8.0.x, and a local publishToMavenLocal is picked up through Grape's default ~/.m2 resolver. setSnapshotGrailsVersion.sh, which the post-release step runs with the next version, now moves the script's @Grab to that snapshot together with projectVersion, and fails if the @Grab line no longer matches. --- .github/scripts/setSnapshotGrailsVersion.sh | 7 +++++++ grails-test-examples/gsp-spring-boot/script/app.groovy | 4 +++- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/.github/scripts/setSnapshotGrailsVersion.sh b/.github/scripts/setSnapshotGrailsVersion.sh index d5d91ec3ce18..7c3210a6ec42 100755 --- a/.github/scripts/setSnapshotGrailsVersion.sh +++ b/.github/scripts/setSnapshotGrailsVersion.sh @@ -25,3 +25,10 @@ echo "Setting new version in GrailsUtilsTests.java: ${NEXT_VERSION}-SNAPSHOT" sed -i "s/assertEquals(\".*$/assertEquals(\"${NEXT_VERSION}-SNAPSHOT\", GrailsUtil.getGrailsVersion());/" "${GITHUB_WORKSPACE}/grails-core/src/test/groovy/grails/util/GrailsUtilTests.java" sed -n "/assertEquals(\".*/p" "${GITHUB_WORKSPACE}/grails-core/src/test/groovy/grails/util/GrailsUtilTests.java" git add "${GITHUB_WORKSPACE}/grails-core/src/test/groovy/grails/util/GrailsUtilTests.java" + +GSP_SCRIPT="${GITHUB_WORKSPACE}/grails-test-examples/gsp-spring-boot/script/app.groovy" +echo "Setting new version in the GSP Spring Boot script example: ${NEXT_VERSION}-SNAPSHOT" +sed -i "s/^@Grab('org.apache.grails:grails-gsp-spring-boot:.*')$/@Grab('org.apache.grails:grails-gsp-spring-boot:${NEXT_VERSION}-SNAPSHOT')/" "${GSP_SCRIPT}" +grep -q "^@Grab('org.apache.grails:grails-gsp-spring-boot:${NEXT_VERSION}-SNAPSHOT')$" "${GSP_SCRIPT}" +sed -n "/^@Grab(/p" "${GSP_SCRIPT}" +git add "${GSP_SCRIPT}" diff --git a/grails-test-examples/gsp-spring-boot/script/app.groovy b/grails-test-examples/gsp-spring-boot/script/app.groovy index ca6a62834db4..218ae9cbb78f 100644 --- a/grails-test-examples/gsp-spring-boot/script/app.groovy +++ b/grails-test-examples/gsp-spring-boot/script/app.groovy @@ -19,7 +19,9 @@ package demo -@Grab('org.apache.grails:grails-gsp-spring-boot:8.0.0') +@GrabResolver(name = 'apache-snapshots', root = 'https://repository.apache.org/content/groups/snapshots/') +// the release workflow sets this to the next snapshot after each release (.github/scripts/setSnapshotGrailsVersion.sh) +@Grab('org.apache.grails:grails-gsp-spring-boot:8.0.1-SNAPSHOT') // the groovy command supplies Groovy itself: grabbing it again loads a second copy, and Groovy refuses to start @GrabExclude('org.apache.groovy:*')