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/collect.py ADDED
@@ -0,0 +1,518 @@
1
+ """Running analyzers and turning their output into an upload payload.
2
+
3
+ Shared by the server (scanning a mirror worktree) and the codewatch-scan client (scanning a local working copy),
4
+ so it must not import Django.
5
+ """
6
+ import fnmatch
7
+ import re
8
+ import subprocess
9
+ import time
10
+ from dataclasses import asdict, dataclass, field
11
+ from datetime import UTC, datetime, timedelta
12
+ from pathlib import Path
13
+
14
+ from .analyzers import ANALYZERS
15
+ from .analyzers.base import CODE, Context, Result
16
+ from .duplicates import dedupe
17
+ from .fingerprint import assign_fingerprints
18
+
19
+ HUNK_RE = re.compile(r"^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@")
20
+ MAX_SOURCE_BYTES = 512 * 1024
21
+ MAX_TOTAL_SOURCE_BYTES = 50 * 1024 * 1024
22
+ # new_code_period values: "30d" (days), otherwise a git ref; a leading "-" would be read as a git option.
23
+ DAYS_RE = re.compile(r"^(\d{1,4})d$")
24
+ REF_RE = re.compile(r"^\w[\w./~^@{}-]{0,199}$")
25
+
26
+
27
+ DEFAULT_EXCLUSIONS = [
28
+ "**/node_modules/**",
29
+ # A virtualenv committed with the project (one of the maintainer's has 9,773 files of it).
30
+ "**/site-packages/**",
31
+ "**/migrations/**",
32
+ "**/vendor/**",
33
+ "**/third_party/**",
34
+ "**/dist/**",
35
+ "**/build/**",
36
+ "**/*.min.js",
37
+ "**/package-lock.json",
38
+ "**/yarn.lock",
39
+ "**/poetry.lock",
40
+ "**/uv.lock",
41
+ ]
42
+ @dataclass
43
+ class ScanConfig:
44
+ main_branch: str = ""
45
+ exclusions: list[str] = field(default_factory=lambda: list(DEFAULT_EXCLUSIONS))
46
+ disabled_analyzers: list[str] = field(default_factory=list)
47
+ semgrep_config: str = "p/default"
48
+ complexity_threshold: int = 10
49
+ cognitive_complexity_threshold: int = 15
50
+ duplicate_literal_threshold: int = 3
51
+ custom_rules: str = ""
52
+ a11y_urls: list[str] = field(default_factory=list)
53
+ new_code_period: str = ""
54
+ # Successful main-branch analyses, newest first: [{"commit": ..., "reference_commit": ..., "started_at": ...}]
55
+ main_analyses: list[dict] = field(default_factory=list)
56
+
57
+ @classmethod
58
+ def from_dict(cls, data):
59
+ return cls(**{k: v for k, v in data.items() if k in cls.__dataclass_fields__})
60
+
61
+
62
+ class GitError(RuntimeError):
63
+ pass
64
+
65
+
66
+ # Before every revision passed to git: a value from an upload or the server's config ("--output=/path") is then
67
+ # a bad revision, not an option that writes a file.
68
+ END_OF_OPTIONS = "--end-of-options"
69
+
70
+
71
+ def run_git(*args, cwd=None, check=True, env=None):
72
+ proc = subprocess.run(["git", *args], cwd=cwd, capture_output=True, text=True, check=False, env=env)
73
+ if check and proc.returncode != 0:
74
+ raise GitError(f"git {' '.join(args)} failed: {proc.stderr.strip()}")
75
+ return proc.stdout
76
+
77
+
78
+ def parse_diff(diff):
79
+ """Map of path -> set of line numbers added or modified, from `git diff -U0` output."""
80
+ changed, current = {}, None
81
+ for line in diff.splitlines():
82
+ if line.startswith("+++ "):
83
+ target = line[4:]
84
+ current = None if target == "/dev/null" else target.removeprefix("b/")
85
+ if current:
86
+ changed.setdefault(current, set())
87
+ elif current and (m := HUNK_RE.match(line)):
88
+ start, count = int(m[1]), int(m[2]) if m[2] is not None else 1
89
+ changed[current].update(range(start, start + count))
90
+ return changed
91
+
92
+
93
+ class LocalRepo:
94
+ """A developer's working copy, scanned as-is, including uncommitted and untracked (non-ignored) files."""
95
+
96
+ def __init__(self, path):
97
+ self.root = Path(run_git("rev-parse", "--show-toplevel", cwd=path).strip())
98
+
99
+ def git(self, *args, check=True):
100
+ return run_git(*args, cwd=self.root, check=check)
101
+
102
+ def head(self):
103
+ return self.git("rev-parse", "HEAD").strip()
104
+
105
+ def branch(self):
106
+ """Current branch, also before the first commit; "HEAD" when detached."""
107
+ return self.git("symbolic-ref", "--short", "-q", "HEAD", check=False).strip() or "HEAD"
108
+
109
+ def dirty(self):
110
+ return bool(self.git("status", "--porcelain").strip())
111
+
112
+ def files(self):
113
+ # -z: without it git quotes paths with non-ASCII characters, and those would no longer exist on disk.
114
+ listed = self.git("ls-files", "-z", "--cached", "--others", "--exclude-standard").split("\0")
115
+ return sorted({f for f in listed if (self.root / f).is_file()})
116
+
117
+ def untracked(self):
118
+ return [f for f in self.git("ls-files", "-z", "--others", "--exclude-standard").split("\0") if f]
119
+
120
+ def has_commit(self, commit):
121
+ return bool(commit) and subprocess.run(
122
+ ["git", "cat-file", "-e", END_OF_OPTIONS, f"{commit}^{{commit}}"], cwd=self.root, capture_output=True, check=False
123
+ ).returncode == 0
124
+
125
+ def is_ancestor(self, a, b):
126
+ return subprocess.run(["git", "merge-base", "--is-ancestor", END_OF_OPTIONS, a, b], cwd=self.root, check=False).returncode == 0
127
+
128
+ def merge_base(self, a, b):
129
+ return self.git("merge-base", END_OF_OPTIONS, a, b, check=False).strip() or None
130
+
131
+ def resolve_commit(self, ref):
132
+ return self.git("rev-parse", "--verify", "--quiet", END_OF_OPTIONS, f"{ref}^{{commit}}",
133
+ check=False).strip() or None
134
+
135
+ def resolve_main(self, main_branch):
136
+ """Prefer the remote-tracking ref: a local main is often stale."""
137
+ for ref in (f"origin/{main_branch}", main_branch):
138
+ commit = self.resolve_commit(ref)
139
+ if commit:
140
+ return commit
141
+ return None
142
+
143
+ def changed_lines(self, base):
144
+ changed = parse_diff(self.git("diff", "-U0", "--no-renames", "--no-color", END_OF_OPTIONS, base))
145
+ for f in self.untracked():
146
+ try:
147
+ count = len((self.root / f).read_text(errors="replace").splitlines())
148
+ except OSError:
149
+ continue
150
+ changed[f] = set(range(1, count + 1))
151
+ return changed
152
+
153
+
154
+ def choose_reference(branch, head, cfg, repo, now=None):
155
+ """(reference_commit, reference_analysis_commit) defining "new code".
156
+
157
+ Branches compare with their merge-base on main. Main compares with the project's new_code_period (an
158
+ analysis at least N days old, or a git ref), else with its previous analysis. The reference analysis is the
159
+ newest main analysis at or before the reference commit, whose issues count as already known.
160
+ """
161
+ ref = reference_commit(branch, head, cfg, repo, now)
162
+ if not ref:
163
+ return None, None
164
+ commits = [a["commit"] for a in cfg.main_analyses]
165
+ return ref, next((c for c in commits if c == ref or is_ancestor(repo, c, ref)), None)
166
+
167
+
168
+ def period_days(period) -> int | None:
169
+ m = DAYS_RE.match((period or "").strip())
170
+ return int(m[1]) if m else None
171
+
172
+
173
+ def parse_period(period):
174
+ """("days", N), ("ref", name), or ("previous", None) for blank or unrecognised values."""
175
+ period = (period or "").strip()
176
+ if (days := period_days(period)) is not None:
177
+ return "days", days
178
+ if REF_RE.match(period):
179
+ return "ref", period
180
+ return "previous", None
181
+
182
+
183
+ def reference_commit(branch, head, cfg, repo, now=None):
184
+ if branch != cfg.main_branch:
185
+ main = repo.resolve_main(cfg.main_branch)
186
+ return repo.merge_base(main, head) if main else None
187
+ kind, value = parse_period(cfg.new_code_period)
188
+ # A ref that doesn't resolve or isn't in main's history falls back, so the gate keeps its new-code checks.
189
+ if kind == "ref":
190
+ commit = repo.resolve_commit(value)
191
+ if commit and is_ancestor(repo, commit, head):
192
+ return commit
193
+ elif kind == "days":
194
+ commit = days_reference(head, cfg, repo, value, now)
195
+ if commit:
196
+ return commit
197
+ return previous_reference(head, cfg, repo)
198
+
199
+
200
+ def started(analysis):
201
+ value = analysis.get("started_at")
202
+ return datetime.fromisoformat(value) if value else None
203
+
204
+
205
+ def days_reference(head, cfg, repo, days, now=None):
206
+ """Newest main analysis at least `days` old; the oldest one if the project is younger than that."""
207
+ cutoff = (now or datetime.now(UTC)) - timedelta(days=days)
208
+ old = [a for a in cfg.main_analyses if (t := started(a)) and t <= cutoff]
209
+ commit = next((a["commit"] for a in old if is_ancestor(repo, a["commit"], head)), None)
210
+ if commit:
211
+ return commit
212
+ return next((a["commit"] for a in reversed(cfg.main_analyses) if is_ancestor(repo, a["commit"], head)), None)
213
+
214
+
215
+ def previous_reference(head, cfg, repo):
216
+ if not cfg.main_analyses:
217
+ return None
218
+ if cfg.main_analyses[0]["commit"] == head:
219
+ return cfg.main_analyses[0].get("reference_commit") or None
220
+ return next((a["commit"] for a in cfg.main_analyses if is_ancestor(repo, a["commit"], head)), None)
221
+
222
+
223
+ def is_ancestor(repo, a, b):
224
+ return repo.has_commit(a) and repo.is_ancestor(a, b)
225
+
226
+
227
+ def excluded(path, patterns):
228
+ # fnmatch's "*" already spans "/", so "**/x/**" needs a variant that also matches at the repo root.
229
+ return any(fnmatch.fnmatch(path, p) or (p.startswith("**/") and fnmatch.fnmatch(path, p[3:])) for p in patterns)
230
+
231
+
232
+ # Bundler output (webpack/Next.js chunks committed with an app) is not the project's source, and its hundreds of
233
+ # regexes and huge lines cost the ReDoS check and Semgrep minutes per file. Recognised by content, since bundles
234
+ # aren't always named .min.js or kept under dist/: long lines on average.
235
+ BUNDLE_SUFFIXES = {".js", ".mjs", ".cjs"}
236
+ BUNDLE_MIN_BYTES = 20_000
237
+ BUNDLE_LINE_LENGTH = 500
238
+ # A smaller file counts when it is all one line, as a bundler's per-page chunk is (CTFd's 3 KB
239
+ # static/assets/pages/submissions-BsvbO10u.js); hand-written code isn't kept on one line that long.
240
+ SMALL_BUNDLE_MIN_BYTES = 2 * BUNDLE_LINE_LENGTH
241
+
242
+
243
+ def minified(path):
244
+ """A JavaScript file whose lines average over BUNDLE_LINE_LENGTH characters (a minified bundle), or a smaller
245
+ one that is a single long line."""
246
+ if path.suffix.lower() not in BUNDLE_SUFFIXES:
247
+ return False
248
+ try:
249
+ size = path.stat().st_size
250
+ if size < SMALL_BUNDLE_MIN_BYTES:
251
+ return False
252
+ data = path.read_bytes()
253
+ except OSError:
254
+ return False
255
+ if size < BUNDLE_MIN_BYTES:
256
+ return data.rstrip(b"\n").count(b"\n") == 0
257
+ return len(data) / (data.count(b"\n") + 1) > BUNDLE_LINE_LENGTH
258
+
259
+
260
+ # A library copied into an app's static folder (jQuery, Bootstrap, Font Awesome) opens with a comment naming it and
261
+ # its version. Name and version, not a copyright or licence line: projects such as Airflow put a licence header on
262
+ # their own files. Checked on all 30 apps and the benchmark checkouts: it matched only third-party libraries.
263
+ LIBRARY_SUFFIXES = BUNDLE_SUFFIXES | {".css"}
264
+ # A date is not a version: calibre-web's own edit_books.js opens "Created by SpeedProg on 05.04.2015".
265
+ LIBRARY_BANNER = re.compile(rb"\A\s*/\*[!*]?[\s*]*([A-Za-z][\w.\- ]{0,40}?)\s+(?!\d{1,2}[./]\d{1,2}[./]\d{4}\b)"
266
+ rb"v?\d+\.\d+(\.\d+)?\b")
267
+
268
+
269
+ def vendored(path):
270
+ """A JavaScript or CSS file that opens with a library banner ("/*! jQuery v3.3.1")."""
271
+ if path.suffix.lower() not in LIBRARY_SUFFIXES:
272
+ return False
273
+ try:
274
+ with path.open("rb") as handle:
275
+ head = handle.read(400)
276
+ except OSError:
277
+ return False
278
+ return bool(LIBRARY_BANNER.match(head))
279
+
280
+
281
+ # Libraries without a banner (TinyMCE: 235 files, a minute of ReDoS checking a side in Grappelli) still ship their
282
+ # licence file. Inside an asset folder that marks the library's folder: across the 30 apps and benchmark checkouts
283
+ # every licence file under static/, public/ or assets/ belonged to a vendored library (monorepo packages have
284
+ # licence files too, so the asset folder is required).
285
+ ASSET_FOLDERS = {"static", "public", "assets"}
286
+ LICENCE_FILE = re.compile(r"(licen[cs]e|copying)([-.][^/]*)?$", re.IGNORECASE)
287
+
288
+
289
+ def library_folders(files):
290
+ """Folders inside an asset folder that hold a licence file."""
291
+ folders = set()
292
+ for f in files:
293
+ parent, _, name = f.rpartition("/")
294
+ if LICENCE_FILE.match(name) and ASSET_FOLDERS & set(parent.split("/")[:-1]):
295
+ folders.add(parent + "/")
296
+ return folders
297
+
298
+
299
+ def in_library_folder(path, folders):
300
+ return Path(path).suffix.lower() in LIBRARY_SUFFIXES and any(path.startswith(f) for f in folders)
301
+
302
+
303
+ def library_files(root, files, bundles):
304
+ """Files of vendored libraries: in a library folder, or carrying a library's banner."""
305
+ folders = library_folders(files)
306
+ return [f for f in files if f not in bundles and (in_library_folder(f, folders) or vendored(root / f))]
307
+
308
+
309
+ def without_third_party(root, files, log=print):
310
+ """files less minified bundles and vendored libraries, which the dependency audit covers instead."""
311
+ bundles = [f for f in files if minified(root / f)]
312
+ libraries = library_files(root, files, bundles)
313
+ for found, what in ((bundles, "minified JavaScript"), (libraries, "vendored library")):
314
+ if found:
315
+ log(f"Skipping {len(found)} {what} file(s), e.g. {found[0]}")
316
+ skipped = set(bundles) | set(libraries)
317
+ return [f for f in files if f not in skipped]
318
+
319
+
320
+ def is_url(path):
321
+ return path.startswith(("http://", "https://", "file://"))
322
+
323
+
324
+ # Counted by more than one analyzer (pip-audit for Python, osv for JavaScript lockfiles): totals, not the last one.
325
+ ADDITIVE_METRICS = {"vulnerable_dependencies", "dependency_vulnerabilities", "dependency_critical_vulnerabilities",
326
+ "dependency_manifests_unresolved"}
327
+
328
+
329
+ def analyzer_skip_reason(analyzer, cfg, ctx):
330
+ if analyzer.name in cfg.disabled_analyzers:
331
+ return {"status": "disabled"}
332
+ if not analyzer.applies(ctx):
333
+ return {"status": "not_applicable"}
334
+ if not analyzer.available():
335
+ return {"status": "missing", "detail": f"{analyzer.executable} not found"}
336
+ return None
337
+
338
+
339
+ def merge_result(combined, result, kept):
340
+ """Add one analyzer's kept findings, metrics and line sets to the combined result."""
341
+ combined.findings += kept
342
+ for key, value in result.metrics.items():
343
+ combined.metrics[key] = combined.metrics.get(key, 0) + value if key in ADDITIVE_METRICS else value
344
+ combined.covered_lines.update(result.covered_lines)
345
+ combined.coverable_lines.update(result.coverable_lines)
346
+ combined.duplicated_lines.update(result.duplicated_lines)
347
+
348
+
349
+ def run_analyzer(analyzer, ctx, log):
350
+ """(result, None) or (None, the error status) for one analyzer: one tool failing doesn't fail the analysis."""
351
+ log(f"Running {analyzer.name}")
352
+ try:
353
+ return analyzer.run(ctx), None
354
+ except Exception as exc: # noqa: BLE001 - reported per tool in the UI
355
+ log(f" {analyzer.name} failed: {exc}")
356
+ return None, {"status": "error", "detail": str(exc)[-2000:]}
357
+
358
+
359
+ def run_analyzers(cfg, ctx, log):
360
+ """Run every applicable analyzer, merging their results; one tool failing doesn't fail the analysis."""
361
+ # Tools report a "./"-prefixed path (collect) by its plain name.
362
+ tracked = set(ctx.files) | {f.removeprefix("./") for f in ctx.files}
363
+ combined, tools = Result(), {}
364
+ for analyzer in ANALYZERS:
365
+ skip = analyzer_skip_reason(analyzer, cfg, ctx)
366
+ if skip:
367
+ tools[analyzer.name] = skip
368
+ continue
369
+ started = time.monotonic()
370
+ result, failure = run_analyzer(analyzer, ctx, log)
371
+ if result is None:
372
+ tools[analyzer.name] = failure
373
+ continue
374
+ kept = [f for f in result.findings if f.path in tracked or is_url(f.path)]
375
+ merge_result(combined, result, kept)
376
+ tools[analyzer.name] = {"status": "ok", "issues": len(kept), "seconds": round(time.monotonic() - started, 1)}
377
+ if result.notes:
378
+ tools[analyzer.name]["detail"] = " ".join(result.notes)
379
+ if result.gave_up:
380
+ tools[analyzer.name]["gave_up"] = result.gave_up
381
+ return combined, tools
382
+
383
+
384
+ class LineReader:
385
+ def __init__(self, root):
386
+ self.root = root
387
+ self.cache = {}
388
+
389
+ def lines(self, path):
390
+ if path not in self.cache:
391
+ try:
392
+ self.cache[path] = (self.root / path).read_text(errors="replace").splitlines()
393
+ except OSError:
394
+ self.cache[path] = []
395
+ return self.cache[path]
396
+
397
+ def __call__(self, path, line):
398
+ lines = self.lines(path)
399
+ return lines[line - 1] if line and 0 < line <= len(lines) else ""
400
+
401
+
402
+ def count_code_lines(reader, files):
403
+ return sum(sum(1 for line in reader.lines(f) if line.strip()) for f in files)
404
+
405
+
406
+ def new_code_metrics(new_code, covered, coverable, duplicated):
407
+ new_lines = sum(len(v) for v in new_code.values())
408
+ metrics: dict[str, float] = {"new_lines": new_lines}
409
+ to_cover = sum(len(lines & coverable.get(p, set())) for p, lines in new_code.items())
410
+ if coverable and to_cover:
411
+ hit = sum(len(lines & covered.get(p, set())) for p, lines in new_code.items())
412
+ metrics["new_lines_to_cover"] = to_cover
413
+ metrics["new_coverage"] = round(100 * hit / to_cover, 1)
414
+ if new_lines and duplicated is not None:
415
+ dup = sum(len(lines & duplicated.get(p, set())) for p, lines in new_code.items())
416
+ metrics["new_duplicated_lines_percent"] = round(100 * dup / new_lines, 2)
417
+ return metrics
418
+
419
+
420
+ def inside(root, path):
421
+ """A file of the project itself, not a link out of it: a repository can commit `a.py -> ~/.ssh/id_rsa`, which
422
+ an analyzer would read and flag and the scan would then upload as that file's source."""
423
+ try:
424
+ full = Path(root) / path
425
+ # A link the server checkout deleted (git still lists it) isn't there either.
426
+ return full.exists() and full.resolve().is_relative_to(Path(root).resolve())
427
+ except (OSError, RuntimeError): # RuntimeError: a symlink loop
428
+ return False
429
+
430
+
431
+ def read_sources(root, paths):
432
+ """Contents of files that have issues, so the server can show code without access to the repository."""
433
+ sources, total = {}, 0
434
+ for path in sorted(paths):
435
+ p = root / path
436
+ if not inside(root, path):
437
+ continue
438
+ try:
439
+ size = p.stat().st_size
440
+ except OSError:
441
+ continue
442
+ if size > MAX_SOURCE_BYTES or total + size > MAX_TOTAL_SOURCE_BYTES:
443
+ continue
444
+ sources[path] = p.read_text(errors="replace")
445
+ total += size
446
+ return sources
447
+
448
+
449
+ @dataclass
450
+ class ScanInput:
451
+ """What to analyse: files under root on a branch, lines changed since the reference (or None), coverage."""
452
+
453
+ root: Path
454
+ files: list[str]
455
+ branch: str
456
+ changed: dict | None = None
457
+ coverage_report: Path | None = None
458
+ coverage_base: Path | None = None
459
+ focus: list[str] | None = None
460
+ local: bool = False
461
+
462
+
463
+ def make_context(cfg, scan, files):
464
+ return Context(
465
+ root=Path(scan.root),
466
+ files=files,
467
+ complexity_threshold=cfg.complexity_threshold,
468
+ semgrep_config=cfg.semgrep_config,
469
+ exclusions=cfg.exclusions,
470
+ a11y_urls=[u.replace("{branch}", scan.branch) for u in cfg.a11y_urls],
471
+ cognitive_threshold=cfg.cognitive_complexity_threshold,
472
+ max_literal_repeats=cfg.duplicate_literal_threshold,
473
+ custom_rules=cfg.custom_rules,
474
+ coverage_report=Path(scan.coverage_report) if scan.coverage_report else None,
475
+ coverage_base=Path(scan.coverage_base) if scan.coverage_base else None,
476
+ focus=scan.focus,
477
+ local=scan.local,
478
+ )
479
+
480
+
481
+ def code_only(changed, tracked):
482
+ return {p: lines for p, lines in changed.items() if p in tracked and Path(p).suffix.lower() in CODE}
483
+
484
+
485
+ def collect(cfg, scan, log=print):
486
+ """Analyse a ScanInput with the project's ScanConfig; returns the upload payload."""
487
+ # A path starting with "-" would reach each tool's command line as an option ("--output-file=x.py").
488
+ files = [f"./{f}" if f.startswith("-") else f
489
+ for f in scan.files if not excluded(f, cfg.exclusions) and inside(scan.root, f)]
490
+ files = without_third_party(Path(scan.root), files, log)
491
+ changed = scan.changed
492
+ ctx = make_context(cfg, scan, files)
493
+ combined, tools = run_analyzers(cfg, ctx, log)
494
+ metrics = combined.metrics
495
+ reader = LineReader(ctx.root)
496
+ code_files = [f for f in files if Path(f).suffix.lower() in CODE]
497
+ metrics["files"] = len(code_files)
498
+ metrics["ncloc"] = count_code_lines(reader, code_files)
499
+ fingerprints = assign_fingerprints(combined.findings, reader)
500
+ if changed is not None:
501
+ duplicated = combined.duplicated_lines if "duplicated_lines" in metrics else None
502
+ metrics.update(new_code_metrics(code_only(changed, set(files)), combined.covered_lines,
503
+ combined.coverable_lines, duplicated))
504
+ return build_payload(ctx.root, combined, tools, fingerprints, changed)
505
+
506
+
507
+ def build_payload(root, combined, tools, fingerprints, changed):
508
+ issue_paths = {f.path for f in combined.findings if not is_url(f.path)}
509
+ return {
510
+ "tools": tools,
511
+ "metrics": combined.metrics,
512
+ "issues": dedupe([{**asdict(f), "fingerprint": fp}
513
+ for f, fp in zip(combined.findings, fingerprints, strict=True)]),
514
+ "changed_lines": None if changed is None else {
515
+ p: sorted(lines) for p, lines in changed.items() if p in issue_paths
516
+ },
517
+ "sources": read_sources(root, issue_paths),
518
+ }
core/duplicates.py ADDED
@@ -0,0 +1,60 @@
1
+ """Merge findings that several analyzers (or one analyzer, repeatedly) report for the same problem on one line.
2
+
3
+ The strongest report is kept (a confirmed vulnerability over a hotspot to review, then the most severe) and
4
+ takes the group's highest severity; the others are listed in its also_reported_by as "tool:rule", so a finding
5
+ still shows every detector that agreed on it.
6
+ """
7
+ from . import catalog
8
+
9
+ SEVERITY_RANK = {"blocker": 0, "critical": 1, "major": 2, "minor": 3, "info": 4}
10
+ TYPE_RANK = {"vulnerability": 0, "bug": 1, "security_hotspot": 2, "accessibility": 3, "code_smell": 4}
11
+ SECURITY_TYPES = {"vulnerability", "security_hotspot"}
12
+ # Pillar and category CWEs that many unrelated quality rules share; agreeing on one of these says nothing.
13
+ BROAD_CWES = {398, 664, 682, 691, 693, 697, 703, 707, 710, 1006, 1041, 1076, 1078, 1164, 1177}
14
+
15
+
16
+ def declared_same(ra, rb):
17
+ """The catalogue lists one rule as the same as the other."""
18
+ return rb["id"] in (ra.get("same_as") or []) or ra["id"] in (rb.get("same_as") or [])
19
+
20
+
21
+ def same_check(a, b):
22
+ """Same tool and rule, rules the catalogue calls equivalent, or rules sharing a specific CWE."""
23
+ if a["tool"] == b["tool"]:
24
+ return a["rule"] == b["rule"]
25
+ ra, rb = catalog.lookup(a["tool"], a["rule"]), catalog.lookup(b["tool"], b["rule"])
26
+ if not (ra and rb):
27
+ return False
28
+ if declared_same(ra, rb):
29
+ return True
30
+ shared = set(ra["cwe"]) & set(rb["cwe"])
31
+ if a["type"] in SECURITY_TYPES and b["type"] in SECURITY_TYPES:
32
+ return bool(shared)
33
+ return a["type"] == b["type"] and bool(shared - BROAD_CWES)
34
+
35
+
36
+ def dedupe(issues):
37
+ """One finding per problem per line; already-merged input (from the scan client) is merged again unchanged."""
38
+ by_line, kept = {}, []
39
+ for issue in sorted(issues, key=lambda i: (TYPE_RANK.get(i["type"], 5), SEVERITY_RANK.get(i["severity"], 5))):
40
+ issue["also_reported_by"] = list(issue.get("also_reported_by") or [])
41
+ if issue.get("line") is None:
42
+ kept.append(issue)
43
+ continue
44
+ group = by_line.setdefault((issue["path"], issue["line"]), [])
45
+ twin = next((k for k in group if same_check(k, issue)), None)
46
+ if twin is None:
47
+ group.append(issue)
48
+ kept.append(issue)
49
+ continue
50
+ merge_into(twin, issue)
51
+ return kept
52
+
53
+
54
+ def merge_into(twin, issue):
55
+ """The kept finding takes the merged one's higher severity and lists its detectors."""
56
+ if SEVERITY_RANK.get(issue["severity"], 5) < SEVERITY_RANK.get(twin["severity"], 5):
57
+ twin["severity"] = issue["severity"]
58
+ for source in [f"{issue['tool']}:{issue['rule']}", *issue["also_reported_by"]]:
59
+ if source != f"{twin['tool']}:{twin['rule']}" and source not in twin["also_reported_by"]:
60
+ twin["also_reported_by"].append(source)
core/fingerprint.py ADDED
@@ -0,0 +1,25 @@
1
+ import hashlib
2
+ from collections import Counter
3
+
4
+
5
+ def normalize(text):
6
+ return " ".join(text.split())
7
+
8
+
9
+ def assign_fingerprints(findings, read_line):
10
+ """Fingerprint from rule, file and source text rather than line number, so issues survive edits above them.
11
+
12
+ read_line(path, line) returns that line's text (or "" if unavailable). Identical issues on identical lines
13
+ in the same file are told apart by occurrence order.
14
+ """
15
+ seen = Counter()
16
+ fingerprints = {}
17
+ for f in sorted(findings, key=lambda f: (f.path, f.line or 0, f.tool, f.rule)):
18
+ anchor = normalize(read_line(f.path, f.line)) if f.line else normalize(f.message)
19
+ key = (f.tool, f.rule, f.path, anchor)
20
+ seen[key] += 1
21
+ raw = "\0".join([*key, str(seen[key])])
22
+ # Identity, not security; changing the algorithm would change every issue's identity.
23
+ # SHA-1 only names an issue so it can be matched across scans (usedforsecurity=False); nothing relies on it resisting collisions.
24
+ fingerprints[id(f)] = hashlib.sha1(raw.encode(), usedforsecurity=False).hexdigest() # nosemgrep
25
+ return [fingerprints[id(f)] for f in findings]
core/folders.py ADDED
@@ -0,0 +1,73 @@
1
+ """Server-side folder browsing for the new-project page: an administrator picks a local repository by name.
2
+
3
+ A browser's folder picker can't do this: it uploads the files and never tells the page where the folder is. The
4
+ server lists folders itself, only under CODEWATCH_BROWSE_ROOT (the home directory by default), and only folder
5
+ names: no file is read.
6
+ """
7
+ from pathlib import Path
8
+
9
+ from django.conf import settings
10
+ from django.utils.text import slugify
11
+
12
+ from .models import Project
13
+
14
+ MAX_FOLDERS = 500
15
+
16
+
17
+ def browse_root():
18
+ return Path(getattr(settings, "CODEWATCH_BROWSE_ROOT", None) or Path.home()).resolve()
19
+
20
+
21
+ def under_root(requested):
22
+ """The requested folder, resolved, if it is a folder under the browse root; else None."""
23
+ root = browse_root()
24
+ path = (root / requested).resolve()
25
+ if not path.is_relative_to(root) or not path.is_dir():
26
+ return None
27
+ return path
28
+
29
+
30
+ def within_root(requested):
31
+ """The requested folder under the browse root, or the root itself."""
32
+ return (under_root(requested) if requested else None) or browse_root()
33
+
34
+
35
+ def is_repository(path):
36
+ return (path / ".git").exists()
37
+
38
+
39
+ def listing(requested):
40
+ """{path, parent, repository, folders: [{name, path, repository}]} for a folder under the browse root. Paths are
41
+ relative to the root; hidden folders are left out."""
42
+ root = browse_root()
43
+ path = within_root(requested)
44
+ try:
45
+ children = sorted((c for c in path.iterdir() if c.is_dir() and not c.name.startswith(".")),
46
+ key=lambda c: c.name.lower())[:MAX_FOLDERS]
47
+ except OSError:
48
+ children = []
49
+ return {
50
+ "path": path.relative_to(root).as_posix() if path != root else "",
51
+ "absolute": str(path),
52
+ "parent": None if path == root else (path.parent.relative_to(root).as_posix() if path.parent != root else ""),
53
+ "repository": is_repository(path),
54
+ "folders": [{"name": c.name, "path": c.relative_to(root).as_posix(), "repository": is_repository(c)}
55
+ for c in children],
56
+ }
57
+
58
+
59
+ def unused_key(name):
60
+ base = slugify(name)[:40] or "project"
61
+ key, n = base, 2
62
+ while Project.objects.filter(key=key).exists():
63
+ key, n = f"{base}-{n}", n + 1
64
+ return key
65
+
66
+
67
+ def suggestion(requested):
68
+ """Form values for a chosen repository folder under the browse root (else None): its path, its name as the title
69
+ and a free key from it."""
70
+ path = under_root(requested) if requested else None
71
+ if path is None or path == browse_root():
72
+ return None
73
+ return {"repo_url": str(path), "name": path.name, "key": unused_key(path.name)}