Commit ba07333fed

ba07333fedcc7faae1fa010f216d42f1c5903b7d

parent: e21492fd1a

Verified · cmc ci/build: success ci/quality: success ci/test: success

cmc <hello@cleberg.net> · 2026-11-20 20:25 UTC

codescan: set aside string-concat-in-list hits inside calls

A hit counts only where the joined strings are an element of the list or set, not an argument of a call or part of a tuple within it. A file that does not read to the end keeps its hits.

Closes #353

Layout: unified · split

.gitbay/wiki/Admin.org +5
@@ -503,6 +503,11 @@ or stands in for attributes. A hit of
503503=bash/lang/correctness/unquoted-variable-expansion-in-command=, which
504504also reports an expansion inside a =$(( ))= in double quotes, is checked against the script the same way: it
505505counts only where the command has an expansion the shell word-splits.
506A hit of =python/lang/correctness/common-mistakes/string-concat-in-list=
507is set aside where the joined strings sit inside a call or a tuple
508within the brackets, such as a query split over lines in
509=[r for r in conn.execute("select … " "from …")]=, and kept where they
510are an element of the list or set.
506511A file either check cannot read to the end keeps its hits. The issue
507512says how many were set aside
508513and why. A finding a writer dismisses (=repo security dismiss=, by the
internal/codescan/codescan.go +3
@@ -323,6 +323,9 @@ func Body(r Report) string {
323323 if r.Aside.Unsplit > 0 {
324324 notListed = append(notListed, fmt.Sprintf("%d unquoted-expansion hits on expansions the shell does not split", r.Aside.Unsplit))
325325 }
326 if r.Aside.Joined > 0 {
327 notListed = append(notListed, fmt.Sprintf("%d string-concat-in-list hits on strings joined inside a call, not as a list element", r.Aside.Joined))
328 }
326329 if len(notListed) > 0 {
327330 fmt.Fprintf(&b, "\nNot listed: %s. `repo security status %s` shows them.\n", strings.Join(notListed, "; "), r.Repo)
328331 }
internal/codescan/python.go added +207
@@ -0,0 +1,207 @@
1package codescan
2
3import "strings"
4
5// joinedStringRule flags implicitly joined strings ("a" "b") anywhere inside
6// [...] or {...}. A missing comma only matters where the joined string is
7// itself an element of the list or set. Inside a call or a tuple within the
8// brackets, as in [r for r in conn.execute("select … " "from …")], the
9// strings are one argument split over lines on purpose.
10// joinedOutsideLists reads the source to tell those apart.
11const joinedStringRule = "python.lang.correctness.common-mistakes.string-concat-in-list"
12
13// keepJoined returns the lines of a Python file a string-concat-in-list hit
14// is kept on: every line but those joinedOutsideLists returns.
15func keepJoined(src []byte) (map[int]bool, bool) {
16 outside, ok := joinedOutsideLists(src)
17 if !ok {
18 return nil, false
19 }
20 keep := map[int]bool{}
21 for l := 1; l <= strings.Count(string(src), "\n")+1; l++ {
22 if !outside[l] {
23 keep[l] = true
24 }
25 }
26 return keep, true
27}
28
29// joinedOutsideLists returns the lines of a Python file where implicitly
30// joined strings start or continue with ( as their innermost bracket, or
31// none, and no joined string directly inside [ or { touches the line. ok is
32// false when the file does not read to the end with every string and
33// bracket closed.
34func joinedOutsideLists(src []byte) (lines map[int]bool, ok bool) {
35 s := string(src)
36 var brackets []byte
37 inList, outside := map[int]bool{}, map[int]bool{}
38 line := 1
39 // The string just read and whether only space, comments and line
40 // breaks have followed it: the start of a join.
41 prevEnd, prevLine := -1, 0
42 joinStart := 0
43 for i := 0; i < len(s); {
44 c := s[i]
45 switch {
46 case c == '\n':
47 line++
48 i++
49 continue
50 case c == ' ' || c == '\t' || c == '\r' || c == '\f':
51 i++
52 continue
53 case c == '\\' && i+1 < len(s) && s[i+1] == '\n':
54 line++
55 i += 2
56 continue
57 case c == '#':
58 if end := strings.IndexByte(s[i:], '\n'); end >= 0 {
59 i += end
60 } else {
61 i = len(s)
62 }
63 continue
64 }
65 if q, n := stringStart(s, i); n >= 0 {
66 end, l, ok := pyString(s, i+n, q, strings.ContainsAny(strings.ToLower(s[i:i+n]), "f"))
67 if !ok {
68 return nil, false
69 }
70 if prevEnd >= 0 {
71 if joinStart == 0 {
72 joinStart = prevLine
73 }
74 mark := outside
75 if len(brackets) > 0 && brackets[len(brackets)-1] != '(' {
76 mark = inList
77 }
78 for k := joinStart; k <= line+l; k++ {
79 mark[k] = true
80 }
81 } else {
82 joinStart = 0
83 }
84 prevEnd, prevLine = end, line
85 line += l
86 i = end
87 continue
88 }
89 prevEnd, joinStart = -1, 0
90 switch c {
91 case '(', '[', '{':
92 brackets = append(brackets, c)
93 case ')', ']', '}':
94 if len(brackets) == 0 || brackets[len(brackets)-1] != map[byte]byte{')': '(', ']': '[', '}': '{'}[c] {
95 return nil, false
96 }
97 brackets = brackets[:len(brackets)-1]
98 }
99 i++
100 }
101 if len(brackets) > 0 {
102 return nil, false
103 }
104 for l := range inList {
105 delete(outside, l)
106 }
107 return outside, true
108}
109
110// stringStart reports whether a string literal opens at i: its quote, and
111// the length of its prefix (r, b, u, f and pairs of them), or -1.
112func stringStart(s string, i int) (quote string, n int) {
113 j := i
114 for j < len(s) && j-i < 2 && strings.IndexByte("rRbBuUfF", s[j]) >= 0 {
115 j++
116 }
117 if j < len(s) && (s[j] == '"' || s[j] == '\'') {
118 if j > i && isIdentByte(s, i-1) {
119 return "", -1
120 }
121 q := s[j : j+1]
122 if strings.HasPrefix(s[j:], strings.Repeat(q, 3)) {
123 q = strings.Repeat(q, 3)
124 }
125 return q, j - i
126 }
127 return "", -1
128}
129
130func isIdentByte(s string, i int) bool {
131 if i < 0 {
132 return false
133 }
134 c := s[i]
135 return c == '_' || isLetter(c) || c >= '0' && c <= '9' || c >= 0x80
136}
137
138// pyString reads a string from i, the start of its quote q, to just past its
139// closing quote. lines is how many line breaks it spans. In an f-string the
140// expressions in braces are skipped with their own strings and brackets.
141func pyString(s string, i int, q string, f bool) (end, lines int, ok bool) {
142 j := i + len(q)
143 for j < len(s) {
144 c := s[j]
145 switch {
146 case strings.HasPrefix(s[j:], q):
147 return j + len(q), lines, true
148 case c == '\\':
149 if j+1 < len(s) && s[j+1] == '\n' {
150 lines++
151 }
152 j += 2
153 continue
154 case c == '\n':
155 if len(q) == 1 {
156 return 0, 0, false
157 }
158 lines++
159 case f && c == '{' && strings.HasPrefix(s[j:], "{{"):
160 j += 2
161 continue
162 case f && c == '{':
163 n, l, ok := fieldEnd(s, j+1)
164 if !ok {
165 return 0, 0, false
166 }
167 lines += l
168 j = n
169 continue
170 }
171 j++
172 }
173 return 0, 0, false
174}
175
176// fieldEnd reads an f-string replacement field from i, just past its {, to
177// just past its }.
178func fieldEnd(s string, i int) (end, lines int, ok bool) {
179 depth := 0
180 for i < len(s) {
181 c := s[i]
182 if q, n := stringStart(s, i); n >= 0 {
183 e, l, ok := pyString(s, i+n, q, strings.ContainsAny(strings.ToLower(s[i:i+n]), "f"))
184 if !ok {
185 return 0, 0, false
186 }
187 lines += l
188 i = e
189 continue
190 }
191 switch c {
192 case '\n':
193 lines++
194 case '(', '[', '{':
195 depth++
196 case ')', ']':
197 depth--
198 case '}':
199 if depth == 0 {
200 return i + 1, lines, true
201 }
202 depth--
203 }
204 i++
205 }
206 return 0, 0, false
207}
internal/codescan/python_test.go added +77
@@ -0,0 +1,77 @@
1package codescan
2
3import (
4 "errors"
5 "testing"
6
7 "gitbay.org/gitbay/internal/store"
8)
9
10func TestJoinedOutsideLists(t *testing.T) {
11 for _, tc := range []struct {
12 name, src string
13 line int
14 want bool
15 }{
16 {"call in a comprehension", "rows = [\n r[\"a\"]\n for r in conn.execute(\n \"select a \"\n \"from t\",\n (x,),\n )\n]\n", 4, true},
17 {"call in a list", "rules = [\n Rule(\n \"name\",\n \"one message \"\n \"over two lines\",\n ),\n]\n", 4, true},
18 {"tuple in a list", "[(\"a\" \"b\", 1)]\n", 1, true},
19 {"list element", "names = [\n \"alpha\"\n \"beta\",\n]\n", 2, false},
20 {"set element", "{\"a\" \"b\", \"c\"}\n", 1, false},
21 {"one-element list", "raise Failed([\n \"a message \"\n \"over two lines\"\n])\n", 2, false},
22 {"list and call on one line", "[\"a\" \"b\", f(\"c\" \"d\")]\n", 1, false},
23 {"f-string with nested quotes", "[f(f\"{x[\"k\"]}\" \"y\")]\n", 1, true},
24 {"triple-quoted", "[g(\"\"\"a\nb\"\"\" \"c\")]\n", 1, true},
25 {"comment between", "[g(\"a\" # note ]\n \"b\")]\n", 1, true},
26 {"no join on the line", "[g(\"a\")]\n", 1, false},
27 } {
28 lines, ok := joinedOutsideLists([]byte(tc.src))
29 if !ok {
30 t.Errorf("%s: not read", tc.name)
31 continue
32 }
33 if lines[tc.line] != tc.want {
34 t.Errorf("%s: line %d outside = %v, want %v (%v)", tc.name, tc.line, lines[tc.line], tc.want, lines)
35 }
36 }
37 for _, src := range []string{`x = ["a`, `x = ("a" "b"`, "x = '''a", `x = f"{y"`, `x = )`} {
38 if _, ok := joinedOutsideLists([]byte(src)); ok {
39 t.Errorf("%q read", src)
40 }
41 }
42}
43
44func TestScopeChecksJoinedStrings(t *testing.T) {
45 rule := "opt.opengrep-rules.python.lang.correctness.common-mistakes.string-concat-in-list"
46 files := map[string]string{
47 "call.py": "x = [\n f(\n \"a \"\n \"b\"\n )\n]\n",
48 "list.py": "x = [\n \"a\"\n \"b\",\n]\n",
49 "broken.py": "x = [f(\"a\" \"b\"\n",
50 }
51 read := func(p string) ([]byte, error) {
52 if src, ok := files[p]; ok {
53 return []byte(src), nil
54 }
55 return nil, errors.New("missing")
56 }
57 findings := []store.SecurityFinding{
58 {Rule: rule, Path: "call.py", Line: 3},
59 {Rule: rule, Path: "list.py", Line: 2},
60 {Rule: rule, Path: "call.py", Line: 1},
61 {Rule: rule, Path: "broken.py", Line: 1},
62 {Rule: rule, Path: "gone.py", Line: 1},
63 {Rule: "other", Path: "call.py", Line: 3},
64 }
65 kept, aside, _ := Scope{Read: read}.Apply(findings)
66 if aside.Joined != 1 || len(kept) != 5 {
67 t.Fatalf("kept %+v aside %+v", kept, aside)
68 }
69 for _, f := range kept {
70 if f.Path == "call.py" && f.Line == 3 && f.Rule == rule {
71 t.Errorf("joined-in-a-call hit kept")
72 }
73 }
74 if kept, aside, _ := (Scope{}).Apply(findings); aside.Joined != 0 || len(kept) != 6 {
75 t.Errorf("without Read: kept %d aside %+v", len(kept), aside)
76 }
77}
internal/codescan/scope.go +9 −3
@@ -29,17 +29,19 @@ type Scope struct {
2929// Aside counts the findings a scope set aside: Ignored by path or rule,
3030// Unused by the library a rule is about, Quoted by reading the template an
3131// unquoted-attribute hit is in, Unsplit by reading the script an
32// unquoted-expansion hit is in.
32// unquoted-expansion hit is in, Joined by reading the Python file a
33// string-concat-in-list hit is in.
3334type Aside struct {
3435 Ignored int `json:"ignored,omitempty"`
3536 Unused map[string]int `json:"unused,omitempty"`
3637 Quoted int `json:"quoted,omitempty"`
3738 Unsplit int `json:"unsplit,omitempty"`
39 Joined int `json:"joined,omitempty"`
3840}
3941
4042// Any reports whether anything was set aside.
4143func (a Aside) Any() bool {
42 return a.Ignored > 0 || len(a.Unused) > 0 || a.Quoted > 0 || a.Unsplit > 0
44 return a.Ignored > 0 || len(a.Unused) > 0 || a.Quoted > 0 || a.Unsplit > 0 || a.Joined > 0
4345}
4446
4547// Apply splits findings into those reported, at most MaxFindings of them,
@@ -49,7 +51,7 @@ func (s Scope) Apply(findings []store.SecurityFinding) ([]store.SecurityFinding,
4951 var kept []store.SecurityFinding
5052 var aside Aside
5153 truncated := false
52 unquoted, unsplit := map[string]map[int]bool{}, map[string]map[int]bool{}
54 unquoted, unsplit, joined := map[string]map[int]bool{}, map[string]map[int]bool{}, map[string]map[int]bool{}
5355 for _, f := range findings {
5456 if s.ignored(f) {
5557 aside.Ignored++
@@ -70,6 +72,10 @@ func (s Scope) Apply(findings []store.SecurityFinding) ([]store.SecurityFinding,
7072 aside.Unsplit++
7173 continue
7274 }
75 if ruleIn(f.Rule, joinedStringRule) && !s.onLine(f, joined, keepJoined) {
76 aside.Joined++
77 continue
78 }
7379 if len(kept) == MaxFindings {
7480 truncated = true
7581 continue
internal/control/security.go +3
@@ -494,6 +494,9 @@ func asideText(a codescan.Aside) string {
494494 if a.Unsplit > 0 {
495495 parts = append(parts, fmt.Sprintf("%d unsplit expansions", a.Unsplit))
496496 }
497 if a.Joined > 0 {
498 parts = append(parts, fmt.Sprintf("%d strings joined in calls", a.Joined))
499 }
497500 return strings.Join(parts, ", ")
498501}
499502
internal/web/templates/settings.html +1 −1
@@ -188,7 +188,7 @@
188188</form>{{end}}
189189{{if .Security.Enabled}}
190190<p class="meta">Next scan {{.Security.NextRun}} · last results {{if .Security.LastResults}}{{when .Security.LastResults}}{{else}}never{{end}}{{if .Security.IssueNumber}} · <a href="/{{.Repo.OwnerName}}/{{.Repo.Name}}/issues/{{.Security.IssueNumber}}">#{{.Security.IssueNumber}}</a>{{end}}</p>
191{{with .Security.Aside}}{{if .Any}}<p class="meta">Set aside by the last scan:{{if .Ignored}} {{.Ignored}} under the paths or rules below, or marked vendored or generated in <code>.gitattributes</code>.{{end}}{{range $lib, $n := .Unused}} {{$n}} from {{$lib}} rules, which no manifest names.{{end}}{{if .Quoted}} {{.Quoted}} unquoted-attribute hits on attributes the template quotes.{{end}}{{if .Unsplit}} {{.Unsplit}} unquoted-expansion hits on expansions the shell does not split.{{end}}</p>{{end}}{{end}}
191{{with .Security.Aside}}{{if .Any}}<p class="meta">Set aside by the last scan:{{if .Ignored}} {{.Ignored}} under the paths or rules below, or marked vendored or generated in <code>.gitattributes</code>.{{end}}{{range $lib, $n := .Unused}} {{$n}} from {{$lib}} rules, which no manifest names.{{end}}{{if .Quoted}} {{.Quoted}} unquoted-attribute hits on attributes the template quotes.{{end}}{{if .Unsplit}} {{.Unsplit}} unquoted-expansion hits on expansions the shell does not split.{{end}}{{if .Joined}} {{.Joined}} string-concat-in-list hits on strings joined inside a call, not as a list element.{{end}}</p>{{end}}{{end}}
192192{{if .Security.Findings}}<div class="tablewrap"><table class="keys">
193193<tr class="cols"><th scope="col">location</th><th scope="col">rule</th><th scope="col">level</th><th scope="col"><span class="vh">dismiss</span></th></tr>
194194{{range .Security.Findings}}<tr>