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/client.py ADDED
@@ -0,0 +1,645 @@
1
+ """codewatch: scan a local working copy and upload the results.
2
+
3
+ The repository never leaves the machine; only issues, metrics and the source of files with issues are sent.
4
+ """
5
+ import argparse
6
+ import contextlib
7
+ import gzip
8
+ import json
9
+ import os
10
+ import re
11
+ import shlex
12
+ import stat
13
+ import subprocess
14
+ import sys
15
+ import urllib.error
16
+ import urllib.parse
17
+ import urllib.request
18
+ from dataclasses import dataclass
19
+ from pathlib import Path
20
+
21
+ from .analyzers.base import TOOLS_DIR, node_tool
22
+ from .catalog import custom_semgrep_rules
23
+ from .collect import GitError, LocalRepo, ScanConfig, ScanInput, choose_reference, collect, excluded
24
+
25
+ CONFIG_FILE = "codewatch-project.json"
26
+ COVERAGE_CANDIDATES = ["coverage.xml", "coverage/cobertura-coverage.xml", "coverage/lcov.info", "lcov.info"]
27
+ HOOK_MARKER = "# installed by codewatch init"
28
+ COVERAGE = "coverage"
29
+ ERROR = "error"
30
+ MISSING = "missing"
31
+ STORE_TRUE = "store_true"
32
+
33
+
34
+ class ClientError(Exception):
35
+ pass
36
+
37
+
38
+ def log(message):
39
+ print(message, file=sys.stderr, flush=True)
40
+
41
+
42
+ LOCAL_HOSTS = {"localhost", "127.0.0.1", "::1"}
43
+ # Servers this user has said they trust. The repository's codewatch-project.json may name one, but it is part of
44
+ # the repository: a branch could point it anywhere and collect the token and the code.
45
+ TRUSTED_SERVERS_FILE = Path(os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config") / "codewatch" / "servers.txt"
46
+
47
+
48
+ def trusted_servers():
49
+ listed = os.environ.get("CODEWATCH_TRUSTED_URLS", "").split(",")
50
+ with contextlib.suppress(OSError):
51
+ listed += TRUSTED_SERVERS_FILE.read_text().split()
52
+ return {url.strip().rstrip("/") for url in listed if url.strip()}
53
+
54
+
55
+ def trust_server(url):
56
+ if url.rstrip("/") not in trusted_servers():
57
+ TRUSTED_SERVERS_FILE.parent.mkdir(parents=True, exist_ok=True)
58
+ with TRUSTED_SERVERS_FILE.open("a") as out:
59
+ out.write(url.rstrip("/") + "\n")
60
+
61
+
62
+ def request(url, token, data=None, timeout=600):
63
+ parts = urllib.parse.urlsplit(url)
64
+ if parts.scheme not in ("http", "https"):
65
+ raise ClientError(f"codewatch server URL must be http(s): {url}")
66
+ if parts.scheme == "http" and parts.hostname not in LOCAL_HOSTS:
67
+ raise ClientError(f"Not sending the token to {parts.hostname} over plain http; use https")
68
+ headers = {"Authorization": f"Bearer {token}", "Accept": "application/json"}
69
+ if data is not None:
70
+ data = gzip.compress(json.dumps(data).encode())
71
+ headers.update({"Content-Type": "application/json", "Content-Encoding": "gzip"})
72
+ req = urllib.request.Request(url, data=data, headers=headers, method="POST" if data is not None else "GET")
73
+ try:
74
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
75
+ return resp.status, json.load(resp)
76
+ except urllib.error.HTTPError as exc:
77
+ try:
78
+ body = json.load(exc)
79
+ except ValueError:
80
+ body = {ERROR: exc.reason}
81
+ return exc.code, body
82
+ except urllib.error.URLError as exc:
83
+ raise ClientError(f"Can't reach {url}: {exc.reason}") from exc
84
+
85
+
86
+ def detect_main_branch(repo):
87
+ head = repo.git("symbolic-ref", "--quiet", "refs/remotes/origin/HEAD", check=False).strip()
88
+ if head:
89
+ return head.removeprefix("refs/remotes/origin/")
90
+ for name in ("main", "master", "trunk", "develop"):
91
+ if repo.git("rev-parse", "--verify", "--quiet", name, check=False).strip():
92
+ return name
93
+ return repo.branch()
94
+
95
+
96
+ def load_config(root):
97
+ path = root / CONFIG_FILE
98
+ if not path.exists():
99
+ return {}
100
+ try:
101
+ return json.loads(path.read_text())
102
+ except ValueError as exc:
103
+ raise ClientError(f"{path} is not valid JSON: {exc}") from exc
104
+
105
+
106
+ def default_key(root):
107
+ return re.sub(r"[^a-z0-9_-]+", "-", root.name.lower()).strip("-")
108
+
109
+
110
+ # --- scan -------------------------------------------------------------------------------------------------
111
+
112
+
113
+ def first(*values):
114
+ return next((v for v in values if v), "")
115
+
116
+
117
+ @dataclass
118
+ class ScanTarget:
119
+ """The working copy being scanned and where its results go."""
120
+
121
+ args: argparse.Namespace
122
+ repo: LocalRepo
123
+ conf: dict
124
+ url: str
125
+ token: str
126
+ key: str
127
+ branch: str
128
+
129
+
130
+ def scan_target(args, repo, conf):
131
+ url = first(args.url, os.environ.get("CODEWATCH_URL"))
132
+ named = conf.get("serverUrl")
133
+ if not url and named:
134
+ if named.rstrip("/") not in trusted_servers():
135
+ raise ClientError(f"{CONFIG_FILE} names the server {named}, which you haven't trusted. It is part of the "
136
+ f"repository, so check it, then add it to {TRUSTED_SERVERS_FILE} (or set CODEWATCH_URL)")
137
+ url = named
138
+ url = (url or "").rstrip("/")
139
+ token = first(args.token, os.environ.get("CODEWATCH_TOKEN"))
140
+ key = first(args.project, os.environ.get("CODEWATCH_PROJECT"), conf.get("projectKey"), default_key(repo.root))
141
+ branch = first(args.branch, repo.branch())
142
+ if branch == "HEAD":
143
+ raise ClientError("Detached HEAD: pass --branch")
144
+ return ScanTarget(args, repo, conf, url, token, key, branch)
145
+
146
+
147
+ def require_server(target):
148
+ """An upload needs a server and a token (writing the payload to a file doesn't)."""
149
+ if not target.args.output and not (target.url and target.token):
150
+ raise ClientError(f"Set CODEWATCH_URL and CODEWATCH_TOKEN (or serverUrl in {CONFIG_FILE}, --url/--token)")
151
+
152
+
153
+ def fetch_config(target):
154
+ cfg, created = server_config(target)
155
+ # Local opt-outs (e.g. a slow tool) add to the server's list rather than replacing it.
156
+ conf = target.conf
157
+ cfg.disabled_analyzers = sorted(set(cfg.disabled_analyzers) | set(conf.get("disabledAnalyzers", [])))
158
+ cfg.exclusions = list(dict.fromkeys([*cfg.exclusions, *conf.get("exclusions", [])]))
159
+ return cfg, created
160
+
161
+
162
+ def server_config(target):
163
+ url, token, key, repo = target.url, target.token, target.key, target.repo
164
+ main = target.args.main_branch or target.conf.get("mainBranch")
165
+ if not url:
166
+ return default_config(main or detect_main_branch(repo)), True
167
+ status, body = request(f"{url}/api/projects/{key}/config/", token)
168
+ if status == 200:
169
+ return ScanConfig.from_dict(body), False
170
+ if status == 404:
171
+ main = main or detect_main_branch(repo)
172
+ log(f"Project {key} doesn't exist yet; it will be created (main branch: {main})")
173
+ return default_config(main), True
174
+ raise ClientError(f"Config request failed ({status}): {body.get('error')}")
175
+
176
+
177
+ def default_config(main_branch):
178
+ """A new project's settings: the server would send the same built-in rules once the project exists."""
179
+ return ScanConfig(main_branch=main_branch, custom_rules=custom_semgrep_rules())
180
+
181
+
182
+ def find_coverage(args, root, conf):
183
+ explicit = args.coverage or conf.get("coverageReport")
184
+ if explicit:
185
+ return (root / explicit).resolve()
186
+ return next((root / c for c in COVERAGE_CANDIDATES if (root / c).exists()), None)
187
+
188
+
189
+ def cmd_scan(args):
190
+ repo = LocalRepo(args.path)
191
+ conf = load_config(repo.root)
192
+ target = scan_target(args, repo, conf)
193
+ url, token, key, branch = target.url, target.token, target.key, target.branch
194
+ require_server(target)
195
+ cfg, created = fetch_config(target)
196
+ head = repo.head()
197
+ ref, ref_analysis = choose_reference(branch, head, cfg, repo)
198
+ log(f"Scanning {repo.root} ({branch} @ {head[:8]}"
199
+ + (f", new code since {ref[:8]})" if ref else ", no new-code reference yet)"))
200
+ coverage = find_coverage(args, repo.root, conf)
201
+ if coverage:
202
+ log(f"Using coverage report {coverage}")
203
+ changed = repo.changed_lines(ref) if ref else None
204
+ payload = collect(cfg, ScanInput(repo.root, repo.files(), branch, changed, coverage, repo.root, local=True), log)
205
+ payload.update(
206
+ branch=branch, commit=head, dirty=repo.dirty(), reference_commit=ref,
207
+ reference_analysis_commit=ref_analysis, main_branch=cfg.main_branch,
208
+ project_name=args.name or conf.get("projectName") or key,
209
+ )
210
+ if args.output:
211
+ Path(args.output).write_text(json.dumps(payload))
212
+ log(f"Wrote {args.output}")
213
+ return 0
214
+ status, body = request(f"{url}/api/projects/{key}/analyses/", token, payload)
215
+ if status != 201:
216
+ raise ClientError(f"Upload failed ({status}): {body.get('error')}")
217
+ report(body, created)
218
+ return 1 if args.fail_on_gate and body.get("gate_passed") is False else 0
219
+
220
+
221
+ def report(body, created):
222
+ m = body.get("metrics", {})
223
+ gate = "passed" if body.get("gate_passed") else "FAILED"
224
+ log(f"{'Created project. ' if created else ''}Quality gate {gate}: "
225
+ f"{int(m.get('new_issues', 0))} new issues, {int(m.get('issues', 0))} total")
226
+ for cond in body.get("gate", []):
227
+ if cond["status"] == ERROR:
228
+ log(f" {cond['metric']} = {cond['value']:g} ({'>' if cond['op'] == 'gt' else '<'} {cond['threshold']:g})")
229
+ log(body.get("url", ""))
230
+
231
+
232
+ # --- check ------------------------------------------------------------------------------------------------
233
+
234
+ # Whole-project checks, left out of a check of some files: the dependency audit, coverage and live pages.
235
+ PROJECT_WIDE_ANALYZERS = ("pip-audit", "osv", COVERAGE, "axe")
236
+ # What stops a commit, as the default gate's conditions on new issues: blockers and criticals, bugs, vulnerabilities.
237
+ BLOCKING_SEVERITIES = ("blocker", "critical")
238
+ BLOCKING_TYPES = ("bug", "vulnerability")
239
+
240
+
241
+ def files_to_check(repo, named, everything=False):
242
+ """The named files, else (everything) the whole project, else the staged ones, else every file changed since
243
+ the last commit (untracked too)."""
244
+ if everything:
245
+ return repo.files()
246
+ if named:
247
+ return sorted({os.path.relpath(Path(f).resolve(), repo.root) for f in named})
248
+ def listed(*args):
249
+ return [f for f in repo.git(*args).split("\0") if f]
250
+ files = listed("diff", "--cached", "--name-only", "-z", "--diff-filter=ACMR")
251
+ if not files and repo.resolve_commit("HEAD"):
252
+ files = listed("diff", "HEAD", "--name-only", "-z", "--diff-filter=ACMR") + repo.untracked()
253
+ elif not files:
254
+ files = repo.files()
255
+ return sorted(set(files))
256
+
257
+
258
+ def check_config(args, repo, conf):
259
+ """The project's settings from its server when one is configured and reachable, else the defaults; local
260
+ opt-outs added either way, and the whole-project analyzers left out."""
261
+ # Only the settings depend on the branch: a detached HEAD (a rebase in progress) is still checked.
262
+ args.branch = args.branch or ("detached" if repo.branch() == "HEAD" else None)
263
+ target = scan_target(args, repo, conf)
264
+ cfg = default_config(target.conf.get("mainBranch", ""))
265
+ if target.url and target.token:
266
+ try:
267
+ cfg, _created = server_config(target)
268
+ except ClientError as exc:
269
+ log(f"Using the default settings: {exc}")
270
+ cfg.disabled_analyzers = sorted({*cfg.disabled_analyzers, *conf.get("disabledAnalyzers", []), *PROJECT_WIDE_ANALYZERS})
271
+ cfg.exclusions = list(dict.fromkeys([*cfg.exclusions, *conf.get("exclusions", [])]))
272
+ return cfg
273
+
274
+
275
+ def blocks(issue, changed, strict=False):
276
+ """Whether an issue stops the commit: a blocking kind (any kind, strict), on a line this change touched (or
277
+ anywhere, with changed=None)."""
278
+ serious = strict or issue["severity"] in BLOCKING_SEVERITIES or issue["type"] in BLOCKING_TYPES
279
+ if not serious:
280
+ return False
281
+ if changed is None:
282
+ return True
283
+ return bool(issue["line"]) and issue["line"] in changed.get(issue["path"], ())
284
+
285
+
286
+ def checked_files(repo, args, cfg):
287
+ """files_to_check that exist; when none were named, without the project's exclusions."""
288
+ return [f for f in files_to_check(repo, args.files, args.all)
289
+ if (repo.root / f).is_file() and (args.files or not excluded(f, cfg.exclusions))]
290
+
291
+
292
+ REVIEWS_FILE = "codewatch-reviews.json"
293
+ REVIEW_STATUSES = ("safe", "false_positive")
294
+
295
+
296
+ def load_reviews(root):
297
+ """{fingerprint: review} from the repository's codewatch-reviews.json: findings someone read and judged safe
298
+ or a false positive, each with the reason, kept in the repository where anyone can read and question it."""
299
+ path = root / REVIEWS_FILE
300
+ if not path.exists():
301
+ return {}
302
+ reviews = json.loads(path.read_text())
303
+ bad = [r for r in reviews if r.get("status") not in REVIEW_STATUSES or not r.get("comment")]
304
+ if bad:
305
+ raise ClientError(f"{REVIEWS_FILE}: every review needs a status ({', '.join(REVIEW_STATUSES)}) and a "
306
+ f"reason in comment; not {bad[0]}")
307
+ return {r["fingerprint"]: r for r in reviews}
308
+
309
+
310
+ def issue_line(issue):
311
+ return (f"{issue['path']}:{issue['line'] or '-'}: {issue['severity']} {issue['type']} "
312
+ f"{issue['tool']}:{issue['rule']}: {issue['message'].splitlines()[0][:200]}")
313
+
314
+
315
+ def print_issues(issues, blocking, reviewed):
316
+ for i in issues:
317
+ mark = "!" if i in blocking else " "
318
+ print(f"{mark} {issue_line(i)}", flush=True)
319
+ for i in reviewed:
320
+ review = i["review"]
321
+ print(f"= {issue_line(i)}\n reviewed {review['status']}: {review['comment']}", flush=True)
322
+
323
+
324
+ def tools_by_status(payload):
325
+ """{status: {analyzer: its detail, or ""}} for the analyzers in a payload."""
326
+ grouped = {}
327
+ for name, tool in payload["tools"].items():
328
+ grouped.setdefault(tool.get("status"), {})[name] = tool.get("detail", "")
329
+ return grouped
330
+
331
+
332
+ def failed_tools(payload):
333
+ """{analyzer: what went wrong} for each analyzer that failed, said aloud: their files weren't fully checked."""
334
+ failed = tools_by_status(payload).get(ERROR, {})
335
+ for name, detail in failed.items():
336
+ log(f"codewatch check: {name} failed, so these files weren't fully checked: {detail[:300]}")
337
+ return failed
338
+
339
+
340
+ def missing_tools(payload):
341
+ """{analyzer: what's missing} for each analyzer these files needed that can't run, said aloud and counted as a
342
+ failure: a check that skipped Semgrep must not pass as if it had run."""
343
+ missing = tools_by_status(payload).get(MISSING, {})
344
+ for name, detail in missing.items():
345
+ log(f"codewatch check: {name} can't run ({detail}), so these files weren't fully checked. Run `codewatch "
346
+ f"setup` (the JavaScript analyzers also need Node.js 20+), or list {name} in disabledAnalyzers in "
347
+ f"{CONFIG_FILE}")
348
+ return missing
349
+
350
+
351
+ def tool_notes(payload):
352
+ """What each analyzer said about its run (Semgrep giving up on rules in a file, which may hide findings), said
353
+ aloud: a check that passes must not have quietly skipped part of a file."""
354
+ notes = {name: detail for status, tools in tools_by_status(payload).items() if status not in {ERROR, MISSING}
355
+ for name, detail in tools.items() if detail}
356
+ for name, detail in notes.items():
357
+ log(f"codewatch check: {name}: {detail[:300]}")
358
+ return notes
359
+
360
+
361
+ def cmd_check(args):
362
+ """Every analyzer on some files, nothing uploaded and nothing run: exit 1 if a changed line has a bug, a
363
+ vulnerability or a blocker/critical issue, 2 if an analyzer failed or isn't installed (the files weren't fully
364
+ checked)."""
365
+ repo = LocalRepo(".")
366
+ cfg = check_config(args, repo, load_config(repo.root))
367
+ files = checked_files(repo, args, cfg)
368
+ if not files:
369
+ log("codewatch check: no files to check")
370
+ return 0
371
+ changed = changed_lines(repo, args.all_lines or args.all)
372
+ log(f"Checking {len(files)} file(s): " + ", ".join(files[:5]) + (", ..." if len(files) > 5 else ""))
373
+ payload = collect(cfg, ScanInput(repo.root, files, repo.branch(), changed, None, repo.root, local=True),
374
+ check_log(args.verbose))
375
+ reviews = load_reviews(repo.root)
376
+ issues, reviewed = split_reviewed(payload["issues"], reviews)
377
+ blocking = [i for i in issues if blocks(i, changed, args.strict)] + unused_reviews(args, reviews, reviewed)
378
+ print_issues(issues, blocking, reviewed)
379
+ tool_notes(payload)
380
+ failed = failed_tools(payload) | missing_tools(payload)
381
+ where = "anywhere in these files" if changed is None else "on changed lines"
382
+ log(f"{len(issues)} open issue(s) and {len(reviewed)} reviewed in {len(files)} file(s); "
383
+ f"{len(blocking)} blocking {where} (marked !)")
384
+ write_summary(files, issues, reviewed, blocking, failed)
385
+ return check_exit(blocking, failed)
386
+
387
+
388
+ def unused_reviews(args, reviews, reviewed):
389
+ """With --all --strict, reviews that match no finding any more: a reason given for code that is gone, which
390
+ the file must not keep claiming. Returned as blocking entries."""
391
+ if not (args.all and args.strict):
392
+ return []
393
+ used = {i["fingerprint"] for i in reviewed}
394
+ unused = [r for fp, r in reviews.items() if fp not in used]
395
+ for r in unused:
396
+ log(f"codewatch check: {REVIEWS_FILE} reviews {r.get('tool')}:{r.get('rule')} in {r.get('path')}, which no "
397
+ "longer has that finding; remove the review")
398
+ return unused
399
+
400
+
401
+ def split_reviewed(found, reviews):
402
+ """(open issues, reviewed ones with their review), each in file and line order."""
403
+ found = sorted(found, key=lambda i: (i["path"], i["line"] or 0))
404
+ return ([i for i in found if i["fingerprint"] not in reviews],
405
+ [{**i, "review": reviews[i["fingerprint"]]} for i in found if i["fingerprint"] in reviews])
406
+
407
+
408
+ def open_counts(issues):
409
+ """"2 bug, 1 code smell" for the open issues, or "none"."""
410
+ kinds = {}
411
+ for i in issues:
412
+ kinds[i["type"]] = kinds.get(i["type"], 0) + 1
413
+ return ", ".join(f"{n} {kind.replace('_', ' ')}" for kind, n in sorted(kinds.items())) or "none"
414
+
415
+
416
+ def reviewed_table(reviewed):
417
+ if not reviewed:
418
+ return []
419
+ return ["", f"### {len(reviewed)} reviewed findings ({REVIEWS_FILE})", "",
420
+ "| Where | Finding | Verdict | Reason |", "|---|---|---|---|"] + [
421
+ f"| `{i['path']}:{i['line'] or '-'}` | {i['tool']}:{i['rule']} | {i['review']['status']} | "
422
+ f"{i['review']['comment'].replace('|', '/')} |" for i in reviewed]
423
+
424
+
425
+ def write_summary(files, issues, reviewed, blocking, failed):
426
+ """A Markdown report where GitHub Actions shows one ($GITHUB_STEP_SUMMARY), for anyone reading the run."""
427
+ path = os.environ.get("GITHUB_STEP_SUMMARY")
428
+ if not path:
429
+ return
430
+ verdict = "fails" if blocking or failed else "passes"
431
+ lines = [f"## codewatch check {verdict}", "",
432
+ f"{len(files)} files checked by every analyzer. Open issues: {open_counts(issues)}.", ""]
433
+ lines += [f"- **{name} failed**, so the files weren't fully checked: {detail[:300]}" for name, detail in failed.items()]
434
+ lines += [f"- `{issue_line(i)}`" for i in issues] + reviewed_table(reviewed)
435
+ with open(path, "a") as out:
436
+ out.write("\n".join(lines) + "\n")
437
+
438
+
439
+ def changed_lines(repo, all_lines):
440
+ """{path: lines} changed since the last commit; None (every line counts) with --all-lines or no commit yet."""
441
+ if all_lines or not repo.resolve_commit("HEAD"):
442
+ return None
443
+ return repo.changed_lines("HEAD")
444
+
445
+
446
+ def check_log(verbose):
447
+ """Each analyzer as it runs with --verbose, else only what went wrong."""
448
+ if verbose:
449
+ return log
450
+ return lambda message: log(message) if "failed" in message else None
451
+
452
+
453
+ def check_exit(blocking, failed):
454
+ """1 when something blocks, else 2 when an analyzer failed (not fully checked), else 0."""
455
+ if blocking:
456
+ return 1
457
+ return 2 if failed else 0
458
+
459
+
460
+ # --- coverage ---------------------------------------------------------------------------------------------
461
+
462
+
463
+ def project_python(root):
464
+ for candidate in ("venv/bin/python", ".venv/bin/python", "env/bin/python"):
465
+ if (root / candidate).exists():
466
+ return str(root / candidate)
467
+ return sys.executable
468
+
469
+
470
+ def coverage_commands(root, conf):
471
+ """Commands that run the project's tests and leave a coverage report where `scan` looks for one."""
472
+ if conf.get("testCommand"):
473
+ return [["sh", "-c", conf["testCommand"]]]
474
+ if any((root / f).exists() for f in ("pyproject.toml", "setup.py", "setup.cfg", "pytest.ini", "manage.py")):
475
+ py = project_python(root)
476
+ if subprocess.run([py, "-c", "import coverage, pytest"], capture_output=True, check=False).returncode:
477
+ raise ClientError(f"{py} needs coverage and pytest: {py} -m pip install coverage pytest "
478
+ f"(or set testCommand in {CONFIG_FILE})")
479
+ return [[py, "-m", COVERAGE, "run", "-m", "pytest"], [py, "-m", COVERAGE, "xml", "-o", "coverage.xml"]]
480
+ package = root / "package.json"
481
+ if package.exists() and json.loads(package.read_text()).get("scripts", {}).get("test"):
482
+ c8 = node_tool("c8")
483
+ if c8 is None:
484
+ raise ClientError("c8 missing: run codewatch setup")
485
+ return [[c8, "--reporter=cobertura", "--reports-dir=coverage", "npm", "test"]]
486
+ raise ClientError(f"Don't know how to run these tests; set testCommand in {CONFIG_FILE}")
487
+
488
+
489
+ def cmd_coverage(args):
490
+ repo = LocalRepo(args.path)
491
+ for command in coverage_commands(repo.root, load_config(repo.root)):
492
+ log("$ " + shlex.join(command))
493
+ code = subprocess.run(command, cwd=repo.root, check=False).returncode
494
+ if code != 0:
495
+ log(f"codewatch: tests failed (exit {code})")
496
+ return code
497
+ return 0
498
+
499
+
500
+ # --- init -------------------------------------------------------------------------------------------------
501
+
502
+
503
+ def hook_script(strict, name="pre-push"):
504
+ exe = shlex.quote(str(Path(sys.argv[0]).resolve()))
505
+ if name == "pre-commit":
506
+ return f"""#!/bin/sh
507
+ {HOOK_MARKER}
508
+ # Checks the staged files: a bug, vulnerability or blocker/critical issue on a changed line stops the commit
509
+ # (git commit --no-verify skips it). Nothing is uploaded or run. Remove this file to disable.
510
+ {exe} check
511
+ """
512
+ scan = f"{exe} scan --fail-on-gate" if strict else f"{exe} scan || echo 'codewatch: scan failed (push continues)'"
513
+ return f"""#!/bin/sh
514
+ {HOOK_MARKER}
515
+ # Runs tests with coverage, then uploads a scan of this branch. Remove this file to disable.
516
+ {exe} coverage || exit 1
517
+ {scan}
518
+ """
519
+
520
+
521
+ def install_hook(repo, name, strict):
522
+ hooks = Path(repo.git("rev-parse", "--git-path", "hooks").strip())
523
+ hooks = hooks if hooks.is_absolute() else repo.root / hooks
524
+ path = hooks / name
525
+ if path.exists() and HOOK_MARKER not in path.read_text():
526
+ raise ClientError(f"{path} already exists and wasn't written by codewatch; add these lines to it:\n"
527
+ + hook_script(strict, name))
528
+ hooks.mkdir(parents=True, exist_ok=True)
529
+ path.write_text(hook_script(strict, name))
530
+ path.chmod(path.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
531
+ log(f"Installed {path}")
532
+
533
+
534
+ def cmd_init(args):
535
+ repo = LocalRepo(args.path)
536
+ path = repo.root / CONFIG_FILE
537
+ conf = load_config(repo.root)
538
+ conf.setdefault("projectKey", args.project or default_key(repo.root))
539
+ conf.setdefault("projectName", args.name or conf["projectKey"])
540
+ conf.setdefault("mainBranch", detect_main_branch(repo))
541
+ if args.url or os.environ.get("CODEWATCH_URL"):
542
+ conf.setdefault("serverUrl", (args.url or os.environ["CODEWATCH_URL"]).rstrip("/"))
543
+ # This user chose it.
544
+ trust_server(args.url or os.environ["CODEWATCH_URL"])
545
+ path.write_text(json.dumps(conf, indent=2) + "\n")
546
+ log(f"Wrote {path} (commit it; keep the token in CODEWATCH_TOKEN, never in this file)")
547
+ if args.hook != "none":
548
+ install_hook(repo, args.hook, args.strict)
549
+ return 0
550
+
551
+
552
+ # --- entry points -----------------------------------------------------------------------------------------
553
+
554
+
555
+ def add_scan_args(p):
556
+ p.add_argument("path", nargs="?", default=".", help="Working copy (default: current directory)")
557
+ p.add_argument("--url", help="codewatch server (env CODEWATCH_URL, or serverUrl in codewatch-project.json)")
558
+ p.add_argument("--token", help="API token with scan scope (env CODEWATCH_TOKEN)")
559
+ p.add_argument("--project", help="Project key (default: projectKey in codewatch-project.json, else folder name)")
560
+ p.add_argument("--name", help="Display name when the project is created")
561
+ p.add_argument("--branch", help="Branch name (default: current branch; required on a detached HEAD)")
562
+ p.add_argument("--main-branch", help="Main branch for a new project (default: origin's HEAD branch)")
563
+ p.add_argument("--coverage", help="Cobertura XML or LCOV report (default: auto-detected)")
564
+ p.add_argument("--fail-on-gate", action=STORE_TRUE, help="Exit 1 if the quality gate fails")
565
+ p.add_argument("--output", help="Write the payload to this file instead of uploading")
566
+
567
+
568
+ def build_parser():
569
+ parser = argparse.ArgumentParser(prog="codewatch", description=(__doc__ or "codewatch").splitlines()[0])
570
+ sub = parser.add_subparsers(dest="command", required=True)
571
+ add_scan_args(sub.add_parser("scan", help="Analyse the working copy and upload the results"))
572
+ check = sub.add_parser("check", help="Check some files locally, uploading nothing (default: the changed ones)")
573
+ check.add_argument("files", nargs="*", help="Files to check (default: staged files, else every changed file)")
574
+ check.add_argument("--all", action=STORE_TRUE, help="Every file in the project (the whole-project check CI runs)")
575
+ check.add_argument("--strict", action=STORE_TRUE,
576
+ help="Every open issue blocks, of any kind or severity, not only new serious ones")
577
+ check.add_argument("--all-lines", action=STORE_TRUE,
578
+ help="Block on issues anywhere in the files, not only on changed lines")
579
+ check.add_argument("--verbose", action=STORE_TRUE, help="Show each analyzer as it runs")
580
+ for name in ("--url", "--token", "--project", "--branch"):
581
+ check.add_argument(name, help="As for scan: where the project's settings come from")
582
+ check.set_defaults(main_branch=None)
583
+ cov = sub.add_parser(COVERAGE, help="Run the tests with coverage, writing a report scan picks up")
584
+ cov.add_argument("path", nargs="?", default=".")
585
+ init = sub.add_parser("init", help=f"Write {CONFIG_FILE} and optionally install a git hook")
586
+ init.add_argument("path", nargs="?", default=".")
587
+ init.add_argument("--project")
588
+ init.add_argument("--name")
589
+ init.add_argument("--url")
590
+ init.add_argument("--hook", choices=["pre-push", "pre-commit", "none"], default="none")
591
+ init.add_argument("--strict", action=STORE_TRUE, help="Make the hook block when the quality gate fails")
592
+ setup = sub.add_parser("setup", help="Install the analyzers codewatch runs, at the versions it is tested with")
593
+ setup.add_argument("--browser", action=STORE_TRUE,
594
+ help="Also Chromium, for the accessibility checks of live pages (axe)")
595
+ bench = sub.add_parser("benchmark", help="Score codewatch against suites with known vulnerabilities")
596
+ bench.add_argument("suites", nargs="*", help="Suite names from benchmarks/suites.json (default: all)")
597
+ return parser
598
+
599
+
600
+ def cmd_setup(args):
601
+ from .tool_setup import install_tools
602
+
603
+ log(f"Installing codewatch's analyzers into {TOOLS_DIR} (the versions and hashes it is tested with)")
604
+ if install_tools(log, browser=args.browser):
605
+ log("codewatch setup: done")
606
+ return 0
607
+ log("codewatch setup: some analyzers weren't installed (see above); codewatch check will say which")
608
+ return 2
609
+
610
+
611
+ def cmd_benchmark(args):
612
+ from .benchmark import ROOT, WORKERS
613
+ from .benchmark import run as run_benchmarks
614
+
615
+ if not ROOT.is_dir():
616
+ raise ClientError("benchmarks run from a source checkout (git clone https://github.com/shwan-ps5/codewatch)")
617
+
618
+ for name, result in run_benchmarks(args.suites or None, log=log, workers=WORKERS).items():
619
+ log(f"{name}: {json.dumps(result['overall'])}")
620
+ return 0
621
+
622
+
623
+ COMMANDS = {"scan": cmd_scan, "check": cmd_check, COVERAGE: cmd_coverage, "init": cmd_init, "setup": cmd_setup,
624
+ "benchmark": cmd_benchmark}
625
+
626
+
627
+ def run(args):
628
+ try:
629
+ return COMMANDS[args.command](args)
630
+ except (ClientError, GitError) as exc:
631
+ log(f"codewatch: {exc}")
632
+ return 2
633
+
634
+
635
+ def main(argv=None):
636
+ return run(build_parser().parse_args(argv))
637
+
638
+
639
+ def scan_main(argv=None):
640
+ """`codewatch-scan` is shorthand for `codewatch scan`."""
641
+ return main(["scan", *(sys.argv[1:] if argv is None else argv)])
642
+
643
+
644
+ if __name__ == "__main__":
645
+ sys.exit(main())