Skip to content

Recognise constant HQL fragments and declaration-level suppression in the query safety check - #16463

Merged
jdaugherty merged 2 commits into
apache:8.0.xfrom
jdaugherty:fix/gorm-query-safety-hql-fragments
Oct 2, 2026
Merged

jdaugherty merged 2 commits into
apache:8.0.xfrom
jdaugherty:fix/gorm-query-safety-hql-fragments

Conversation

@jdaugherty

@jdaugherty jdaugherty commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

The GormUnsafeQueryString check flagged every GString coerced to a String
before reaching a GORM query method, including the common pattern of
assembling query text from fixed HQL fragments chosen at runtime:

String restriction = shouldIncludeTitle ? " and b.title = :title" : ""
String query = "from Book b where 1 = 1 ${restriction}"
Book.executeQuery(query, queryParams)

The documented fix - keep the query a GString - does not apply there: GORM
binds every interpolation as a parameter, so the fragment would be bound as
a value and the query would stop working.

The check now tells query text from values. An interpolation that is
constant text (a literal, a static final field initialised from constant
text, a ternary or Elvis over constant text, a +/GString/cast/toString of
constant text, or a local that only ever held constant text on every path)
cannot carry user input and is no longer a finding. Compound assignment
with += is tracked like x = x + y, so a constant query stays constant when
constant text is appended, and a live GString or already-flattened operand
anywhere in a + concatenation makes the result flattened (an error) rather
than the lower-confidence concatenation warning.

Local tracking is flow-sensitive across every control-flow construct, not
only if/else. The cases of a switch (including fall-through), the paths of
a try/catch/finally (a catch block starts from every state the try block
passed through, since an exception may leave it after any statement), loop
bodies and closure bodies (re-walked until the loop-head state is stable,
so an assignment late in the body is seen by a use earlier in it) are each
walked from the state before the construct and merged pessimistically
afterwards: a variable unsafe on any path stays unsafe, and is constant
text only if it is constant on every path. break, continue and a closure's
return carry their state to where they jump, and a path ending in a jump
or a throw contributes nothing to the state after the statement.

@SuppressWarnings("GormUnsafeQueryString") can now also go on a local
variable or field declaration. It marks that one variable as reviewed for
the rest of the method, whatever it is later assigned, treats it as
constant text wherever it is interpolated, and leaves every other variable
checked.

The error and warning messages, the security guide and the Grails 8
upgrade notes explain the query-text case and no longer recommend a GString
for fragments.

… the query safety check

The GormUnsafeQueryString check flagged every GString coerced to a String
before reaching a GORM query method, including the common pattern of
assembling query text from fixed HQL fragments chosen at runtime:

    String restriction = shouldIncludeTitle ? " and b.title = :title" : ""
    String query = "from Book b where 1 = 1 ${restriction}"
    Book.executeQuery(query, queryParams)

The documented fix - keep the query a GString - does not apply there: GORM
binds every interpolation as a parameter, so the fragment would be bound as
a value and the query would stop working.

The check now tells query text from values. An interpolation that is
constant text (a literal, a static final field initialised from constant
text, a ternary or Elvis over constant text, a +/GString/cast/toString of
constant text, or a local that only ever held constant text on every path)
cannot carry user input and is no longer a finding. Compound assignment
with += is tracked like x = x + y, so a constant query stays constant when
constant text is appended, and a live GString or already-flattened operand
anywhere in a + concatenation makes the result flattened (an error) rather
than the lower-confidence concatenation warning.

@SuppressWarnings("GormUnsafeQueryString") can now also go on a local
variable or field declaration. It marks that one variable as reviewed for
the rest of the method, whatever it is later assigned, treats it as
constant text wherever it is interpolated, and leaves every other variable
checked.

The error and warning messages, the security guide and the Grails 8
upgrade notes explain the query-text case and no longer recommend a GString
for fragments.
@codecov

codecov Bot commented Oct 1, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 88.08664% with 33 lines in your changes missing coverage. Please review.
✅ Project coverage is 59.0023%. Comparing base (d13aa33) to head (9ebd139).

Files with missing lines Patch % Lines
...rm/query/transform/GormQuerySafetyTransformer.java 88.0866% 10 Missing and 23 partials ⚠️
Additional details and impacted files

Impacted file tree graph

@@                Coverage Diff                 @@
##                8.0.x     #16463        +/-   ##
==================================================
+ Coverage     58.9274%   59.0023%   +0.0749%     
- Complexity      24440      24534        +94     
==================================================
  Files            2174       2174                
  Lines          107366     107606       +240     
  Branches        19557      19613        +56     
==================================================
+ Hits            63268      63490       +222     
  Misses          35235      35235                
- Partials         8863       8881        +18     
Files with missing lines Coverage Δ
...rm/query/transform/GormQuerySafetyTransformer.java 86.7850% <88.0866%> (+3.2644%) ⬆️

... and 4 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@sbglasius

sbglasius commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

Constant-text tracking is last-write-wins outside if/else, which creates a new false negative

Only visitIfElse merges state per branch. In try/catch, switch and loops the AST is walked in source order, so a data assignment followed by a constant one leaves the variable classified as constant text:

String frag = ""
try { frag = sort } catch (Exception ex) { frag = "" }
String q = "from Book order by ${frag}"
executeQuery(q)   // not flagged: frag is in constantTextVars

Before this PR any GString with an interpolation assigned to a String was a build error, so this is a regression rather than the already-documented limitation (that limitation only used to hide unsafe-to-safe transitions for the flattened state, not the direct-interpolation check). GormQuerySafetyTransformer.isConstantTextVariable ends in constantTextVars.contains(...).

