Repository navigation
Recognise constant HQL fragments and declaration-level suppression in the query safety check - #16463
Conversation
… 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 Report❌ Patch coverage is
Additional details and impacted files@@ 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
🚀 New features to boost your workflow:
|
|
Constant-text tracking is last-write-wins outside Only String frag = ""
try { frag = sort } catch (Exception ex) { frag = "" }
String q = "from Book order by ${frag}"
executeQuery(q) // not flagged: frag is in constantTextVarsBefore this PR any GString with an interpolation assigned to a I found this by reading the code and have not run the spec below; the @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 ( Possible fix: treat any assignment inside a |
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.
|
@sbglasius good catch - that was a real regression. Fixed in 9ebd139 by applying the snapshot/merge model
A side effect of modelling jumps: a branch that Your spec is in verbatim (the |
✅ All tests passed ✅🏷️ Commit: 9ebd139 Learn more about TestLens at testlens.app/docs. |
|
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:
#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. |
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:
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.