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/views.py ADDED
@@ -0,0 +1,564 @@
1
+ import re
2
+ from collections import Counter
3
+
4
+ from django import forms
5
+ from django.contrib import messages
6
+ from django.contrib.auth import get_user_model
7
+ from django.contrib.auth.forms import SetPasswordForm, UserCreationForm
8
+ from django.contrib.auth.views import LoginView, PasswordChangeView
9
+ from django.core.cache import cache
10
+ from django.core.exceptions import PermissionDenied
11
+ from django.core.paginator import Paginator
12
+ from django.forms import modelformset_factory
13
+ from django.http import Http404
14
+ from django.shortcuts import get_object_or_404, redirect, render
15
+ from django.urls import reverse, reverse_lazy
16
+ from django.utils.http import url_has_allowed_host_and_scheme
17
+ from django.views.decorators.http import require_POST, require_safe
18
+
19
+ from . import folders, gate
20
+ from .analyzers import ANALYZERS
21
+ from .catalog import update as catalog_update
22
+ from .collect import parse_period
23
+ from .git import GitError, Mirror, validate_repo_url
24
+ from .jobs import launch_scan, scan_refusal
25
+ from .models import (
26
+ DEFAULT_GATE,
27
+ ISSUE_TYPES,
28
+ SEVERITIES,
29
+ Analysis,
30
+ ApiToken,
31
+ GateCondition,
32
+ IssueResolution,
33
+ Profile,
34
+ Project,
35
+ ProjectMember,
36
+ )
37
+ from .network import check_public, trusted_owner
38
+
39
+ User = get_user_model()
40
+ SEMGREP_REGISTRY_RE = re.compile(r"^(p|r)/[\w.-]+(/[\w.-]+)*$")
41
+ PROJECT_PAGE = "project"
42
+
43
+
44
+ def get_project(request, key):
45
+ return get_object_or_404(Project.visible_to(request.user), key=key)
46
+
47
+
48
+ def get_analysis(request, key, pk):
49
+ return get_object_or_404(Analysis, pk=pk, project=get_project(request, key))
50
+
51
+
52
+ def require(allowed):
53
+ if not allowed:
54
+ raise PermissionDenied
55
+
56
+
57
+ def safe_next(request, fallback):
58
+ target = request.POST.get("next", "")
59
+ if url_has_allowed_host_and_scheme(target, allowed_hosts={request.get_host()}):
60
+ return target
61
+ return fallback
62
+
63
+
64
+ def refresh_gates(project):
65
+ for analysis in project.latest_analyses():
66
+ if analysis.status == Analysis.SUCCESS:
67
+ gate.refresh(analysis)
68
+
69
+
70
+ @require_safe
71
+ def index(request):
72
+ catalog_update.maybe_launch()
73
+ visible = Project.visible_to(request.user).order_by("key")
74
+ running = {a.project_id: a for a in Analysis.objects.filter(project__in=visible, status=Analysis.RUNNING)}
75
+ projects = [(p, next(iter(p.latest_analyses()), None), bool(p.repo_url) and p.can_scan(request.user),
76
+ running.get(p.pk)) for p in visible]
77
+ return render(request, "core/index.html", {"projects": projects, "any_running": bool(running)})
78
+
79
+
80
+ class NewProjectForm(forms.ModelForm):
81
+ class Meta:
82
+ model = Project
83
+ fields = ["key", "name", "repo_url", "main_branch"]
84
+ labels = {"repo_url": "Repository URL"}
85
+
86
+ def __init__(self, *args, user, **kwargs):
87
+ super().__init__(*args, **kwargs)
88
+ self.user = user
89
+ if not user.is_superuser:
90
+ self.fields["repo_url"].help_text = "https://, ssh:// or git@host: URL"
91
+
92
+ def clean_repo_url(self):
93
+ try:
94
+ return validate_repo_url(self.cleaned_data["repo_url"], allow_local=self.user.is_superuser)
95
+ except ValueError as exc:
96
+ raise forms.ValidationError(str(exc)) from exc
97
+
98
+
99
+ def create_project(owner, **fields):
100
+ project = Project.objects.create(owner=owner, **fields)
101
+ GateCondition.objects.bulk_create(
102
+ GateCondition(project=project, metric=m, op=op, threshold=t) for m, op, t in DEFAULT_GATE
103
+ )
104
+ return project
105
+
106
+
107
+ JUST_CREATED = "just_created_project"
108
+
109
+
110
+ def new_project(request):
111
+ picked = folders.suggestion(request.GET.get("use")) if request.user.is_superuser and "use" in request.GET else None
112
+ form = NewProjectForm(request.POST or None, user=request.user, initial=picked)
113
+ if request.method == "POST" and form.is_valid():
114
+ project = create_project(request.user, **form.cleaned_data)
115
+ # A scan token for codewatch-scan in the working copy, shown once on the project page.
116
+ _, raw = ApiToken.issue(request.user, f"{project.key} (created with the project)", ApiToken.SCAN)
117
+ request.session[JUST_CREATED] = {"key": project.key, "raw": raw}
118
+ refusal = scan_refusal(project)
119
+ if refusal:
120
+ messages.info(request, f"Created {project.key}. {refusal}")
121
+ else:
122
+ launch_scan(project)
123
+ messages.success(request, f"Created {project.key}; the first scan of the main branch has started.")
124
+ return redirect(PROJECT_PAGE, key=project.key)
125
+ return render(request, "core/new_project.html", {
126
+ "form": form,
127
+ "picked": picked,
128
+ "browse": folders.listing(request.GET.get("folder")) if request.user.is_superuser else None,
129
+ })
130
+
131
+
132
+ @require_safe
133
+ def project_detail(request, key):
134
+ project = get_project(request, key)
135
+ latest = project.latest_analyses()
136
+ scanned = {a.branch for a in latest}
137
+ try:
138
+ unscanned = [b for b in Mirror(project).branches() if b not in scanned]
139
+ except GitError:
140
+ unscanned = []
141
+ new_token = request.session.get(JUST_CREATED)
142
+ if new_token and new_token["key"] == project.key:
143
+ del request.session[JUST_CREATED]
144
+ else:
145
+ new_token = None
146
+ return render(request, "core/project.html", {
147
+ "project": project,
148
+ "new_token": new_token and new_token["raw"],
149
+ "latest": latest,
150
+ "unscanned": unscanned,
151
+ "can_scan": project.can_scan(request.user),
152
+ "can_admin": project.can_admin(request.user),
153
+ "running": project.analyses.filter(status=Analysis.RUNNING),
154
+ "history": project.analyses.all()[:30],
155
+ })
156
+
157
+
158
+ @require_POST
159
+ def start_scan(request, key):
160
+ project = get_project(request, key)
161
+ require(project.can_scan(request.user))
162
+ branch = request.POST.get("branch") or None
163
+ refusal = scan_refusal(project, branch)
164
+ if refusal:
165
+ messages.info(request, refusal)
166
+ else:
167
+ launch_scan(project, branch)
168
+ messages.success(request, f"Scan of {project.name}, {branch or 'the main branch'}, started.")
169
+ return redirect(safe_next(request, reverse(PROJECT_PAGE, args=[key])))
170
+
171
+
172
+ TYPE_ROWS = [("bug", "bugs"), ("vulnerability", "vulnerabilities"), ("security_hotspot", "security_hotspots"),
173
+ ("code_smell", "code_smells"), ("accessibility", "accessibility_issues")]
174
+
175
+
176
+ # The new-code issues behind each gate condition, as an issue-list query: a failed condition links to them.
177
+ GATE_ISSUES = {
178
+ "new_bugs": "type=bug", "new_reliability_rating": "type=bug",
179
+ "new_vulnerabilities": "type=vulnerability", "new_security_rating": "type=vulnerability",
180
+ "new_security_review_rating": "type=security_hotspot", "new_security_hotspots": "type=security_hotspot",
181
+ "new_maintainability_rating": "type=code_smell", "new_code_smells": "type=code_smell",
182
+ "new_accessibility_issues": "type=accessibility", "new_accessibility_rating": "type=accessibility",
183
+ "reliability_rating": "type=bug", "security_rating": "type=vulnerability",
184
+ "security_review_rating": "type=security_hotspot", "maintainability_rating": "type=code_smell",
185
+ "new_blocker_issues": "severity=blocker", "new_critical_issues": "severity=critical",
186
+ "new_major_issues": "severity=major", "new_issues": "",
187
+ }
188
+
189
+
190
+ def gate_rows(analysis):
191
+ """Gate conditions with a ratings value shown as its letter (a rating of 1 is A, not one issue) and the
192
+ issue list a condition is about, so a failed gate always points at the issues that failed it."""
193
+ base = reverse("issues", args=[analysis.project.key, analysis.pk])
194
+ rows = []
195
+ for d in analysis.gate_details or []:
196
+ is_rating = d["metric"].endswith("_rating")
197
+ query = GATE_ISSUES.get(d["metric"])
198
+ # A condition on new code links to the new issues; one on the whole codebase to all of them.
199
+ scope = ["new=1"] if d["metric"].startswith("new_") else []
200
+ rows.append({**d, "is_rating": is_rating,
201
+ "link": None if query is None else f"{base}?{'&'.join([query, *scope] if query else scope)}"})
202
+ return rows
203
+
204
+
205
+ @require_safe
206
+ def analysis_detail(request, key, pk):
207
+ analysis = get_analysis(request, key, pk)
208
+ m = analysis.metrics_dict
209
+ return render(request, "core/analysis.html", {
210
+ "analysis": analysis,
211
+ "project": analysis.project,
212
+ "m": m,
213
+ "gate": gate_rows(analysis),
214
+ "severities": [(s, m.get(f"{s}_issues"), m.get(f"new_{s}_issues")) for s in SEVERITIES],
215
+ "types": [(t, m.get(k), m.get(f"new_{k}")) for t, k in TYPE_ROWS],
216
+ "by_tool": counts_by_tool(analysis),
217
+ "other_metrics": sorted(
218
+ (k, v) for k, v in m.items()
219
+ if not k.endswith(("issues", "bugs", "vulnerabilities", "code_smells", "hotspots", "rating"))
220
+ and not k.startswith("_")
221
+ ),
222
+ })
223
+
224
+
225
+ def counts_by_tool(analysis):
226
+ resolved = set(analysis.project.resolutions.values_list("fingerprint", flat=True))
227
+ overall, new = Counter(), Counter()
228
+ for tool, fp, is_new in analysis.issues.values_list("tool", "fingerprint", "is_new"):
229
+ if fp not in resolved:
230
+ overall[tool] += 1
231
+ new[tool] += is_new
232
+ return [(t, overall[t], new[t]) for t in sorted(overall)]
233
+
234
+
235
+ def filter_issues(analysis, params):
236
+ """Shared by the issue page and the API: new, type/severity/tool/rule (comma lists), path, status."""
237
+ resolutions = {r.fingerprint: r for r in analysis.project.resolutions.all()}
238
+ issues = analysis.issues.all()
239
+ if params.get("new") in ("1", "true"):
240
+ issues = issues.filter(is_new=True)
241
+ for field in ("type", "severity", "tool", "rule"):
242
+ if params.get(field):
243
+ issues = issues.filter(**{f"{field}__in": params[field].split(",")})
244
+ if params.get("path"):
245
+ issues = issues.filter(path__icontains=params["path"])
246
+ status = params.get("status", "open")
247
+ if status == "open":
248
+ issues = issues.exclude(fingerprint__in=resolutions)
249
+ elif status == "resolved":
250
+ issues = issues.filter(fingerprint__in=resolutions)
251
+ return issues, resolutions, status
252
+
253
+
254
+ @require_safe
255
+ def issue_list(request, key, pk):
256
+ analysis = get_analysis(request, key, pk)
257
+ issues, resolutions, status = filter_issues(analysis, request.GET)
258
+ page = Paginator(issues, 100).get_page(request.GET.get("page"))
259
+ for issue in page:
260
+ issue.resolution = resolutions.get(issue.fingerprint)
261
+ query = request.GET.copy()
262
+ query.pop("page", None)
263
+ return render(request, "core/issues.html", {
264
+ "analysis": analysis,
265
+ "project": analysis.project,
266
+ "page": page,
267
+ "f": request.GET,
268
+ "status": status,
269
+ "query": query.urlencode(),
270
+ "severities": SEVERITIES,
271
+ "types": ISSUE_TYPES,
272
+ "tools": sorted(set(analysis.issues.values_list("tool", flat=True))),
273
+ "resolution_choices": IssueResolution.STATUSES,
274
+ "can_resolve": analysis.project.can_scan(request.user),
275
+ })
276
+
277
+
278
+ def set_resolution(project, fingerprint, status, comment=""):
279
+ if status == "reopen":
280
+ IssueResolution.objects.filter(project=project, fingerprint=fingerprint).delete()
281
+ elif status in dict(IssueResolution.STATUSES):
282
+ IssueResolution.objects.update_or_create(
283
+ project=project, fingerprint=fingerprint, defaults={"status": status, "comment": comment}
284
+ )
285
+ else:
286
+ raise ValueError(f"Unknown status {status}")
287
+ refresh_gates(project)
288
+
289
+
290
+ @require_POST
291
+ def resolve_issue(request, key):
292
+ project = get_project(request, key)
293
+ require(project.can_scan(request.user))
294
+ try:
295
+ set_resolution(project, request.POST["fingerprint"], request.POST["status"], request.POST.get("comment", ""))
296
+ except ValueError as exc:
297
+ messages.error(request, str(exc))
298
+ return redirect(safe_next(request, reverse(PROJECT_PAGE, args=[key])))
299
+
300
+
301
+ def source_text(analysis, path):
302
+ """Source uploaded with the analysis, else the server-side mirror; None if neither has it."""
303
+ stored = analysis.sources.filter(path=path).select_related("blob").first()
304
+ if stored:
305
+ return stored.blob.content
306
+ if analysis.project.repo_url:
307
+ try:
308
+ return Mirror(analysis.project).show(analysis.commit, path)
309
+ except GitError:
310
+ return None
311
+ return None
312
+
313
+
314
+ @require_safe
315
+ def source_view(request, key, pk):
316
+ analysis = get_analysis(request, key, pk)
317
+ path = request.GET.get("path", "")
318
+ text = source_text(analysis, path)
319
+ if text is None:
320
+ raise Http404(path)
321
+ by_line = {}
322
+ for issue in analysis.issues.filter(path=path):
323
+ by_line.setdefault(issue.line or 0, []).append(issue)
324
+ lines = [(n, line, by_line.get(n, [])) for n, line in enumerate(text.splitlines(), 1)]
325
+ return render(request, "core/source.html", {
326
+ "analysis": analysis, "project": analysis.project, "path": path, "lines": lines,
327
+ "file_issues": by_line.get(0, []),
328
+ })
329
+
330
+
331
+ class ProjectSettingsForm(forms.ModelForm):
332
+ exclusions = forms.CharField(widget=forms.Textarea(attrs={"rows": 6}), required=False,
333
+ help_text="One glob per line")
334
+ a11y_urls = forms.CharField(widget=forms.Textarea(attrs={"rows": 4}), required=False,
335
+ label="Accessibility URLs",
336
+ help_text="One live page per line, checked with axe-core on every scan. "
337
+ "{branch} is replaced by the branch name.")
338
+ disabled_analyzers = forms.MultipleChoiceField(
339
+ choices=[(a.name, a.name) for a in ANALYZERS], required=False, widget=forms.CheckboxSelectMultiple
340
+ )
341
+
342
+ class Meta:
343
+ model = Project
344
+ fields = ["name", "repo_url", "main_branch", "semgrep_config", "complexity_threshold", "cognitive_complexity_threshold",
345
+ "duplicate_literal_threshold", "new_code_period", "exclusions", "a11y_urls", "disabled_analyzers"]
346
+ labels = {"repo_url": "Repository URL or folder"}
347
+ help_texts = {"repo_url": "Where server-side scans (and the Scan button) clone from: a repository URL or, for "
348
+ "an administrator's project, a folder on this server. Blank: codewatch-scan only."}
349
+
350
+ def __init__(self, *args, **kwargs):
351
+ super().__init__(*args, **kwargs)
352
+ self.initial["exclusions"] = "\n".join(self.instance.exclusions)
353
+ self.initial["a11y_urls"] = "\n".join(self.instance.a11y_urls)
354
+
355
+ @staticmethod
356
+ def lines(value):
357
+ return [line.strip() for line in value.splitlines() if line.strip()]
358
+
359
+ def clean_exclusions(self):
360
+ return self.lines(self.cleaned_data["exclusions"])
361
+
362
+ def clean_repo_url(self):
363
+ """As for a new project: a local path, or a host on the server's network, only for an administrator's."""
364
+ url = self.cleaned_data["repo_url"].strip()
365
+ if not url:
366
+ return url
367
+ try:
368
+ return validate_repo_url(url, allow_local=trusted_owner(self.instance))
369
+ except ValueError as exc:
370
+ raise forms.ValidationError(str(exc)) from exc
371
+
372
+ def clean_new_code_period(self):
373
+ value = self.cleaned_data["new_code_period"].strip()
374
+ if value and parse_period(value)[0] == "previous":
375
+ raise forms.ValidationError("Use a number of days such as 30d, or a tag, branch or commit name")
376
+ return value
377
+
378
+ def clean_a11y_urls(self):
379
+ urls = self.lines(self.cleaned_data["a11y_urls"])
380
+ bad = [u for u in urls if not u.startswith(("http://", "https://"))]
381
+ if bad:
382
+ raise forms.ValidationError(f"Not an http(s) URL: {', '.join(bad)}")
383
+ if not trusted_owner(self.instance):
384
+ try:
385
+ for url in urls:
386
+ check_public(url.replace("{branch}", "main"))
387
+ except ValueError as exc:
388
+ raise forms.ValidationError(str(exc)) from exc
389
+ return urls
390
+
391
+ def clean_semgrep_config(self):
392
+ """A registry ruleset (p/default, r/python.flask...) unless an administrator owns the project: Semgrep also
393
+ reads a URL or a file on the server, and its errors would show what it found there."""
394
+ value = self.cleaned_data["semgrep_config"].strip()
395
+ if value and not trusted_owner(self.instance) and not SEMGREP_REGISTRY_RE.match(value):
396
+ raise forms.ValidationError("Use a Semgrep registry ruleset such as p/default")
397
+ return value
398
+
399
+
400
+ GateFormSet = modelformset_factory(GateCondition, fields=["metric", "op", "threshold"], extra=1, can_delete=True)
401
+
402
+
403
+ class MemberForm(forms.Form):
404
+ username = forms.CharField()
405
+ role = forms.ChoiceField(choices=ProjectMember.ROLES, initial=ProjectMember.CONTRIBUTOR)
406
+
407
+ def clean_username(self):
408
+ try:
409
+ return User.objects.get(username=self.cleaned_data["username"], is_active=True)
410
+ except User.DoesNotExist as exc:
411
+ raise forms.ValidationError("No active user with that username") from exc
412
+
413
+
414
+ def project_settings(request, key):
415
+ project = get_project(request, key)
416
+ require(project.can_admin(request.user))
417
+ form = ProjectSettingsForm(request.POST or None, instance=project)
418
+ formset = GateFormSet(request.POST or None, queryset=project.gate_conditions.all(), prefix="gate")
419
+ if request.method == "POST" and form.is_valid() and formset.is_valid():
420
+ form.save()
421
+ for cond in formset.save(commit=False):
422
+ cond.project = project
423
+ cond.save()
424
+ for cond in formset.deleted_objects:
425
+ cond.delete()
426
+ refresh_gates(project)
427
+ messages.success(request, "Settings saved.")
428
+ return redirect(PROJECT_PAGE, key=key)
429
+ return render(request, "core/settings.html", {
430
+ "project": project, "form": form, "formset": formset, "member_form": MemberForm(),
431
+ "members": project.members.select_related("user").order_by("user__username"),
432
+ })
433
+
434
+
435
+ @require_POST
436
+ def project_members(request, key):
437
+ project = get_project(request, key)
438
+ require(project.can_admin(request.user))
439
+ if request.POST.get("remove"):
440
+ project.members.filter(pk=request.POST["remove"]).delete()
441
+ return redirect("settings", key=key)
442
+ form = MemberForm(request.POST)
443
+ if not form.is_valid():
444
+ messages.error(request, "; ".join(e for errs in (form.errors or {}).values() for e in errs))
445
+ elif form.cleaned_data["username"].pk == project.owner_id:
446
+ messages.error(request, "That user already owns this project.")
447
+ else:
448
+ user, role = form.cleaned_data["username"], form.cleaned_data["role"]
449
+ ProjectMember.objects.update_or_create(project=project, user=user, defaults={"role": role})
450
+ messages.success(request, f"{user.username} added as {role}.")
451
+ return redirect("settings", key=key)
452
+
453
+
454
+ @require_POST
455
+ def delete_project(request, key):
456
+ project = get_project(request, key)
457
+ require(project.can_admin(request.user))
458
+ if request.POST.get("confirm") != project.key:
459
+ messages.error(request, "Type the project key to confirm deletion.")
460
+ return redirect("settings", key=key)
461
+ Mirror(project).delete()
462
+ project.delete()
463
+ messages.success(request, f"Deleted {key}.")
464
+ return redirect("index")
465
+
466
+
467
+ LOGIN_FAILURES_ALLOWED = 10
468
+ LOGIN_LOCKOUT_SECONDS = 15 * 60
469
+
470
+
471
+ class ThrottledLoginView(LoginView):
472
+ """Django's login, refusing a username from an address after LOGIN_FAILURES_ALLOWED wrong passwords in a row
473
+ (for LOGIN_LOCKOUT_SECONDS): otherwise passwords could be guessed as fast as requests can be sent."""
474
+
475
+ template_name = "core/login.html"
476
+
477
+ def post(self, request, *args, **kwargs):
478
+ key = f"login-failures:{request.META.get('REMOTE_ADDR', '')}:{request.POST.get('username', '')[:150]}"
479
+ if cache.get(key, 0) >= LOGIN_FAILURES_ALLOWED:
480
+ form = self.get_form()
481
+ form.add_error(None, "Too many failed attempts; try again in 15 minutes.")
482
+ return self.render_to_response(self.get_context_data(form=form), status=429)
483
+ response = super().post(request, *args, **kwargs)
484
+ if request.user.is_authenticated:
485
+ cache.delete(key)
486
+ else:
487
+ cache.set(key, cache.get(key, 0) + 1, LOGIN_LOCKOUT_SECONDS)
488
+ return response
489
+
490
+
491
+ class ChangePasswordView(PasswordChangeView):
492
+ template_name = "core/password_change.html"
493
+ success_url = reverse_lazy("account")
494
+
495
+ def form_valid(self, form):
496
+ response = super().form_valid(form)
497
+ # bandit B105 reads the profile flag must_change_password as a password; it is a boolean.
498
+ Profile.objects.update_or_create(user=self.request.user, defaults={"must_change_password": False}) # nosec B105
499
+ messages.success(self.request, "Password changed.")
500
+ return response
501
+
502
+
503
+ class TokenForm(forms.Form):
504
+ name = forms.CharField(max_length=100, help_text="e.g. 'CI' or 'Claude'")
505
+ scope = forms.ChoiceField(choices=ApiToken.SCOPES, initial=ApiToken.SCAN)
506
+
507
+
508
+ def account(request):
509
+ form = TokenForm(request.POST or None)
510
+ new_token = None
511
+ if request.method == "POST":
512
+ if request.POST.get("revoke"):
513
+ request.user.api_tokens.filter(pk=request.POST["revoke"]).delete()
514
+ messages.success(request, "Token revoked.")
515
+ return redirect("account")
516
+ if form.is_valid():
517
+ _, new_token = ApiToken.issue(request.user, form.cleaned_data["name"], form.cleaned_data["scope"])
518
+ form = TokenForm()
519
+ return render(request, "core/account.html", {
520
+ "form": form, "new_token": new_token, "tokens": request.user.api_tokens.all(),
521
+ "api_base": request.build_absolute_uri("/api/"),
522
+ })
523
+
524
+
525
+ class NewUserForm(UserCreationForm):
526
+ is_superuser = forms.BooleanField(required=False, label="Administrator",
527
+ help_text="Sees all projects and manages users")
528
+
529
+ class Meta(UserCreationForm.Meta):
530
+ model = User
531
+ fields = ["username", "email"]
532
+
533
+
534
+ def users(request):
535
+ require(request.user.is_superuser)
536
+ form = NewUserForm(request.POST or None)
537
+ if request.method == "POST" and form.is_valid():
538
+ user = form.save(commit=False)
539
+ user.is_superuser = user.is_staff = form.cleaned_data["is_superuser"]
540
+ user.save()
541
+ messages.success(request, f"Created {user.username}.")
542
+ return redirect("users")
543
+ return render(request, "core/users.html", {"form": form, "users": User.objects.order_by("username")})
544
+
545
+
546
+ def user_edit(request, pk):
547
+ require(request.user.is_superuser)
548
+ target = get_object_or_404(User, pk=pk)
549
+ form = SetPasswordForm(target, request.POST or None)
550
+ if request.method == "POST" and "toggle_active" in request.POST:
551
+ if target == request.user:
552
+ messages.error(request, "You can't deactivate yourself.")
553
+ else:
554
+ target.is_active = not target.is_active
555
+ target.save(update_fields=["is_active"])
556
+ messages.success(request, f"{target.username} {'activated' if target.is_active else 'deactivated'}.")
557
+ return redirect("users")
558
+ if request.method == "POST" and form.is_valid():
559
+ form.save()
560
+ # bandit B105 reads the profile flag must_change_password as a password; it is a boolean.
561
+ Profile.objects.update_or_create(user=target, defaults={"must_change_password": True}) # nosec B105
562
+ messages.success(request, f"Password reset for {target.username}; they must change it on next login.")
563
+ return redirect("users")
564
+ return render(request, "core/user_edit.html", {"target": target, "form": form})