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.
- codewatch/__init__.py +0 -0
- codewatch/__main__.py +14 -0
- codewatch/asgi.py +16 -0
- codewatch/settings.py +175 -0
- codewatch/urls.py +40 -0
- codewatch/wsgi.py +16 -0
- codewatch_scan-0.1.0.dist-info/METADATA +81 -0
- codewatch_scan-0.1.0.dist-info/RECORD +136 -0
- codewatch_scan-0.1.0.dist-info/WHEEL +5 -0
- codewatch_scan-0.1.0.dist-info/entry_points.txt +4 -0
- codewatch_scan-0.1.0.dist-info/licenses/LICENSE +21 -0
- codewatch_scan-0.1.0.dist-info/top_level.txt +2 -0
- core/__init__.py +0 -0
- core/analyzers/__init__.py +19 -0
- core/analyzers/accessibility.py +199 -0
- core/analyzers/base.py +192 -0
- core/analyzers/body_models.py +154 -0
- core/analyzers/codewatch_checks.py +394 -0
- core/analyzers/constant_branches.py +251 -0
- core/analyzers/containers.py +316 -0
- core/analyzers/coverage.py +131 -0
- core/analyzers/dependencies.py +347 -0
- core/analyzers/drf_serializers.py +65 -0
- core/analyzers/else_branches.py +106 -0
- core/analyzers/extra.py +400 -0
- core/analyzers/flask_resources.py +65 -0
- core/analyzers/inline_scripts.py +50 -0
- core/analyzers/jinja_sandboxes.py +63 -0
- core/analyzers/match_statements.py +148 -0
- core/analyzers/multi_tools.py +888 -0
- core/analyzers/php_template_sinks.py +444 -0
- core/analyzers/project_checks.py +150 -0
- core/analyzers/python_tools.py +333 -0
- core/analyzers/route_converters.py +237 -0
- core/analyzers/slices.py +94 -0
- core/analyzers/starred_targets.py +42 -0
- core/analyzers/stored_fields.py +386 -0
- core/analyzers/summaries.py +1387 -0
- core/analyzers/template_sinks.py +162 -0
- core/api.py +360 -0
- core/apps.py +6 -0
- core/benchmark.py +955 -0
- core/bundled/catalog/codewatch/rules/javascript-crypto.yml +224 -0
- core/bundled/catalog/codewatch/rules/javascript-injection.yml +116 -0
- core/bundled/catalog/codewatch/rules/javascript-taint.yml +1539 -0
- core/bundled/catalog/codewatch/rules/javascript-web.yml +562 -0
- core/bundled/catalog/codewatch/rules/php-web.yml +719 -0
- core/bundled/catalog/codewatch/rules/python-crypto.yml +203 -0
- core/bundled/catalog/codewatch/rules/python-django.yml +267 -0
- core/bundled/catalog/codewatch/rules/python-injection.yml +115 -0
- core/bundled/catalog/codewatch/rules/python-web.yml +3382 -0
- core/bundled/catalog/custom/mappings.json +360 -0
- core/bundled/catalog/custom/overrides.json +4 -0
- core/bundled/catalog/custom/rules/django-settings.yml +19 -0
- core/bundled/catalog/imported/changes.json +5 -0
- core/bundled/catalog/imported/docs.json +1143 -0
- core/bundled/catalog/imported/meta.json +54 -0
- core/bundled/catalog/imported/rules.json +85421 -0
- core/bundled/catalog/imported/standards.json +11191 -0
- core/bundled/tools/analyzers.lock +786 -0
- core/bundled/tools/axe-scan.mjs +45 -0
- core/bundled/tools/checkov.lock +2463 -0
- core/bundled/tools/codewatch-checks.mjs +99 -0
- core/bundled/tools/eslint-a11y.config.js +16 -0
- core/bundled/tools/eslint-quality.config.js +63 -0
- core/bundled/tools/eslint-typed.config.js +18 -0
- core/bundled/tools/package-lock.json +6102 -0
- core/bundled/tools/package.json +32 -0
- core/bundled/tools/rule-metadata.mjs +56 -0
- core/bundled/tools/semgrep.lock +1232 -0
- core/bundled/tools/stylelint.config.json +11 -0
- core/catalog/__init__.py +190 -0
- core/catalog/build.py +84 -0
- core/catalog/merge.py +122 -0
- core/catalog/sources.py +418 -0
- core/catalog/standards.py +119 -0
- core/catalog/update.py +99 -0
- core/catalog_views.py +115 -0
- core/client.py +645 -0
- core/collect.py +518 -0
- core/duplicates.py +60 -0
- core/fingerprint.py +25 -0
- core/folders.py +73 -0
- core/gate.py +77 -0
- core/git.py +149 -0
- core/jobs.py +86 -0
- core/management/__init__.py +0 -0
- core/management/commands/__init__.py +0 -0
- core/management/commands/addproject.py +40 -0
- core/management/commands/buildcatalog.py +15 -0
- core/management/commands/scan.py +74 -0
- core/management/commands/updatecatalog.py +14 -0
- core/mcp_server.py +140 -0
- core/middleware.py +17 -0
- core/migrations/0001_initial.py +115 -0
- core/migrations/0002_auth_tokens_a11y.py +60 -0
- core/migrations/0003_default_admin.py +43 -0
- core/migrations/0004_project_members.py +28 -0
- core/migrations/0005_uploads_and_sources.py +55 -0
- core/migrations/0006_thresholds.py +28 -0
- core/migrations/0007_also_reported_by.py +18 -0
- core/migrations/0008_new_code_period.py +18 -0
- core/migrations/0009_resolution_safe.py +18 -0
- core/migrations/0010_analysis_progress.py +18 -0
- core/migrations/0011_overall_gate_conditions.py +20 -0
- core/migrations/__init__.py +0 -0
- core/models.py +323 -0
- core/network.py +41 -0
- core/paths.py +29 -0
- core/ratings.py +67 -0
- core/runner.py +168 -0
- core/templates/core/account.html +30 -0
- core/templates/core/analysis.html +49 -0
- core/templates/core/base.html +121 -0
- core/templates/core/form_table.html +12 -0
- core/templates/core/gate_badge.html +1 -0
- core/templates/core/index.html +26 -0
- core/templates/core/issues.html +38 -0
- core/templates/core/login.html +13 -0
- core/templates/core/new_project.html +27 -0
- core/templates/core/password_change.html +10 -0
- core/templates/core/project.html +40 -0
- core/templates/core/rating.html +1 -0
- core/templates/core/ratings.html +32 -0
- core/templates/core/rule.html +33 -0
- core/templates/core/rules.html +42 -0
- core/templates/core/scan_progress.html +2 -0
- core/templates/core/settings.html +36 -0
- core/templates/core/source.html +15 -0
- core/templates/core/standards.html +30 -0
- core/templates/core/user_edit.html +15 -0
- core/templates/core/users.html +18 -0
- core/templatetags/__init__.py +0 -0
- core/templatetags/codewatch.py +42 -0
- core/tool_setup.py +68 -0
- core/views.py +564 -0
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
"""Template variables written out unescaped, as sinks for a copy of the Python XSS rule.
|
|
2
|
+
|
|
3
|
+
Jinja and Django escape what a template prints, except where it says not to: `{{ message|safe }}`, or anything inside
|
|
4
|
+
`{% autoescape false %}` / `{% autoescape off %}`. A view that passes request data as such a variable writes it into
|
|
5
|
+
the page as HTML: Whoogle (GHSA-mxvc-fwgx-j778) rendered render_template('error.html', error_message='Unable to
|
|
6
|
+
resolve query: ' + q) into `{{ error_message|safe }}`. The project's templates are read once per scan, and each
|
|
7
|
+
variable printed unescaped makes the argument that sets it, in a render_template / render / render_to_string /
|
|
8
|
+
TemplateResponse call naming that template, a sink of a copy of the XSS rule
|
|
9
|
+
(codewatch.python.web.template.xss). A value escaped or sanitized on the way
|
|
10
|
+
(`{{ text|sanitize_html|safe }}`, `{{ data|tojson|safe }}`) isn't one, and neither is a template no view names.
|
|
11
|
+
|
|
12
|
+
Flask's autoescape is chosen by extension: only .html, .htm, .xml, .xhtml and .svg are escaped, so a .jinja, .jinja2
|
|
13
|
+
or .j2 template prints every value raw. Those variables are sinks for Flask's render_template only; Django's Jinja
|
|
14
|
+
backend autoescapes them, so its render calls stay safe. Django also has .djhtml templates; they follow Django's
|
|
15
|
+
autoescaping and are not in the Flask-raw set.
|
|
16
|
+
"""
|
|
17
|
+
import re
|
|
18
|
+
from pathlib import PurePosixPath
|
|
19
|
+
|
|
20
|
+
TEMPLATE_EXTENSIONS = {".html", ".htm", ".jinja", ".jinja2", ".j2", ".djhtml"}
|
|
21
|
+
# Extensions Flask's select_jinja_autoescape leaves off (Flask 2.2+ also escapes .svg, which is not read here).
|
|
22
|
+
FLASK_RAW_EXTENSIONS = {".jinja", ".jinja2", ".j2"}
|
|
23
|
+
XSS_RULE = "codewatch.python.web.xss"
|
|
24
|
+
# {{ expression|filter|...|safe }}: the expression's first name, and the filters before safe.
|
|
25
|
+
# The name ends where the filters start, and a block's contents can't hold another opener (as php_template_sinks).
|
|
26
|
+
SAFE_RE = re.compile(r"\{\{-?\s*([A-Za-z_]\w*)(?!\w)([^{}|]*(?:\|[^{}|]*)*?)\|\s*safe\s*-?\}\}")
|
|
27
|
+
PRINT_RE = re.compile(r"\{\{-?\s*([A-Za-z_]\w*)(?!\w)([^{}]*?)-?\}\}")
|
|
28
|
+
FOR_RE = re.compile(r"\{%-?\s*for\s+(\w+)(?:\s*,\s*\w+)*\s+in\s+([A-Za-z_]\w*)")
|
|
29
|
+
AUTOESCAPE_OFF_RE = re.compile(
|
|
30
|
+
r"\{%-?\s*autoescape\s+(?:false|off)\s*-?%\}((?:(?!\{%-?\s*autoescape\b)[\s\S])*?)\{%-?\s*endautoescape\s*-?%\}")
|
|
31
|
+
# Filters that leave text that can't carry markup: escaping, sanitizing, JSON, numbers and counts.
|
|
32
|
+
ESCAPING_FILTER_RE = re.compile(r"\|\s*(?:(?=\w*(?:escape|saniti[sz]e|clean|bleach|json))\w+|e|striptags|int|float|length|count|"
|
|
33
|
+
r"urlencode|filesizeformat)\b", re.IGNORECASE)
|
|
34
|
+
ADMIN_ONLY = ("admins_only", "admin_required", "staff_member_required", "superuser_required")
|
|
35
|
+
KEYWORDS = {"loop", "super", "self", "caller", "varargs", "kwargs", "true", "false", "none", "True", "False", "None"}
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def template_name(path):
|
|
39
|
+
"""The name a view gives a template: its path after the last templates/ folder, or its file name."""
|
|
40
|
+
parts = PurePosixPath(path).parts
|
|
41
|
+
if "templates" in parts:
|
|
42
|
+
index = len(parts) - 1 - parts[::-1].index("templates")
|
|
43
|
+
return "/".join(parts[index + 1:])
|
|
44
|
+
return parts[-1]
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def unescaped_variables(text, all_prints=False):
|
|
48
|
+
"""The context variables a template prints unescaped: the first name of each {{ ...|safe }} expression and of
|
|
49
|
+
everything printed under autoescape off, with a loop variable traced back to the list it walks. all_prints also
|
|
50
|
+
counts every other {{ ... }} a template prints (Flask's non-autoescaped extensions)."""
|
|
51
|
+
loops = dict(FOR_RE.findall(text))
|
|
52
|
+
printed = [(name, filters) for name, filters in SAFE_RE.findall(text)]
|
|
53
|
+
for block in AUTOESCAPE_OFF_RE.findall(text):
|
|
54
|
+
printed += PRINT_RE.findall(block)
|
|
55
|
+
if all_prints:
|
|
56
|
+
printed += PRINT_RE.findall(text)
|
|
57
|
+
names = set()
|
|
58
|
+
for printed_name, filters in printed:
|
|
59
|
+
if ESCAPING_FILTER_RE.search(filters) or form_field(printed_name, filters.split("|")[0].strip()):
|
|
60
|
+
continue
|
|
61
|
+
name, seen = printed_name, set()
|
|
62
|
+
while name in loops and name not in seen:
|
|
63
|
+
seen.add(name)
|
|
64
|
+
name = loops[name]
|
|
65
|
+
if name not in KEYWORDS:
|
|
66
|
+
names.add(name)
|
|
67
|
+
return names
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
FORM_RE = re.compile(r"(?i)^(\w+_)?form$")
|
|
71
|
+
FORM_DATA = {".data", ".cleaned_data", ".initial"}
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def form_field(name, rest):
|
|
75
|
+
"""{{ form|safe }} or {{ form.username|safe }}: a Django form or bound field renders its widgets and escapes the
|
|
76
|
+
values in them itself, so |safe changes nothing (pygoat's login.html). Its data (form.cleaned_data.x) doesn't."""
|
|
77
|
+
return bool(FORM_RE.match(name)) and (rest == "" or (re.fullmatch(r"\.\w+", rest) is not None
|
|
78
|
+
and rest not in FORM_DATA))
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def unescaped_template_variables(templates):
|
|
82
|
+
"""({template name: {variable}} for variables printed with |safe/autoescape off,
|
|
83
|
+
{template name: {variable}} for every variable in a Flask non-autoescaped extension)."""
|
|
84
|
+
found, flask_raw = {}, {}
|
|
85
|
+
for path, text in templates.items():
|
|
86
|
+
names = unescaped_variables(text)
|
|
87
|
+
if names:
|
|
88
|
+
found.setdefault(template_name(path), set()).update(names)
|
|
89
|
+
if PurePosixPath(path).suffix.lower() in FLASK_RAW_EXTENSIONS:
|
|
90
|
+
names = unescaped_variables(text, all_prints=True)
|
|
91
|
+
if names:
|
|
92
|
+
flask_raw.setdefault(template_name(path), set()).update(names)
|
|
93
|
+
return found, flask_raw
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def quoted(text):
|
|
97
|
+
return '"' + text.replace("\\", "\\\\").replace('"', '\\"') + '"'
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
RENDERERS = {"render_template", "flask.render_template", "django.shortcuts.render",
|
|
101
|
+
"django.template.loader.render_to_string", "django.template.response.TemplateResponse"}
|
|
102
|
+
TEMPLATE_RULE = "codewatch.python.web.template.xss"
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def is_renderer(sanitizer):
|
|
106
|
+
"""The XSS rule's sanitizers for render calls (a template escapes what it prints). Semgrep reports no sink inside
|
|
107
|
+
a sanitizer's match, so the rule for unescaped variables leaves them out."""
|
|
108
|
+
return isinstance(sanitizer, dict) and sanitizer.get("pattern", "").removesuffix("(...)") in RENDERERS
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def render_patterns(name, variable, django):
|
|
112
|
+
"""The render calls that set one template variable to $VALUE. django adds Django's renderers, which autoescape
|
|
113
|
+
their Jinja backend; a Flask raw-extension variable belongs to render_template calls only."""
|
|
114
|
+
template = quoted(name)
|
|
115
|
+
patterns = [
|
|
116
|
+
f"render_template({template}, ..., {variable}=$VALUE, ...)",
|
|
117
|
+
f"flask.render_template({template}, ..., {variable}=$VALUE, ...)",
|
|
118
|
+
]
|
|
119
|
+
if django:
|
|
120
|
+
key = quoted(variable)
|
|
121
|
+
patterns += [
|
|
122
|
+
f"django.shortcuts.render($REQUEST, {template}, {{..., {key}: $VALUE, ...}}, ...)",
|
|
123
|
+
f"django.template.loader.render_to_string({template}, {{..., {key}: $VALUE, ...}}, ...)",
|
|
124
|
+
f"django.template.response.TemplateResponse($REQUEST, {template}, {{..., {key}: $VALUE, ...}}, ...)",
|
|
125
|
+
]
|
|
126
|
+
return patterns
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def template_sinks(found, flask_raw):
|
|
130
|
+
"""Semgrep sink patterns for the arguments that set found's unescaped variables, and for every variable in a
|
|
131
|
+
Flask non-autoescaped template (those only for Flask's render_template calls)."""
|
|
132
|
+
patterns = []
|
|
133
|
+
for name, variables in sorted(found.items()):
|
|
134
|
+
for variable in sorted(variables):
|
|
135
|
+
patterns += render_patterns(name, variable, django=True)
|
|
136
|
+
for name, variables in sorted(flask_raw.items()):
|
|
137
|
+
for variable in sorted(variables):
|
|
138
|
+
patterns += render_patterns(name, variable, django=False)
|
|
139
|
+
patterns = list(dict.fromkeys(patterns))
|
|
140
|
+
if not patterns:
|
|
141
|
+
return None
|
|
142
|
+
# An admin-only view's input is the administrator's own: CTFd's page preview renders the HTML an admin is
|
|
143
|
+
# writing into {{ content|safe }}, as its pages are meant to.
|
|
144
|
+
admin_only = [{"pattern-not-inside": f"@{name}\ndef $VIEW(...):\n ...\n"} for name in ADMIN_ONLY]
|
|
145
|
+
return {"patterns": [{"pattern-either": [{"pattern": p} for p in patterns]}, *admin_only,
|
|
146
|
+
{"focus-metavariable": "$VALUE"}]}
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def with_template_sinks(rules, templates):
|
|
150
|
+
"""The rules, plus a copy of the XSS rule whose sinks are the arguments that set variables the project's
|
|
151
|
+
templates print unescaped (none when no template does)."""
|
|
152
|
+
sink = template_sinks(*unescaped_template_variables(templates))
|
|
153
|
+
xss = next((rule for rule in rules if rule.get("id") == XSS_RULE), None)
|
|
154
|
+
if sink is None or xss is None:
|
|
155
|
+
return rules
|
|
156
|
+
return [*rules, {
|
|
157
|
+
**xss, "id": TEMPLATE_RULE,
|
|
158
|
+
"message": "Data from the HTTP request is passed to a template variable the template prints unescaped "
|
|
159
|
+
"(|safe, autoescape off, or a Flask .jinja/.jinja2/.j2 template), so it's written into the page "
|
|
160
|
+
"as HTML. Escape or sanitize it, or drop |safe in the template.",
|
|
161
|
+
"pattern-sanitizers": [s for s in xss.get("pattern-sanitizers", []) if not is_renderer(s)],
|
|
162
|
+
"pattern-sinks": [sink]}]
|
core/api.py
ADDED
|
@@ -0,0 +1,360 @@
|
|
|
1
|
+
import gzip
|
|
2
|
+
import json
|
|
3
|
+
import re
|
|
4
|
+
import zlib
|
|
5
|
+
from functools import wraps
|
|
6
|
+
|
|
7
|
+
from django.conf import settings
|
|
8
|
+
from django.contrib.auth.decorators import login_not_required
|
|
9
|
+
from django.db import IntegrityError
|
|
10
|
+
from django.db.models import Case, F, Value, When
|
|
11
|
+
from django.http import JsonResponse
|
|
12
|
+
from django.utils import timezone
|
|
13
|
+
from django.views.decorators.csrf import csrf_exempt
|
|
14
|
+
|
|
15
|
+
from . import catalog
|
|
16
|
+
from .git import validate_repo_url
|
|
17
|
+
from .jobs import BRANCH_RE, launch_scan, save_coverage_upload, scan_refusal
|
|
18
|
+
from .models import SEVERITIES, Analysis, ApiToken, Issue, Project
|
|
19
|
+
from .runner import create_uploaded_analysis, ingest
|
|
20
|
+
from .views import create_project, filter_issues, set_resolution, source_text
|
|
21
|
+
|
|
22
|
+
BRANCH, MAIN_BRANCH = "branch", "main_branch"
|
|
23
|
+
MAX_PAYLOAD_BYTES = 500 * 1024 * 1024
|
|
24
|
+
MAX_PAGE = 500
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class ApiError(Exception):
|
|
28
|
+
def __init__(self, status, message):
|
|
29
|
+
super().__init__(message)
|
|
30
|
+
self.status = status
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def api(scope=ApiToken.READ, methods=("GET",)):
|
|
34
|
+
"""Bearer-token auth. "read" tokens can read and resolve issues; "scan" tokens can also upload and start scans."""
|
|
35
|
+
def decorator(view):
|
|
36
|
+
@csrf_exempt
|
|
37
|
+
@login_not_required
|
|
38
|
+
@wraps(view)
|
|
39
|
+
def wrapper(request, *args, **kwargs):
|
|
40
|
+
if request.method not in methods:
|
|
41
|
+
return JsonResponse({"error": f"{request.method} not allowed"}, status=405)
|
|
42
|
+
header = request.headers.get("Authorization", "")
|
|
43
|
+
scheme, _, raw = header.partition(" ")
|
|
44
|
+
token = ApiToken.authenticate(raw.strip()) if scheme.lower() in ("bearer", "token") else None
|
|
45
|
+
if token is None:
|
|
46
|
+
return JsonResponse({"error": "Missing or invalid API token"}, status=401)
|
|
47
|
+
if scope == ApiToken.SCAN and token.scope != ApiToken.SCAN:
|
|
48
|
+
return JsonResponse({"error": "This token is read-only; a scan token is required"}, status=403)
|
|
49
|
+
ApiToken.objects.filter(pk=token.pk).update(last_used_at=timezone.now())
|
|
50
|
+
request.user = token.user
|
|
51
|
+
try:
|
|
52
|
+
return view(request, *args, **kwargs)
|
|
53
|
+
except ApiError as exc:
|
|
54
|
+
return JsonResponse({"error": str(exc)}, status=exc.status)
|
|
55
|
+
return wrapper
|
|
56
|
+
return decorator
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def int_param(request, name, default, low, high):
|
|
60
|
+
"""A whole-number query parameter within [low, high] (high None: no limit); 400 otherwise."""
|
|
61
|
+
try:
|
|
62
|
+
value = int(request.GET.get(name, default))
|
|
63
|
+
except ValueError as exc:
|
|
64
|
+
raise ApiError(400, f"{name} must be a whole number") from exc
|
|
65
|
+
if value < low:
|
|
66
|
+
raise ApiError(400, f"{name} must be at least {low}")
|
|
67
|
+
return value if high is None else min(value, high)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def visible_project(request, key):
|
|
71
|
+
project = Project.visible_to(request.user).filter(key=key).first()
|
|
72
|
+
if project is None:
|
|
73
|
+
raise ApiError(404, f"No project {key} (or no access)")
|
|
74
|
+
return project
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def latest_analysis(project, branch, include_running=False):
|
|
78
|
+
qs = project.analyses.filter(branch=branch or project.main_branch)
|
|
79
|
+
if not include_running:
|
|
80
|
+
qs = qs.filter(status=Analysis.SUCCESS)
|
|
81
|
+
analysis = qs.order_by("-started_at").first()
|
|
82
|
+
if analysis is None:
|
|
83
|
+
raise ApiError(404, f"No analysis of {branch or project.main_branch} yet")
|
|
84
|
+
return analysis
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def analysis_json(request, a, full=False):
|
|
88
|
+
data = {
|
|
89
|
+
"id": a.pk,
|
|
90
|
+
"branch": a.branch,
|
|
91
|
+
"commit": a.commit,
|
|
92
|
+
"status": a.status,
|
|
93
|
+
"origin": a.origin,
|
|
94
|
+
"dirty": a.dirty,
|
|
95
|
+
"started_at": a.started_at.isoformat(),
|
|
96
|
+
"gate_passed": a.gate_passed,
|
|
97
|
+
"url": request.build_absolute_uri(f"/p/{a.project.key}/a/{a.pk}/"),
|
|
98
|
+
}
|
|
99
|
+
if full:
|
|
100
|
+
data.update(
|
|
101
|
+
reference_commit=a.reference_commit, gate=a.gate_details, metrics=a.metrics_dict, tools=a.tools,
|
|
102
|
+
error=a.error,
|
|
103
|
+
)
|
|
104
|
+
return data
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def issue_json(issue, resolution=None):
|
|
108
|
+
return {
|
|
109
|
+
"id": issue.pk,
|
|
110
|
+
"type": issue.type,
|
|
111
|
+
"severity": issue.severity,
|
|
112
|
+
"tool": issue.tool,
|
|
113
|
+
"rule": issue.rule,
|
|
114
|
+
"message": issue.message,
|
|
115
|
+
"path": issue.path,
|
|
116
|
+
"line": issue.line,
|
|
117
|
+
"end_line": issue.end_line,
|
|
118
|
+
"is_new": issue.is_new,
|
|
119
|
+
"fingerprint": issue.fingerprint,
|
|
120
|
+
"also_reported_by": issue.also_reported_by,
|
|
121
|
+
"resolution": resolution and {"status": resolution.status, "comment": resolution.comment},
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def project_json(request, p):
|
|
126
|
+
return {
|
|
127
|
+
"key": p.key,
|
|
128
|
+
"name": p.name,
|
|
129
|
+
"main_branch": p.main_branch,
|
|
130
|
+
"repo_url": p.repo_url,
|
|
131
|
+
"role": p.role_of(request.user),
|
|
132
|
+
"branches": [analysis_json(request, a) for a in p.latest_analyses()],
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
@api()
|
|
137
|
+
def projects(request):
|
|
138
|
+
return JsonResponse({"projects": [project_json(request, p) for p in Project.visible_to(request.user)]})
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
@api()
|
|
142
|
+
def project(request, key):
|
|
143
|
+
return JsonResponse(project_json(request, visible_project(request, key)))
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
@api(scope=ApiToken.SCAN)
|
|
147
|
+
def project_config(request, key):
|
|
148
|
+
p = visible_project(request, key)
|
|
149
|
+
if not p.can_scan(request.user):
|
|
150
|
+
raise ApiError(403, "You can view this project but not scan it")
|
|
151
|
+
return JsonResponse(p.scan_config())
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
@api()
|
|
155
|
+
def status(request, key):
|
|
156
|
+
p = visible_project(request, key)
|
|
157
|
+
return JsonResponse(analysis_json(request, latest_analysis(p, request.GET.get(BRANCH), True), full=True))
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
@api()
|
|
161
|
+
def analysis(request, pk):
|
|
162
|
+
a = Analysis.objects.filter(pk=pk, project__in=Project.visible_to(request.user)).first()
|
|
163
|
+
if a is None:
|
|
164
|
+
raise ApiError(404, "No such analysis")
|
|
165
|
+
return JsonResponse(analysis_json(request, a, full=True))
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
@api()
|
|
169
|
+
def issues(request, key):
|
|
170
|
+
p = visible_project(request, key)
|
|
171
|
+
a = latest_analysis(p, request.GET.get(BRANCH))
|
|
172
|
+
qs, resolutions, _ = filter_issues(a, request.GET)
|
|
173
|
+
limit = int_param(request, "limit", 100, 1, MAX_PAGE)
|
|
174
|
+
offset = int_param(request, "offset", 0, 0, None)
|
|
175
|
+
total = qs.count()
|
|
176
|
+
# Most severe first, in the database: sorting every issue in Python loaded them all for one page.
|
|
177
|
+
rank = Case(*(When(severity=s, then=Value(n)) for n, s in enumerate(SEVERITIES)), default=Value(len(SEVERITIES)))
|
|
178
|
+
rows = qs.order_by(rank, "path", F("line").asc(nulls_first=True))[offset:offset + limit]
|
|
179
|
+
return JsonResponse({
|
|
180
|
+
"analysis": analysis_json(request, a),
|
|
181
|
+
"total": total,
|
|
182
|
+
"offset": offset,
|
|
183
|
+
"issues": [issue_json(i, resolutions.get(i.fingerprint)) for i in rows],
|
|
184
|
+
})
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def snippet(issue, context):
|
|
188
|
+
text = source_text(issue.analysis, issue.path) if issue.line else None
|
|
189
|
+
if text is None:
|
|
190
|
+
return None
|
|
191
|
+
lines = text.splitlines()
|
|
192
|
+
start = max(1, issue.line - context)
|
|
193
|
+
# Some rules span a whole function; the start of the range is what matters.
|
|
194
|
+
end = min(len(lines), min(issue.end_line or issue.line, issue.line + 10) + context)
|
|
195
|
+
return [{"line": n, "text": lines[n - 1]} for n in range(start, end + 1)]
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
@api()
|
|
199
|
+
def issue_detail(request, pk):
|
|
200
|
+
issue = Issue.objects.select_related("analysis__project").filter(
|
|
201
|
+
pk=pk, analysis__project__in=Project.visible_to(request.user)
|
|
202
|
+
).first()
|
|
203
|
+
if issue is None:
|
|
204
|
+
raise ApiError(404, "No such issue")
|
|
205
|
+
resolution = issue.analysis.project.resolutions.filter(fingerprint=issue.fingerprint).first()
|
|
206
|
+
data = issue_json(issue, resolution)
|
|
207
|
+
data["project"] = issue.analysis.project.key
|
|
208
|
+
data["analysis"] = analysis_json(request, issue.analysis)
|
|
209
|
+
data["snippet"] = snippet(issue, int_param(request, "context", 5, 0, 50))
|
|
210
|
+
entry = catalog.lookup(issue.tool, issue.rule)
|
|
211
|
+
data["rule"] = rule_json(entry, full=False) if entry else None
|
|
212
|
+
return JsonResponse(data)
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def rule_json(entry, full=True):
|
|
216
|
+
data = {k: entry.get(k) for k in ("id", "title", "summary", "type", "severity", "languages", "docs", "cwe",
|
|
217
|
+
"owasp", "wcag", "same_as", "origin", "references")}
|
|
218
|
+
if full:
|
|
219
|
+
details = catalog.load()[1].get("cwe_details", {})
|
|
220
|
+
data["explanation"] = catalog.docs().get(entry["id"])
|
|
221
|
+
data["cwe_guidance"] = [{"cwe": c, **{k: details[str(c)][k] for k in ("description", "mitigations")}}
|
|
222
|
+
for c in entry["cwe"] if str(c) in details]
|
|
223
|
+
return data
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
@api()
|
|
227
|
+
def rule(request, rule_id): # noqa: ARG001 # Django passes the request to every view
|
|
228
|
+
entry = catalog.find(rule_id)
|
|
229
|
+
if entry is None:
|
|
230
|
+
raise ApiError(404, f"No rule {rule_id}")
|
|
231
|
+
return JsonResponse(rule_json(entry))
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
@api(methods=("POST",))
|
|
235
|
+
def resolve(request, pk):
|
|
236
|
+
issue = Issue.objects.select_related("analysis__project").filter(
|
|
237
|
+
pk=pk, analysis__project__in=Project.visible_to(request.user)
|
|
238
|
+
).first()
|
|
239
|
+
if issue is None:
|
|
240
|
+
raise ApiError(404, "No such issue")
|
|
241
|
+
project = issue.analysis.project
|
|
242
|
+
if not project.can_scan(request.user):
|
|
243
|
+
raise ApiError(403, "Viewers can't resolve issues")
|
|
244
|
+
body = json_body(request)
|
|
245
|
+
try:
|
|
246
|
+
set_resolution(project, issue.fingerprint, body.get("status", ""), body.get("comment", ""))
|
|
247
|
+
except ValueError as exc:
|
|
248
|
+
raise ApiError(400, str(exc)) from exc
|
|
249
|
+
return JsonResponse({"ok": True, "fingerprint": issue.fingerprint, "status": body.get("status")})
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def json_body(request):
|
|
253
|
+
raw = request.body
|
|
254
|
+
if request.headers.get("Content-Encoding") == "gzip":
|
|
255
|
+
try:
|
|
256
|
+
raw = zlib.decompressobj(wbits=16 + zlib.MAX_WBITS).decompress(raw, MAX_PAYLOAD_BYTES)
|
|
257
|
+
except (zlib.error, gzip.BadGzipFile) as exc:
|
|
258
|
+
raise ApiError(400, "Invalid gzip body") from exc
|
|
259
|
+
try:
|
|
260
|
+
return json.loads(raw or b"{}")
|
|
261
|
+
except ValueError as exc:
|
|
262
|
+
raise ApiError(400, "Body must be JSON") from exc
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def project_for_scan(request, key, create_fields):
|
|
266
|
+
"""Existing project the user may scan, or a new one owned by them."""
|
|
267
|
+
project = Project.objects.filter(key=key).first()
|
|
268
|
+
if project is None:
|
|
269
|
+
try:
|
|
270
|
+
return create_project(request.user, key=key, **create_fields)
|
|
271
|
+
except IntegrityError as exc:
|
|
272
|
+
raise ApiError(409, f"Project key {key} is taken") from exc
|
|
273
|
+
if not project.can_scan(request.user):
|
|
274
|
+
raise ApiError(403 if project.role_of(request.user) else 404, f"No project {key} (or no scan access)")
|
|
275
|
+
return project
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
COMMIT_RE = re.compile(r"^[0-9a-f]{40}([0-9a-f]{24})?$")
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
def check_upload(payload):
|
|
282
|
+
"""400 unless the commits are hashes and the branch a branch name: they reach git on the server, and on every
|
|
283
|
+
developer's machine through the project's config (`--output=/path` as a commit wrote a file)."""
|
|
284
|
+
for field in (BRANCH, "commit", "issues", "metrics"):
|
|
285
|
+
if field not in payload:
|
|
286
|
+
raise ApiError(400, f"Missing {field}")
|
|
287
|
+
if not isinstance(payload[BRANCH], str) or not BRANCH_RE.match(payload[BRANCH]):
|
|
288
|
+
raise ApiError(400, "branch must be a branch name")
|
|
289
|
+
for field in ("commit", "reference_commit", "reference_analysis_commit"):
|
|
290
|
+
value = payload.get(field)
|
|
291
|
+
if (value or field == "commit") and not (isinstance(value, str) and COMMIT_RE.match(value)):
|
|
292
|
+
raise ApiError(400, f"{field} must be a full commit hash")
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
@api(scope=ApiToken.SCAN, methods=("POST",))
|
|
296
|
+
def upload(request, key):
|
|
297
|
+
"""Results from codewatch-scan run against a local working copy."""
|
|
298
|
+
payload = json_body(request)
|
|
299
|
+
check_upload(payload)
|
|
300
|
+
project = project_for_scan(request, key, {
|
|
301
|
+
"name": payload.get("project_name") or key, "repo_url": "", MAIN_BRANCH: payload.get(MAIN_BRANCH, ""),
|
|
302
|
+
})
|
|
303
|
+
if not project.main_branch and payload.get(MAIN_BRANCH):
|
|
304
|
+
project.main_branch = payload[MAIN_BRANCH]
|
|
305
|
+
project.save(update_fields=[MAIN_BRANCH])
|
|
306
|
+
analysis = create_uploaded_analysis(project, payload, request.user)
|
|
307
|
+
try:
|
|
308
|
+
ingest(analysis, payload)
|
|
309
|
+
except (KeyError, TypeError, ValueError) as exc:
|
|
310
|
+
analysis.status = Analysis.FAILED
|
|
311
|
+
analysis.error = f"Malformed upload: {exc!r}"
|
|
312
|
+
analysis.save()
|
|
313
|
+
raise ApiError(400, analysis.error) from exc
|
|
314
|
+
data = analysis_json(request, analysis, full=True)
|
|
315
|
+
return JsonResponse(data, status=201)
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
def new_server_project_fields(request, key, body):
|
|
319
|
+
fields = {"name": body.get("name") or key, MAIN_BRANCH: body.get(MAIN_BRANCH, "")}
|
|
320
|
+
if Project.objects.filter(key=key).exists():
|
|
321
|
+
return fields
|
|
322
|
+
try:
|
|
323
|
+
fields["repo_url"] = validate_repo_url(body.get("repo_url", ""), allow_local=request.user.is_superuser)
|
|
324
|
+
except ValueError as exc:
|
|
325
|
+
raise ApiError(400, str(exc)) from exc
|
|
326
|
+
return fields
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
def cloneable_project(request, key, body):
|
|
330
|
+
"""The project to scan on the server (created if the token may), which must have a repository URL."""
|
|
331
|
+
project = project_for_scan(request, key, new_server_project_fields(request, key, body))
|
|
332
|
+
if not project.repo_url:
|
|
333
|
+
raise ApiError(400, "This project has no repository URL; upload results with codewatch-scan instead")
|
|
334
|
+
return project
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
def uploaded_coverage(request, project):
|
|
338
|
+
"""Where a coverage report sent with the scan request was saved, or None; refused over the size limit."""
|
|
339
|
+
coverage = request.FILES.get("coverage")
|
|
340
|
+
if not coverage:
|
|
341
|
+
return None
|
|
342
|
+
if coverage.size > settings.CODEWATCH_MAX_COVERAGE_UPLOAD:
|
|
343
|
+
raise ApiError(413, f"Coverage reports are limited to {settings.CODEWATCH_MAX_COVERAGE_UPLOAD // 2**20} MB")
|
|
344
|
+
return save_coverage_upload(project, coverage)
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
@api(scope=ApiToken.SCAN, methods=("POST",))
|
|
348
|
+
def server_scan(request, key):
|
|
349
|
+
"""Ask the server to clone/fetch the repository URL and scan a branch itself."""
|
|
350
|
+
body = request.POST if request.content_type.startswith("multipart/") else json_body(request)
|
|
351
|
+
project = cloneable_project(request, key, body)
|
|
352
|
+
branch = body.get(BRANCH) or None
|
|
353
|
+
if branch is not None and not (isinstance(branch, str) and BRANCH_RE.match(branch)):
|
|
354
|
+
raise ApiError(400, "branch must be a branch name")
|
|
355
|
+
refusal = scan_refusal(project, branch)
|
|
356
|
+
if refusal:
|
|
357
|
+
raise ApiError(409, refusal)
|
|
358
|
+
launch_scan(project, branch, coverage=uploaded_coverage(request, project))
|
|
359
|
+
return JsonResponse({"project": project.key, BRANCH: branch or project.main_branch or None,
|
|
360
|
+
"status": "queued"}, status=202)
|