Repository navigation
Close the constant-text gaps in the query safety check and keep its cost linear in nesting depth - #16482
Conversation
Constant-text tracking assumed every assignment to a local was a statement walked in the order it runs, and tracked locals by name. A local holding a value could therefore pass as constant text when it was assigned by multiple assignment, inside a ternary, an && or || operand, a method argument or a do/while condition, or inside a closure called later, and a loop variable or closure parameter could inherit the status of an earlier local with the same name. Tracking is now keyed by the declaration each reference resolves to. A pre-scan of each method finds the assignments the walk cannot place in order; a local assigned that way, or declared outside a closure and read inside it, is constant text only if every assignment to it in the method is constant text. A loop or closure body that assigns no local declared outside it is walked once instead of being re-walked to a fixpoint, and a nested body that has already settled silently is not walked again, so compile time no longer grows exponentially with nesting depth. Constructors, field initialisers and object initialisers are analysed with a fresh state like methods, so a suppression on a constructor now takes effect. The error message no longer recommends a StringBuilder, which the check cannot follow, and the guide says which constructs are not reported.
jdaugherty
left a comment
There was a problem hiding this comment.
Minor feedback and then we can merge.
| * the merged loop-head state until that state is stable before findings are reported: an | ||
| * assignment late in the body is seen by a use earlier in it, which the next iteration reaches. | ||
| * {@code break}, {@code continue} and, in a closure, {@code return} carry their state to the | ||
| * exit or head they jump to, and a path ending in such a jump or in {@code throw} contributes |
There was a problem hiding this comment.
A break or continue inside a try that has a finally takes the state from the moment of the jump to its target. But the finally block runs before the jump lands, so anything it assigns is lost:
static void sorted(String sort, List<String> sorts) {
String frag = ' title'
for (String s in sorts) {
try {
if (s == 'stop') break
} finally {
frag = sort
}
frag = ' id'
}
String q = "from Book order by ${frag}"
executeQuery(q) // compiles cleanly; with sorts == ['stop'] it runs as "from Book order by <sort>"
}The same happens with a continue when the query is at the top of the loop body, and with a break out of a switch case. All three compile cleanly on this branch and on 8.0.x, and fail before #16463. I ran each one to confirm that the query really contains sort. The gap comes from #16463, not from this change. It is the same kind of false negative as the cases in #16481, though, so could it be closed here as well?
One way to do it: give each jump made inside the try or a catch the state the finally block ends with, instead of the state at the jump. The walk from intoFinally already starts from a merge of every jump's state. So merging its end state into the exit, or head, of each target jumped to from inside would be enough, and it errs on the safe side.
| } | ||
|
|
||
| @Override | ||
| public void visitClosureExpression(ClosureExpression expression) { |
There was a problem hiding this comment.
A closure that assigns a local declared outside it is now covered, but an anonymous inner class that does the same is not. The pre-scan does not descend into the class body. The class itself is analysed separately, with its own state, so the enclosing method never learns of the assignment:
static void sorted(String sort) {
String frag = ' title'
Runnable r = new Runnable() { void run() { frag = sort } }
r.run()
String q = "from Book order by ${frag}"
executeQuery(q) // compiles cleanly; runs as "from Book order by <sort>"
}This compiles cleanly on this branch and on 8.0.x, and fails before #16463. A Java-style lambda doing the same assignment is already caught, because it is a ClosureExpression. Could the pre-scan treat the method bodies of an anonymous inner class (ConstructorCallExpression.isUsingAnonymousInnerClass()) like a closure body? A local of the enclosing method assigned there would then count as unordered.
| 'closures' | 24 | 'titles.each { String t# ->' | 'println(t1)' | ||
| 'for loops' | 24 | 'for (String t# in titles) {' | 'println(t1)' | ||
| 'for loops appending to a query' | 24 | 'for (String t# in titles) {' | 'q += " and b.title is not null"' | ||
| 'closures appending to a query' | 24 | 'titles.each { String t# ->' | 'q += " and b.title is not null"' |
There was a problem hiding this comment.
Optional, low priority. Nested finally blocks still cost exponential time, because each finally is walked twice (silently from the normal exits, then from intoFinally to report), and a try nested inside it is walked twice on each of those walks. Compiling try { } finally { try { } finally { ... } }:
| depth | this branch | before #16463 |
|---|---|---|
| 16 | 133 ms | 11 ms |
| 18 | 270 ms | 10 ms |
| 20 | 973 ms | 11 ms |
Nobody writes code like this, so it doesn't matter in practice. Still, when silentPasses > 0 and afterFinally != null, the walk from intoFinally throws away both its findings and its end state, so it could be skipped there. That would leave every walk in a silent pass linear. If the fix for jumps through finally ends up using the end state of that walk, skip it only when the try contains no jump. A nested finally row here would keep the time bounded.
| ---- | ||
|
|
||
| The check tells query text and values apart. An interpolation that is *constant text* cannot carry user input, so it is not flagged even when the `GString` is coerced to a `String`. Constant text is a string literal, a `static final` field initialized from constant text, a ternary or Elvis expression choosing between constant text, a `+` concatenation or `GString` made only of constant text, and a local variable that only ever held constant text on every path leading to the query, whichever `if`/`else`, `switch`, `try`/`catch`, loop or closure those paths run through. This is what lets restrictions be chosen at runtime while the values stay bound: | ||
| The check tells query text and values apart. An interpolation that is *constant text* cannot carry user input, so it is not flagged even when the `GString` is coerced to a `String`. Constant text is a string literal, a `static final` field initialized from constant text, a ternary or Elvis expression choosing between constant text, a `+` concatenation or `GString` made only of constant text, and a local variable that only ever held constant text on every path leading to the query, whichever `if`/`else`, `switch`, `try`/`catch` or loop those paths run through. A closure can run at any point after it is defined, and an assignment inside another expression — a ternary or Elvis branch, an `&&` or `||` operand, a method argument or a loop condition — or a multiple assignment may or may not run, so a local that a closure reads or assigns, or that is assigned in one of those ways, counts as constant text only if every assignment to it in the method is constant text. This is what lets restrictions be chosen at runtime while the values stay bound: |
There was a problem hiding this comment.
Nit: "a local that a closure reads or assigns" also covers a local declared inside the closure, which is still tracked in order. The Javadoc wording is more precise: "a local declared outside a closure that the closure reads or assigns".
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## 8.0.x #16482 +/- ##
==================================================
+ Coverage 59.0342% 59.2650% +0.2308%
- Complexity 24550 24713 +163
==================================================
Files 2175 2170 -5
Lines 107668 108008 +340
Branches 19618 19702 +84
==================================================
+ Hits 63561 64011 +450
+ Misses 35224 35121 -103
+ Partials 8883 8876 -7
🚀 New features to boost your workflow:
|
This comment has been minimized.
This comment has been minimized.
A break, continue or closure return inside a try statement carried the state at the jump to its target, but the finally block runs before the jump lands, so an assignment in it was lost. An exception leaving through a finally block lost the same assignments on its way to an enclosing catch. A jump out of a try statement with a finally block is now held until that block has run, and every abrupt way out carries the state the finally block ends with when walked from every path into it. The pre-scan now looks into the methods and initializers of an anonymous inner class, so a local of the enclosing method assigned there counts as assigned out of order, as it does for a closure. In a silent pass, the reporting walk of a finally block is skipped unless a jump or an enclosing handler takes the state it ends with, so nested finally blocks no longer cost exponential time.
A local assigned where the walk cannot place the assignment, read inside a closure that shares it, or read inside an anonymous inner class of the method declaring it was judged by every assignment for constant text only. Its flattened, live or concatenated state was still taken from the walk, which could not see it there, so a GString flattened in a ternary branch, a multiple assignment, a do/while condition, a closure called after a reset or an anonymous inner class compiled cleanly, as did a local flattened after a closure reading it was created. The pre-scan now also settles the worst that any assignment stores in each local, and every such local holds it. An anonymous inner class is checked with the facts of the methods enclosing it, so a local of theirs is judged the same way there, and a query method called on this, written or implied, in a class nested in a domain class is checked when the nested class has no method of that name, since Groovy sends the call on to the domain class. A suppression on an enclosing class or method covers the nested code. A ternary or Elvis expression is classified by its worst branch, and a closure called on the spot, which is what a switch expression compiles to, by its worst result, so a switch expression choosing constant fragments is constant text. Multiple assignment pairs each target with the element of a list literal in its position.
|
I've closed all of the remaining gaps and will merge this. we can iterate if we find more. |
Fixes #16481
A follow-up to #16463. The constant-text tracking that PR added let some locals holding a parameter value pass as constant text. Each case listed in the issue was a build error before #16463, compiles cleanly on
8.0.x, and is a build error again with this change. The fixpoint walk that #16463 added also made compile time grow exponentially with nesting depth.Changes
Locals are tracked per declaration, not per name. The tracking state is keyed by the declaration the compiler resolved each reference to. A loop variable, closure parameter or later local that reuses a name no longer inherits the constant-text status of an earlier, out-of-scope local. This also replaces the bookkeeping that re-armed a suppressed name when it was declared again.
Assignments the walk cannot place in order no longer count as constant text. Some assignments sit in places the walk cannot order:
&&/||operand, a method argument or a loop condition, including ado/whileconditionA pre-scan of each method finds these. A local assigned in one of these ways, or declared outside a closure and read inside it, is constant text only if every assignment to it in the method is constant text. The dynamic-restriction idioms still compile cleanly, including constant text appended inside a closure, a constant chosen by a ternary assignment, and a constant fragment read inside a closure. New no-warning tests cover each of these.
Bodies that cannot change the state are walked once. A loop or closure body that assigns no local declared outside it cannot change the state at its head, so it no longer gets a fixpoint. A nested body that has already settled silently is not walked again just to report. With 24 levels of nested closures or loops, compiling the test class takes 0.06–0.34 s, against about 33 s on
8.0.x.Constructors, field initialisers and object initialisers get a fresh state each. They are analysed like methods, so
@SuppressWarnings("GormUnsafeQueryString")on a constructor now takes effect as it does on a method.The error message no longer recommends
StringBuilder, which the check cannot follow.The guide is updated. It now explains when a local that a closure touches counts as constant text. It also says plainly that text joined from a
List, built with aStringBuilderor returned from a helper is treated as data: it is reported when it is interpolated or concatenated, and not at all when it is passed to the query method on its own.Testing
GormQuerySafetyTransformerSpechas 22 new cases:return8.0.x, exactly 15 cases fail: the 10 false negatives, the 4 nesting bounds and the constructor suppression. Everything else passes on both versions.grails-datamapping-coresuite passes: 1493 tests, 1 skipped, 0 failures. Every module's main and test classes compile with the check active, andaggregateViolationsis clean.