codewatch-scan 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (136) hide show
  1. codewatch/__init__.py +0 -0
  2. codewatch/__main__.py +14 -0
  3. codewatch/asgi.py +16 -0
  4. codewatch/settings.py +175 -0
  5. codewatch/urls.py +40 -0
  6. codewatch/wsgi.py +16 -0
  7. codewatch_scan-0.1.0.dist-info/METADATA +81 -0
  8. codewatch_scan-0.1.0.dist-info/RECORD +136 -0
  9. codewatch_scan-0.1.0.dist-info/WHEEL +5 -0
  10. codewatch_scan-0.1.0.dist-info/entry_points.txt +4 -0
  11. codewatch_scan-0.1.0.dist-info/licenses/LICENSE +21 -0
  12. codewatch_scan-0.1.0.dist-info/top_level.txt +2 -0
  13. core/__init__.py +0 -0
  14. core/analyzers/__init__.py +19 -0
  15. core/analyzers/accessibility.py +199 -0
  16. core/analyzers/base.py +192 -0
  17. core/analyzers/body_models.py +154 -0
  18. core/analyzers/codewatch_checks.py +394 -0
  19. core/analyzers/constant_branches.py +251 -0
  20. core/analyzers/containers.py +316 -0
  21. core/analyzers/coverage.py +131 -0
  22. core/analyzers/dependencies.py +347 -0
  23. core/analyzers/drf_serializers.py +65 -0
  24. core/analyzers/else_branches.py +106 -0
  25. core/analyzers/extra.py +400 -0
  26. core/analyzers/flask_resources.py +65 -0
  27. core/analyzers/inline_scripts.py +50 -0
  28. core/analyzers/jinja_sandboxes.py +63 -0
  29. core/analyzers/match_statements.py +148 -0
  30. core/analyzers/multi_tools.py +888 -0
  31. core/analyzers/php_template_sinks.py +444 -0
  32. core/analyzers/project_checks.py +150 -0
  33. core/analyzers/python_tools.py +333 -0
  34. core/analyzers/route_converters.py +237 -0
  35. core/analyzers/slices.py +94 -0
  36. core/analyzers/starred_targets.py +42 -0
  37. core/analyzers/stored_fields.py +386 -0
  38. core/analyzers/summaries.py +1387 -0
  39. core/analyzers/template_sinks.py +162 -0
  40. core/api.py +360 -0
  41. core/apps.py +6 -0
  42. core/benchmark.py +955 -0
  43. core/bundled/catalog/codewatch/rules/javascript-crypto.yml +224 -0
  44. core/bundled/catalog/codewatch/rules/javascript-injection.yml +116 -0
  45. core/bundled/catalog/codewatch/rules/javascript-taint.yml +1539 -0
  46. core/bundled/catalog/codewatch/rules/javascript-web.yml +562 -0
  47. core/bundled/catalog/codewatch/rules/php-web.yml +719 -0
  48. core/bundled/catalog/codewatch/rules/python-crypto.yml +203 -0
  49. core/bundled/catalog/codewatch/rules/python-django.yml +267 -0
  50. core/bundled/catalog/codewatch/rules/python-injection.yml +115 -0
  51. core/bundled/catalog/codewatch/rules/python-web.yml +3382 -0
  52. core/bundled/catalog/custom/mappings.json +360 -0
  53. core/bundled/catalog/custom/overrides.json +4 -0
  54. core/bundled/catalog/custom/rules/django-settings.yml +19 -0
  55. core/bundled/catalog/imported/changes.json +5 -0
  56. core/bundled/catalog/imported/docs.json +1143 -0
  57. core/bundled/catalog/imported/meta.json +54 -0
  58. core/bundled/catalog/imported/rules.json +85421 -0
  59. core/bundled/catalog/imported/standards.json +11191 -0
  60. core/bundled/tools/analyzers.lock +786 -0
  61. core/bundled/tools/axe-scan.mjs +45 -0
  62. core/bundled/tools/checkov.lock +2463 -0
  63. core/bundled/tools/codewatch-checks.mjs +99 -0
  64. core/bundled/tools/eslint-a11y.config.js +16 -0
  65. core/bundled/tools/eslint-quality.config.js +63 -0
  66. core/bundled/tools/eslint-typed.config.js +18 -0
  67. core/bundled/tools/package-lock.json +6102 -0
  68. core/bundled/tools/package.json +32 -0
  69. core/bundled/tools/rule-metadata.mjs +56 -0
  70. core/bundled/tools/semgrep.lock +1232 -0
  71. core/bundled/tools/stylelint.config.json +11 -0
  72. core/catalog/__init__.py +190 -0
  73. core/catalog/build.py +84 -0
  74. core/catalog/merge.py +122 -0
  75. core/catalog/sources.py +418 -0
  76. core/catalog/standards.py +119 -0
  77. core/catalog/update.py +99 -0
  78. core/catalog_views.py +115 -0
  79. core/client.py +645 -0
  80. core/collect.py +518 -0
  81. core/duplicates.py +60 -0
  82. core/fingerprint.py +25 -0
  83. core/folders.py +73 -0
  84. core/gate.py +77 -0
  85. core/git.py +149 -0
  86. core/jobs.py +86 -0
  87. core/management/__init__.py +0 -0
  88. core/management/commands/__init__.py +0 -0
  89. core/management/commands/addproject.py +40 -0
  90. core/management/commands/buildcatalog.py +15 -0
  91. core/management/commands/scan.py +74 -0
  92. core/management/commands/updatecatalog.py +14 -0
  93. core/mcp_server.py +140 -0
  94. core/middleware.py +17 -0
  95. core/migrations/0001_initial.py +115 -0
  96. core/migrations/0002_auth_tokens_a11y.py +60 -0
  97. core/migrations/0003_default_admin.py +43 -0
  98. core/migrations/0004_project_members.py +28 -0
  99. core/migrations/0005_uploads_and_sources.py +55 -0
  100. core/migrations/0006_thresholds.py +28 -0
  101. core/migrations/0007_also_reported_by.py +18 -0
  102. core/migrations/0008_new_code_period.py +18 -0
  103. core/migrations/0009_resolution_safe.py +18 -0
  104. core/migrations/0010_analysis_progress.py +18 -0
  105. core/migrations/0011_overall_gate_conditions.py +20 -0
  106. core/migrations/__init__.py +0 -0
  107. core/models.py +323 -0
  108. core/network.py +41 -0
  109. core/paths.py +29 -0
  110. core/ratings.py +67 -0
  111. core/runner.py +168 -0
  112. core/templates/core/account.html +30 -0
  113. core/templates/core/analysis.html +49 -0
  114. core/templates/core/base.html +121 -0
  115. core/templates/core/form_table.html +12 -0
  116. core/templates/core/gate_badge.html +1 -0
  117. core/templates/core/index.html +26 -0
  118. core/templates/core/issues.html +38 -0
  119. core/templates/core/login.html +13 -0
  120. core/templates/core/new_project.html +27 -0
  121. core/templates/core/password_change.html +10 -0
  122. core/templates/core/project.html +40 -0
  123. core/templates/core/rating.html +1 -0
  124. core/templates/core/ratings.html +32 -0
  125. core/templates/core/rule.html +33 -0
  126. core/templates/core/rules.html +42 -0
  127. core/templates/core/scan_progress.html +2 -0
  128. core/templates/core/settings.html +36 -0
  129. core/templates/core/source.html +15 -0
  130. core/templates/core/standards.html +30 -0
  131. core/templates/core/user_edit.html +15 -0
  132. core/templates/core/users.html +18 -0
  133. core/templatetags/__init__.py +0 -0
  134. core/templatetags/codewatch.py +42 -0
  135. core/tool_setup.py +68 -0
  136. core/views.py +564 -0
