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/THREAT_MODEL.md b/THREAT_MODEL.md index b7b1c59a0479..386bee6ca3f8 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/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 50b3d7c329a1..4352b18d30f8 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 @@ -97,7 +97,8 @@ public ColumnBinder( columnNameFetcher(metadataBuildingContext, namingStrategy), new StringColumnConstraintsBinder(), new NumericColumnConstraintsBinder(dialect), - new CreateKeyForProps(columnNameFetcher(metadataBuildingContext, namingStrategy)), + new CreateKeyForProps(columnNameFetcher(metadataBuildingContext, namingStrategy), + metadataBuildingContext == null ? null : metadataBuildingContext.getMetadataCollector()), new IndexBinder()); } diff --git a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/CompositeUserTypeBinder.java b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/CompositeUserTypeBinder.java index b9eff694caa4..4399c7dcc0cc 100644 --- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/CompositeUserTypeBinder.java +++ b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/binder/CompositeUserTypeBinder.java @@ -94,7 +94,7 @@ public CompositeUserTypeBinder( new ColumnBinder(metadataBuildingContext, namingStrategy, jdbcEnvironment.getDialect()), new CreateKeyForProps(new ColumnNameForPropertyAndPathFetcher( namingStrategy, new DefaultColumnNameFetcher(namingStrategy), new BackticksRemover(), - metadataBuildingContext)), + metadataBuildingContext), metadataBuildingContext.getMetadataCollector()), new CompositeUserTypeColumns(namingStrategy, new BackticksRemover(), metadataBuildingContext)); } 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/util/ColumnNameForPropertyAndPathFetcher.java b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/util/ColumnNameForPropertyAndPathFetcher.java index 4f86f90fb9b1..2e4752e28172 100644 --- a/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/util/ColumnNameForPropertyAndPathFetcher.java +++ b/grails-data-hibernate7/core/src/main/groovy/org/grails/orm/hibernate/cfg/domainbinding/util/ColumnNameForPropertyAndPathFetcher.java @@ -101,9 +101,9 @@ public String getColumnNameForPropertyAndPath( /** * The names of all the columns of the property: the one name {@link #getColumnNameForPropertyAndPath} resolves - * without a column configuration for a property that has one column, or one name per attribute of the - * embeddable class for a property mapped with a composite user type, which spans one column per attribute and - * has no single column name. + * without a column configuration for an unconfigured property, one name per configured column, or one name + * per attribute of the embeddable class for a property mapped with a composite user type, which spans one + * column per attribute and has no single column name. * * @param grailsProp the property * @param path the path of the property within its entity @@ -114,6 +114,12 @@ public List getColumnNamesForPropertyAndPath(HibernatePersistentProperty if (grailsProp.getCompositeUserType() != null) { return compositeUserTypeColumns.columnNamesOf(grailsProp, path); } + List columns = grailsProp.getHibernateMappedForm().getColumns(); + if (!columns.isEmpty()) { + return columns.stream() + .map(column -> getColumnNameForPropertyAndPath(grailsProp, path, column)) + .toList(); + } return Collections.singletonList(getColumnNameForPropertyAndPath(grailsProp, path, null)); } } 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 f9dd336f81af..35a7072e5e2d 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 @@ -22,6 +22,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; @@ -35,17 +36,31 @@ 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(); + this(columnNameForPropertyAndPathFetcher, new UniqueKeyForColumnsCreator(), null); + } + + public CreateKeyForProps( + ColumnNameForPropertyAndPathFetcher columnNameForPropertyAndPathFetcher, + InFlightMetadataCollector metadataCollector) { + this(columnNameForPropertyAndPathFetcher, new UniqueKeyForColumnsCreator(), metadataCollector); } protected CreateKeyForProps( ColumnNameForPropertyAndPathFetcher columnNameForPropertyAndPathFetcher, UniqueKeyForColumnsCreator uniqueKeyForColumnsCreator) { + this(columnNameForPropertyAndPathFetcher, uniqueKeyForColumnsCreator, null); + } + + protected CreateKeyForProps( + ColumnNameForPropertyAndPathFetcher columnNameForPropertyAndPathFetcher, + UniqueKeyForColumnsCreator uniqueKeyForColumnsCreator, + InFlightMetadataCollector metadataCollector) { this.columnNameForPropertyAndPathFetcher = columnNameForPropertyAndPathFetcher; this.uniqueKeyForColumnsCreator = uniqueKeyForColumnsCreator; + this.metadataCollector = metadataCollector; } public void createKeyForProps(HibernatePersistentProperty grailsProp, String path, Table table, String columnName) { @@ -59,11 +74,8 @@ 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)); - addGroupColumns(grailsProp, mappedForm, path, keyList); - uniqueKeyForColumnsCreator.createUniqueKeyForColumns(table, keyList); + createKeyWhenReady(() -> createKeyForGroup(grailsProp, path, table, + List.of(new Column(columnName)), mappedForm)); } } @@ -85,6 +97,20 @@ public void createKeyForColumns( if (!mappedForm.isUnique() || columns.isEmpty()) { return; } + createKeyWhenReady(() -> createKeyForGroup(grailsProp, path, table, columns, mappedForm)); + } + + private void createKeyWhenReady(Runnable createKey) { + if (metadataCollector == null || metadataCollector.isInSecondPass()) { + createKey.run(); + } else { + metadataCollector.addSecondPass(persistentClasses -> createKey.run()); + } + } + + private void createKeyForGroup( + HibernatePersistentProperty grailsProp, String path, Table table, List columns, + PropertyConfig mappedForm) { List keyList = new ArrayList<>(columns); if (mappedForm.isUniqueWithinGroup()) { addGroupColumns(grailsProp, mappedForm, path, 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..8f9351f1c2e7 --- /dev/null +++ b/grails-data-hibernate7/core/src/test/groovy/grails/gorm/tests/EnumUniqueGroupAssociationSpec.groovy @@ -0,0 +1,228 @@ +/* + * 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 org.grails.orm.hibernate.CompositeMoney +import org.grails.orm.hibernate.CompositeMoneyType +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, + StringUniqueCompositeChild, DeclaredFirstUniqueCompositeChild, DeclaredFirstCompositeAmountChild) + } + + 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 + } + + 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 declared-first composite user type group includes every implicit composite-association column"() { + given: + def table = datastore.metadata.getEntityBinding(DeclaredFirstCompositeAmountChild.name).table + + expect: + table.uniqueKeys.values().collect { it.columns*.name.toSet() } == + [['amount_amount', 'amount_currency', 'enum_unique_composite_parent_code', + 'enum_unique_composite_parent_revision'] as Set] + } + + void "a declared-first composite user type group accepts 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 DeclaredFirstCompositeAmountChild(parent: parent, amount: new CompositeMoney(amount: 10, currency: 'EUR')) + .save(failOnError: true) + } + manager.session.flush() + manager.session.clear() + + then: + DeclaredFirstCompositeAmountChild.count() == 3 + } + + void "a duplicate declared-first composite value for the same parent violates the unique key"() { + given: + def parent = new EnumUniqueCompositeParent(code: 'duplicate', revision: 1).save(failOnError: true) + new DeclaredFirstCompositeAmountChild(parent: parent, amount: new CompositeMoney(amount: 10, currency: 'EUR')) + .save(flush: true, failOnError: true) + + when: + new DeclaredFirstCompositeAmountChild(parent: parent, amount: new CompositeMoney(amount: 10, currency: 'EUR')) + .save(flush: true, validate: false) + + then: + thrown(DataIntegrityViolationException) + } + + 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 { + 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' + } + } +} + +@Entity +class StringUniqueCompositeChild 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' + } +} + +@Entity +class DeclaredFirstCompositeAmountChild implements HibernateEntity { + CompositeMoney amount + EnumUniqueCompositeParent parent + + static mapping = { + amount type: CompositeMoneyType, unique: 'parent' + } +} 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 b03c93f31679..242e67f14b1b 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 @@ -609,6 +617,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] : [] + } } /** A criterion with no built-in handling, so only a registered handler converts it. */ 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/cfg/domainbinding/ColumnNameForPropertyAndPathFetcherSpec.groovy b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/ColumnNameForPropertyAndPathFetcherSpec.groovy index e411e0652102..0566f241bce2 100644 --- a/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/ColumnNameForPropertyAndPathFetcherSpec.groovy +++ b/grails-data-hibernate7/core/src/test/groovy/org/grails/orm/hibernate/cfg/domainbinding/ColumnNameForPropertyAndPathFetcherSpec.groovy @@ -129,6 +129,7 @@ class ColumnNameForPropertyAndPathFetcherSpec extends Specification { ) def grailsProp = Mock(HibernatePersistentProperty) { getCompositeUserType() >> null + getHibernateMappedForm() >> new PropertyConfig() getColumnName(null) >> "`explicit_col`" } @@ -165,6 +166,53 @@ class ColumnNameForPropertyAndPathFetcherSpec extends Specification { 0 * defaultColumnFetcher._ } + def "expands every configured column in config order"() { + given: + def namingStrategy = Mock(PersistentEntityNamingStrategy) + def defaultColumnFetcher = Mock(DefaultColumnNameFetcher) + def fetcher = new ColumnNameForPropertyAndPathFetcher(namingStrategy, defaultColumnFetcher, backticksRemover) + def firstColumn = new ColumnConfig(name: 'parent_code') + def secondColumn = new ColumnConfig(name: 'parent_revision') + def property = Mock(HibernatePersistentProperty) { + getHibernateMappedForm() >> new PropertyConfig(columns: [firstColumn, secondColumn]) + getColumnName(firstColumn) >> 'parent_code' + getColumnName(secondColumn) >> 'parent_revision' + } + + when: + def names = fetcher.getColumnNamesForPropertyAndPath(property, 'child_path') + + then: + names == ['parent_code', 'parent_revision'] + 0 * property.getColumnName(null) + 0 * defaultColumnFetcher._ + } + + def "keeps configured column order when an explicit column is followed by an implicit column"() { + given: + def namingStrategy = Stub(PersistentEntityNamingStrategy) { + resolveColumnName('childPath') >> 'child_path' + } + def defaultColumnFetcher = Stub(DefaultColumnNameFetcher) { + getDefaultColumnName(_) >> 'parent_id' + } + def fetcher = new ColumnNameForPropertyAndPathFetcher(namingStrategy, defaultColumnFetcher, backticksRemover) + def explicitColumn = new ColumnConfig(name: '`parent_code`') + def implicitColumn = new ColumnConfig() + def property = Mock(HibernatePersistentProperty) { + getHibernateMappedForm() >> new PropertyConfig(columns: [explicitColumn, implicitColumn]) + getColumnName(explicitColumn) >> '`parent_code`' + getColumnName(implicitColumn) >> null + } + + when: + def names = fetcher.getColumnNamesForPropertyAndPath(property, 'childPath') + + then: + names == ['`parent_code`', 'child_path_parent_id'] + 0 * property.getColumnName(null) + } + def "a fetcher built with a building context resolves a composite user type as the binder of its property does"() { given: "a building context that allows extensions in CDI, whose bean registry creates a user type without a default constructor" UtilCdiMoneyType managed = new UtilCdiMoneyType('cdi') 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 1889ecf7c8b3..8101affef4a5 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 @@ -23,16 +23,103 @@ import org.grails.orm.hibernate.cfg.domainbinding.hibernate.GrailsHibernatePersi 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.Column import org.hibernate.mapping.Table import spock.lang.Specification +import org.grails.orm.hibernate.cfg.PropertyConfig import org.grails.orm.hibernate.cfg.domainbinding.util.ColumnNameForPropertyAndPathFetcher import org.grails.orm.hibernate.cfg.domainbinding.util.CreateKeyForProps import org.grails.orm.hibernate.cfg.domainbinding.util.UniqueKeyForColumnsCreator class CreateKeyForPropsSpec extends Specification { + def "resolves group columns in the second pass for #entryPoint"() { + given: + def collector = Mock(InFlightMetadataCollector) + def columnNameFetcher = Mock(ColumnNameForPropertyAndPathFetcher) + def uniqueKeyCreator = Mock(UniqueKeyForColumnsCreator) + def subject = new CreateKeyForProps(columnNameFetcher, uniqueKeyCreator, collector) + def owner = Stub(GrailsHibernatePersistentEntity) + def parent = Stub(HibernatePersistentProperty) + def grailsProp = Stub(HibernatePersistentProperty) { + getMappedForm() >> new PropertyConfig(unique: ['parent']) + getHibernateOwner() >> owner + } + owner.getHibernatePropertyByName('parent') >> parent + def table = new Table(name: 'child') + def columns = [new Column('`Amount`'), new Column('currency')] + SecondPass secondPass + + when: + if (entryPoint == 'columns') { + subject.createKeyForColumns(grailsProp, null, table, columns) + } else { + subject.createKeyForProps(grailsProp, null, table, 'child_state') + } + + then: 'no member is resolved before the association columns have been bound' + 1 * collector.addSecondPass(_) >> { SecondPass pass -> secondPass = pass } + 0 * columnNameFetcher._ + 0 * uniqueKeyCreator._ + + when: + secondPass.doSecondPass([:]) + + then: + 1 * columnNameFetcher.getColumnNamesForPropertyAndPath(parent, null) >> ['parent_code', 'parent_revision'] + 1 * uniqueKeyCreator.createUniqueKeyForColumns(table, { List key -> + key*.name == expected && (entryPoint != 'columns' || key[0].is(columns[0]) && key[1].is(columns[1])) + }) + + where: + entryPoint | expected + 'props' | ['child_state', 'parent_code', 'parent_revision'] + 'columns' | ['Amount', 'currency', 'parent_code', 'parent_revision'] + } + + def "creates a key immediately for #entryPoint with #collectorState collector"() { + given: + def columnNameFetcher = Stub(ColumnNameForPropertyAndPathFetcher) + def collector = collectorState == 'absent' ? null : Mock(InFlightMetadataCollector) { + isInSecondPass() >> true + } + def subject = collector == null ? new CreateKeyForProps(columnNameFetcher) : + new CreateKeyForProps(columnNameFetcher, collector) + def parent = Stub(HibernatePersistentProperty) + def owner = Stub(GrailsHibernatePersistentEntity) { + getHibernatePropertyByName('parent') >> parent + } + def grailsProp = Stub(HibernatePersistentProperty) { + getMappedForm() >> new PropertyConfig(unique: ['parent']) + getHibernateOwner() >> owner + } + columnNameFetcher.getColumnNamesForPropertyAndPath(parent, null) >> ['parent_code', 'parent_revision'] + def table = new Table(name: 'child') + + when: + if (entryPoint == 'columns') { + subject.createKeyForColumns(grailsProp, null, table, [new Column('amount'), new Column('currency')]) + } else { + subject.createKeyForProps(grailsProp, null, table, 'child_state') + } + + then: + table.uniqueKeys.values().collect { it.columns*.name.toSet() } == [expected as Set] + if (collector != null) { + 0 * collector.addSecondPass(_) + } + + where: + entryPoint | collectorState | expected + 'props' | 'absent' | ['child_state', 'parent_code', 'parent_revision'] + 'columns' | 'absent' | ['amount', 'currency', 'parent_code', 'parent_revision'] + 'props' | 'second-pass' | ['child_state', 'parent_code', 'parent_revision'] + 'columns' | 'second-pass' | ['amount', 'currency', 'parent_code', 'parent_revision'] + } + def "creates unique key when property is unique within group"() { given: def columnNameFetcher = Mock(ColumnNameForPropertyAndPathFetcher) @@ -70,7 +157,7 @@ class CreateKeyForPropsSpec extends Specification { 1 * grailsProp.getMappedForm() >> mappedForm 1 * grailsProp.getHibernateOwner() >> owner 1 * mappedForm.isUnique() >> true - 1 * mappedForm.isUniqueWithinGroup() >> true + 2 * mappedForm.isUniqueWithinGroup() >> true 1 * mappedForm.getUniquenessGroup() >> ["p1", "p2"] 1 * owner.getHibernatePropertyByName("p1") >> otherProp1 1 * owner.getHibernatePropertyByName("p2") >> otherProp2 @@ -162,7 +249,7 @@ class CreateKeyForPropsSpec extends Specification { 1 * grailsProp.getMappedForm() >> mappedForm 1 * grailsProp.getHibernateOwner() >> owner 1 * mappedForm.isUnique() >> true - 1 * mappedForm.isUniqueWithinGroup() >> true + 2 * mappedForm.isUniqueWithinGroup() >> true 1 * mappedForm.getUniquenessGroup() >> ["missingProp"] 1 * owner.getJavaClass() >> CreateKeyForPropsSpec 1 * owner.getHibernatePropertyByName("missingProp") 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) + } } diff --git a/grails-doc/src/en/guide/upgrading/upgrading80x.adoc b/grails-doc/src/en/guide/upgrading/upgrading80x.adoc index 7656d4cb72c8..5dbdf6e27d34 100644 --- a/grails-doc/src/en/guide/upgrading/upgrading80x.adoc +++ b/grails-doc/src/en/guide/upgrading/upgrading80x.adoc @@ -5001,6 +5001,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. 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..218ae9cbb78f 100644 --- a/grails-test-examples/gsp-spring-boot/script/app.groovy +++ b/grails-test-examples/gsp-spring-boot/script/app.groovy @@ -19,9 +19,11 @@ 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 +@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:*') import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.SpringApplication @@ -52,7 +54,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() } diff --git a/threat-model.yaml b/threat-model.yaml index 3bfdcb05d6aa..c5cfbef700ea 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"