I found this by reading the code and have not run the spec below; the try/catch and switch rows should currently fail with "Expected exception ... but no exception was thrown", and the if/else row is the control that should pass.

@Unroll
void "test variable assigned from data on one path of #construct is not treated as constant text"() {
    when:
    new GroovyClassLoader().parseClass("""
import grails.gorm.annotation.Entity

@Entity
class Book {
    String title

    static List sorted(String sort) {
        String frag = "$body"
        
        String q = "from Book order by \${frag}"
        executeQuery(q)
    }
}
""")

    then:
    def e = thrown(MultipleCompilationErrorsException)
    e.message.contains('GormUnsafeQueryString')
    e.message.contains("passed to 'executeQuery'")

    where:
    construct   | body
    'if/else'   | 'if (sort) { frag = sort } else { frag = " title" }'
    'try/catch' | 'try { frag = sort } catch (Exception ex) { frag = "" }'
    'switch'    | 'switch (sort) { case "a": frag = sort; break; default: frag = " title" }'
}

A use-before-write loop (frag interpolated, then frag = sort later in the same loop body) has the same problem and is worth a row too.

Possible fix: treat any assignment inside a try, switch or loop as making the variable non-constant for the rest of the method, or override those visitors to merge pessimistically like visitIfElse does.

Constant-text tracking was last-write-wins inside try/catch, switch,
loops and closure bodies: a local assigned data on one path and constant
text on a later path in source order ended up classified as constant
text, so a GString interpolating it was no longer a finding - a false
negative that the previous unconditional error for a String-coerced
GString did not have.

Every control-flow construct is now walked the way if/else already was:
from a snapshot of the state before it, with the states at the end of
its paths merged pessimistically afterwards. A catch block starts from
the merge of every state the try block passed through, since an
exception can leave it after any statement, and a finally block is
checked against every path into it while only the paths that complete
the try or a catch block normally continue past the statement. A loop
body or closure body is re-walked, without reporting, from the merged
loop-head state until that state is stable, so an assignment late in the
body is seen by a use earlier in it that the next iteration reaches; the
walk from the settled state reports each finding once. break, continue
and a closure's return carry their state to the exit or head they jump
to, and a path that ends in a jump or a throw no longer contributes to
the state after the statement, which also removes the false positive for
a branch that returns after flattening a query.
@jdaugherty

Copy link
Copy Markdown
Contributor Author

@sbglasius good catch - that was a real regression. Fixed in 9ebd139 by applying the snapshot/merge model visitIfElse already had to every control-flow construct, rather than the blunt "non-constant for the rest of the method" option, so the dynamic-restriction idioms keep working inside loops and switches:

  • switch: every case starts from the pre-switch state merged with the previous case's fall-through state (none when that case ends in break/return/throw/continue); the state after the statement is merged from the normal exit and every break.
  • try/catch/finally: a catch starts from the merge of every state the try block passed through, since an exception can leave it after any statement - so a data assignment that is overwritten later in the same block still reaches the handler. The finally block is checked against every path into it, but only the paths that complete the try or a catch normally continue past the statement.
  • Loops and closure bodies: re-walked silently from the merged loop-head state until it stops changing, then walked once more with reporting on, so the use-before-write loop case is caught and each finding is reported exactly once. break, continue and a closure return carry their state to where they jump, including labelled jumps.

A side effect of modelling jumps: a branch that returns after flattening a query no longer poisons the state after the if (previously a false positive), and a case that breaks no longer leaks its state into the next case.

Your spec is in verbatim (the if/else row as the control), extended with do/while, loop break/continue, closures, and a try block that overwrites the data assignment before the catch, plus dedicated cases for the use-before-write loop, continue, labelled break, fall-through and finally, and no-warning counterparts for constant text appended in a loop, chosen in every switch case, or assigned in both try and catch. Against dd71f8e the try/catch, switch, loop, continue, labelled-break and finally cases fail as you predicted, and so do the two "returns before the query" no-warning cases. Docs and the class Javadoc's limitations list are updated accordingly.

@testlens-app

testlens-app Bot commented Oct 1, 2026 •

Copy link
Copy Markdown

✅ All tests passed ✅

🏷️ Commit: 9ebd139
▶️ Tests: 23228 executed
⚪️ Checks: 91/91 completed


Learn more about TestLens at testlens.app/docs.

@jdaugherty
jdaugherty merged commit c23b19e into apache:8.0.x Oct 2, 2026
158 of 159 checks passed
@jdaugherty
jdaugherty deleted the fix/gorm-query-safety-hql-fragments branch October 2, 2026 13:07
@matrei

matrei commented Oct 2, 2026

Copy link
Copy Markdown
Contributor

Post-merge review: the constant-text idea works well for the dynamic-restriction idioms. While reviewing, though, I found a few gaps that I've written up in #16481 and fixed in #16482:

  • Some locals holding a value still pass as constant text. This happens when a local is assigned somewhere the walk cannot place in order: a multiple assignment, a ternary or &&/|| operand, a method argument, a do/while condition, or a closure called later. It also happens when a loop variable or closure parameter reuses the name of an earlier constant local. Each case was a build error before this PR.
  • Compile time grows exponentially with nesting. Every loop and closure body is walked at least twice, inside each walk of its enclosing body. 24 nested closures take about 33 s to compile, and this check runs on every class compiled with grails-datamapping-core on the classpath.
  • The docs and the error message overstate what is reported. Text joined from a List or returned from a helper method is not reported when it is passed to the query method on its own. The error message also recommends StringBuilder, which the check cannot follow.

#16482 tracks locals per declaration and settles the locals the walk cannot order with a per-method pre-scan. It walks a body that assigns nothing outside it only once, and corrects the message and the guide. Reviews welcome.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

3 participants