Commit 22770ebc07

22770ebc07798652622de50b1ea036186d3781e9

parent: ba07333fed

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

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

codescan: set aside lambda returns, is_ attributes and random in tests

Return hits count only on a line with a return statement. An is-function-without-parentheses hit is set aside where the repository's Python files define the name only as an attribute or property. insecure-random hits in test paths are set aside. The scope carries the commit's file list for the second.

Closes #354

Layout: unified · split

.gitbay/wiki/Admin.org +10
@@ -508,6 +508,16 @@ is set aside where the joined strings sit inside a call or a tuple
508508within the brackets, such as a query split over lines in
509509=[r for r in conn.execute("select … " "from …")]=, and kept where they
510510are an element of the list or set.
511=python/lang/maintainability/return-not-in-function= and
512=python/lang/correctness/return-in-init= hits count only on a line with
513a =return= statement: the rules read a =lambda='s body as one. An
514=is-function-without-parentheses= hit is set aside where the
515repository's Python files define the =is_= name only as an attribute,
516by annotation, assignment or =@property=, and never by a plain =def=.
517=insecure-random= hits in tests are set aside: a =test=, =tests=,
518=__tests__=, =spec= or =testdata= directory, one ending in =Tests=, or a
519file named as a test (=*_test.go=, =test_*.py=, =*.test.js=,
520=*Tests.swift=, …).
511521A file either check cannot read to the end keeps its hits. The issue
512522says how many were set aside
513523and why. A finding a writer dismisses (=repo security dismiss=, by the
internal/codescan/codescan.go +9
@@ -326,6 +326,15 @@ func Body(r Report) string {
326326 if r.Aside.Joined > 0 {
327327 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))
328328 }
329 if r.Aside.NoReturn > 0 {
330 notListed = append(notListed, fmt.Sprintf("%d return hits on lines with no return statement", r.Aside.NoReturn))
331 }
332 if r.Aside.Attributes > 0 {
333 notListed = append(notListed, fmt.Sprintf("%d is-function-without-parentheses hits on names the repository defines as attributes", r.Aside.Attributes))
334 }
335 if r.Aside.InTests > 0 {
336 notListed = append(notListed, fmt.Sprintf("%d insecure-random hits in tests", r.Aside.InTests))
337 }
329338 if len(notListed) > 0 {
330339 fmt.Fprintf(&b, "\nNot listed: %s. `repo security status %s` shows them.\n", strings.Join(notListed, "; "), r.Repo)
331340 }
internal/codescan/python.go +117 −1
@@ -1,6 +1,10 @@
11package codescan
22
3import "strings"
3import (
4 "regexp"
5 "slices"
6 "strings"
7)
48
59// joinedStringRule flags implicitly joined strings ("a" "b") anywhere inside
610// [...] or {...}. A missing comma only matters where the joined string is
@@ -205,3 +209,115 @@ func fieldEnd(s string, i int) (end, lines int, ok bool) {
205209 }
206210 return 0, 0, false
207211}
212
213// returnRules are about a return statement. Opengrep reads a lambda's body
214// as one, so a lambda in a module-level dict, or a sort key in __init__, is
215// reported as a return. returnLines reads the file for the lines that have
216// one.
217var returnRules = []string{
218 "python.lang.maintainability.return-not-in-function",
219 "python.lang.correctness.return-in-init",
220}
221
222// returnLines returns the lines of a Python file with the keyword return
223// outside strings and comments. ok is false when a string is not closed.
224func returnLines(src []byte) (lines map[int]bool, ok bool) {
225 s := string(src)
226 lines = map[int]bool{}
227 line := 1
228 for i := 0; i < len(s); {
229 c := s[i]
230 switch {
231 case c == '\n':
232 line++
233 i++
234 continue
235 case c == '#':
236 if end := strings.IndexByte(s[i:], '\n'); end >= 0 {
237 i += end
238 } else {
239 i = len(s)
240 }
241 continue
242 }
243 if q, n := stringStart(s, i); n >= 0 {
244 end, l, ok := pyString(s, i+n, q, strings.ContainsAny(strings.ToLower(s[i:i+n]), "f"))
245 if !ok {
246 return nil, false
247 }
248 line += l
249 i = end
250 continue
251 }
252 if c == '_' || isLetter(c) || c >= 0x80 {
253 j := i
254 for j < len(s) && isIdentByte(s, j) {
255 j++
256 }
257 if s[i:j] == "return" {
258 lines[line] = true
259 }
260 i = j
261 continue
262 }
263 i++
264 }
265 return lines, true
266}
267
268// attrCallRule flags x.is_name that is not called, asking whether is_name is
269// a method. Where the repository defines is_name only as an attribute or a
270// property, it is not one.
271const attrCallRule = "python.lang.maintainability.is-function-without-parentheses"
272
273// attrCallName is the name in the rule's message.
274var attrCallName = regexp.MustCompile(`^Is "(is_\w+)" a function`)
275
276var (
277 pyDef = regexp.MustCompile(`^(?:async[ \t]+)?def[ \t]+(is_\w+)[ \t]*\(`)
278 // An annotation starts the line; an assignment may be to self.is_name.
279 pyAttr = regexp.MustCompile(`^(is_\w+)[ \t]*(?::[^=]|:$|=[^=])|^[\w.]*\.(is_\w+)[ \t]*=[^=]`)
280)
281
282// pyNames are the is_ names a repository's Python files define: as methods,
283// by a def without a property decorator, and as attributes, by an
284// annotation, an assignment or a property.
285type pyNames struct {
286 methods, attrs map[string]bool
287}
288
289// add reads one file's definitions.
290func (n pyNames) add(src []byte) {
291 var decorators []string
292 for _, raw := range strings.Split(string(src), "\n") {
293 text := strings.TrimSpace(raw)
294 switch {
295 case text == "" || strings.HasPrefix(text, "#"):
296 continue
297 case strings.HasPrefix(text, "@"):
298 decorators = append(decorators, text)
299 continue
300 }
301 if m := pyDef.FindStringSubmatch(text); m != nil {
302 if slices.ContainsFunc(decorators, isProperty) {
303 n.attrs[m[1]] = true
304 } else {
305 n.methods[m[1]] = true
306 }
307 } else if m := pyAttr.FindStringSubmatch(text); m != nil {
308 n.attrs[m[1]+m[2]] = true
309 }
310 decorators = nil
311 }
312}
313
314func isProperty(decorator string) bool {
315 name, _, _ := strings.Cut(strings.TrimPrefix(decorator, "@"), "(")
316 return name == "property" || strings.HasSuffix(name, "cached_property") || strings.HasSuffix(name, ".setter")
317}
318
319// attribute reports whether the repository defines name as an attribute and
320// never as a method.
321func (n pyNames) attribute(name string) bool {
322 return n.attrs[name] && !n.methods[name]
323}
internal/codescan/python_test.go +100
@@ -75,3 +75,103 @@ func TestScopeChecksJoinedStrings(t *testing.T) {
7575 t.Errorf("without Read: kept %d aside %+v", len(kept), aside)
7676 }
7777}
78
79func TestReturnLines(t *testing.T) {
80 src := "TARGETS = {\n" +
81 " \"a\": lambda p: f\"x:{p['k']}\",\n" +
82 "}\n" +
83 "def f(x):\n" +
84 " return (\n" +
85 " x\n" +
86 " )\n" +
87 "s = \"return\" # return\n" +
88 "returned = 1\n" +
89 "class A:\n" +
90 " def __init__(self):\n" +
91 " self.k = sorted(r, key=lambda r: r[0])\n"
92 lines, ok := returnLines([]byte(src))
93 if !ok || len(lines) != 1 || !lines[5] {
94 t.Errorf("lines = %v ok %v", lines, ok)
95 }
96 if _, ok := returnLines([]byte("x = 'open\n")); ok {
97 t.Error("unclosed string read")
98 }
99}
100
101func TestPyNames(t *testing.T) {
102 n := pyNames{methods: map[string]bool{}, attrs: map[string]bool{}}
103 n.add([]byte("@dataclass\nclass Actor:\n is_admin: bool\n is_owner: bool = False\n" +
104 " @property\n def is_active(self):\n return True\n" +
105 " @functools.cached_property\n def is_cached(self):\n return True\n" +
106 " def is_method(self):\n return True\n" +
107 " async def is_async(self):\n return True\n"))
108 n.add([]byte("class B:\n def __init__(self):\n self.is_set = True\n" +
109 "def f(user):\n if user.is_used:\n return user.is_used2\n" +
110 "x.is_compared == 1\n"))
111 for name, want := range map[string]bool{
112 "is_admin": true, "is_owner": true, "is_active": true, "is_cached": true, "is_set": true,
113 "is_method": false, "is_async": false, "is_used": false, "is_used2": false, "is_compared": false, "is_unknown": false,
114 } {
115 if got := n.attribute(name); got != want {
116 t.Errorf("%s: attribute = %v, want %v", name, got, want)
117 }
118 }
119 n.add([]byte("class C:\n def is_admin(self):\n return False\n"))
120 if n.attribute("is_admin") {
121 t.Error("is_admin is a method somewhere and still an attribute")
122 }
123}
124
125func TestTestPath(t *testing.T) {
126 for p, want := range map[string]bool{
127 "Tests/OrgCoreTests/CalcTests.swift": true,
128 "Sources/App/AppTests.swift": true,
129 "internal/x/x_test.go": true,
130 "tests/web/test_views.py": true,
131 "pkg/test_util.py": true,
132 "src/__tests__/a.js": true,
133 "web/src/api.test.ts": true,
134 "conftest.py": true,
135 "Sources/CityAppKit/Audio/AudioMix.swift": false,
136 "src/latest.py": false,
137 "contest/main.go": false,
138 } {
139 if got := testPath(p); got != want {
140 t.Errorf("%s: test = %v, want %v", p, got, want)
141 }
142 }
143}
144
145func TestScopeChecksPythonNamesReturnsAndTests(t *testing.T) {
146 files := map[string]string{
147 "app/users.py": "@dataclass\nclass Actor:\n is_admin: bool\n def is_live(self):\n return True\n",
148 "app/records.py": "T = {\n \"a\": lambda p: p,\n}\ndef f():\n return 1\n",
149 "vendor/x.py": "def is_admin(self):\n pass\n",
150 }
151 read := func(p string) ([]byte, error) {
152 if src, ok := files[p]; ok {
153 return []byte(src), nil
154 }
155 return nil, errors.New("missing")
156 }
157 attr := "opt.opengrep-rules.python.lang.maintainability.is-function-without-parentheses"
158 ret := "opt.opengrep-rules.python.lang.maintainability.return-not-in-function"
159 rnd := "opt.opengrep-rules.swift.lang.crypto.insecure-random"
160 findings := []store.SecurityFinding{
161 {Rule: attr, Path: "app/views.py", Line: 3, Message: `Is "is_admin" a function or an attribute? …`},
162 {Rule: attr, Path: "app/views.py", Line: 4, Message: `Is "is_live" a function or an attribute? …`},
163 {Rule: attr, Path: "app/views.py", Line: 5, Message: `Is "is_dir" a function or an attribute? …`},
164 {Rule: ret, Path: "app/records.py", Line: 2},
165 {Rule: ret, Path: "app/records.py", Line: 5},
166 {Rule: rnd, Path: "Tests/CoreTests/CalcTests.swift", Line: 1},
167 {Rule: rnd, Path: "Sources/Audio/Mix.swift", Line: 1},
168 }
169 paths := []string{"app/users.py", "app/records.py", "vendor/x.py", "README.md"}
170 kept, aside, _ := Scope{Read: read, Paths: paths}.Apply(findings)
171 if aside.Attributes != 1 || aside.NoReturn != 1 || aside.InTests != 1 || len(kept) != 4 {
172 t.Fatalf("kept %+v aside %+v", kept, aside)
173 }
174 if kept, aside, _ := (Scope{Read: read}).Apply(findings); aside.Attributes != 0 || len(kept) != 5 {
175 t.Errorf("without Paths: kept %d aside %+v", len(kept), aside)
176 }
177}
internal/codescan/scope.go +75 −7
@@ -4,6 +4,7 @@ import (
44 "bufio"
55 "bytes"
66 "path"
7 "slices"
78 "strings"
89
910 "gitbay.org/gitbay/internal/ci"
@@ -24,24 +25,37 @@ type Scope struct {
2425 // Read returns a file at the scanned commit, for rules whose hits are
2526 // checked against the source. Nil checks nothing.
2627 Read func(path string) ([]byte, error)
28 // Paths are the files at the scanned commit, for rules whose hits are
29 // checked against the rest of the repository. Nil checks nothing.
30 Paths []string
2731}
2832
33// maxPythonFiles bounds how many Python files a scope reads for the names
34// they define.
35const maxPythonFiles = 2000
36
2937// Aside counts the findings a scope set aside: Ignored by path or rule,
3038// Unused by the library a rule is about, Quoted by reading the template an
3139// unquoted-attribute hit is in, Unsplit by reading the script an
3240// unquoted-expansion hit is in, Joined by reading the Python file a
33// string-concat-in-list hit is in.
41// string-concat-in-list hit is in, NoReturn by reading the line a return
42// hit is on, Attributes by reading what the repository defines an
43// is_ name as, InTests by the path of an insecure-random hit.
3444type Aside struct {
35 Ignored int `json:"ignored,omitempty"`
36 Unused map[string]int `json:"unused,omitempty"`
37 Quoted int `json:"quoted,omitempty"`
38 Unsplit int `json:"unsplit,omitempty"`
39 Joined int `json:"joined,omitempty"`
45 Ignored int `json:"ignored,omitempty"`
46 Unused map[string]int `json:"unused,omitempty"`
47 Quoted int `json:"quoted,omitempty"`
48 Unsplit int `json:"unsplit,omitempty"`
49 Joined int `json:"joined,omitempty"`
50 NoReturn int `json:"no_return,omitempty"`
51 Attributes int `json:"attributes,omitempty"`
52 InTests int `json:"in_tests,omitempty"`
4053}
4154
4255// Any reports whether anything was set aside.
4356func (a Aside) Any() bool {
44 return a.Ignored > 0 || len(a.Unused) > 0 || a.Quoted > 0 || a.Unsplit > 0 || a.Joined > 0
57 return a.Ignored > 0 || len(a.Unused) > 0 || a.Quoted > 0 || a.Unsplit > 0 || a.Joined > 0 ||
58 a.NoReturn > 0 || a.Attributes > 0 || a.InTests > 0
4559}
4660
4761// Apply splits findings into those reported, at most MaxFindings of them,
@@ -52,6 +66,8 @@ func (s Scope) Apply(findings []store.SecurityFinding) ([]store.SecurityFinding,
5266 var aside Aside
5367 truncated := false
5468 unquoted, unsplit, joined := map[string]map[int]bool{}, map[string]map[int]bool{}, map[string]map[int]bool{}
69 returns := map[string]map[int]bool{}
70 var names *pyNames
5571 for _, f := range findings {
5672 if s.ignored(f) {
5773 aside.Ignored++
@@ -76,6 +92,18 @@ func (s Scope) Apply(findings []store.SecurityFinding) ([]store.SecurityFinding,
7692 aside.Joined++
7793 continue
7894 }
95 if slices.ContainsFunc(returnRules, func(r string) bool { return ruleIn(f.Rule, r) }) && !s.onLine(f, returns, returnLines) {
96 aside.NoReturn++
97 continue
98 }
99 if ruleIn(f.Rule, attrCallRule) && s.attribute(f, &names) {
100 aside.Attributes++
101 continue
102 }
103 if ruleIn(f.Rule, insecureRandomRule) && testPath(f.Path) {
104 aside.InTests++
105 continue
106 }
79107 if len(kept) == MaxFindings {
80108 truncated = true
81109 continue
@@ -103,6 +131,46 @@ func (s Scope) onLine(f store.SecurityFinding, seen map[string]map[int]bool, lin
103131 return marked == nil || marked[f.Line]
104132}
105133
134// attribute reports whether an is-function-without-parentheses hit names
135// something the repository's Python files define as an attribute and never
136// as a method. The files are read on the first such hit, into names.
137func (s Scope) attribute(f store.SecurityFinding, names **pyNames) bool {
138 m := attrCallName.FindStringSubmatch(f.Message)
139 if m == nil || s.Read == nil || s.Paths == nil {
140 return false
141 }
142 if *names == nil {
143 n := pyNames{methods: map[string]bool{}, attrs: map[string]bool{}}
144 read := 0
145 for _, p := range s.Paths {
146 if !strings.HasSuffix(p, ".py") || otherProject(p) {
147 continue
148 }
149 if read == maxPythonFiles {
150 break
151 }
152 read++
153 if src, err := s.Read(p); err == nil {
154 n.add(src)
155 }
156 }
157 *names = &n
158 }
159 return (*names).attribute(m[1])
160}
161
162// otherProject reports whether a path is inside a directory of other
163// projects' code or an environment.
164func otherProject(p string) bool {
165 for _, part := range strings.Split(path.Dir(p), "/") {
166 switch part {
167 case "node_modules", "vendor", "third_party", "site-packages", ".venv", "venv":
168 return true
169 }
170 }
171 return false
172}
173
106174func (s Scope) ignored(f store.SecurityFinding) bool {
107175 for _, g := range s.Ignore {
108176 if ci.Match(g, f.Path) {
internal/codescan/tests.go added +35
@@ -0,0 +1,35 @@
1package codescan
2
3import (
4 "path"
5 "strings"
6)
7
8// insecureRandomRule flags random number generators that are not
9// cryptographically secure. In a test the numbers protect nothing.
10const insecureRandomRule = "insecure-random"
11
12// testPath reports whether a path is a test by the usual layouts: a tests
13// directory, or a file named as one.
14func testPath(p string) bool {
15 dirs := strings.Split(path.Dir(p), "/")
16 for _, d := range dirs {
17 switch {
18 case d == "test", d == "tests", d == "__tests__", d == "spec", d == "testdata", strings.HasSuffix(d, "Tests"):
19 return true
20 }
21 }
22 base := path.Base(p)
23 stem := strings.TrimSuffix(base, path.Ext(base))
24 switch {
25 case strings.HasSuffix(base, "_test.go"),
26 strings.HasPrefix(base, "test_") && strings.HasSuffix(base, ".py"),
27 strings.HasSuffix(base, "_test.py"),
28 base == "conftest.py",
29 strings.HasSuffix(stem, ".test"), strings.HasSuffix(stem, ".spec"),
30 path.Ext(base) == ".swift" && (strings.HasSuffix(stem, "Tests") || strings.HasSuffix(stem, "Test")),
31 (path.Ext(base) == ".java" || path.Ext(base) == ".kt") && strings.HasSuffix(stem, "Test"):
32 return true
33 }
34 return false
35}
internal/control/security.go +11
@@ -417,7 +417,9 @@ func scanScope(dir string, repo store.Repo, sha string) codescan.Scope {
417417 dirs := []string{""}
418418 if entries, err := gitutil.ListTreeRecursive(dir, sha, ""); err == nil {
419419 seen := map[string]bool{"": true}
420 sc.Paths = make([]string, 0, len(entries))
420421 for _, e := range entries {
422 sc.Paths = append(sc.Paths, e.Name)
421423 d := path.Dir(e.Name)
422424 if seen[d] || len(dirs) == maxManifestDirs || !slices.Contains(deps.ManifestFiles, path.Base(e.Name)) || dependencyDir(d) {
423425 continue
@@ -497,6 +499,15 @@ func asideText(a codescan.Aside) string {
497499 if a.Joined > 0 {
498500 parts = append(parts, fmt.Sprintf("%d strings joined in calls", a.Joined))
499501 }
502 if a.NoReturn > 0 {
503 parts = append(parts, fmt.Sprintf("%d lines with no return", a.NoReturn))
504 }
505 if a.Attributes > 0 {
506 parts = append(parts, fmt.Sprintf("%d is_ attributes", a.Attributes))
507 }
508 if a.InTests > 0 {
509 parts = append(parts, fmt.Sprintf("%d random in tests", a.InTests))
510 }
500511 return strings.Join(parts, ", ")
501512}
502513
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}}{{if .Joined}} {{.Joined}} string-concat-in-list hits on strings joined inside a call, not as a list element.{{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}}{{if .NoReturn}} {{.NoReturn}} return hits on lines with no return statement.{{end}}{{if .Attributes}} {{.Attributes}} is-function-without-parentheses hits on names the repository defines as attributes.{{end}}{{if .InTests}} {{.InTests}} insecure-random hits in tests.{{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>