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/models.py ADDED
@@ -0,0 +1,323 @@
1
+ import hashlib
2
+ import secrets
3
+ from datetime import datetime, timedelta
4
+
5
+ from django.conf import settings
6
+ from django.db import models
7
+ from django.utils import timezone
8
+
9
+ from .catalog import custom_semgrep_rules
10
+ from .collect import DEFAULT_EXCLUSIONS, period_days
11
+
12
+ SEVERITIES = ["blocker", "critical", "major", "minor", "info"]
13
+ ISSUE_TYPES = ["bug", "vulnerability", "security_hotspot", "code_smell", "accessibility"]
14
+
15
+
16
+ def default_exclusions():
17
+ return list(DEFAULT_EXCLUSIONS)
18
+
19
+
20
+ class Project(models.Model):
21
+ key = models.SlugField(unique=True)
22
+ name = models.CharField(max_length=200)
23
+ repo_url = models.CharField(
24
+ max_length=500, blank=True, help_text="Only for server-side scans; leave blank when using codewatch-scan"
25
+ )
26
+ main_branch = models.CharField(max_length=200, blank=True, help_text="Detected on first scan if blank")
27
+ exclusions = models.JSONField(default=default_exclusions, blank=True)
28
+ disabled_analyzers = models.JSONField(default=list, blank=True)
29
+ semgrep_config = models.CharField(max_length=200, default="p/default")
30
+ complexity_threshold = models.PositiveIntegerField(default=10, help_text="Cyclomatic complexity per function")
31
+ cognitive_complexity_threshold = models.PositiveIntegerField(
32
+ default=15, help_text="Cognitive complexity per function (Python)"
33
+ )
34
+ duplicate_literal_threshold = models.PositiveIntegerField(
35
+ default=3, help_text="Flag a string literal repeated more than this many times in a file"
36
+ )
37
+ a11y_urls = models.JSONField(
38
+ default=list, blank=True, help_text="Live pages to check with axe-core; {branch} is replaced by the branch name"
39
+ )
40
+ new_code_period = models.CharField(
41
+ max_length=200, blank=True, verbose_name="New code on the main branch",
42
+ help_text="Blank: since the previous analysis. 30d: since the newest analysis at least 30 days old. "
43
+ "Anything else is a tag, branch or commit, e.g. v1.4.",
44
+ )
45
+ owner = models.ForeignKey(
46
+ settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, related_name="projects"
47
+ )
48
+ created_at = models.DateTimeField(auto_now_add=True)
49
+
50
+ def __str__(self):
51
+ return self.key
52
+
53
+ @classmethod
54
+ def visible_to(cls, user):
55
+ if user.is_superuser:
56
+ return cls.objects.all()
57
+ return cls.objects.filter(models.Q(owner=user) | models.Q(members__user=user)).distinct()
58
+
59
+ def scan_config(self):
60
+ """Settings the codewatch-scan client needs, mirroring collect.ScanConfig."""
61
+ main = self.main_analyses_for_reference()
62
+ return {
63
+ "main_branch": self.main_branch,
64
+ "exclusions": self.exclusions,
65
+ "disabled_analyzers": self.disabled_analyzers,
66
+ "semgrep_config": self.semgrep_config,
67
+ "complexity_threshold": self.complexity_threshold,
68
+ "cognitive_complexity_threshold": self.cognitive_complexity_threshold,
69
+ "duplicate_literal_threshold": self.duplicate_literal_threshold,
70
+ "custom_rules": custom_semgrep_rules(),
71
+ "a11y_urls": self.a11y_urls,
72
+ "new_code_period": self.new_code_period,
73
+ "main_analyses": [
74
+ {"commit": a.commit, "reference_commit": a.reference_commit, "started_at": a.started_at.isoformat()}
75
+ for a in main
76
+ ],
77
+ }
78
+
79
+ def main_analyses_for_reference(self):
80
+ """Recent main analyses, newest first, plus what a days-based new-code period needs further back:
81
+ the newest few older than the cutoff, and the first ever (the fallback for a younger project)."""
82
+ done = self.analyses.filter(branch=self.main_branch, status=Analysis.SUCCESS).order_by("-started_at")
83
+ main = list(done[:50])
84
+ days = period_days(self.new_code_period)
85
+ if days is not None:
86
+ older = [*done.filter(started_at__lte=timezone.now() - timedelta(days=days))[:10], *done.reverse()[:1]]
87
+ main += [a for a in dict.fromkeys(older) if a not in main]
88
+ return main
89
+
90
+ def role_of(self, user):
91
+ if user.is_superuser or self.owner_id == user.pk:
92
+ return ProjectMember.OWNER
93
+ member = self.members.filter(user=user).first()
94
+ return member.role if member else None
95
+
96
+ def can_scan(self, user):
97
+ return self.role_of(user) in (ProjectMember.OWNER, ProjectMember.CONTRIBUTOR)
98
+
99
+ def can_admin(self, user):
100
+ return self.role_of(user) == ProjectMember.OWNER
101
+
102
+ def latest_analyses(self):
103
+ """Latest finished analysis per branch, main branch first."""
104
+ latest = {}
105
+ for a in self.analyses.exclude(status=Analysis.RUNNING).order_by("-started_at"):
106
+ latest.setdefault(a.branch, a)
107
+ return sorted(latest.values(), key=lambda a: (a.branch != self.main_branch, a.branch))
108
+
109
+
110
+ class ProjectMember(models.Model):
111
+ OWNER, CONTRIBUTOR, VIEWER = "owner", "contributor", "viewer"
112
+ ROLES = [(VIEWER, "Viewer: see results"), (CONTRIBUTOR, "Contributor: also scan branches and resolve issues")]
113
+
114
+ project = models.ForeignKey("Project", on_delete=models.CASCADE, related_name="members")
115
+ user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="memberships")
116
+ role = models.CharField(max_length=12, choices=ROLES, default=CONTRIBUTOR)
117
+
118
+ class Meta:
119
+ constraints = [models.UniqueConstraint(fields=["project", "user"], name="uniq_member")]
120
+
121
+ def __str__(self):
122
+ return f"{self.user} ({self.role}) on {self.project}"
123
+
124
+
125
+ class Analysis(models.Model):
126
+ RUNNING, SUCCESS, FAILED = "running", "success", "failed"
127
+ STATUSES = [(s, s) for s in (RUNNING, SUCCESS, FAILED)]
128
+
129
+ project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name="analyses")
130
+ branch = models.CharField(max_length=200)
131
+ commit = models.CharField(max_length=40)
132
+ reference_branch = models.CharField(max_length=200, blank=True)
133
+ reference_commit = models.CharField(max_length=40, blank=True)
134
+ started_at = models.DateTimeField(auto_now_add=True)
135
+ finished_at = models.DateTimeField(null=True, blank=True)
136
+ status = models.CharField(max_length=10, choices=STATUSES, default=RUNNING)
137
+ error = models.TextField(blank=True)
138
+ gate_passed = models.BooleanField(null=True)
139
+ gate_details = models.JSONField(default=list, blank=True)
140
+ tools = models.JSONField(default=dict, blank=True)
141
+ dirty = models.BooleanField(default=False, help_text="Scanned from a working copy with uncommitted changes")
142
+ origin = models.CharField(max_length=10, default="server", choices=[("server", "server"), ("client", "client")])
143
+ scanned_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True)
144
+ # A running server scan's steps so far, [{"step", "at"}], the last one in progress.
145
+ progress = models.JSONField(default=list, blank=True)
146
+
147
+ class Meta:
148
+ ordering = ["-started_at"]
149
+
150
+ def __str__(self):
151
+ return f"{self.project.key}@{self.branch} {self.commit[:8]}"
152
+
153
+ @property
154
+ def metrics_dict(self):
155
+ return {m.key: m.value for m in self.metrics.all()}
156
+
157
+ @property
158
+ def steps(self):
159
+ """The running scan's steps so far, each with when it started; the last is in progress."""
160
+ return progress_steps(self.progress)
161
+
162
+
163
+ def progress_steps(progress):
164
+ """Stored progress entries ({"step", "at": ISO time}) with their times parsed."""
165
+ return [{"step": s["step"], "at": datetime.fromisoformat(s["at"])} for s in progress or []]
166
+
167
+
168
+ class Issue(models.Model):
169
+ analysis = models.ForeignKey(Analysis, on_delete=models.CASCADE, related_name="issues")
170
+ fingerprint = models.CharField(max_length=40, db_index=True)
171
+ tool = models.CharField(max_length=30)
172
+ rule = models.CharField(max_length=300)
173
+ severity = models.CharField(max_length=10, choices=[(s, s) for s in SEVERITIES])
174
+ type = models.CharField(max_length=20, choices=[(t, t) for t in ISSUE_TYPES])
175
+ message = models.TextField()
176
+ path = models.CharField(max_length=500)
177
+ line = models.PositiveIntegerField(null=True)
178
+ end_line = models.PositiveIntegerField(null=True)
179
+ is_new = models.BooleanField(default=False)
180
+ also_reported_by = models.JSONField(default=list, blank=True)
181
+
182
+ class Meta:
183
+ ordering = ["path", "line"]
184
+
185
+ def __str__(self):
186
+ return f"{self.tool}:{self.rule} at {self.path}:{self.line}"
187
+
188
+
189
+ class SourceBlob(models.Model):
190
+ sha = models.CharField(max_length=64, primary_key=True)
191
+ content = models.TextField()
192
+
193
+ def __str__(self):
194
+ return self.sha[:12]
195
+
196
+
197
+ class AnalysisSource(models.Model):
198
+ analysis = models.ForeignKey(Analysis, on_delete=models.CASCADE, related_name="sources")
199
+ path = models.CharField(max_length=500)
200
+ blob = models.ForeignKey(SourceBlob, on_delete=models.PROTECT)
201
+
202
+ class Meta:
203
+ constraints = [models.UniqueConstraint(fields=["analysis", "path"], name="uniq_source")]
204
+
205
+ def __str__(self):
206
+ return f"{self.analysis} {self.path}"
207
+
208
+
209
+ class Metric(models.Model):
210
+ analysis = models.ForeignKey(Analysis, on_delete=models.CASCADE, related_name="metrics")
211
+ key = models.CharField(max_length=60)
212
+ value = models.FloatField()
213
+
214
+ class Meta:
215
+ constraints = [models.UniqueConstraint(fields=["analysis", "key"], name="uniq_metric")]
216
+
217
+ def __str__(self):
218
+ return f"{self.key}={self.value:g}"
219
+
220
+
221
+ class IssueResolution(models.Model):
222
+ WONT_FIX, FALSE_POSITIVE, SAFE = "wont_fix", "false_positive", "safe"
223
+ # Safe: a security hotspot reviewed and found acceptable where it is (neither a false alarm nor a known risk).
224
+ STATUSES = [(WONT_FIX, "Won't fix"), (FALSE_POSITIVE, "False positive"), (SAFE, "Safe (reviewed)")]
225
+
226
+ project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name="resolutions")
227
+ fingerprint = models.CharField(max_length=40)
228
+ status = models.CharField(max_length=20, choices=STATUSES)
229
+ comment = models.TextField(blank=True)
230
+ updated_at = models.DateTimeField(auto_now=True)
231
+
232
+ class Meta:
233
+ constraints = [models.UniqueConstraint(fields=["project", "fingerprint"], name="uniq_resolution")]
234
+
235
+ def __str__(self):
236
+ return f"{self.fingerprint[:8]} {self.status}"
237
+
238
+
239
+ class GateCondition(models.Model):
240
+ GT, LT = "gt", "lt"
241
+ OPS = [(GT, "is greater than"), (LT, "is less than")]
242
+
243
+ project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name="gate_conditions")
244
+ metric = models.CharField(max_length=60)
245
+ op = models.CharField(max_length=2, choices=OPS)
246
+ threshold = models.FloatField()
247
+
248
+ class Meta:
249
+ ordering = ["metric"]
250
+
251
+ def __str__(self):
252
+ return f"{self.metric} {self.op} {self.threshold:g}"
253
+
254
+ def fails(self, value):
255
+ return value > self.threshold if self.op == self.GT else value < self.threshold
256
+
257
+
258
+ class Profile(models.Model):
259
+ user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="profile")
260
+ must_change_password = models.BooleanField(default=False)
261
+
262
+ def __str__(self):
263
+ return str(self.user)
264
+
265
+
266
+ def hash_token(raw):
267
+ return hashlib.sha256(raw.encode()).hexdigest()
268
+
269
+
270
+ class ApiToken(models.Model):
271
+ READ, SCAN = "read", "scan"
272
+ SCOPES = [(READ, "Read issues and results, resolve issues"), (SCAN, "Read, resolve, and create projects / start scans")]
273
+
274
+ user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="api_tokens")
275
+ name = models.CharField(max_length=100)
276
+ scope = models.CharField(max_length=10, choices=SCOPES, default=SCAN)
277
+ prefix = models.CharField(max_length=12)
278
+ key_hash = models.CharField(max_length=64, unique=True)
279
+ created_at = models.DateTimeField(auto_now_add=True)
280
+ last_used_at = models.DateTimeField(null=True, blank=True)
281
+
282
+ class Meta:
283
+ ordering = ["-created_at"]
284
+
285
+ def __str__(self):
286
+ return f"{self.user}: {self.name} ({self.prefix}\u2026)"
287
+
288
+ @classmethod
289
+ def issue(cls, user, name, scope):
290
+ """Create a token; the raw value is returned once and only its hash is stored."""
291
+ raw = "cw_" + secrets.token_urlsafe(32)
292
+ token = cls.objects.create(user=user, name=name, scope=scope, prefix=raw[:10], key_hash=hash_token(raw))
293
+ return token, raw
294
+
295
+ @classmethod
296
+ def authenticate(cls, raw):
297
+ token = cls.objects.select_related("user").filter(key_hash=hash_token(raw)).first()
298
+ if token is None or not token.user.is_active:
299
+ return None
300
+ return token
301
+
302
+
303
+ # The whole codebase too, not only new code: a first scan has no new code, so without these a project with a
304
+ # hundred bugs and unreviewed hotspots passed (VibeVoice, 2026-11-19). Worse than C (3) fails.
305
+ OVERALL_GATE = [
306
+ ("reliability_rating", GateCondition.GT, 3),
307
+ ("security_rating", GateCondition.GT, 3),
308
+ ("security_review_rating", GateCondition.GT, 3),
309
+ ("maintainability_rating", GateCondition.GT, 3),
310
+ ]
311
+ DEFAULT_GATE = [
312
+ ("new_blocker_issues", GateCondition.GT, 0),
313
+ ("new_critical_issues", GateCondition.GT, 0),
314
+ ("new_bugs", GateCondition.GT, 0),
315
+ ("new_vulnerabilities", GateCondition.GT, 0),
316
+ ("new_coverage", GateCondition.LT, 80),
317
+ ("new_duplicated_lines_percent", GateCondition.GT, 3),
318
+ ("dependency_critical_vulnerabilities", GateCondition.GT, 0),
319
+ ("new_accessibility_issues", GateCondition.GT, 0),
320
+ ("new_maintainability_rating", GateCondition.GT, 1),
321
+ ("new_security_review_rating", GateCondition.GT, 1),
322
+ *OVERALL_GATE,
323
+ ]
core/network.py ADDED
@@ -0,0 +1,41 @@
1
+ """Which addresses the server may be asked to reach on a user's behalf: only public ones, unless an administrator
2
+ set the project up (a staging site or a git server on the local network is their call, not a user's)."""
3
+ import ipaddress
4
+ import re
5
+ import socket
6
+ from urllib.parse import urlsplit
7
+
8
+ # git@host:path (scp-like) has no scheme for urlsplit.
9
+ SCP_LIKE_RE = re.compile(r"^[\w.-]+@([\w.-]+):")
10
+
11
+
12
+ def url_host(url):
13
+ match = SCP_LIKE_RE.match(url)
14
+ return match[1] if match else urlsplit(url).hostname
15
+
16
+
17
+ def public_address(address):
18
+ ip = ipaddress.ip_address(address)
19
+ if ip.version == 6 and ip.ipv4_mapped: # an IP version, not a magic number
20
+ ip = ip.ipv4_mapped
21
+ return ip.is_global and not ip.is_multicast
22
+
23
+
24
+ def check_public(url):
25
+ """ValueError unless every address the URL's host resolves to is public (not loopback, private, link-local such
26
+ as a cloud metadata service, or reserved). Checked again when the server connects, since DNS can change."""
27
+ host = url_host(url)
28
+ if not host:
29
+ raise ValueError(f"No host in {url}")
30
+ try:
31
+ addresses = {info[4][0] for info in socket.getaddrinfo(host, None)}
32
+ except (socket.gaierror, UnicodeError) as exc:
33
+ raise ValueError(f"{host} doesn't resolve") from exc
34
+ if not all(public_address(a.split("%", 1)[0]) for a in addresses):
35
+ raise ValueError(f"{host} is on a private or local network; only an administrator can use it")
36
+ return url
37
+
38
+
39
+ def trusted_owner(project):
40
+ """Set up by an administrator: owned by one, or added with `manage.py addproject` (no owner)."""
41
+ return project.owner_id is None or project.owner.is_superuser
core/paths.py ADDED
@@ -0,0 +1,29 @@
1
+ """Where codewatch's own files are.
2
+
3
+ In a source checkout (or an editable install of one): its catalog/ and tools/ folders, and db.sqlite3 beside them.
4
+ An installed package has neither folder, so setup.py copies the rules and the tool files it needs (configs, scripts,
5
+ lock files) into core/bundled/ when the wheel is built. What gets installed or stored at run time (the analyzers'
6
+ venvs and node_modules, the database) then goes to a data folder, since site-packages may not be writable.
7
+ """
8
+ import os
9
+ from pathlib import Path
10
+
11
+ PACKAGE = Path(__file__).resolve().parent
12
+ CHECKOUT = PACKAGE.parent
13
+ BUNDLED = PACKAGE / "bundled"
14
+ INSTALLED = BUNDLED.is_dir()
15
+ DATA_HOME = Path(os.environ.get("XDG_DATA_HOME") or Path.home() / ".local" / "share") / "codewatch"
16
+
17
+
18
+ def shipped(name):
19
+ """catalog/ or tools/ as codewatch came with it: the checkout's folder, or the package's copy."""
20
+ return (BUNDLED if INSTALLED else CHECKOUT) / name
21
+
22
+
23
+ def tools_dir():
24
+ """Where the analyzers are installed (`codewatch setup`): CODEWATCH_TOOLS, else the checkout's tools/, else the
25
+ data folder."""
26
+ configured = os.environ.get("CODEWATCH_TOOLS")
27
+ if configured:
28
+ return Path(configured)
29
+ return DATA_HOME / "tools" if INSTALLED else CHECKOUT / "tools"
core/ratings.py ADDED
@@ -0,0 +1,67 @@
1
+ """Project ratings (A-E) and an overall health score.
2
+
3
+ Reliability, security and accessibility are rated by the worst open issue of that type. Maintainability is the worse
4
+ of the SQALE technical-debt ratio (estimated remediation effort for code smells divided by the estimated cost of
5
+ writing the code) and the worst open code smell: a density alone let a hundred complex functions in a large project
6
+ rate A. Security review is the share of security hotspots that have been reviewed (resolved).
7
+ """
8
+ GRADES = "ABCDE"
9
+ WORST_SEVERITY_RATING = {"blocker": 5, "critical": 4, "major": 3, "minor": 2, "info": 2}
10
+ # Remediation estimates in minutes per code smell, by severity.
11
+ REMEDIATION_MINUTES = {"blocker": 120, "critical": 60, "major": 20, "minor": 5, "info": 1}
12
+ MINUTES_PER_LINE = 30
13
+ DEBT_RATIO_LIMITS = [(5, 1), (10, 2), (20, 3), (50, 4)]
14
+ REVIEW_LIMITS = [(80, 1), (70, 2), (50, 3), (30, 4)]
15
+ SCORE = {1: 100, 2: 80, 3: 60, 4: 40, 5: 20}
16
+
17
+ RATED_TYPES = {"bug": "reliability", "vulnerability": "security", "accessibility": "accessibility"}
18
+
19
+
20
+ def grade(rating):
21
+ return GRADES[int(rating) - 1] if rating else "\u2013"
22
+
23
+
24
+ def worst(severities):
25
+ return max((WORST_SEVERITY_RATING[s] for s in severities), default=1)
26
+
27
+
28
+ def debt_rating(minutes, lines):
29
+ if not lines:
30
+ return 1
31
+ ratio = 100 * minutes / (lines * MINUTES_PER_LINE)
32
+ return next((r for limit, r in DEBT_RATIO_LIMITS if ratio <= limit), 5)
33
+
34
+
35
+ def review_rating(open_hotspots, reviewed):
36
+ total = open_hotspots + reviewed
37
+ if not total:
38
+ return 1
39
+ pct = 100 * reviewed / total
40
+ return next((r for limit, r in REVIEW_LIMITS if pct >= limit), 5)
41
+
42
+
43
+ def compute(rows, resolved_hotspots, metrics, scope):
44
+ """Ratings for one scope ("" overall, "new_" new code) from (type, severity) rows of open issues."""
45
+ by_type = {}
46
+ for type_, severity in rows:
47
+ by_type.setdefault(type_, []).append(severity)
48
+ smell_minutes = sum(REMEDIATION_MINUTES[s] for s in by_type.get("code_smell", []))
49
+ lines = metrics.get("new_lines" if scope else "ncloc", 0)
50
+ out = {f"{scope}{name}_rating": worst(by_type.get(t, [])) for t, name in RATED_TYPES.items()}
51
+ out[f"{scope}maintainability_rating"] = max(debt_rating(smell_minutes, lines), worst(by_type.get("code_smell", [])))
52
+ out[f"{scope}technical_debt_minutes"] = smell_minutes
53
+ if lines:
54
+ out[f"{scope}debt_ratio_percent"] = round(100 * smell_minutes / (lines * MINUTES_PER_LINE), 2)
55
+ out[f"{scope}security_review_rating"] = review_rating(len(by_type.get("security_hotspot", [])),
56
+ resolved_hotspots)
57
+ if not scope:
58
+ ratings = [out[k] for k in ("reliability_rating", "security_rating", "maintainability_rating",
59
+ "security_review_rating")]
60
+ if metrics.get("_has_accessibility"):
61
+ ratings.append(out["accessibility_rating"])
62
+ out["health_score"] = round(sum(SCORE[r] for r in ratings) / len(ratings))
63
+ return out
64
+
65
+
66
+ def score_grade(score):
67
+ return next((g for g, limit in zip(GRADES, (90, 75, 60, 40), strict=False) if score >= limit), "E")
core/runner.py ADDED
@@ -0,0 +1,168 @@
1
+ import hashlib
2
+ import traceback
3
+
4
+ from django.db import transaction
5
+ from django.utils import timezone
6
+
7
+ from . import gate
8
+ from .collect import ScanConfig, ScanInput, choose_reference, collect
9
+ from .duplicates import dedupe
10
+ from .git import Mirror
11
+ from .models import ISSUE_TYPES, SEVERITIES, Analysis, AnalysisSource, Issue, Metric, SourceBlob
12
+ from .network import check_public, trusted_owner
13
+
14
+
15
+ def public_url(url):
16
+ """Checked again at scan time: a name that resolved to a public address when saved may not now."""
17
+ try:
18
+ check_public(url)
19
+ except ValueError:
20
+ return False
21
+ return True
22
+
23
+
24
+ ISSUE_FIELDS = ("tool", "rule", "severity", "type", "message", "path", "line", "end_line", "fingerprint",
25
+ "also_reported_by")
26
+
27
+
28
+ def ensure_main_branch(project, mirror):
29
+ if not project.main_branch:
30
+ project.main_branch = mirror.default_branch()
31
+ project.save(update_fields=["main_branch"])
32
+
33
+
34
+ def progress_recorder(analysis, log):
35
+ """A log function that also records each analyzer starting on the running analysis, for its page."""
36
+ def step(line):
37
+ log(line)
38
+ if line.startswith(("Running ", "Saving ")):
39
+ analysis.progress = [*analysis.progress, {"step": line, "at": timezone.now().isoformat()}]
40
+ analysis.save(update_fields=["progress"])
41
+ return step
42
+
43
+
44
+ def scan(project, branch, coverage_report=None, coverage_base=None, log=print):
45
+ """Server-side scan of a branch from the project's repository URL."""
46
+ mirror = Mirror(project)
47
+ log(f"Syncing {project.repo_url}")
48
+ mirror.sync()
49
+ ensure_main_branch(project, mirror)
50
+ branch = branch or project.main_branch
51
+ commit = mirror.rev_parse(branch)
52
+ cfg = ScanConfig.from_dict(project.scan_config())
53
+ if not trusted_owner(project):
54
+ cfg.a11y_urls = [u for u in cfg.a11y_urls if public_url(u.replace("{branch}", branch))]
55
+ ref, ref_analysis = choose_reference(branch, commit, cfg, mirror)
56
+ analysis = Analysis.objects.create(
57
+ project=project, branch=branch, commit=commit, reference_branch=project.main_branch,
58
+ reference_commit=ref or "",
59
+ )
60
+ step = progress_recorder(analysis, log)
61
+ try:
62
+ with mirror.worktree(commit, f"a{analysis.pk}") as root:
63
+ changed = mirror.changed_lines(ref, commit) if ref else None
64
+ payload = collect(cfg, ScanInput(root, mirror.tracked_files(commit), branch, changed,
65
+ coverage_report, coverage_base), step)
66
+ step("Saving the results")
67
+ payload.update(reference_analysis_commit=ref_analysis)
68
+ ingest(analysis, payload)
69
+ log(f"{len(payload['issues'])} issues, gate {'passed' if analysis.gate_passed else 'FAILED'}")
70
+ except Exception: # noqa: BLE001 - recorded on the analysis and shown in the UI
71
+ analysis.status = Analysis.FAILED
72
+ analysis.error = traceback.format_exc()
73
+ analysis.finished_at = timezone.now()
74
+ analysis.save()
75
+ log(analysis.error)
76
+ return analysis
77
+
78
+
79
+ def create_uploaded_analysis(project, payload, user):
80
+ """Analysis record for a codewatch-scan upload; branch/commit/reference come from the client's git."""
81
+ return Analysis.objects.create(
82
+ project=project,
83
+ branch=payload["branch"],
84
+ commit=payload["commit"],
85
+ reference_branch=project.main_branch,
86
+ reference_commit=payload.get("reference_commit") or "",
87
+ dirty=bool(payload.get("dirty")),
88
+ origin="client",
89
+ scanned_by=user,
90
+ )
91
+
92
+
93
+ def ingest(analysis, payload):
94
+ """Store a collect() payload on an analysis: issues with new-code flags, metrics, sources, then the gate."""
95
+ ref_fps = reference_fingerprints(analysis.project, payload.get("reference_analysis_commit"))
96
+ changed = {p: set(lines) for p, lines in (payload.get("changed_lines") or {}).items()}
97
+ issues = checked_issues(payload["issues"])
98
+ metrics = analysis_metrics(analysis, payload["metrics"], issues)
99
+
100
+ with transaction.atomic():
101
+ Issue.objects.bulk_create(
102
+ Issue(analysis=analysis, **{**i, "rule": i["rule"][:300], "path": i["path"][:500]},
103
+ is_new=is_new(i, changed, ref_fps))
104
+ for i in issues
105
+ )
106
+ Metric.objects.bulk_create(Metric(analysis=analysis, key=k, value=v) for k, v in metrics.items())
107
+ store_sources(analysis, payload.get("sources") or {})
108
+ analysis.tools = payload.get("tools", {})
109
+ analysis.status = Analysis.SUCCESS
110
+ analysis.finished_at = timezone.now()
111
+ analysis.save()
112
+ gate.refresh(analysis)
113
+ return analysis
114
+
115
+
116
+ def checked_issues(raw):
117
+ """The payload's issues, duplicates merged, each with a known severity and type: pages and the API index by
118
+ these, and one unknown value made every view of the analysis fail."""
119
+ issues = dedupe([{k: i.get(k) for k in ISSUE_FIELDS} for i in raw])
120
+ for i in issues:
121
+ if i["severity"] not in SEVERITIES or i["type"] not in ISSUE_TYPES:
122
+ raise ValueError(f"Unknown severity or type: {i['severity']!r}, {i['type']!r}")
123
+ return issues
124
+
125
+
126
+ def analysis_metrics(analysis, metrics, issues):
127
+ """The payload's metrics, plus how many of the branch's previous analysis's issues are gone."""
128
+ metrics = dict(metrics)
129
+ fixed = fixed_issue_count(analysis, {i["fingerprint"] for i in issues})
130
+ if fixed is not None:
131
+ metrics["fixed_issues"] = fixed
132
+ return metrics
133
+
134
+
135
+ def reference_fingerprints(project, commit):
136
+ if not commit:
137
+ return None
138
+ ref = project.analyses.filter(
139
+ branch=project.main_branch, commit=commit, status=Analysis.SUCCESS
140
+ ).order_by("-started_at").first()
141
+ return set(ref.issues.values_list("fingerprint", flat=True)) if ref else None
142
+
143
+
144
+ def store_sources(analysis, sources):
145
+ for path, content in sources.items():
146
+ sha = hashlib.sha256(content.encode()).hexdigest()
147
+ blob, _ = SourceBlob.objects.get_or_create(sha=sha, defaults={"content": content})
148
+ AnalysisSource.objects.create(analysis=analysis, path=path[:500], blob=blob)
149
+
150
+
151
+ def fixed_issue_count(analysis, fingerprints):
152
+ previous = (
153
+ analysis.project.analyses.filter(branch=analysis.branch, status=Analysis.SUCCESS)
154
+ .exclude(pk=analysis.pk).order_by("-started_at").first()
155
+ )
156
+ if previous is None:
157
+ return None
158
+ return len(set(previous.issues.values_list("fingerprint", flat=True)) - fingerprints)
159
+
160
+
161
+ def is_new(issue, changed, ref_fps):
162
+ lines = changed.get(issue["path"])
163
+ if lines is None:
164
+ return False
165
+ if issue["line"] and issue["line"] in lines:
166
+ return True
167
+ # Issues caused by a change elsewhere in the file (e.g. an import left unused) sit on untouched lines.
168
+ return ref_fps is not None and issue["fingerprint"] not in ref_fps
@@ -0,0 +1,30 @@
1
+ {% extends "core/base.html" %}
2
+ {% block title %}Account · codewatch{% endblock %}
3
+ {% block crumbs %}<li aria-current="page">Account</li>{% endblock %}
4
+ {% block content %}
5
+ <h1>Account: {{ user.username }}</h1>
6
+ <p><a href="{% url 'password_change' %}">Change password</a></p>
7
+ {% if new_token %}
8
+ <section class="card" aria-labelledby="new-token-h" role="alert">
9
+ <h2 id="new-token-h">New token</h2>
10
+ <p>Copy it now; it won't be shown again.</p>
11
+ <p class="token"><code>{{ new_token }}</code></p>
12
+ </section>
13
+ {% endif %}
14
+ <section class="card" aria-labelledby="tokens-h">
15
+ <h2 id="tokens-h">API tokens</h2>
16
+ <p class="muted">Used by <code>codewatch-scan</code>, CI and the MCP server. API base: <code>{{ api_base }}</code></p>
17
+ <table>
18
+ <caption class="sr-only">Your API tokens</caption>
19
+ <thead><tr><th scope="col">Name</th><th scope="col">Scope</th><th scope="col">Prefix</th><th scope="col">Created</th><th scope="col">Last used</th><th scope="col"><span class="sr-only">Actions</span></th></tr></thead>
20
+ <tbody>
21
+ {% for t in tokens %}<tr><td>{{ t.name }}</td><td>{{ t.scope }}</td><td><code>{{ t.prefix }}…</code></td><td>{{ t.created_at|date:"Y-m-d" }}</td><td>{{ t.last_used_at|date:"Y-m-d H:i"|default:"never" }}</td>
22
+ <td><form class="inline" method="post">{% csrf_token %}<input type="hidden" name="revoke" value="{{ t.pk }}"><button aria-label="Revoke token {{ t.name }}">Revoke</button></form></td></tr>
23
+ {% empty %}<tr><td colspan="6" class="muted">No tokens yet.</td></tr>{% endfor %}
24
+ </tbody></table>
25
+ </section>
26
+ <section class="card" aria-labelledby="create-h" style="max-width:640px">
27
+ <h2 id="create-h">Create a token</h2>
28
+ <form method="post">{% csrf_token %}{% include "core/form_table.html" %}<p><button>Create token</button></p></form>
29
+ </section>
30
+ {% endblock %}