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
@@ -0,0 +1,888 @@
1
+ import csv
2
+ import io
3
+ import json
4
+ import os
5
+ import re
6
+ import tempfile
7
+ from pathlib import Path
8
+ from typing import NamedTuple
9
+
10
+ import yaml
11
+
12
+ from . import summaries as summaries_module
13
+ from .base import (
14
+ BUG,
15
+ CODE,
16
+ CODE_SMELL,
17
+ CRITICAL,
18
+ HOTSPOT,
19
+ JS,
20
+ MAJOR,
21
+ MINOR,
22
+ PHP_VIEWS,
23
+ PY,
24
+ VULNERABILITY,
25
+ Analyzer,
26
+ C,
27
+ Finding,
28
+ Result,
29
+ is_test_file,
30
+ isolated_tool,
31
+ node_tool,
32
+ )
33
+ from .body_models import with_model_sources
34
+ from .constant_branches import blank_dead_branches
35
+ from .containers import track_slots
36
+ from .drf_serializers import with_serializer_checks
37
+ from .else_branches import rules_for_copies, split_else
38
+ from .flask_resources import with_resource_sources
39
+ from .inline_scripts import inline_scripts
40
+ from .jinja_sandboxes import with_sandbox_sanitizers
41
+ from .match_statements import match_as_if
42
+ from .php_template_sinks import TEMPLATE_RULE as PHP_TEMPLATE_RULE
43
+ from .php_template_sinks import tidy_message as tidy_php_template_message
44
+ from .php_template_sinks import with_php_template_sinks
45
+ from .project_checks import with_project_checks
46
+ from .python_tools import LineCache, complexity_severity, security_purpose
47
+ from .route_converters import (
48
+ django_text_parameters,
49
+ mark_url_text,
50
+ mark_viewset_lookups,
51
+ scalar_parameters,
52
+ type_route_converters,
53
+ )
54
+ from .slices import index_slices
55
+ from .starred_targets import unstar_targets
56
+ from .stored_fields import with_stored_sources
57
+ from .template_sinks import TEMPLATE_EXTENSIONS, with_template_sinks
58
+
59
+ SEMGREP_SEVERITY = {"ERROR": CRITICAL, "WARNING": MAJOR, "INFO": MINOR}
60
+ JS_SUFFIXES = {".js", ".jsx", ".mjs", ".cjs", ".ts", ".tsx"}
61
+ RETURNER_MAX_JS_BYTES = 200_000
62
+ # Seconds a rule may take on one focus file in the final scan (Semgrep's default is 5, then skips the file after
63
+ # three rules time out).
64
+ FOCUS_TIMEOUT = 60
65
+ SEMGREP_TYPE = {"security": VULNERABILITY, "correctness": BUG}
66
+
67
+ CPPCHECK_SEVERITY = {
68
+ "error": (CRITICAL, BUG),
69
+ "warning": (MAJOR, BUG),
70
+ "portability": (MINOR, BUG),
71
+ "performance": (MINOR, CODE_SMELL),
72
+ "style": (MINOR, CODE_SMELL),
73
+ }
74
+ CPPCHECK_NOISE = {"missingInclude", "missingIncludeSystem", "checkersReport", "unmatchedSuppression",
75
+ "toomanyconfigs", "normalCheckLevelMaxBranches", "unknownMacro", "syntaxError"}
76
+ # Structs declared in headers often mirror an external layout (SDK, hardware, file format): every field exists
77
+ # to match it, so cppcheck's "never read" is expected there. Structs local to a .c/.cpp file are still checked.
78
+ HEADER_ONLY_NOISE = {"unusedStructMember"}
79
+ HEADERS = {".h", ".hh", ".hpp", ".hxx", ".inl"}
80
+
81
+ JSCPD_FORMATS = "python,javascript,typescript,jsx,tsx,c,cpp,java,go,rust,csharp"
82
+
83
+
84
+ class Lizard(Analyzer):
85
+ """Complexity for non-Python languages; radon covers Python."""
86
+
87
+ name = executable = "lizard"
88
+ extensions = JS | C | (CODE - PY)
89
+
90
+ def run(self, ctx):
91
+ files = ctx.files_with(self.extensions)
92
+ out = self.exec(["--csv", *files], ctx, ok_codes=(0, 1))
93
+ threshold = ctx.complexity_threshold
94
+ result = Result()
95
+ total = 0
96
+ for row in csv.reader(io.StringIO(out)):
97
+ if len(row) < 11 or not row[1].isdigit():
98
+ continue
99
+ ccn, path, func, start, end = int(row[1]), row[6], row[7], int(row[9]), int(row[10])
100
+ total += ccn
101
+ if ccn > threshold:
102
+ result.findings.append(
103
+ Finding("lizard", "cyclomatic-complexity", complexity_severity(ccn, threshold), CODE_SMELL,
104
+ f"{func} has cyclomatic complexity {ccn} (threshold {threshold})",
105
+ ctx.rel(path), start, end)
106
+ )
107
+ result.metrics["complexity_other"] = total
108
+ return result
109
+
110
+
111
+ class Semgrep(Analyzer):
112
+ name = executable = "semgrep"
113
+ # Templates are scanned as text by the generic template rules (|safe/autoescape off and Flask's non-autoescaped
114
+ # extensions); the Python render calls are scanned by the generated taint rule.
115
+ extensions = CODE | {".yml", ".yaml"} | TEMPLATE_EXTENSIONS | PHP_VIEWS
116
+
117
+ def __init__(self):
118
+ self.timeouts = set()
119
+ self.first_rules, self.first_found, self.aliases, self.receivers = [], [], {}, {}
120
+
121
+ def binary(self):
122
+ # Own venv: semgrep pins dependencies (e.g. an old mcp) that conflict with codewatch's.
123
+ return isolated_tool("semgrep") or super().binary()
124
+
125
+ def exec(self, args, ctx, ok_codes=(0,), stream="stdout", cwd=None):
126
+ # semgrep-core gives each of its workers an io_uring, whose memory counts against the user's locked-memory
127
+ # limit (8 MB by default): a few scans at once failed with "io_uring_queue_init: Cannot allocate memory".
128
+ # Plain POSIX I/O has no such limit.
129
+ os.environ.setdefault("EIO_BACKEND", "posix")
130
+ return super().exec(args, ctx, ok_codes, stream, cwd)
131
+
132
+ @staticmethod
133
+ def project_rules(ctx, custom_rules):
134
+ """codewatch's rules with the sources, sinks and sanitizers learnt from this project's own code."""
135
+ python_texts = [read_source(ctx.root / f) or "" for f in ctx.files_with({".py"})]
136
+ for add in (with_model_sources, with_serializer_checks, with_resource_sources, with_sandbox_sanitizers,
137
+ with_project_checks, with_stored_sources):
138
+ custom_rules = add(custom_rules, python_texts)
139
+ custom_rules = with_template_sinks(custom_rules, {
140
+ f: text for f in ctx.files_with(TEMPLATE_EXTENSIONS) if (text := read_source(ctx.root / f)) is not None})
141
+ php_texts = {f: text for f in ctx.files_with(PHP_TEMPLATE_CANDIDATES)
142
+ if (text := read_source(ctx.root / f)) is not None}
143
+ return with_php_template_sinks(custom_rules, php_texts,
144
+ [t for f, t in php_texts.items() if f.endswith(".php")])
145
+
146
+ def learn(self, ctx, custom_rules, copies):
147
+ """The summary rounds of summaries.py over the summary targets: what the final rules are built from."""
148
+ targets, originals, work = copies
149
+ near = self.summary_targets(ctx, targets, originals)
150
+ # The first round of pass_rules shares pass 1's first scan.
151
+ signatures = self.signatures(ctx, near)
152
+ js_functions = self.js_functions(ctx, near)
153
+ self.first_rules = (summaries_module.pass_rules(custom_rules, set(signatures))
154
+ + summaries_module.js_pass_rules(custom_rules, js_functions))
155
+ summaries, hits = self.summarise(ctx, custom_rules, near, originals, work)
156
+ passes = self.find_passes(ctx, custom_rules, (near, originals, work), signatures)
157
+ summaries, hits = self.resummarise(ctx, custom_rules, (near, originals, work),
158
+ (summaries, hits), (signatures, js_functions, passes))
159
+ returners, fields = self.find_returners(
160
+ ctx, summaries_module.with_arguments(custom_rules, signatures, passes), near, originals, work)
161
+ return Learnt(signatures, js_functions, passes, summaries, hits, returners, fields)
162
+
163
+ def final_rules(self, custom_rules, known):
164
+ final = summaries_module.with_pass_through(
165
+ summaries_module.with_arguments(custom_rules, known.signatures, known.passes, known.summaries),
166
+ {False: set(known.signatures), True: known.js_functions}, known.passes, known.summaries, known.returners)
167
+ return (final + summaries_module.via_rules(final, known.summaries, self.receivers)
168
+ + summaries_module.from_rules(final, known.returners, known.summaries)
169
+ + summaries_module.field_variants(final, known.fields, known.summaries))
170
+
171
+ def main_scan(self, ctx, rules, copies):
172
+ """The scan whose results are reported: the registry config and the final rules."""
173
+ targets, originals, work = copies
174
+ configs = [CONFIG, ctx.semgrep_config] if ctx.semgrep_config else []
175
+ if rules:
176
+ (work / "custom.yml").write_text(yaml.safe_dump({"rules": rules}, sort_keys=False))
177
+ configs += [CONFIG, str(work / "custom.yml")]
178
+ # Every rule in this pass reads one file at a time, so narrowing it to the focus changes nothing
179
+ # in those files; the summaries above still saw every file.
180
+ focus = None if ctx.focus is None else set(ctx.focus)
181
+ main_targets = targets if focus is None else [t for t in targets if ctx.rel(originals.get(t, t)) in focus]
182
+ # Semgrep given no targets scans the working directory. The focus is the only place findings count,
183
+ # and a few files: there each rule gets FOCUS_TIMEOUT and no file is skipped for its timeouts (mlflow
184
+ # GHSA-wqmh's file_store.py and handlers.py were skipped at the default 5 s; PLAN.md step 68). So does a
185
+ # developer's own check (codewatch check, in CI too), where every finding counts: on a busy CI runner the
186
+ # default dropped this repository's 4,300-line tests/test_detection.py now and then (PLAN.md step 125).
187
+ long = focus is not None or ctx.local
188
+ limits = ["--timeout", str(FOCUS_TIMEOUT), "--timeout-threshold", "0"] if long else []
189
+ return self.scan(ctx, configs, main_targets, limits) if main_targets else {"results": []}
190
+
191
+ def gave_up_paths(self, ctx, originals):
192
+ """The files some rule timed out on, in any round (summary passes included), relative to the root."""
193
+ return sorted({ctx.rel(originals.get(p, p)) for p in self.timeouts})
194
+
195
+ def timeout_notes(self, ctx, originals):
196
+ if not self.timeouts:
197
+ return []
198
+ paths = self.gave_up_paths(ctx, originals)
199
+ listed = f"{', '.join(paths[:5])}{' and more' if len(paths) > 5 else ''}"
200
+ return [f"Semgrep gave up on some rules in {len(paths)} file(s), so they may hide findings: {listed}."]
201
+
202
+ def run(self, ctx):
203
+ custom_rules = yaml.safe_load(ctx.custom_rules).get("rules", []) if ctx.custom_rules else []
204
+ if not ctx.semgrep_config and not custom_rules:
205
+ return Result()
206
+ custom_rules = self.project_rules(ctx, rules_for_copies(custom_rules))
207
+ self.timeouts, self.first_found = set(), []
208
+ with tempfile.TemporaryDirectory() as work:
209
+ targets, originals = analysis_copies(ctx, ctx.files_with(self.extensions), Path(work) / "copies")
210
+ copies = (targets, originals, Path(work))
211
+ known = self.learn(ctx, custom_rules, copies)
212
+ data = self.main_scan(ctx, self.final_rules(custom_rules, known), copies)
213
+ result = Result()
214
+ result.notes += self.timeout_notes(ctx, originals)
215
+ result.gave_up = self.gave_up_paths(ctx, originals)
216
+ reading = Reading(ctx, originals, custom_rules, known, taint_checked(custom_rules), LineCache(ctx.root))
217
+ found = [f for item in data["results"] if (f := self.result_finding(reading, item)) is not None]
218
+ result.findings = without_derived_duplicates(found)
219
+ result.findings += self.uncalled_entry_points(ctx, custom_rules, known.hits, result.findings)
220
+ return result
221
+
222
+ def result_visible(self, reading, item, check, said):
223
+ """Whether a result stands: a summarised keyword reached, a via/from/field variant whose function is
224
+ visible from the file, and no CSRF token in a form the registry rule flagged."""
225
+ ctx, known = reading.ctx, reading.known
226
+ path, (check_id, via, field, derived), (custom_id, message, callee, keyword) = reading.path(item), check, said
227
+ if not summaries_module.keyword_summarised(callee, keyword, known.summaries.get(custom_id, ())):
228
+ return False
229
+ if not self.variant_visible(ctx, path, (via, field, derived), (custom_id, message, known)):
230
+ return False
231
+ return not (check_id.endswith(CSRF_FORM_RULE) and form_has_csrf_token(
232
+ reading.source.lines(path), item["start"]["line"], item["end"]["line"]))
233
+
234
+ def variant_visible(self, ctx, path, variant, said):
235
+ """A via, field or from variant's function (or field) is visible from the result's file."""
236
+ (via, field, derived), (custom_id, message, known) = variant, said
237
+ if via:
238
+ return self.via_visible(ctx, path, message, known.summaries.get(custom_id, ()))
239
+ if field:
240
+ return self.field_stored(path, message, known.fields.get(custom_id, ()))
241
+ return not derived or self.from_visible(ctx, path, message, known.returners.get(custom_id, ()))
242
+
243
+ def result_finding(self, reading, item):
244
+ """A Semgrep result as a finding, or None when it doesn't stand (result_visible)."""
245
+ path = reading.path(item)
246
+ extra = item["extra"]
247
+ check = derived_check(item["check_id"])
248
+ # Semgrep prefixes rules from a local file with path segments; map them back to codewatch's IDs.
249
+ custom_id = next((cid for cid in reading.custom_ids if check[0].endswith(cid)), None)
250
+ message, callee, keyword = summaries_module.split_keyword(extra["message"].strip())
251
+ if custom_id == PHP_TEMPLATE_RULE:
252
+ message = tidy_php_template_message(message)
253
+ if not self.result_visible(reading, item, check, (custom_id, message, callee, keyword)):
254
+ return None
255
+ kind = result_kind(reading, item, check[0], custom_id)
256
+ return Finding("codewatch" if custom_id else "semgrep", custom_id or check[0],
257
+ SEMGREP_SEVERITY.get(extra.get("severity"), MINOR), kind, message,
258
+ path, item["start"]["line"], item["end"]["line"])
259
+
260
+ @staticmethod
261
+ def summary_targets(ctx, targets, originals):
262
+ """The targets the summary rounds scan: with a focus, the focus files and what they import
263
+ (summaries.import_closure; PLAN step 64), otherwise all of them. CODEWATCH_SUMMARY_SCOPE=all scans all
264
+ of them anyway, to compare the two."""
265
+ if ctx.focus is None or os.environ.get("CODEWATCH_SUMMARY_SCOPE") == "all":
266
+ return targets
267
+ rels = {t: ctx.rel(originals.get(t, t)) for t in targets}
268
+ near = summaries_module.import_closure(set(rels.values()), ctx.focus,
269
+ lambda rel: read_source(ctx.root / rel))
270
+ return [t for t in targets if rels[t] in near]
271
+
272
+ def project_names(self, ctx):
273
+ """(names the project's code uses outside their definitions, {Python file: scalar parameters})."""
274
+ files = [(f, read_source(ctx.root / f) or "") for f in ctx.files_with((self.extensions or set()) & CODE)]
275
+ return (summaries_module.referenced_names(files),
276
+ {f: scalar_parameters(text) for f, text in files if f.endswith(".py")})
277
+
278
+ def uncalled_entry_points(self, ctx, custom_rules, hits, findings):
279
+ """A parameter that reaches a sink in a function nothing in the project calls: the data comes from
280
+ whoever does (a library user, a framework, a handler registered by name elsewhere), so it is left for
281
+ review rather than claimed as a vulnerability."""
282
+ if not hits:
283
+ return []
284
+ used, scalars = self.project_names(ctx)
285
+ rules = {r["id"]: r for r in custom_rules}
286
+ seen = {(f.rule, f.path, f.line) for f in findings}
287
+ out = []
288
+ for rule_id, path, line, func, param in sorted(hits):
289
+ if entry_point(func, path, (used, scalars.get(path, ()), ctx.focus), param) and \
290
+ (rule_id, path, line) not in seen:
291
+ seen.add((rule_id, path, line))
292
+ out.append(entry_point_finding(rules[rule_id], rule_id, (path, line, func, param)))
293
+ return out
294
+
295
+ def scan(self, ctx, configs, targets, limits=()):
296
+ # Several scans at once (parallel benchmarks) share the CPUs: Semgrep's default, a job per CPU each,
297
+ # stretched every rule past its timeout and dropped findings without an error.
298
+ jobs = ["--jobs", os.environ["CODEWATCH_SEMGREP_JOBS"]] if os.environ.get("CODEWATCH_SEMGREP_JOBS") else []
299
+ args = ["scan", *configs, *jobs, *limits, "--json", "--metrics=off", "--quiet", "--disable-version-check", *targets]
300
+ data = json.loads(self.exec(args, ctx, ok_codes=(0, 1)))
301
+ # A timeout skips that rule on that file, silently unless it's reported.
302
+ self.timeouts.update(e["path"] for e in data.get("errors", []) if e.get("type") == "Timeout" and e.get("path"))
303
+ return data
304
+
305
+ def rule_results(self, ctx, rules, scanned, place):
306
+ """(rule id, original path, line, message) for each result of scanning with rules. place: (config file,
307
+ originals, form). A result's id is the rule's own (Semgrep prefixes a local file's rules with path
308
+ segments), except in the "pass" form, which keeps Semgrep's; "pass" and "returner" strip the message."""
309
+ config, originals, form = place
310
+ strip = form in ("pass", "returner")
311
+ config.write_text(yaml.safe_dump({"rules": rules}, sort_keys=False))
312
+ data = self.scan(ctx, [CONFIG, str(config)], scanned)
313
+ ids = [] if form == "pass" else [r["id"] for r in rules]
314
+ return [(next((i for i in ids if item["check_id"].endswith(i)), item["check_id"]),
315
+ ctx.rel(originals.get(item["path"], item["path"])), item["start"]["line"],
316
+ item["extra"]["message"].strip() if strip else item["extra"]["message"])
317
+ for item in data["results"]]
318
+
319
+ def summarise(self, ctx, custom_rules, targets, originals, work):
320
+ """Pass 1 of summaries.py: which function parameters reach each taint rule's sinks, directly or through
321
+ functions already summarised. self.first_rules join the first scan, their results kept in
322
+ self.first_found."""
323
+ summaries, known, new, hits = {}, None, None, []
324
+ scanned = targets
325
+ texts = list(python_texts(ctx, targets).values())
326
+ self.aliases = {}
327
+ # Keyed by the original's path, as summaries are: a rewritten file is scanned from its analysis copy.
328
+ self.receivers = summaries_module.typed_receivers(dict(zip(
329
+ [ctx.rel(originals.get(t, t)) for t in python_texts(ctx, targets)], texts, strict=True)))
330
+ for _ in range(summaries_module.MAX_DEPTH):
331
+ # Semi-naive: a deeper pass has only the summaries the last one added as sinks. Whatever reaches an
332
+ # older one was found when it was added, in every file that names it.
333
+ own = summaries_module.summary_rules(custom_rules, new, base=new is None, receivers=self.receivers)
334
+ rules = own + (self.first_rules if new is None else [])
335
+ if not rules or not scanned:
336
+ break
337
+ found = self.rule_results(ctx, rules, scanned, (work / "summaries.yml", originals, "summary"))
338
+ if new is None:
339
+ found = self.keep_first_found(found, rules, own)
340
+ more = summaries_module.parse_summaries(found, lambda rel: read_source(ctx.root / rel), known, hits)
341
+ self.aliases.update(summaries_module.python_aliases(texts, all_names(more)))
342
+ merged = summaries_module.merge(summaries, summaries_module.with_aliases(more, self.aliases))
343
+ if merged is None:
344
+ break
345
+ new = summaries_module.added(summaries, merged)
346
+ scanned = mentioning(ctx, targets, added_names(summaries, merged))
347
+ summaries = known = merged
348
+ return summaries, hits
349
+
350
+ def keep_first_found(self, found, rules, own):
351
+ """The first scan's results for the pass rules that joined it, set aside in self.first_found; the rest."""
352
+ theirs = {r["id"] for r in rules} - {r["id"] for r in own}
353
+ self.first_found = [f for f in found if f[0] in theirs]
354
+ return [f for f in found if f[0] not in theirs]
355
+
356
+ def resummarise(self, ctx, custom_rules, copies, found, known):
357
+ """Pass 1 again for the summaries that rest on a call the passes now say hands nothing back
358
+ (stale_summaries): only their defining files, with with_pass_through's sanitizers; a function no longer
359
+ summarised makes its summarised callers stale in turn. copies: (targets, originals, work); found:
360
+ (summaries, hits); known: (signatures, js_functions, passes)."""
361
+ targets, originals, work = copies
362
+ summaries, hits = found
363
+ signatures, js_functions, passes = known
364
+ functions = {False: set(signatures), True: js_functions}
365
+ texts = python_texts(ctx, targets)
366
+ stale = summaries_module.stale_summaries(custom_rules, summaries, texts, (functions, passes, signatures))
367
+ # A round scans its stale functions without their summaries as sinks, so one resting on another stale one
368
+ # (SQLBot's preview on exec_sql, CVE-2026-53556) is dropped though its callee comes back: such functions
369
+ # get another round, with the callees this round confirmed.
370
+ for _ in range(summaries_module.MAX_DEPTH + 1):
371
+ if not stale:
372
+ break
373
+ kept = without_stale(summaries, stale)
374
+ rules = self.stale_rules(custom_rules, stale, kept, (signatures, functions, passes))
375
+ scanned = sorted(summaries_module.python_definers(texts, set().union(*stale.values())))
376
+ if not rules or not scanned:
377
+ break
378
+ results = tuple(self.rule_results(ctx, rules, scanned, (work / "resummaries.yml", originals, "summary")))
379
+ again = only_stale(summaries_module.parse_summaries(results, lambda rel: read_source(ctx.root / rel),
380
+ kept), stale)
381
+ updated = summaries_module.merge(kept, again) or kept
382
+ gone = {rule: names_of(summaries.get(rule, set()) - updated.get(rule, set())) for rule in stale}
383
+ summaries = updated
384
+ stale = still_stale(texts, gone, {rule: names_of(entries) for rule, entries in again.items()}, summaries)
385
+ summaries = summaries_module.realiased(summaries, self.aliases)
386
+ return summaries, live_hits(summaries, hits)
387
+
388
+ def stale_rules(self, custom_rules, stale, kept, known):
389
+ """Summary rules for the stale functions' rules, with the sanitizers the passes allow."""
390
+ signatures, functions, passes = known
391
+ cleaned = summaries_module.with_pass_through(
392
+ summaries_module.with_arguments(custom_rules, signatures, passes, kept), functions, passes, kept, {})
393
+ return [r for r in summaries_module.summary_rules(cleaned, kept, base=True, receivers=self.receivers)
394
+ if r["id"].removesuffix(summaries_module.SUMMARY_SUFFIX) in stale]
395
+
396
+ @staticmethod
397
+ def signatures(ctx, targets):
398
+ """python_signatures of the functions whose result is assigned, returned or passed on to another call: the
399
+ ones pass_rules asks about."""
400
+ calls = summaries_module.assigned_calls(
401
+ (read_source(ctx.root / t) or "" for t in targets if t.endswith(".py")), python=True)
402
+ return {name: defs for name, defs in summaries_module.python_signatures(
403
+ read_source(ctx.root / f) or "" for f in ctx.files_with({".py"})).items() if name in calls}
404
+
405
+ @staticmethod
406
+ def js_functions(ctx, targets):
407
+ """js_functions whose result is assigned or returned in a file that reads the request, and not also a Python
408
+ function's name (pass-through rounds after the first replace Python's answers by name). Asking about every
409
+ assigned call made a large app's scan half as long again (actual)."""
410
+ texts = [read_source(ctx.root / t) or "" for t in targets if Path(t).suffix in JS]
411
+ handling = [text for text in texts if summaries_module.JS_REQUEST_RE.search(text)]
412
+ python = {name for text in python_texts(ctx, targets).values() for name in summaries_module.python_functions(text)}
413
+ return summaries_module.js_functions(texts) & summaries_module.assigned_calls(handling) - python
414
+
415
+ def find_passes(self, ctx, custom_rules, copies, signatures):
416
+ """Which parameters of signatures' functions can be returned (pass_rules), from the first round's results
417
+ (self.first_found). Later rounds clean the arguments the last one found aren't handed back, asking again only
418
+ about the functions that call one whose answer changed. copies: (targets, originals, work)."""
419
+ targets, originals, work = copies
420
+ js_ids = {rule["id"] for rule in custom_rules if summaries_module.is_js(rule)}
421
+ texts = python_texts(ctx, targets)
422
+ passes = summaries_module.parse_passes([(c, p, line, m.strip()) for c, p, line, m in self.first_found])
423
+ # Before the first round every argument counted as handed back.
424
+ changed = set(signatures)
425
+ for _ in range(summaries_module.PASS_MAX_ROUNDS - 1):
426
+ # Only a function that hands something back and calls one whose answer changed can change, and only
427
+ # the files defining one need a scan.
428
+ asked = set(summaries_module.python_callers(texts, changed)) & all_names(passes)
429
+ found = self.pass_round(ctx, custom_rules, (texts, asked, signatures, passes), (work, originals))
430
+ if found is None:
431
+ break
432
+ kept = kept_passes(passes, js_ids, asked)
433
+ found = summaries_module.merge(kept, found) or kept
434
+ changed = changed_names(found, passes)
435
+ passes = found
436
+ return passes
437
+
438
+ def pass_round(self, ctx, custom_rules, asking, place):
439
+ """The passes a round finds for the functions asked about, or None when there is nothing to scan. asking:
440
+ (texts, asked, signatures, passes); place: (work, originals)."""
441
+ texts, asked, signatures, passes = asking
442
+ work, originals = place
443
+ scanned = sorted(summaries_module.python_definers(texts, asked))
444
+ rules = summaries_module.pass_rules(custom_rules, asked, signatures, passes)
445
+ if not rules or not scanned:
446
+ return None
447
+ return summaries_module.parse_passes(
448
+ self.rule_results(ctx, rules, scanned, (work / "passes.yml", originals, "pass")))
449
+
450
+ def find_returners(self, ctx, custom_rules, targets, originals, work):
451
+ """Pass 3 of summaries.py: which functions return request data, directly or from returners found before,
452
+ and (in the first scan) which fields of self/this request data is stored in."""
453
+ returners, fields = {}, {}
454
+ # An unminified library bundled with the app (materialize.js, 366 KB) multiplies this pass's time by ten,
455
+ # and big single-file apps are Python's habit, not JavaScript's.
456
+ targets = [t for t in targets if not oversized_js(ctx, t)]
457
+ scanned, new = targets, {}
458
+ for depth in range(summaries_module.MAX_DEPTH):
459
+ # Semi-naive, as in summarise: a deeper pass's sources are calls to the returners the last one added.
460
+ rules = returner_round_rules(custom_rules, new, depth)
461
+ if not rules or not scanned:
462
+ break
463
+ found = self.rule_results(ctx, rules, scanned, (work / "returners.yml", originals, "returner"))
464
+ stored = [f for f in found if f[0].endswith(summaries_module.FIELDS_SUFFIX)]
465
+ fields = summaries_module.merge(fields, summaries_module.parse_fields(stored)) or fields
466
+ more = summaries_module.parse_returners(without(found, stored), lambda rel: read_source(ctx.root / rel))
467
+ merged = summaries_module.merge(returners, more)
468
+ if merged is None:
469
+ break
470
+ new = summaries_module.added(returners, merged)
471
+ scanned = mentioning(ctx, targets, added_names(returners, merged))
472
+ returners = merged
473
+ return returners, fields
474
+
475
+ @staticmethod
476
+ def field_stored(path, message, fields):
477
+ match = summaries_module.FIELD_RE.search(message.strip())
478
+ return bool(match) and (match.group(1), path) in fields
479
+
480
+ @staticmethod
481
+ def from_visible(ctx, path, message, returners):
482
+ match = summaries_module.FROM_RE.search(message.strip())
483
+ if not match:
484
+ return False
485
+ defining = {p for func, p in returners if func == match.group(1)}
486
+ return bool(defining) and summaries_module.visible(path, defining, lambda rel: read_source(ctx.root / rel))
487
+
488
+ @staticmethod
489
+ def via_visible(ctx, path, message, summaries):
490
+ match = summaries_module.VIA_RE.search(message.strip())
491
+ if not match:
492
+ return False
493
+ defining = {s[4] for s in summaries if s[0] == match.group(1)}
494
+ return bool(defining) and summaries_module.visible(path, defining, lambda rel: read_source(ctx.root / rel))
495
+
496
+
497
+ CONFIG = "--config"
498
+
499
+
500
+ class Learnt(NamedTuple):
501
+ """What the summary rounds found, which the final rules and the results' checks are built from."""
502
+ signatures: dict
503
+ js_functions: set
504
+ passes: dict
505
+ summaries: dict
506
+ hits: list
507
+ returners: dict
508
+ fields: dict
509
+
510
+
511
+ class Reading(NamedTuple):
512
+ """What reading the main scan's results needs."""
513
+ ctx: object
514
+ originals: dict
515
+ custom_rules: list
516
+ known: Learnt
517
+ traced: dict
518
+ source: LineCache
519
+
520
+ @property
521
+ def custom_ids(self):
522
+ return [r["id"] for r in self.custom_rules]
523
+
524
+ def path(self, item):
525
+ return self.ctx.rel(self.originals.get(item["path"], item["path"]))
526
+
527
+
528
+ def derived_check(check_id):
529
+ """(rule id without variant suffixes, a via variant, a field variant, any variant)."""
530
+ plain = check_id.removesuffix(summaries_module.VIA_SUFFIX)
531
+ via, field = plain != check_id, plain.endswith(summaries_module.FIELD_SUFFIX)
532
+ plain = plain.removesuffix(summaries_module.FIELD_SUFFIX).removesuffix(summaries_module.FROM_SUFFIX)
533
+ return plain, via, field, plain != check_id
534
+
535
+
536
+ def result_kind(reading, item, check_id, custom_id):
537
+ """A result's type: the rule's, made a hotspot where it is left for review."""
538
+ path, metadata = reading.path(item), item["extra"].get("metadata", {})
539
+ kind = semgrep_type(check_id, metadata)
540
+ if kind != VULNERABILITY:
541
+ return kind
542
+ # codewatch's own taint rule for this weakness already followed the data here; a registry rule that matches
543
+ # the same weakness without seeing guards or sanitizers is left for review, not a verdict. A template's
544
+ # inline scripts are scanned as JavaScript, so its findings are judged like a .js file's.
545
+ suffix = ".js" if Path(path).suffix in TEMPLATE_EXTENSIONS else Path(path).suffix
546
+ if not custom_id and cwe_numbers(metadata.get("cwe")) & reading.traced.get(suffix, set()):
547
+ return HOTSPOT
548
+ # Rules for primitives that are only weak when they protect something (MD5 for a Gravatar URL is fine): a
549
+ # vulnerability where the code is about secrets or verification, otherwise for review.
550
+ if (metadata.get("security-purpose") == "required"
551
+ and not security_purpose(reading.source, path, item["start"]["line"])):
552
+ return HOTSPOT
553
+ # Test code isn't served to anyone, so what flows through it is for review, not a verdict.
554
+ return HOTSPOT if is_test_file(path) else kind
555
+
556
+
557
+ def derived(finding):
558
+ return any(r.search(finding.message) for r in (summaries_module.VIA_RE, summaries_module.FROM_RE,
559
+ summaries_module.FIELD_RE))
560
+
561
+
562
+ def without_derived_duplicates(findings):
563
+ """A via/from/field finding on a line a direct finding of the same rule already reports is dropped."""
564
+ direct = {(f.rule, f.path, f.line) for f in findings if not derived(f)}
565
+ return [f for f in findings if not (derived(f) and (f.rule, f.path, f.line) in direct)]
566
+
567
+
568
+ def still_stale(texts, gone, confirmed, summaries):
569
+ """{rule: functions to summarise again}: callers summarised through a function that no longer is, and
570
+ functions this round dropped that call one it kept."""
571
+ stale = {}
572
+ for rule, names_gone in gone.items():
573
+ if not names_gone:
574
+ continue
575
+ callers = ((set(summaries_module.python_callers(texts, names_gone)) & {e[0] for e in summaries.get(rule, ())})
576
+ | (names_gone & set(summaries_module.python_callers(texts, confirmed.get(rule, set())))))
577
+ if callers:
578
+ stale[rule] = callers
579
+ return stale
580
+
581
+
582
+ def python_texts(ctx, targets):
583
+ """{target: its text} for the Python targets, in order."""
584
+ return {t: read_source(ctx.root / t) or "" for t in targets if t.endswith(".py")}
585
+
586
+
587
+ def names_of(entries):
588
+ return {e[0] for e in entries}
589
+
590
+
591
+ def all_names(found):
592
+ """Every function name in a {rule: {(name, ...)}}."""
593
+ return {e[0] for entries in found.values() for e in entries}
594
+
595
+
596
+ def without_stale(summaries, stale):
597
+ return {rule: {e for e in entries if e[0] not in stale.get(rule, ())} for rule, entries in summaries.items()}
598
+
599
+
600
+ def only_stale(found, stale):
601
+ return {rule: {e for e in entries if e[0] in stale.get(rule, ())} for rule, entries in found.items()}
602
+
603
+
604
+ def live_hits(summaries, hits):
605
+ """The hits of functions still summarised."""
606
+ live = {(rule, e[0], e[4]) for rule, entries in summaries.items() for e in entries}
607
+ return [h for h in hits if (h[0], h[3], h[1]) in live]
608
+
609
+
610
+ def changed_names(found, before):
611
+ """Function names whose answers differ between two {rule: {(name, ...)}}."""
612
+ return {e[0] for rule in set(found) | set(before) for e in found.get(rule, set()) ^ before.get(rule, set())}
613
+
614
+
615
+ def oversized_js(ctx, target):
616
+ return Path(target).suffix in JS_SUFFIXES and (ctx.root / target).stat().st_size > RETURNER_MAX_JS_BYTES
617
+
618
+
619
+ def kept_passes(passes, js_ids, asked):
620
+ """The passes kept into the next round: a JavaScript rule's all, a Python rule's except the functions asked
621
+ about again."""
622
+ return {rule: {e for e in entries if rule in js_ids or e[0] not in asked} for rule, entries in passes.items()}
623
+
624
+
625
+ def returner_round_rules(custom_rules, new, depth):
626
+ """A returner round's rules; the first also asks which self/this fields store request data."""
627
+ rules = summaries_module.returner_rules(custom_rules, new, base=depth == 0)
628
+ return rules + (summaries_module.field_rules(custom_rules) if depth == 0 else [])
629
+
630
+
631
+ def without(items, dropped):
632
+ return [x for x in items if x not in dropped]
633
+
634
+
635
+ def entry_point(func, path, known, param):
636
+ """Whether a summarised parameter is an uncalled entry point to report: a public function nothing calls, not
637
+ in a test, with a parameter that can carry text, in the focus. known: (names used, scalar parameters, focus)."""
638
+ used, scalars, focus = known
639
+ return not (func in used or func.startswith("_") or is_test_file(path) or (func, param) in scalars
640
+ or (focus is not None and path not in focus))
641
+
642
+
643
+ def entry_point_finding(rule, rule_id, hit):
644
+ path, line, func, param = hit
645
+ message = (f"{rule['message'].strip()} [parameter {param} of {func}(), which nothing in the project "
646
+ f"calls: check what its callers pass]")
647
+ return Finding("codewatch", rule_id, SEMGREP_SEVERITY.get(rule.get("severity"), MINOR), HOTSPOT,
648
+ message, path, line, line)
649
+
650
+
651
+ LANGUAGE_SUFFIXES = {"python": [".py"], "javascript": [".js", ".jsx", ".mjs", ".cjs"], "typescript": [".ts", ".tsx"],
652
+ "php": [".php"]}
653
+ CWE_RE = re.compile(r"CWE-(\d+)")
654
+
655
+
656
+ def cwe_numbers(cwes):
657
+ if isinstance(cwes, str):
658
+ cwes = [cwes]
659
+ return {int(m.group(1)) for c in cwes or [] if (m := CWE_RE.search(str(c)))}
660
+
661
+
662
+ def taint_checked(rules):
663
+ """{file suffix: CWEs that codewatch's taint rules check in that language}."""
664
+ checked = {}
665
+ for rule in rules:
666
+ if rule.get("mode") != "taint":
667
+ continue
668
+ for language in rule.get("languages", []):
669
+ for suffix in LANGUAGE_SUFFIXES.get(language, []):
670
+ checked.setdefault(suffix, set()).update(cwe_numbers(rule.get("metadata", {}).get("cwe")))
671
+ return checked
672
+
673
+
674
+ def added_names(before, after):
675
+ """Function names in after's {rule: {(name, ...)}} that before lacks."""
676
+ return {entry[0] for rule, found in after.items() for entry in found - before.get(rule, set())}
677
+
678
+
679
+ def mentioning(ctx, targets, names):
680
+ """The targets whose text uses one of names. A deeper summary pass only adds sinks or sources for calls to the
681
+ functions the last one found, so a file that never names one gives what it gave before."""
682
+ return [t for t in targets if not names.isdisjoint(WORD_RE.findall(read_source(ctx.root / t) or ""))]
683
+
684
+
685
+ WORD_RE = re.compile(r"\w+")
686
+
687
+
688
+ def read_source(path):
689
+ try:
690
+ return Path(path).read_text()
691
+ except (OSError, UnicodeDecodeError):
692
+ return None
693
+
694
+
695
+ def analysis_copy(source, url_views=None):
696
+ """Python source as Semgrep should see it: dead constant branches blanked, slices made indexes, starred targets unstarred, container
697
+ slots tracked one by one, match statements made ifs, else branches made ifs of their own, Flask converter types written on view parameters and
698
+ Django views' free-text URL arguments marked (url_views, from django_text_parameters), and DRF ViewSets'
699
+ lookups. None when nothing changes."""
700
+ current = None
701
+ for rewrite in (blank_dead_branches, index_slices, unstar_targets, track_slots, match_as_if, split_else,
702
+ type_route_converters, mark_viewset_lookups,
703
+ lambda text: mark_url_text(text, url_views)):
704
+ current = rewrite(current or source) or current
705
+ return current
706
+
707
+
708
+ def url_routes(ctx, files):
709
+ """django_text_parameters for the project's Django URL modules (urls.py, or a urls package)."""
710
+ return django_text_parameters(
711
+ text for rel in files if "urls" in Path(rel).parts[-1] or "urls" in Path(rel).parts[:-1]
712
+ if (text := read_source(ctx.root / rel)) is not None)
713
+
714
+
715
+ def rewritten_source(ctx, rel, url_views):
716
+ """A PHP or Python file's analysis copy text (see analysis_copy and php_copy_text), or None."""
717
+ if rel.endswith(".php"):
718
+ text = read_source(ctx.root / rel)
719
+ return php_copy_text(text) if text and "compact(" in text else None
720
+ if rel.endswith(".py"):
721
+ try:
722
+ return analysis_copy((ctx.root / rel).read_text(), url_views)
723
+ except (OSError, UnicodeDecodeError):
724
+ return None
725
+ return None
726
+
727
+
728
+ def add_rewritten(rel, rewritten, copies, found):
729
+ """The file as a target: itself, or its rewritten copy mapped back to it. found: (targets, originals)."""
730
+ targets, originals = found
731
+ if rewritten is None:
732
+ targets.append(rel)
733
+ return
734
+ copy = copies / rel
735
+ copy.parent.mkdir(parents=True, exist_ok=True)
736
+ copy.write_text(rewritten)
737
+ targets.append(str(copy))
738
+ originals[str(copy)] = rel
739
+
740
+
741
+ def analysis_copies(ctx, files, copies):
742
+ """Targets for Semgrep: Python files that need it are scanned as rewritten copies (see analysis_copy).
743
+ Returns the target list and {copy path: original relative path}."""
744
+ targets, originals = [], {}
745
+ url_views = url_routes(ctx, [rel for rel in files if rel.endswith(".py")])
746
+ # Semgrep refuses a symlink given as a target and fails the whole scan; the file it points to is scanned.
747
+ for rel in (rel for rel in files if not (ctx.root / rel).is_symlink()):
748
+ rewritten = rewritten_source(ctx, rel, url_views)
749
+ suffix = Path(rel).suffix.lower()
750
+ if suffix in TEMPLATE_EXTENSIONS:
751
+ add_inline_scripts(ctx, rel, copies, targets, originals)
752
+ if suffix in PHP_VIEWS:
753
+ add_php_copy(ctx, rel, copies, targets, originals)
754
+ else:
755
+ add_rewritten(rel, rewritten, copies, (targets, originals))
756
+ return targets, originals
757
+
758
+
759
+ # Files read for PHP templates and their variables (php_template_sinks.py).
760
+ PHP_TEMPLATE_CANDIDATES = {".php", ".ctp", ".phtml", ".tpl", ".twig", ".latte"}
761
+ PHP_TAG_RE = re.compile(r"<\?(php\b|=)")
762
+ COMPACT_RE = re.compile(r"\bcompact\(\s*((?:['\"]\w+['\"]\s*,\s*)*['\"]\w+['\"])\s*\)")
763
+
764
+
765
+ def php_copy_text(text):
766
+ """PHP as Semgrep should see it: compact('a', 'b') written out as ['a' => $a, 'b' => $b], on the same line, so
767
+ the variables it passes to a view are seen (Laravel's view('x', compact('user')), CakePHP's
768
+ $this->set(compact('referer'))). None when nothing changes."""
769
+ def written(match):
770
+ keys = re.findall(r"['\"](\w+)['\"]", match.group(1))
771
+ return "[" + ", ".join(f"'{k}' => ${k}" for k in keys) + "]"
772
+ rewritten = COMPACT_RE.sub(written, text)
773
+ return None if rewritten == text else rewritten
774
+
775
+
776
+ def add_php_copy(ctx, rel, copies, targets, originals):
777
+ """A PHP view or include (base.PHP_VIEWS) as a .php copy, mapped back to it: Semgrep picks a file's language by
778
+ its extension and skips these (MISP's CakePHP 2 views, GHSA-p9m5). A file with no PHP tag (an .inc of another
779
+ language) is left out."""
780
+ text = read_source(ctx.root / rel)
781
+ if not text or not PHP_TAG_RE.search(text):
782
+ return
783
+ copy = copies / f"{rel}.php"
784
+ copy.parent.mkdir(parents=True, exist_ok=True)
785
+ copy.write_text(php_copy_text(text) or text)
786
+ targets.append(str(copy))
787
+ originals[str(copy)] = rel
788
+
789
+
790
+ def add_inline_scripts(ctx, rel, copies, targets, originals):
791
+ """A template's inline scripts as a .js copy beside it (inline_scripts.py), mapped back to the template."""
792
+ text = read_source(ctx.root / rel)
793
+ script = inline_scripts(text) if text else None
794
+ if script is None:
795
+ return
796
+ copy = copies / f"{rel}.inline.js"
797
+ copy.parent.mkdir(parents=True, exist_ok=True)
798
+ copy.write_text(script)
799
+ targets.append(str(copy))
800
+ originals[str(copy)] = rel
801
+
802
+
803
+ CSRF_FORM_RULE = "django-no-csrf-token"
804
+ CSRF_TOKEN_RE = re.compile(r"\{%-?\s*csrf_token\s*-?%\}")
805
+
806
+
807
+ def form_has_csrf_token(lines, start, end):
808
+ """Whether the form Semgrep matched (lines start..end) has a {% csrf_token %}. The registry's
809
+ django-no-csrf-token rule checks with `...`, which in generic mode spans about ten lines, so any longer form
810
+ was reported without its token (codewatch's own project settings form, 2026-11-18)."""
811
+ return bool(CSRF_TOKEN_RE.search("\n".join(lines[start - 1:end])))
812
+
813
+
814
+ def semgrep_type(check_id, metadata):
815
+ """Only rules Semgrep marks "vuln" (taint-checked or a definite flaw) are vulnerabilities;
816
+ "audit" and other security rules flag risky code to review, so they're hotspots."""
817
+ category = metadata.get("category", "")
818
+ if category != "security":
819
+ return SEMGREP_TYPE.get(category, CODE_SMELL)
820
+ vuln = "vuln" in (metadata.get("subcategory") or []) and ".audit." not in check_id
821
+ return VULNERABILITY if vuln else HOTSPOT
822
+
823
+
824
+ class Cppcheck(Analyzer):
825
+ name = executable = "cppcheck"
826
+ extensions = C
827
+
828
+ def run(self, ctx):
829
+ with tempfile.NamedTemporaryFile("w", suffix=".txt") as listing:
830
+ listing.write("\n".join(ctx.files_with(C)))
831
+ listing.flush()
832
+ err = self.exec(
833
+ ["--enable=warning,style,performance,portability", "--inline-suppr", "--quiet",
834
+ "--max-configs=1", f"-j{os.cpu_count() or 2}",
835
+ "--template={file}\t{line}\t{severity}\t{id}\t{message}", f"--file-list={listing.name}"],
836
+ ctx, stream="stderr",
837
+ )
838
+ result = Result()
839
+ for line in err.splitlines():
840
+ parts = line.split("\t", 4)
841
+ if len(parts) != 5 or parts[3] in CPPCHECK_NOISE or parts[2] not in CPPCHECK_SEVERITY:
842
+ continue
843
+ path, lineno, sev, rule, message = parts
844
+ if rule in HEADER_ONLY_NOISE and Path(path).suffix.lower() in HEADERS:
845
+ continue
846
+ severity, type_ = CPPCHECK_SEVERITY[sev]
847
+ result.findings.append(
848
+ Finding("cppcheck", rule, severity, type_, message, ctx.rel(path), int(lineno) or None)
849
+ )
850
+ return result
851
+
852
+
853
+ class Jscpd(Analyzer):
854
+ name = executable = "jscpd"
855
+ extensions = CODE
856
+
857
+ def binary(self):
858
+ return node_tool("jscpd")
859
+
860
+ def run(self, ctx):
861
+ with tempfile.TemporaryDirectory() as out_dir:
862
+ self.exec(["--reporters", "json", "--output", out_dir, "--silent",
863
+ "--absolute", "--format", JSCPD_FORMATS, "--min-tokens", "70",
864
+ *(["--ignore", ",".join(ctx.exclusions)] if ctx.exclusions else []), str(ctx.root)],
865
+ ctx, cwd=out_dir)
866
+ report = Path(out_dir) / "jscpd-report.json"
867
+ data = json.loads(report.read_text()) if report.exists() else {"duplicates": [], "statistics": {}}
868
+ tracked = set(ctx.files)
869
+ result = Result()
870
+ for dup in data["duplicates"]:
871
+ sides = [dup["firstFile"], dup["secondFile"]]
872
+ paths = [ctx.rel(s["name"]) for s in sides]
873
+ for side, path, other_side, other in zip(sides, paths, sides[::-1], paths[::-1], strict=True):
874
+ if path not in tracked:
875
+ continue
876
+ start, end = side["start"], side["end"]
877
+ result.duplicated_lines.setdefault(path, set()).update(range(start, end + 1))
878
+ result.findings.append(
879
+ Finding("jscpd", "duplicated-block", MINOR, CODE_SMELL,
880
+ f"{end - start + 1} duplicated lines, also in {other}:{other_side['start']}",
881
+ path, start, end)
882
+ )
883
+ dup_lines = sum(len(v) for v in result.duplicated_lines.values())
884
+ total = data.get("statistics", {}).get("total", {}).get("lines") or 0
885
+ result.metrics["duplicated_lines"] = dup_lines
886
+ if total:
887
+ result.metrics["duplicated_lines_percent"] = round(100 * dup_lines / total, 2)
888
+ return result