core/benchmark.py ADDED
@@ -0,0 +1,955 @@
1
+ """Benchmarks: scan third-party code with published ground truth and score what codewatch catches.
2
+
3
+ Suites are listed in benchmarks/suites.json, fetched at a pinned commit into the cache directory, scanned
4
+ (never executed) and scored. Results go to benchmarks/results/<suite>.json and .md.
5
+ """
6
+ import ast
7
+ import csv
8
+ import json
9
+ import multiprocessing
10
+ import os
11
+ import re
12
+ import subprocess
13
+ import time
14
+ from collections import defaultdict
15
+ from concurrent.futures import ProcessPoolExecutor, as_completed
16
+ from datetime import UTC, datetime
17
+ from pathlib import Path
18
+
19
+ import yaml
20
+
21
+ from . import catalog
22
+ from .analyzers import php_template_sinks
23
+ from .analyzers.base import python_tree
24
+ from .analyzers.template_sinks import TEMPLATE_EXTENSIONS, TEMPLATE_RULE, XSS_RULE, template_name
25
+ from .collect import ScanConfig, ScanInput, collect
26
+
27
+ ROOT = Path(__file__).resolve().parents[1] / "benchmarks"
28
+ CACHE = Path(os.environ.get("CODEWATCH_CACHE", Path.home() / ".cache" / "codewatch")) / "benchmarks"
29
+ SECURITY_TYPES = {"vulnerability", "security_hotspot"}
30
+ # Not about the code under test: dependency audits, live pages, coverage import, duplication.
31
+ SKIPPED_ANALYZERS = ["pip-audit", "osv", "axe", "coverage", "jscpd"]
32
+ # Scans run in parallel by default from the command line (devtools bench, codewatch benchmark): each suite or CVE
33
+ # case is its own process. A third of the CPUs, since each Semgrep run also uses several; memory is about 1-3 GB a run.
34
+ WORKERS = int(os.environ.get("CODEWATCH_BENCH_WORKERS") or max(1, (os.cpu_count() or 2) // 3))
35
+ SNIPPET_RE = re.compile(r"vuln-code-snippet vuln-line ([\w ]{1,500})")
36
+ NEARBY_LINES = 3
37
+
38
+
39
+ def git(*args, cwd):
40
+ # errors="replace": a diff of a file that isn't UTF-8 (TBDev GHSA-88jc's Windows-1251 page) failed the case.
41
+ return subprocess.run(["git", *args], cwd=cwd, check=True, capture_output=True, text=True,
42
+ errors="replace").stdout
43
+
44
+
45
+ BEFORE, AFTER = "before", "after"
46
+ FETCH, GAVE_UP, CVE_PAIRS = "fetch", "gave_up", "cve-pairs"
47
+ ANY_FILE = "*" # Semgrep gave up on some file it didn't name
48
+
49
+
50
+ def lenient_text(path):
51
+ """A file's text, undecodable bytes replaced (a checkout's files needn't be UTF-8)."""
52
+ return path.read_text(errors="replace")
53
+
54
+
55
+ def file_text(path):
56
+ return lenient_text(path) if path.is_file() else ""
57
+
58
+
59
+ def tracked(root, paths):
60
+ """The checkout's tracked files under paths (all of them for none)."""
61
+ return git("ls-files", "-z", "--", *paths, cwd=root).split("\0")
62
+
63
+
64
+ def cwe_parents():
65
+ return catalog.load()[1].get("cwe_parents", {})
66
+
67
+
68
+ def case_scope(case):
69
+ return case.get("scope", [])
70
+
71
+
72
+ def fetch(suite):
73
+ target = CACHE / suite["name"]
74
+ target.mkdir(parents=True, exist_ok=True)
75
+ if not (target / ".git").exists():
76
+ git("init", "-q", cwd=target)
77
+ git(FETCH, "-q", "--depth", "1", suite["repo"], suite["commit"], cwd=target)
78
+ git("checkout", "-q", "--force", "FETCH_HEAD", cwd=target)
79
+ return target
80
+
81
+
82
+ def timing(log, label, seconds, parts=None, gave_up: object = False):
83
+ """Logs one line per fetch or scan: "timing", suite, case ("-" for a whole-repository suite), phase, seconds, then
84
+ its parts' seconds, slowest first (each analyzer, and "prep" for the template renderers and importers looked up
85
+ before them), and whether Semgrep gave up on some files (any truthy record: a bool or the files). devtools.py bench writes them to
86
+ $CODEWATCH_BENCH_TIMINGS."""
87
+ parts = [f"{name}={sec:.0f}" for name, sec in sorted((parts or {}).items(), key=lambda kv: -kv[1]) if sec >= 1]
88
+ log("\t".join(["timing", *label, f"{seconds:.0f}", " ".join(parts + ([GAVE_UP] if gave_up else []))]))
89
+
90
+
91
+ def fetch_and_scan(suite, log):
92
+ """A whole-repository suite's checkout and issues, with the time of each logged."""
93
+ start = time.monotonic()
94
+ root = fetch(suite)
95
+ timing(log, (suite["name"], "-", FETCH), time.monotonic() - start)
96
+ start, tools = time.monotonic(), {}
97
+ issues, gave_up = scan_and_gave_up(root, log, tools=tools)
98
+ timing(log, (suite["name"], "-", "scan"), time.monotonic() - start, tools, gave_up=gave_up)
99
+ return root, issues
100
+
101
+
102
+ def scan(root, log, paths=(), focus=None):
103
+ return scan_and_gave_up(root, log, paths, focus)[0]
104
+
105
+
106
+ def scan_and_gave_up(root, log, paths=(), focus=None, tools=None):
107
+ """The scan's issues, and the files Semgrep gave up on some rules in ([] when none; [ANY_FILE] when it said so
108
+ without naming them). tools, when given, is filled with each analyzer's seconds."""
109
+ files = [f for f in tracked(root, paths) if f]
110
+ cfg = ScanConfig(disabled_analyzers=SKIPPED_ANALYZERS, custom_rules=catalog.custom_semgrep_rules())
111
+ out = collect(cfg, ScanInput(root, files, "benchmark", focus=focus), log)
112
+ if tools is not None:
113
+ tools.update({name: tool.get("seconds") or 0 for name, tool in out["tools"].items()})
114
+ # A suite scored without Semgrep would look like a run of misses and quiet fixed code.
115
+ if (semgrep := out["tools"].get("semgrep", {})).get("status") == "error":
116
+ raise RuntimeError(f"semgrep failed on {root}: {semgrep['detail']}")
117
+ if semgrep.get("detail"):
118
+ log(f" {root}: {semgrep['detail']}")
119
+ return out["issues"], semgrep.get("gave_up") or ([ANY_FILE] if semgrep.get("detail") else [])
120
+
121
+
122
+ def related(a, b, parents):
123
+ """Same weakness, or one is an ancestor of the other in MITRE's hierarchy (e.g. CWE-327 and CWE-328)."""
124
+ return a == b or a in catalog.ancestors(b, parents) or b in catalog.ancestors(a, parents)
125
+
126
+
127
+ # Rules built at scan time, which have no catalogue entry of their own: scored with the CWEs of the rule they copy.
128
+ DERIVED_RULES = {TEMPLATE_RULE: XSS_RULE, php_template_sinks.TEMPLATE_RULE: php_template_sinks.XSS_RULE}
129
+
130
+
131
+ def issue_cwes(issue):
132
+ """CWEs of the rule, and of every other rule that reported the same finding before it was merged."""
133
+ cwes = set()
134
+ for tool, rule in [(issue["tool"], issue["rule"]),
135
+ *(s.split(":", 1) for s in issue.get("also_reported_by") or [] if ":" in s)]:
136
+ entry = catalog.lookup(tool, DERIVED_RULES.get(rule, rule))
137
+ cwes.update(entry["cwe"] if entry else [])
138
+ return cwes
139
+
140
+
141
+ # Verdict mode counts only findings that claim a vulnerability (data flow or definite flaw), which is what the
142
+ # Security rating uses; review mode adds security hotspots, i.e. everything a reviewer is asked to look at.
143
+ MODES = {"verdict": {"vulnerability"}, "review": SECURITY_TYPES}
144
+
145
+
146
+ def issues_by_file(issues, types):
147
+ by_file = defaultdict(list)
148
+ for i in issues:
149
+ if i["type"] in types:
150
+ by_file[i["path"]].append(i)
151
+ return by_file
152
+
153
+
154
+ # --- OWASP Benchmark --------------------------------------------------------------------------------------
155
+
156
+
157
+ def owasp_cases(root, suite):
158
+ with open(root / suite["expected"], newline="") as f:
159
+ rows = [r for r in csv.reader(f) if r and not r[0].startswith("#")]
160
+ return [{"test": r[0].strip(), "category": r[1].strip(), "real": r[2].strip() == "true", "cwe": int(r[3])}
161
+ for r in rows]
162
+
163
+
164
+ def flagged(case, findings, parents):
165
+ """The case counts as flagged if a security finding in its file maps to the expected CWE family; a clean
166
+ control (no CWE) is flagged by any security finding."""
167
+ if case["cwe"] is None:
168
+ return bool(findings)
169
+ return any(any(related(c, case["cwe"], parents) for c in issue_cwes(i)) for i in findings)
170
+
171
+
172
+ def rates(s):
173
+ tpr = s["tp"] / (s["tp"] + s["fn"]) if s["tp"] + s["fn"] else 0.0
174
+ fpr = s["fp"] / (s["fp"] + s["tn"]) if s["fp"] + s["tn"] else 0.0
175
+ return {**s, "tpr": round(tpr, 3), "fpr": round(fpr, 3), "score": round(tpr - fpr, 3)}
176
+
177
+
178
+ def score_owasp_mode(cases, suite, by_file, parents):
179
+ stats = defaultdict(lambda: {"tp": 0, "fn": 0, "fp": 0, "tn": 0, "cwe": None})
180
+ missed = []
181
+ for case in cases:
182
+ hit = flagged(case, by_file.get(f"{suite['test_dir']}/{case['test']}.py", []), parents)
183
+ s = stats[case["category"]]
184
+ s["cwe"] = case["cwe"]
185
+ s[("tp" if hit else "fn") if case["real"] else ("fp" if hit else "tn")] += 1
186
+ if case["real"] != hit:
187
+ missed.append({**case, "flagged": hit})
188
+ categories = {name: rates(s) for name, s in sorted(stats.items())}
189
+ overall = {k: round(sum(c[k] for c in categories.values()) / len(categories), 3) for k in ("tpr", "fpr", "score")}
190
+ return {"overall": overall, "categories": categories, "mistakes": missed[:300]}
191
+
192
+
193
+ def score_owasp(root, suite, issues):
194
+ parents = cwe_parents()
195
+ cases = owasp_cases(root, suite)
196
+ return {mode: score_owasp_mode(cases, suite, issues_by_file(issues, types), parents)
197
+ for mode, types in MODES.items()}
198
+
199
+
200
+ # --- Juice Shop style snippets ----------------------------------------------------------------------------
201
+
202
+
203
+ def marked_lines(root):
204
+ """{challenge: [(path, line)]} from 'vuln-code-snippet vuln-line <challenges>' markers."""
205
+ files = subprocess.run(["git", "grep", "-l", "vuln-code-snippet vuln-line"], cwd=root, capture_output=True,
206
+ text=True, check=False).stdout.split()
207
+ marks = defaultdict(list)
208
+ for path in files:
209
+ if "codefixes" in path:
210
+ continue
211
+ for n, line in enumerate(lenient_text(root / path).splitlines(), 1):
212
+ if match := SNIPPET_RE.search(line):
213
+ for challenge in match[1].split():
214
+ marks[challenge].append((path, n))
215
+ return marks
216
+
217
+
218
+ def score_snippets_mode(marks, categories, by_file):
219
+ results, per_category = [], defaultdict(lambda: {"found": 0, "total": 0})
220
+ for challenge, lines in sorted(marks.items()):
221
+ near = [i for path, n in lines for i in by_file.get(path, []) if abs((i["line"] or 0) - n) <= NEARBY_LINES]
222
+ category = categories.get(challenge, "?")
223
+ per_category[category]["total"] += 1
224
+ per_category[category]["found"] += bool(near)
225
+ results.append({"challenge": challenge, "category": category, "lines": lines, "found": bool(near),
226
+ "by": sorted({f"{i['tool']}:{i['rule']}" for i in near})})
227
+ found = sum(r["found"] for r in results)
228
+ return {"overall": {"found": found, "total": len(results), "recall": round(found / len(results), 3)},
229
+ "categories": dict(sorted(per_category.items())), "challenges": results}
230
+
231
+
232
+ def score_snippets(root, suite, issues):
233
+ categories = {c["key"]: c.get("category", "?") for c in yaml.safe_load((root / suite["challenges"]).read_text())}
234
+ marks = marked_lines(root)
235
+ return {mode: score_snippets_mode(marks, categories, issues_by_file(issues, types))
236
+ for mode, types in MODES.items()}
237
+
238
+
239
+ # --- CWE-labelled folders (SecurityEval style) -------------------------------------------------------------
240
+
241
+
242
+ CWE_DIR_RE = re.compile(r"CWE-(\d{1,5})")
243
+
244
+
245
+ def cwe_cases(root, suite):
246
+ """Every file under test_dir/CWE-<n>/ (or a folder the suite maps to a CWE) is a vulnerable sample of it."""
247
+ folders = suite.get("folders", {})
248
+ extensions = tuple(suite.get("extensions", [".py"]))
249
+ cases = []
250
+ for path in sorted((root / suite["test_dir"]).glob("*/*")):
251
+ if not path.name.endswith(extensions):
252
+ continue
253
+ match = CWE_DIR_RE.fullmatch(path.parent.name)
254
+ cwe = int(match[1]) if match else folders.get(path.parent.name)
255
+ if cwe:
256
+ cases.append({"path": path.relative_to(root).as_posix(), "cwe": cwe})
257
+ return cases
258
+
259
+
260
+ def score_cwe_mode(cases, by_file, parents):
261
+ per_cwe, results = defaultdict(lambda: {"found": 0, "total": 0}), []
262
+ for case in cases:
263
+ findings = by_file.get(case["path"], [])
264
+ hit = flagged(case, findings, parents)
265
+ per_cwe[case["cwe"]]["total"] += 1
266
+ per_cwe[case["cwe"]]["found"] += hit
267
+ results.append({**case, "found": hit, "any_security": bool(findings),
268
+ "by": sorted({f"{i['tool']}:{i['rule']}" for i in findings})})
269
+ found = sum(r["found"] for r in results)
270
+ flagged_any = sum(r["any_security"] for r in results)
271
+ return {"overall": {"found": found, "total": len(results), "recall": round(found / len(results), 3),
272
+ "any_security": round(flagged_any / len(results), 3)},
273
+ "categories": {f"CWE-{k}": v for k, v in sorted(per_cwe.items())}, "cases": results}
274
+
275
+
276
+ def score_cwe_folders(root, suite, issues):
277
+ parents = cwe_parents()
278
+ cases = cwe_cases(root, suite)
279
+ return {mode: score_cwe_mode(cases, issues_by_file(issues, types), parents) for mode, types in MODES.items()}
280
+
281
+
282
+ # --- Labelled files (a CSV of CWE, file and a manual vulnerable/safe verdict) --------------------------------
283
+
284
+
285
+ def labelled_cases(root, suite):
286
+ with open(root / suite["labels"], newline="", encoding="utf-8-sig") as f:
287
+ rows = list(csv.DictReader(f))
288
+ cases = []
289
+ for row in rows:
290
+ verdict, match = row.get(suite["label_column"], "").strip(), CWE_DIR_RE.fullmatch(row["CWEID"].strip())
291
+ path = f"{suite['test_dir']}/{row['CWEID'].strip()}/{row['SampleID'].strip()}"
292
+ if verdict in ("0", "1") and match and (root / path).exists():
293
+ cases.append({"path": path, "cwe": int(match[1]), "real": verdict == "1"})
294
+ return cases
295
+
296
+
297
+ def score_labelled_mode(cases, by_file, parents):
298
+ totals, per_cwe, mistakes = {"tp": 0, "fn": 0, "fp": 0, "tn": 0}, defaultdict(lambda: {"tp": 0, "fn": 0, "fp": 0, "tn": 0}), []
299
+ for case in cases:
300
+ hit = flagged(case, by_file.get(case["path"], []), parents)
301
+ key = ("tp" if hit else "fn") if case["real"] else ("fp" if hit else "tn")
302
+ totals[key] += 1
303
+ per_cwe[f"CWE-{case['cwe']}" if case["cwe"] else "clean controls"][key] += 1
304
+ if case["real"] != hit:
305
+ mistakes.append({**case, "flagged": hit,
306
+ "by": sorted({f"{i['tool']}:{i['rule']}" for i in by_file.get(case["path"], [])})})
307
+ return {"overall": rates(totals), "categories": dict(sorted(per_cwe.items())), "mistakes": mistakes}
308
+
309
+
310
+ def cwe_of_dir(name):
311
+ """The CWE number of a seed directory name such as CWE-089."""
312
+ found = CWE_DIR_RE.fullmatch(name)
313
+ if not found:
314
+ raise ValueError(f"not a CWE directory name: {name!r}")
315
+ return int(found[1])
316
+
317
+
318
+ def seed_cases(root, suite):
319
+ """Seed files from a ground-truth YAML ({seeds: [{file, cwe}]}) plus clean controls that must stay quiet."""
320
+ truth = yaml.safe_load((root / suite["ground_truth"]).read_text())
321
+ cases = [{"path": f"{suite['test_dir']}/{seed['file']}", "cwe": cwe_of_dir(seed["cwe"]), "real": True}
322
+ for seed in truth["seeds"]]
323
+ cases += [{"path": f"{suite['test_dir']}/{p.name}", "cwe": None, "real": False}
324
+ for p in sorted((root / suite["test_dir"]).glob(suite["clean_glob"]))]
325
+ return cases
326
+
327
+
328
+ def score_seeds(root, suite, issues):
329
+ parents = cwe_parents()
330
+ cases = seed_cases(root, suite)
331
+ return {mode: score_labelled_mode(cases, issues_by_file(issues, types), parents) for mode, types in MODES.items()}
332
+
333
+
334
+ def score_labelled(root, suite, issues):
335
+ parents = cwe_parents()
336
+ cases = labelled_cases(root, suite)
337
+ return {mode: score_labelled_mode(cases, issues_by_file(issues, types), parents) for mode, types in MODES.items()}
338
+
339
+
340
+ # --- CVE fix pairs: the commit before a published fix (vulnerable) and the fix itself ------------------------
341
+
342
+
343
+ SOURCE_EXTENSIONS = {"python": (".py",), "javascript": (".js", ".mjs", ".cjs", ".jsx", ".ts", ".tsx")}
344
+ # A Python web app's own templates and front-end scripts (cve-pairs-python-frontend).
345
+ SOURCE_EXTENSIONS["python-web"] = (*SOURCE_EXTENSIONS["python"], *SOURCE_EXTENSIONS["javascript"],
346
+ ".vue", ".html", ".htm", ".jinja", ".jinja2", ".j2")
347
+ # PHP apps and CMSs: their code, templates (Twig, Smarty, Latte, Blade is .blade.php) and the JS they ship.
348
+ SOURCE_EXTENSIONS["php"] = (".php", ".phtml", ".ctp", ".inc", ".module", ".install", ".theme", ".twig", ".tpl", ".latte",
349
+ *SOURCE_EXTENSIONS["javascript"], ".vue", ".html", ".htm")
350
+ TEST_PATH_RE = re.compile(r"(^|/)(tests?|__tests__|spec|e2e)/|(^|/)(test_[^/]*|[^/]*_test\.py|tests?\.py)$"
351
+ r"|\.(test|spec)\.[cm]?[jt]sx?$|\.d\.ts$")
352
+ HUNK_RE = re.compile(r"@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@")
353
+
354
+
355
+ def fetch_pair(suite, case):
356
+ """Fix commit and its parent, blobs fetched lazily; a case's scope limits the checkout to those folders."""
357
+ target = CACHE / suite["name"] / case["id"]
358
+ target.mkdir(parents=True, exist_ok=True)
359
+ if not (target / ".git").exists():
360
+ git("init", "-q", cwd=target)
361
+ git("remote", "add", "origin", case["repo"], cwd=target)
362
+ # Every time, so a scope widened in suites.json reaches a clone made before (SQLBot GHSA-fghj: its request model
363
+ # sat outside the first scope).
364
+ if case_scope(case):
365
+ # --skip-checks: a folder named like a pattern, such as Next.js's `[[...path]]` (Postiz GHSA-2p7p), is
366
+ # refused without it, and that refusal once stopped a whole night's suites.
367
+ git("sparse-checkout", "set", "--skip-checks", *case_scope(case), cwd=target)
368
+ else:
369
+ git("sparse-checkout", "disable", cwd=target)
370
+ git(FETCH, "-q", "--depth", "2", "--filter=blob:none", "origin", case["fix"], cwd=target)
371
+ return target, git("rev-parse", f"{case['fix']}^", cwd=target).strip()
372
+
373
+
374
+ def span(start, count):
375
+ """Lines a hunk side covers; a pure insertion or deletion (count 0) is the gap after line `start`."""
376
+ start, count = int(start), int(count or 1)
377
+ return (max(start, 1), start + 1) if count == 0 else (start, start + count - 1)
378
+
379
+
380
+ def hunk_spots(match, old, new):
381
+ """(side, path, (first, last)) for both sides of a hunk header."""
382
+ return ((BEFORE, old, span(*match.group(1, 2))), (AFTER, new, span(*match.group(3, 4))))
383
+
384
+
385
+ def diff_path(line, prefix):
386
+ """The path of a ---/+++ line, or None for /dev/null."""
387
+ return line[6:] if line.startswith(prefix) else None
388
+
389
+
390
+ def fix_spots(diff, extensions):
391
+ """{"before": {path: [(first, last)]}, "after": ...} for non-test source files changed by the fix."""
392
+ spots = {BEFORE: defaultdict(list), AFTER: defaultdict(list)}
393
+ old = new = None
394
+ for line in diff.splitlines():
395
+ if line.startswith("--- "):
396
+ old = diff_path(line, "--- a/")
397
+ elif line.startswith("+++ "):
398
+ new = diff_path(line, "+++ b/")
399
+ elif match := HUNK_RE.match(line):
400
+ for side, path, lines in hunk_spots(match, old, new):
401
+ if path and path.endswith(extensions) and not TEST_PATH_RE.search(path):
402
+ spots[side][path].append(lines)
403
+ return {side: dict(paths) for side, paths in spots.items()}
404
+
405
+
406
+ # The calls that render a template by name, as template_sinks' patterns see them: the template is the first argument
407
+ # of render_template/render_to_string and the second of Django's render/TemplateResponse (after the request).
408
+ RENDER_CALLS = {"render_template": 0, "render_to_string": 0, "render": 1, "TemplateResponse": 1}
409
+
410
+
411
+ def changed_templates(diff):
412
+ """Names (as a view gives them, template_sinks.template_name) of the non-test templates a fix changed."""
413
+ names = set()
414
+ for line in diff.splitlines():
415
+ if line.startswith(("--- a/", "+++ b/")):
416
+ path = line[6:]
417
+ if path.endswith(tuple(TEMPLATE_EXTENSIONS)) and not TEST_PATH_RE.search(path):
418
+ names.add(template_name(path))
419
+ return names
420
+
421
+
422
+ def rendered_template(node):
423
+ """The template argument of a render call (render_template(x), render(request, x)), or None."""
424
+ if not isinstance(node, ast.Call):
425
+ return None
426
+ func = node.func.attr if isinstance(node.func, ast.Attribute) else getattr(node.func, "id", None)
427
+ if func not in RENDER_CALLS:
428
+ return None
429
+ index = RENDER_CALLS[func]
430
+ return node.args[index] if len(node.args) > index else next(
431
+ (k.value for k in node.keywords if k.arg in ("template_name", "template_name_or_list")), None)
432
+
433
+
434
+ def render_spans(text, names):
435
+ """[(first, last)] lines of the calls in a Python file's text that render one of the named templates."""
436
+ if not any(name in text for name in names):
437
+ return []
438
+ tree = python_tree(text)
439
+ if tree is None:
440
+ return []
441
+ return sorted((node.lineno, node.end_lineno or node.lineno) for node in ast.walk(tree)
442
+ if isinstance(arg := rendered_template(node), ast.Constant) and arg.value in names)
443
+
444
+
445
+ def template_renderers(root, paths, names):
446
+ """{python file: [render call spans]} for the files in the checkout that render a changed template by name."""
447
+ if not names:
448
+ return {}
449
+ found = {}
450
+ for path in tracked(root, paths):
451
+ if (path.endswith(".py") and not TEST_PATH_RE.search(path) and (root / path).is_file()
452
+ and (spans := render_spans(lenient_text(root / path), names))):
453
+ found[path] = spans
454
+ return found
455
+
456
+
457
+ def importers(root, paths, changed):
458
+ """Python files in the checkout that import a changed Python module (summaries.visible): a fix inside a helper
459
+ removes the finding at its caller (Dagster GHSA-q93c: the containment check went into the log manager, the
460
+ FileResponse is in the webserver). Their findings count only when the fix makes them go away."""
461
+ from .analyzers.summaries import visible
462
+
463
+ modules = {c for c in changed if c.endswith(".py")}
464
+ if not modules:
465
+ return set()
466
+ found = set()
467
+ for path in tracked(root, paths):
468
+ if (path.endswith(".py") and path not in modules and not TEST_PATH_RE.search(path) and (root / path).is_file()
469
+ and visible(path, modules, lambda rel: lenient_text(root / rel))):
470
+ found.add(path)
471
+ return found
472
+
473
+
474
+ PHP_KEY_RE = re.compile(r"template variable ['\"](\w+)['\"]")
475
+ PHP_NAME_RE = re.compile(r"\(template ['\"]([^'\"]+)['\"]\)")
476
+
477
+
478
+ def changed_php_templates(root, changed):
479
+ """{path: (template kind, text)} for the changed files that are templates."""
480
+ templates = {}
481
+ for path in changed:
482
+ text = file_text(root / path)
483
+ if (kind := php_template_sinks.kind(path, text)) is not None:
484
+ templates[path] = (kind, text)
485
+ return templates
486
+
487
+
488
+ def renders_changed(issue, templates, raw):
489
+ """A template-rule finding setting a variable a changed template prints unescaped, through a call naming that
490
+ template or naming none."""
491
+ if issue["rule"] != php_template_sinks.TEMPLATE_RULE or not (key := PHP_KEY_RE.search(issue.get("message") or "")):
492
+ return False
493
+ name = PHP_NAME_RE.search(issue["message"])
494
+ return any(key.group(1) in raw[path]
495
+ and (name is None or name.group(1) in php_template_sinks.names(path, templates[path][0]))
496
+ for path in templates)
497
+
498
+
499
+ def php_template_renders(root, changed, found):
500
+ """{path: [(line, line)]} of the PHP template rule's findings that set a variable one of the changed templates
501
+ prints unescaped, through a call naming that template or (Smarty's assign(), CakePHP's set()) naming none: a fix
502
+ in the template removes the finding at the controller, in a file the fix didn't change (oc-server3 GHSA-w8rr)."""
503
+ templates = changed_php_templates(root, changed)
504
+ if not templates:
505
+ return {}
506
+ joined = "\n".join(text for path, (_, text) in templates.items() if path.endswith(".php"))
507
+ settings = {"twig_off": bool(php_template_sinks.TWIG_OFF_RE.search(joined)), "smarty_escapes": False}
508
+ raw = {path: php_template_sinks.raw_variables(text, kind, settings) for path, (kind, text) in templates.items()}
509
+ renders = {}
510
+ for i in (i for i in found if renders_changed(i, templates, raw)):
511
+ renders.setdefault(i["path"], []).append((i["line"], i["line"]))
512
+ return renders
513
+
514
+
515
+ PHP_CALLER_SUFFIXES = (".php", ".ctp", ".phtml", ".inc", ".module", ".tpl")
516
+
517
+
518
+ def printed_variable_words(root, changed):
519
+ """How a PHP file would name a variable the changed templates print unescaped: 'x', "x" or ->x =."""
520
+ words = set()
521
+ for kind, text in changed_php_templates(root, changed).values():
522
+ variables = php_template_sinks.raw_variables(text, kind, {"twig_off": True, "smarty_escapes": False})
523
+ words |= {f"'{v}'" for v in variables} | {f'"{v}"' for v in variables} | {f"->{v} =" for v in variables}
524
+ return words
525
+
526
+
527
+ def php_template_callers(root, paths, changed):
528
+ """PHP files in the checkout that might set a variable a changed template prints unescaped: they name the
529
+ template, or quote the variable (assign('x', ...), set('x', ...)). The focus of the scan, so the template
530
+ rule's finding at the controller is seen."""
531
+ words = printed_variable_words(root, changed)
532
+ if not words:
533
+ return set()
534
+ candidates = (path for path in tracked(root, paths) if path.endswith(PHP_CALLER_SUFFIXES)
535
+ and path not in changed and not TEST_PATH_RE.search(path) and (root / path).is_file())
536
+ return {path for path in candidates if any(w in lenient_text(root / path) for w in words)}
537
+
538
+
539
+ def at_render(issue, renders):
540
+ """A finding of the template rule inside a call that renders a changed template."""
541
+ return issue["rule"] in (TEMPLATE_RULE, php_template_sinks.TEMPLATE_RULE) and any(
542
+ first <= (issue["line"] or 0) <= last for first, last in renders.get(issue["path"], ()))
543
+
544
+
545
+ def with_code(root, issues):
546
+ """Each finding with its stripped source line, so the same finding can be recognised on both sides of a fix."""
547
+ lines = {}
548
+ for i in issues:
549
+ if i["path"] not in lines:
550
+ path = root / i["path"]
551
+ lines[i["path"]] = file_text(path).splitlines()
552
+ text = lines[i["path"]]
553
+ i["code"] = text[i["line"] - 1].strip() if i["line"] and i["line"] <= len(text) else ""
554
+ return issues
555
+
556
+
557
+ def scan_side(suite, case, checkout, known, log):
558
+ """One side of a fix pair: the security findings in the changed files, at the calls that render a changed
559
+ template, and in the changed modules' importers. checkout: (root, side, commit); known: (spots, templates)."""
560
+ (root, side, commit), (spots, templates) = checkout, known
561
+ start, tools = time.monotonic(), {}
562
+ git("checkout", "-q", "--force", commit, cwd=root)
563
+ renders = spots["renders"][side] = template_renderers(root, case_scope(case), templates)
564
+ callers = importers(root, case_scope(case), set(spots[side]))
565
+ # A PHP template's unescaped variable is set in a controller the fix may not touch.
566
+ php_callers = (php_template_callers(root, case_scope(case), set(spots[side]))
567
+ if suite["language"] == "php" else set())
568
+ prep = time.monotonic() - start
569
+ # Only findings in the changed files (and those render calls, and the changed modules' importers) are
570
+ # scored, so Semgrep's per-file pass looks only at those files.
571
+ found, spots[GAVE_UP][side] = scan_and_gave_up(root, log, case_scope(case),
572
+ focus=sorted({*spots[side], *renders, *callers, *php_callers}),
573
+ tools=tools)
574
+ if suite["language"] == "php":
575
+ renders = spots["renders"][side] = php_template_renders(root, set(spots[side]), found)
576
+ timing(log, (suite["name"], case["id"], side), time.monotonic() - start, {"prep": prep, **tools},
577
+ spots[GAVE_UP][side])
578
+ found = [i for i in found if i["type"] in SECURITY_TYPES]
579
+ return with_code(root, [i for i in found if i["path"] in spots[side] or at_render(i, renders)
580
+ or i["path"] in callers])
581
+
582
+
583
+ def scan_pair(suite, case, log):
584
+ start = time.monotonic()
585
+ root, parent = fetch_pair(suite, case)
586
+ timing(log, (suite["name"], case["id"], FETCH), time.monotonic() - start)
587
+ diff = git("diff", "-U0", "--no-renames", parent, case["fix"], cwd=root)
588
+ spots: dict = fix_spots(diff, SOURCE_EXTENSIONS[suite["language"]])
589
+ # A fix in a template (dropping |safe) leaves the finding at the Python call that renders it, in a file the
590
+ # fix didn't change: those calls are scored too, for the template rule only.
591
+ templates = changed_templates(diff) if suite["language"].startswith("python") else set()
592
+ spots["renders"], spots[GAVE_UP] = {}, {}
593
+ sides = {side: scan_side(suite, case, (root, side, commit), (spots, templates), log)
594
+ for side, commit in ((BEFORE, parent), (AFTER, case["fix"]))}
595
+ return spots, sides
596
+
597
+
598
+ def near(issue, spans):
599
+ return any(first - NEARBY_LINES <= (issue["line"] or 0) <= last + NEARBY_LINES for first, last in spans)
600
+
601
+
602
+ def relevant_issues(issues, types, case, parents):
603
+ """The findings of the given types for the advisory's weakness (or a related one)."""
604
+ return [i for i in issues if i["type"] in types
605
+ and any(related(c, w, parents) for c in issue_cwes(i) for w in case["cwe"])]
606
+
607
+
608
+ def issue_key(issue):
609
+ return issue["path"], issue["rule"], issue["code"]
610
+
611
+
612
+ def at_spot(issue, spots, side):
613
+ return near(issue, spots[side].get(issue["path"], ())) or at_render(issue, spots.get("renders", {}).get(side, {}))
614
+
615
+
616
+ def rule_lines(issues):
617
+ return sorted({f"{i['tool']}:{i['rule']}@{i['line']}" for i in issues})
618
+
619
+
620
+ def gave_up_files(flag):
621
+ """A side's gave-up record as a set of paths: a bare True (results from before 2026-11-25) names no file."""
622
+ return set(flag) if isinstance(flag, (list, tuple, set)) else ({ANY_FILE} if flag else set())
623
+
624
+
625
+ def complete_for(issue, spots):
626
+ """Whether the fixed side's scan can be trusted to have kept this finding had it still been there. Semgrep
627
+ giving up on a file under load (the 2026-11-07 nightly, mlflow GHSA-wqmh) drops its findings there without an
628
+ error, and a summary pass giving up drops what its functions hand on. So: no giving up on the fixed side, or
629
+ only on files the vulnerable side gave up on too (the same handicap on both sides, which the vulnerable side
630
+ found the finding despite) and not on the finding's own file (clawmetry da1d1d8fd021: 29 unrelated files on
631
+ both sides hid the finding its fix removes)."""
632
+ after = gave_up_files(spots.get(GAVE_UP, {}).get(AFTER))
633
+ if not after:
634
+ return True
635
+ before = gave_up_files(spots.get(GAVE_UP, {}).get(BEFORE))
636
+ return ANY_FILE not in after and after <= before and issue["path"] not in after
637
+
638
+
639
+ def hits_and_still(before, after, spots):
640
+ """(findings that detect the advisory, findings still there after its fix)."""
641
+ after_keys = {issue_key(i) for i in after}
642
+ # A finding the fix makes go away counts only when the fixed side's scan was complete for it.
643
+ hits = [i for i in before if at_spot(i, spots, BEFORE) or (complete_for(i, spots) and issue_key(i) not in after_keys)]
644
+ hit_keys = {issue_key(i) for i in hits}
645
+ return hits, [i for i in after if issue_key(i) in hit_keys or at_spot(i, spots, AFTER)]
646
+
647
+
648
+ def score_pair(case, spots, sides, types, parents):
649
+ """Detected: a finding of the advisory's weakness at the fixed spot, or one the fix makes go away. Still
650
+ flagged (a false alarm on fixed code): such a finding survives the fix, or a new one appears at the fix."""
651
+ before = relevant_issues(sides[BEFORE], types, case, parents)
652
+ after = relevant_issues(sides[AFTER], types, case, parents)
653
+ hits, still = hits_and_still(before, after, spots)
654
+ gave_up = sorted(side for side, flag in spots.get(GAVE_UP, {}).items() if flag)
655
+ return {"id": case["id"], "repo": case["repo"], "cwe": case["cwe"], **({GAVE_UP: gave_up} if gave_up else {}),
656
+ "detected": bool(hits), "still_flagged": bool(still), "by": rule_lines(hits), "still_by": rule_lines(still)}
657
+
658
+
659
+ def score_pairs_mode(cases, scanned, types, parents):
660
+ totals, per_cwe, results = {"tp": 0, "fn": 0, "fp": 0, "tn": 0}, defaultdict(lambda: {"tp": 0, "fn": 0, "fp": 0, "tn": 0}), []
661
+ for case in cases:
662
+ spots, sides = scanned[case["id"]]
663
+ r = score_pair(case, spots, sides, types, parents)
664
+ for key in ("tp" if r["detected"] else "fn", "fp" if r["still_flagged"] else "tn"):
665
+ totals[key] += 1
666
+ per_cwe[f"CWE-{case['cwe'][0]}"][key] += 1
667
+ results.append(r)
668
+ return {"overall": rates(totals), "categories": dict(sorted(per_cwe.items())), "cases": results}
669
+
670
+
671
+ def score_cve_pairs(suite, log):
672
+ scanned = {}
673
+ for case in suite["cases"]:
674
+ log(f" {case['id']}: {case['repo']} {case['fix'][:10]}")
675
+ scanned[case["id"]] = scan_pair_or_none(suite, case, log)
676
+ return score_scanned_pairs(suite, scanned)
677
+
678
+
679
+ def scan_pair_or_none(suite, case, log):
680
+ """scan_pair, or None (logged as a failure) when fetching or scanning the case fails: one case that can't be
681
+ fetched shouldn't stop every other suite of the night."""
682
+ try:
683
+ return scan_pair(suite, case, log)
684
+ except Exception as error: # noqa: BLE001 - any failure of one case is reported and the run goes on
685
+ detail = getattr(error, "stderr", "") or ""
686
+ log(f" {case['id']}: scan failed: {error} {detail.strip()}".rstrip())
687
+ return None
688
+
689
+
690
+ def score_scanned_pairs(suite, scanned):
691
+ """Scores of the cases that were scanned; a case whose scan failed (None) is left out of this run's scores."""
692
+ parents = cwe_parents()
693
+ scanned = {case_id: pair for case_id, pair in scanned.items() if pair is not None}
694
+ cases = [case for case in suite["cases"] if case["id"] in scanned]
695
+ (CACHE / f"{suite['name']}.issues.json").write_text(json.dumps(scanned))
696
+ return {mode: score_pairs_mode(cases, scanned, types, parents) for mode, types in MODES.items()}
697
+
698
+
699
+ SCORERS = {"owasp-benchmark": score_owasp, "vuln-snippets": score_snippets, "cwe-folders": score_cwe_folders,
700
+ "labelled-files": score_labelled, "seed-files": score_seeds}
701
+
702
+
703
+ def run_suite(suite, log):
704
+ if suite["kind"] == CVE_PAIRS:
705
+ log(f"== {suite['name']}: {len(suite['cases'])} fix commits")
706
+ return score_cve_pairs(suite, log)
707
+ log(f"== {suite['name']}: fetching {suite['commit'][:10]}")
708
+ return score_scanned_suite(suite, *fetch_and_scan(suite, log))
709
+
710
+
711
+ def score_scanned_suite(suite, root, issues):
712
+ (CACHE / f"{suite['name']}.issues.json").write_text(json.dumps(issues))
713
+ return SCORERS[suite["kind"]](root, suite, issues)
714
+
715
+
716
+ def setup_worker(workers=1):
717
+ """A parallel run's process: Django, and its share of the CPUs for Semgrep."""
718
+ os.environ["CODEWATCH_SEMGREP_JOBS"] = str(max(1, (os.cpu_count() or 2) // workers))
719
+ os.environ.setdefault("DJANGO_SETTINGS_MODULE", "codewatch.settings")
720
+ import django # only in a worker process, which starts without Django
721
+
722
+ django.setup()
723
+
724
+
725
+ def scan_job(suite, case=None):
726
+ """One unit of a parallel run: a whole suite, or one CVE case. Returns its scan and the log lines."""
727
+ lines = []
728
+ if case is None:
729
+ lines.append(f"== {suite['name']}: fetching {suite['commit'][:10]}")
730
+ root, issues = fetch_and_scan(suite, lines.append)
731
+ return suite["name"], None, (str(root), issues), lines
732
+ lines.append(f" {suite['name']} {case['id']}: {case['repo']} {case['fix'][:10]}")
733
+ return suite["name"], case["id"], scan_pair_or_none(suite, case, lines.append), lines
734
+
735
+
736
+ def parallel_jobs(suites):
737
+ """(suite, None) for a whole-repository suite and (suite, case) for each CVE case."""
738
+ return ([(suite, None) for suite in suites if suite["kind"] != CVE_PAIRS]
739
+ + [(suite, case) for suite in suites if suite["kind"] == CVE_PAIRS for case in suite["cases"]])
740
+
741
+
742
+ def scan_parallel(suites, log, workers):
743
+ """{suite name: (root, issues) or {case id: pair}}, every suite and CVE case scanned in its own process."""
744
+ jobs = parallel_jobs(suites)
745
+ scanned: dict = {suite["name"]: {} for suite in suites if suite["kind"] == CVE_PAIRS}
746
+ # spawn: a worker starts clean rather than forking a process that may hold threads or open connections.
747
+ with ProcessPoolExecutor(workers, mp_context=multiprocessing.get_context("spawn"),
748
+ initializer=setup_worker, initargs=(workers,)) as pool:
749
+ for future in as_completed([pool.submit(scan_job, suite, case) for suite, case in jobs]):
750
+ name, case_id, result, lines = future.result()
751
+ for line in lines:
752
+ log(line)
753
+ if case_id is None:
754
+ scanned[name] = result
755
+ else:
756
+ scanned[name][case_id] = result
757
+ return scanned
758
+
759
+
760
+ def chosen_cases(ids):
761
+ """The open CVE suites, each with only its cases whose id starts with one of ids; suites left with none dropped."""
762
+ suites = [suite for suite in json.loads((ROOT / "suites.json").read_text())["suites"]
763
+ if suite["kind"] == CVE_PAIRS and not suite.get("blind")]
764
+ chosen = [{**suite, "cases": [c for c in suite["cases"] if c["id"].startswith(tuple(ids))]} for suite in suites]
765
+ return [suite for suite in chosen if suite["cases"]]
766
+
767
+
768
+ def score_cases(ids, log=print, workers=1):
769
+ """Scan only the CVE cases whose id starts with one of ids (from suites that aren't blind) and score each,
770
+ without writing results: a quick check of the cases a rule change is meant to move. Returns
771
+ [(suite name, {mode: case result})]. A case whose scan fails is logged and left out, as in run()."""
772
+ chosen = chosen_cases(ids)
773
+ workers = max(1, min(workers, sum(len(suite["cases"]) for suite in chosen)))
774
+ scanned = scan_parallel(chosen, log, workers) if workers > 1 else {
775
+ suite["name"]: {case["id"]: scan_pair_or_none(suite, case, log) for case in suite["cases"]} for suite in chosen}
776
+ parents = cwe_parents()
777
+ pairs = [(suite["name"], case, scanned[suite["name"]].get(case["id"])) for suite in chosen for case in suite["cases"]]
778
+ return [(name, {mode: score_pair(case, pair[0], pair[1], types, parents) for mode, types in MODES.items()})
779
+ for name, case, pair in pairs if pair is not None]
780
+
781
+
782
+ def selected_suites(names):
783
+ """The named suites, or every suite except blind and deferred ones."""
784
+ return [suite for suite in json.loads((ROOT / "suites.json").read_text())["suites"]
785
+ if not ((names and suite["name"] not in names)
786
+ or (not names and (suite.get("blind") or suite.get("deferred"))))]
787
+
788
+
789
+ def scored_suite(suite, scanned, log):
790
+ """A suite's scores, from its parallel scan when there is one."""
791
+ if suite["name"] not in scanned:
792
+ return run_suite(suite, log)
793
+ if suite["kind"] == CVE_PAIRS:
794
+ # In the suite's order, as a sequential run writes them.
795
+ return score_scanned_pairs(suite, {c["id"]: scanned[suite["name"]][c["id"]] for c in suite["cases"]})
796
+ root, issues = scanned[suite["name"]]
797
+ return score_scanned_suite(suite, Path(root), issues)
798
+
799
+
800
+ def run(names=None, log=print, workers=1):
801
+ """Score the named suites, or every suite except blind and deferred ones, which run only when named (a deferred
802
+ suite is ground truth kept for rules that don't exist yet, such as PHP's). With workers > 1 the scans run in
803
+ that many processes; scoring and the order of the results are the same."""
804
+ suites = selected_suites(names)
805
+ scanned = scan_parallel(suites, log, workers) if workers > 1 else {}
806
+ out = {}
807
+ for suite in suites:
808
+ scored = scored_suite(suite, scanned, log)
809
+ result = {**scored, "suite": suite["name"], "commit": suite.get("commit", "per case"),
810
+ "scanned_at": datetime.now(UTC).isoformat(timespec="seconds"),
811
+ "overall": {mode: scored[mode]["overall"] for mode in MODES}}
812
+ write(suite, result)
813
+ out[suite["name"]] = result
814
+ return out
815
+
816
+
817
+ def write(suite, result):
818
+ results_dir = ROOT / "results"
819
+ results_dir.mkdir(exist_ok=True)
820
+ (results_dir / f"{suite['name']}.json").write_text(json.dumps(result, indent=1) + "\n")
821
+ (results_dir / f"{suite['name']}.md").write_text(render(suite, result))
822
+
823
+
824
+ def render_owasp(mode, r):
825
+ o = r["overall"]
826
+ return [f"## {mode.capitalize()} mode", "",
827
+ (f"**Detection {o['tpr']:.0%}, false alarms {o['fpr']:.0%}, score {o['score']:+.0%}** "
828
+ "(detection minus false alarms, averaged over categories)"), "",
829
+ "| Category | CWE | Detected | Missed | False alarms | Correctly quiet | Detection | False alarms | Score |",
830
+ "|---|---|---|---|---|---|---|---|---|",
831
+ *(f"| {name} | {c['cwe']} | {c['tp']} | {c['fn']} | {c['fp']} | {c['tn']} | {c['tpr']:.0%} | "
832
+ f"{c['fpr']:.0%} | {c['score']:+.0%} |" for name, c in r["categories"].items()), ""]
833
+
834
+
835
+ def render_snippets(mode, r):
836
+ o = r["overall"]
837
+ return [f"## {mode.capitalize()} mode", "",
838
+ f"**{o['found']} of {o['total']} vulnerable challenges flagged ({o['recall']:.0%})**", "",
839
+ "| Category | Flagged | Challenges |", "|---|---|---|",
840
+ *(f"| {k} | {v['found']} | {v['total']} |" for k, v in r["categories"].items()), "",
841
+ "| Challenge | Category | Flagged by |", "|---|---|---|",
842
+ *(f"| {c['challenge']} | {c['category']} | {', '.join(c['by']) or 'missed'} |" for c in r["challenges"]),
843
+ ""]
844
+
845
+
846
+ def render_cwe(mode, r):
847
+ o = r["overall"]
848
+ return [f"## {mode.capitalize()} mode", "",
849
+ (f"**{o['found']} of {o['total']} vulnerable files flagged for their CWE ({o['recall']:.0%}); "
850
+ f"{o['any_security']:.0%} have some security finding**"), "",
851
+ "| CWE | Flagged | Files |", "|---|---|---|",
852
+ *(f"| {k} | {v['found']} | {v['total']} |" for k, v in r["categories"].items()), ""]
853
+
854
+
855
+ def render_labelled(mode, r):
856
+ o = r["overall"]
857
+ return [f"## {mode.capitalize()} mode", "",
858
+ (f"**Detection {o['tpr']:.0%} ({o['tp']} of {o['tp'] + o['fn']} vulnerable files), false alarms "
859
+ f"{o['fpr']:.0%} ({o['fp']} of {o['fp'] + o['tn']} safe files)**"), "",
860
+ "| CWE | Detected | Missed | False alarms | Correctly quiet |", "|---|---|---|---|---|",
861
+ *(f"| {k} | {v['tp']} | {v['fn']} | {v['fp']} | {v['tn']} |" for k, v in r["categories"].items()), ""]
862
+
863
+
864
+ def render_pairs(mode, r):
865
+ o = r["overall"]
866
+ return [f"## {mode.capitalize()} mode", "",
867
+ (f"**Detection {o['tpr']:.0%} ({o['tp']} of {o['tp'] + o['fn']} vulnerable commits), still flagged after "
868
+ f"the fix {o['fpr']:.0%} ({o['fp']} of {o['fp'] + o['tn']})**"), "",
869
+ "| Advisory | CWE | Vulnerable commit | Fixed commit |", "|---|---|---|---|",
870
+ *(f"| {c['id']} | {', '.join(map(str, c['cwe']))} | {', '.join(c['by']) or 'missed'} | "
871
+ f"{', '.join(c['still_by']) or 'quiet'} |" for c in r["cases"]), ""]
872
+
873
+
874
+ RENDERERS = {"owasp-benchmark": render_owasp, "vuln-snippets": render_snippets, "cwe-folders": render_cwe,
875
+ "labelled-files": render_labelled, "seed-files": render_labelled, CVE_PAIRS: render_pairs}
876
+
877
+
878
+ def render(suite, result):
879
+ pinned = (f"Commit `{suite['commit'][:10]}` ({suite['license']})" if "commit" in suite
880
+ else "Fix commits and licenses pinned per case in `benchmarks/suites.json`")
881
+ lines = [f"# {suite['name']}", "", suite["about"], "", f"{pinned}, scanned {result['scanned_at']}.", "",
882
+ "Verdict mode counts only findings that claim a vulnerability; review mode adds security hotspots.", ""]
883
+ renderer = RENDERERS[suite["kind"]]
884
+ for mode in MODES:
885
+ lines += renderer(mode, result[mode])
886
+ return "\n".join(lines) + "\n"
887
+
888
+
889
+ def parse_timings(lines):
890
+ """The `timing` lines a bench run wrote (without their "timing" word), as dicts."""
891
+ rows = []
892
+ for line in lines:
893
+ fields = line.rstrip("\n").split("\t")
894
+ if len(fields) < 4:
895
+ continue
896
+ extra = fields[4].split() if len(fields) > 4 else []
897
+ rows.append({"suite": fields[0], "case": fields[1], "phase": fields[2], "seconds": float(fields[3]),
898
+ "parts": {k: float(v) for k, v in (p.split("=", 1) for p in extra if "=" in p)},
899
+ GAVE_UP: GAVE_UP in extra})
900
+ return rows
901
+
902
+
903
+ def minutes(seconds):
904
+ return f"{seconds / 60:.0f} min"
905
+
906
+
907
+ def summed(key, rows, part=False):
908
+ """[(name, seconds)] summed per row[key], or per analyzer part, largest first."""
909
+ totals = defaultdict(float)
910
+ for row in rows:
911
+ for name, seconds in (row["parts"].items() if part else [(row[key], row["seconds"])]):
912
+ totals[name] += seconds
913
+ return sorted(totals.items(), key=lambda kv: -kv[1])
914
+
915
+
916
+ def per_case(rows):
917
+ totals = defaultdict(float)
918
+ for row in rows:
919
+ totals[row["suite"], row["case"]] += row["seconds"]
920
+ return totals
921
+
922
+
923
+ def slowest(rows, top):
924
+ lines = []
925
+ for row in sorted((r for r in rows if r["phase"] != FETCH), key=lambda r: -r["seconds"])[:top]:
926
+ parts = " ".join(f"{k}={v:.0f}" for k, v in list(row["parts"].items())[:4])
927
+ lines.append(f" {row['seconds']:.0f}s {row['suite']} {row['case']} {row['phase']} {parts}"
928
+ + (" gave_up" if row[GAVE_UP] else ""))
929
+ return lines
930
+
931
+
932
+ def moved_cases(rows, before, top):
933
+ """The cases whose time moved by half or more (and a minute) since the previous run."""
934
+ now, then = per_case(rows), per_case(before)
935
+ moved = sorted(((now[k] - then[k], k) for k in now.keys() & then.keys()
936
+ if abs(now[k] - then[k]) >= max(60, then[k] / 2)), key=lambda d: -abs(d[0]))
937
+ return (["moved most since the previous run:" if moved else "no case's time moved by half or more"]
938
+ + [f" {then[k]:.0f}s -> {now[k]:.0f}s {k[0]} {k[1]}" for _, k in moved[:top]])
939
+
940
+
941
+ def timing_report(lines, previous=(), top=10):
942
+ """Where a bench run's time went: per suite, per analyzer, the slowest scans, and (given the previous run's
943
+ lines) the cases whose time moved most. Times are summed over the parallel processes and are wall time inside
944
+ each, so they rise with the load of the other scans running beside them."""
945
+ rows, before = parse_timings(lines), parse_timings(previous)
946
+ total = sum(r["seconds"] for r in rows)
947
+ fetching = sum(r["seconds"] for r in rows if r["phase"] == FETCH)
948
+ out = [f"{minutes(total)} of scans summed over processes, {minutes(fetching)} of it fetching"
949
+ + (f" (previous run {minutes(sum(r['seconds'] for r in before))})" if before else ""),
950
+ "by suite: " + ", ".join(f"{name} {minutes(s)}" for name, s in summed("suite", rows)),
951
+ "by analyzer: " + ", ".join(f"{name} {minutes(s)}" for name, s in summed(None, rows, part=True)[:8]),
952
+ "slowest:", *slowest(rows, top)]
953
+ if before:
954
+ out += moved_cases(rows, before, top)
955
+ return "\n".join(out)