rules(G202): detect SQL concat in ValueSpec declarations; add test sa… #1384
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Summary
-Fixes a gap in G202 where SQL string concatenation defined via ValueSpec declarations wasn’t detected (e.g., var query string = "..." + user).
-Adds a test sample mirroring issue #1309’s reproduction.
-Keeps existing behavior for AssignStmt-based concatenations; extends coverage to ValueSpec.
Motivation
-Issue #1309 shows a common pattern where a query string is built at declaration time via concatenation, then passed to db.Query/Exec. G202 detected AssignStmt concatenations, but missed ValueSpec concatenations. This PR resolves that gap.
What changed
-rules/sql.go (G202): In sqlStrConcat.checkQuery(...), when the SQL argument is an identifier, also handle declarations of type ast.ValueSpec. Reuses findInjectionInBranch on ValueSpec.Values to detect tainted concatenations.
-testutils/g202_samples.go: Added a new CodeSample using Postgres that initializes a query via var query string = "SELECT ..." + username and passes it to db.Query. Expected errors: 1.
Behavior before/after
Before: G202 flagged string concatenation when built via assignment or inline, but not when built at declaration with var query string = "..." + user.
After: G202 flags all these forms, including the ValueSpec case.
Example covered by the new sample
Detected:
var query string = "SELECT ... WHERE username = '" + username + "'"
rows, err := db.Query(query)
Testing
Ran rules tests: 42 passed, 0 failed.
New sample triggers 1 G202 finding as expected.
Risk/compatibility
Low risk: uses the existing binary-concatenation detection and SQL pattern-matching logic; extends it to another declaration form without changing rule semantics.
No user-facing config changes.
Future work
Broader SQL static analysis (e.g., parse queries/params) and integration with tools like sqlvet is out of scope for this PR, but can be explored in follow-ups.
Fixes #1309