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,199 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import re
|
|
3
|
+
import shutil
|
|
4
|
+
import tempfile
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
from .base import ACCESSIBILITY, CRITICAL, INFO, MAJOR, MINOR, TOOLS_DIR, Analyzer, Finding, Result, node_tool
|
|
8
|
+
|
|
9
|
+
TEMPLATES = {".html", ".htm", ".djhtml", ".jinja", ".jinja2", ".j2"}
|
|
10
|
+
JSX = {".jsx", ".tsx"}
|
|
11
|
+
TAG_DELIMITERS = (("{%", "%}"), ("{#", "#}"), ("{{", "}}"))
|
|
12
|
+
# Alpine/Vue fill these at runtime, so an empty element in the template isn't empty on the page. Two plain patterns
|
|
13
|
+
# and a scan, not one regex: the single regex with a backreference was polynomial under recheck's fuzzer, and failed
|
|
14
|
+
# the self-check only when the fuzzer found it within its time limit (2026-11-20).
|
|
15
|
+
OPEN_TAG = re.compile(r"<(\w{1,40})\b([^<>]{0,4000})>")
|
|
16
|
+
BINDING = re.compile(r"\s(?:x-text|x-html|v-text|v-html)\s{0,20}=")
|
|
17
|
+
MAX_GAP = 200
|
|
18
|
+
AXE_SEVERITY = {CRITICAL: CRITICAL, "serious": MAJOR, "moderate": MINOR, MINOR: INFO}
|
|
19
|
+
ERROR, WARN, OFF = "error", "warn", "off"
|
|
20
|
+
HTML_VALIDATE_CONFIG = {
|
|
21
|
+
"extends": ["html-validate:a11y"],
|
|
22
|
+
# The preset alone misses unlabelled inputs, empty headings, duplicate landmarks and focusable hidden content.
|
|
23
|
+
"rules": {
|
|
24
|
+
"input-missing-label": ERROR,
|
|
25
|
+
"aria-label-misuse": ERROR,
|
|
26
|
+
"unique-landmark": ERROR,
|
|
27
|
+
"empty-heading": ERROR,
|
|
28
|
+
"hidden-focusable": ERROR,
|
|
29
|
+
"area-alt": ERROR,
|
|
30
|
+
"no-abstract-role": ERROR,
|
|
31
|
+
"aria-hidden-body": ERROR,
|
|
32
|
+
"text-content": ERROR,
|
|
33
|
+
"valid-autocomplete": ERROR,
|
|
34
|
+
"no-redundant-role": WARN,
|
|
35
|
+
"prefer-native-element": WARN,
|
|
36
|
+
"no-implicit-button-type": OFF,
|
|
37
|
+
},
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def blank_tag(tag, is_output):
|
|
42
|
+
"""Spaces for {% %}/{# #}; for {{ }} keep the variable's letters so different values stay distinct
|
|
43
|
+
(e.g. two headings filled from different variables don't look like duplicates)."""
|
|
44
|
+
if not is_output:
|
|
45
|
+
return "".join(c if c == "\n" else " " for c in tag)
|
|
46
|
+
return "".join(c if c.isalnum() or c == "\n" else "x" for c in tag)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def next_tag(text, start):
|
|
50
|
+
found = [(pos, opener, closer) for opener, closer in TAG_DELIMITERS if (pos := text.find(opener, start)) != -1]
|
|
51
|
+
return min(found) if found else None
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def blank_template_syntax(text):
|
|
55
|
+
"""Strip Django/Jinja tags so the HTML parses, keeping every line and column where it was.
|
|
56
|
+
|
|
57
|
+
Output expressions keep their letters so attributes like alt="{{ caption }}" still count as non-empty.
|
|
58
|
+
A plain scan rather than a regex, so hostile templates can't trigger backtracking.
|
|
59
|
+
"""
|
|
60
|
+
out, i = [], 0
|
|
61
|
+
while (tag := next_tag(text, i)) is not None:
|
|
62
|
+
pos, opener, closer = tag
|
|
63
|
+
end = text.find(closer, pos + 2)
|
|
64
|
+
if end == -1:
|
|
65
|
+
break
|
|
66
|
+
end += 2
|
|
67
|
+
out += [text[i:pos], blank_tag(text[pos:end], opener == "{{")]
|
|
68
|
+
i = end
|
|
69
|
+
out.append(text[i:])
|
|
70
|
+
return fill_bound_empty("".join(out))
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def fill_bound_empty(text):
|
|
74
|
+
"""An x inside each element that an Alpine/Vue binding (x-text, v-html...) fills, when the template leaves it empty
|
|
75
|
+
or holding only whitespace, so html-validate doesn't report it as empty."""
|
|
76
|
+
out, i = [], 0
|
|
77
|
+
for tag in OPEN_TAG.finditer(text):
|
|
78
|
+
if not BINDING.search(tag.group(2)):
|
|
79
|
+
continue
|
|
80
|
+
gap = tag.end()
|
|
81
|
+
while gap < len(text) and gap - tag.end() < MAX_GAP and text[gap].isspace():
|
|
82
|
+
gap += 1
|
|
83
|
+
if text.startswith(f"</{tag.group(1)}>", gap):
|
|
84
|
+
out += [text[i:tag.end()], "x"]
|
|
85
|
+
i = tag.end()
|
|
86
|
+
out.append(text[i:])
|
|
87
|
+
return "".join(out)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
class HtmlA11y(Analyzer):
|
|
91
|
+
"""Static WCAG checks on HTML and server-side templates (alt text, labels, ARIA, table headers...)."""
|
|
92
|
+
|
|
93
|
+
name = "html-a11y"
|
|
94
|
+
executable = "html-validate"
|
|
95
|
+
extensions = TEMPLATES
|
|
96
|
+
|
|
97
|
+
def binary(self):
|
|
98
|
+
return node_tool("html-validate")
|
|
99
|
+
|
|
100
|
+
def run(self, ctx):
|
|
101
|
+
files = ctx.files_with(TEMPLATES)
|
|
102
|
+
with tempfile.TemporaryDirectory() as tmp_name:
|
|
103
|
+
tmp = Path(tmp_name)
|
|
104
|
+
for f in files:
|
|
105
|
+
target = tmp / f
|
|
106
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
107
|
+
target.write_text(blank_template_syntax((ctx.root / f).read_text(errors="replace")))
|
|
108
|
+
config = tmp / ".codewatch-htmlvalidate.json"
|
|
109
|
+
config.write_text(json.dumps(HTML_VALIDATE_CONFIG))
|
|
110
|
+
# Report to a file: Node truncates large piped stdout when the process exits.
|
|
111
|
+
report_file = tmp / ".codewatch-report.json"
|
|
112
|
+
self.exec(["--config", str(config), "--formatter", f"json={report_file}", *files], ctx,
|
|
113
|
+
ok_codes=(0, 1), cwd=tmp)
|
|
114
|
+
out = report_file.read_text() if report_file.exists() else "[]"
|
|
115
|
+
result = Result()
|
|
116
|
+
for report in json.loads(out or "[]"):
|
|
117
|
+
path = ctx.rel(Path(report["filePath"]).relative_to(tmp) if Path(report["filePath"]).is_absolute()
|
|
118
|
+
else report["filePath"])
|
|
119
|
+
for m in report["messages"]:
|
|
120
|
+
rule = m.get("ruleId") or "parser-error"
|
|
121
|
+
severity = MAJOR if m.get("severity") == 2 else MINOR
|
|
122
|
+
result.findings.append(
|
|
123
|
+
Finding("html-a11y", rule, severity, ACCESSIBILITY, m["message"], path, m.get("line"))
|
|
124
|
+
)
|
|
125
|
+
return result
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
class JsxA11y(Analyzer):
|
|
129
|
+
name = "jsx-a11y"
|
|
130
|
+
executable = "eslint"
|
|
131
|
+
extensions = JSX
|
|
132
|
+
|
|
133
|
+
def binary(self):
|
|
134
|
+
return node_tool("eslint")
|
|
135
|
+
|
|
136
|
+
def run(self, ctx):
|
|
137
|
+
config = TOOLS_DIR / "eslint-a11y.config.js"
|
|
138
|
+
with tempfile.TemporaryDirectory() as tmp:
|
|
139
|
+
report_file = Path(tmp) / "report.json"
|
|
140
|
+
self.exec(["--config", str(config), "--format", "json", "--output-file", str(report_file),
|
|
141
|
+
"--no-warn-ignored", *ctx.files_with(JSX)], ctx, ok_codes=(0, 1))
|
|
142
|
+
out = report_file.read_text() if report_file.exists() else "[]"
|
|
143
|
+
result = Result()
|
|
144
|
+
for report in json.loads(out or "[]"):
|
|
145
|
+
for m in report["messages"]:
|
|
146
|
+
rule = m.get("ruleId") or "parser-error"
|
|
147
|
+
result.findings.append(
|
|
148
|
+
Finding("jsx-a11y", rule, MAJOR if m.get("severity") == 2 else MINOR, ACCESSIBILITY,
|
|
149
|
+
m["message"], ctx.rel(report["filePath"]), m.get("line"), m.get("endLine"))
|
|
150
|
+
)
|
|
151
|
+
return result
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
class Axe(Analyzer):
|
|
155
|
+
"""Runtime WCAG 2.2 AA checks (contrast, ARIA, focus, landmarks) with axe-core on live pages."""
|
|
156
|
+
|
|
157
|
+
name = "axe"
|
|
158
|
+
executable = "node"
|
|
159
|
+
|
|
160
|
+
def applies(self, ctx):
|
|
161
|
+
return bool(ctx.a11y_urls)
|
|
162
|
+
|
|
163
|
+
def available(self):
|
|
164
|
+
script = TOOLS_DIR / "axe-scan.mjs"
|
|
165
|
+
return shutil.which("node") is not None and node_tool("playwright") is not None and script.exists()
|
|
166
|
+
|
|
167
|
+
def __init__(self, color_scheme="light"):
|
|
168
|
+
self.color_scheme = color_scheme
|
|
169
|
+
|
|
170
|
+
def run(self, ctx):
|
|
171
|
+
script = TOOLS_DIR / "axe-scan.mjs"
|
|
172
|
+
with tempfile.NamedTemporaryFile("w", suffix=".json") as spec:
|
|
173
|
+
json.dump({"urls": ctx.a11y_urls, "colorScheme": self.color_scheme}, spec)
|
|
174
|
+
spec.flush()
|
|
175
|
+
out = self.exec([str(script), spec.name], ctx, cwd=TOOLS_DIR)
|
|
176
|
+
result = Result()
|
|
177
|
+
failed = 0
|
|
178
|
+
for page in json.loads(out):
|
|
179
|
+
if page.get("error"):
|
|
180
|
+
failed += 1
|
|
181
|
+
result.findings.append(
|
|
182
|
+
Finding("axe", "page-load-failed", MAJOR, ACCESSIBILITY,
|
|
183
|
+
f"Could not load page: {page['error']}", page["url"])
|
|
184
|
+
)
|
|
185
|
+
for v in page["violations"]:
|
|
186
|
+
for node in v["nodes"]:
|
|
187
|
+
result.findings.append(
|
|
188
|
+
Finding("axe", v["id"], AXE_SEVERITY.get(v["impact"], MINOR), ACCESSIBILITY,
|
|
189
|
+
f"{v['help']} — {node['target']}. {first_line(node['summary'])} ({v['helpUrl']})",
|
|
190
|
+
page["url"])
|
|
191
|
+
)
|
|
192
|
+
result.metrics["a11y_pages_scanned"] = len(ctx.a11y_urls) - failed
|
|
193
|
+
return result
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def first_line(text):
|
|
197
|
+
lines = [ln.strip() for ln in (text or "").splitlines() if ln.strip()]
|
|
198
|
+
# failureSummary starts with "Fix any/all of the following:"; the useful part is the next line.
|
|
199
|
+
return lines[1] if len(lines) > 1 else (lines[0] if lines else "")
|
core/analyzers/base.py
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
import ast
|
|
2
|
+
import json
|
|
3
|
+
import os
|
|
4
|
+
import re
|
|
5
|
+
import shutil
|
|
6
|
+
import signal
|
|
7
|
+
import subprocess
|
|
8
|
+
import sys
|
|
9
|
+
from dataclasses import dataclass, field
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
from ..paths import tools_dir
|
|
13
|
+
|
|
14
|
+
PY = {".py"}
|
|
15
|
+
JS = {".js", ".jsx", ".mjs", ".cjs", ".ts", ".tsx"}
|
|
16
|
+
C = {".c", ".cc", ".cpp", ".cxx", ".h", ".hh", ".hpp", ".hxx"}
|
|
17
|
+
CODE = PY | JS | C | {".java", ".go", ".rs", ".cs", ".rb", ".php", ".kt", ".swift"}
|
|
18
|
+
# PHP in files Semgrep doesn't parse as PHP by their extension: views (.phtml, CakePHP 2's .ctp), includes, and
|
|
19
|
+
# Drupal's .module/.install/.theme, and .tpl views written in PHP (OpenCart 2; a Smarty .tpl has no PHP tag). Semgrep
|
|
20
|
+
# scans them as .php copies (multi_tools.analysis_copies).
|
|
21
|
+
PHP_VIEWS = {".phtml", ".ctp", ".inc", ".module", ".install", ".theme", ".tpl"}
|
|
22
|
+
|
|
23
|
+
BLOCKER, CRITICAL, MAJOR, MINOR, INFO = "blocker", "critical", "major", "minor", "info"
|
|
24
|
+
BUG, VULNERABILITY, HOTSPOT, CODE_SMELL, ACCESSIBILITY = (
|
|
25
|
+
"bug", "vulnerability", "security_hotspot", "code_smell", "accessibility"
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
TOOL_TIMEOUT = 1800
|
|
29
|
+
TOOLS_DIR = tools_dir()
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass
|
|
33
|
+
class Finding:
|
|
34
|
+
tool: str
|
|
35
|
+
rule: str
|
|
36
|
+
severity: str
|
|
37
|
+
type: str
|
|
38
|
+
message: str
|
|
39
|
+
path: str
|
|
40
|
+
line: int | None = None
|
|
41
|
+
end_line: int | None = None
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@dataclass
|
|
45
|
+
class Result:
|
|
46
|
+
findings: list[Finding] = field(default_factory=list)
|
|
47
|
+
metrics: dict[str, float] = field(default_factory=dict)
|
|
48
|
+
covered_lines: dict[str, set[int]] = field(default_factory=dict)
|
|
49
|
+
coverable_lines: dict[str, set[int]] = field(default_factory=dict)
|
|
50
|
+
duplicated_lines: dict[str, set[int]] = field(default_factory=dict)
|
|
51
|
+
# What the analysis couldn't do (a file a tool gave up on), shown with the tool's status.
|
|
52
|
+
notes: list[str] = field(default_factory=list)
|
|
53
|
+
# The files a tool gave up on in some pass (relative paths), for the benchmark's scorer.
|
|
54
|
+
gave_up: list[str] = field(default_factory=list)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
@dataclass
|
|
58
|
+
class Context:
|
|
59
|
+
root: Path
|
|
60
|
+
files: list[str]
|
|
61
|
+
complexity_threshold: int = 10
|
|
62
|
+
semgrep_config: str = "p/default"
|
|
63
|
+
exclusions: list[str] = field(default_factory=list)
|
|
64
|
+
a11y_urls: list[str] = field(default_factory=list)
|
|
65
|
+
cognitive_threshold: int = 15
|
|
66
|
+
max_literal_repeats: int = 3
|
|
67
|
+
custom_rules: str = ""
|
|
68
|
+
coverage_report: Path | None = None
|
|
69
|
+
coverage_base: Path | None = None
|
|
70
|
+
# Files whose findings are wanted, when not all of them are (a benchmark scores only the lines a fix
|
|
71
|
+
# changed). Per-file passes are narrowed to it, and Semgrep's summary rounds to it and what it imports
|
|
72
|
+
# (Semgrep.summary_targets); other analyses that look across files still read every file.
|
|
73
|
+
focus: list[str] | None = None
|
|
74
|
+
# The developer's own working copy (codewatch-scan): its virtualenv may be run and its packages built. Never
|
|
75
|
+
# for a server-side scan, where the repository is anyone's: both run the repository's code.
|
|
76
|
+
local: bool = False
|
|
77
|
+
|
|
78
|
+
def files_with(self, extensions):
|
|
79
|
+
return [f for f in self.files if Path(f).suffix.lower() in extensions]
|
|
80
|
+
|
|
81
|
+
def rel(self, path):
|
|
82
|
+
p = Path(path)
|
|
83
|
+
if p.is_absolute():
|
|
84
|
+
try:
|
|
85
|
+
p = p.relative_to(self.root)
|
|
86
|
+
except ValueError:
|
|
87
|
+
return str(p)
|
|
88
|
+
return os.path.normpath(str(p)).removeprefix("./")
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
class ToolError(RuntimeError):
|
|
92
|
+
pass
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def tool_path(name):
|
|
96
|
+
local = Path(sys.executable).parent / name
|
|
97
|
+
return str(local) if local.exists() else shutil.which(name)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def isolated_tool(name):
|
|
101
|
+
"""Python analyzers kept in their own venv under tools/ because their pins clash with codewatch's."""
|
|
102
|
+
path = TOOLS_DIR / f"{name}-venv" / "bin" / name
|
|
103
|
+
return str(path) if path.exists() else None
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def node_tool(name):
|
|
107
|
+
"""Pinned Node analyzers from tools/ (npm ci --prefix tools); never npx, which would honour a scanned repo's .npmrc."""
|
|
108
|
+
path = TOOLS_DIR / "node_modules" / ".bin" / name
|
|
109
|
+
return str(path) if path.exists() else None
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def run_killing_group(args, cwd, timeout):
|
|
113
|
+
"""subprocess.run with captured text output, except that a timeout kills the tool's children too: semgrep's
|
|
114
|
+
Python wrapper runs semgrep-core, which otherwise keeps running (and holding gigabytes) after the wrapper dies."""
|
|
115
|
+
with subprocess.Popen(args, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True,
|
|
116
|
+
start_new_session=hasattr(os, "killpg")) as proc:
|
|
117
|
+
try:
|
|
118
|
+
stdout, stderr = proc.communicate(timeout=timeout)
|
|
119
|
+
except subprocess.TimeoutExpired:
|
|
120
|
+
if hasattr(os, "killpg"):
|
|
121
|
+
os.killpg(proc.pid, signal.SIGKILL)
|
|
122
|
+
else:
|
|
123
|
+
proc.kill()
|
|
124
|
+
proc.communicate()
|
|
125
|
+
raise
|
|
126
|
+
return subprocess.CompletedProcess(args, proc.returncode, stdout, stderr)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
class Analyzer:
|
|
130
|
+
name = ""
|
|
131
|
+
executable = ""
|
|
132
|
+
extensions: set[str] | None = None
|
|
133
|
+
|
|
134
|
+
def applies(self, ctx: Context) -> bool:
|
|
135
|
+
return self.extensions is None or bool(ctx.files_with(self.extensions))
|
|
136
|
+
|
|
137
|
+
def binary(self):
|
|
138
|
+
return tool_path(self.executable)
|
|
139
|
+
|
|
140
|
+
def available(self) -> bool:
|
|
141
|
+
return self.binary() is not None
|
|
142
|
+
|
|
143
|
+
def run(self, ctx: Context) -> Result:
|
|
144
|
+
raise NotImplementedError
|
|
145
|
+
|
|
146
|
+
def exec(self, args, ctx, ok_codes=(0,), stream="stdout", cwd=None):
|
|
147
|
+
proc = run_killing_group([self.binary(), *args], cwd=cwd or ctx.root, timeout=TOOL_TIMEOUT)
|
|
148
|
+
if proc.returncode not in ok_codes:
|
|
149
|
+
# Some tools (semgrep --json --quiet) report the failure on stdout and leave stderr empty.
|
|
150
|
+
detail = proc.stderr.strip() or proc.stdout.strip()
|
|
151
|
+
raise ToolError(f"{self.name} exited {proc.returncode}: {failure_detail(detail)}")
|
|
152
|
+
return proc.stdout if stream == "stdout" else proc.stderr
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def failure_detail(output):
|
|
156
|
+
"""A failed tool's message. A JSON report (semgrep) gives its errors' messages: its tail is profiling data."""
|
|
157
|
+
try:
|
|
158
|
+
report = json.loads(output)
|
|
159
|
+
except ValueError:
|
|
160
|
+
return output[-2000:]
|
|
161
|
+
errors = report.get("errors") if isinstance(report, dict) else None
|
|
162
|
+
if not errors:
|
|
163
|
+
return output[-2000:]
|
|
164
|
+
# The start of the first error says what failed; a rule's message can quote a long generated regex after it.
|
|
165
|
+
return "; ".join(str(e.get("message") or e.get("type") or e) if isinstance(e, dict) else str(e)
|
|
166
|
+
for e in errors)[:2000]
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
# End-to-end suites too (immich: e2e/src/specs/server/api/oauth.e2e-spec.ts).
|
|
170
|
+
TEST_PATH_RE = re.compile(r"(^|/)(tests?|__tests__|specs?|e2e|cypress)/|(^|/)test_[^/]{0,200}\.py$|_test\.py$"
|
|
171
|
+
r"|[.-](test|spec|e2e-spec|e2e)\.[jt]sx?$")
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def python_tree(text):
|
|
175
|
+
"""The module's syntax tree, or None for a file Python can't parse (another dialect, a template, a fragment)."""
|
|
176
|
+
try:
|
|
177
|
+
return ast.parse(text)
|
|
178
|
+
except (SyntaxError, ValueError):
|
|
179
|
+
return None
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def is_test_file(path):
|
|
183
|
+
return bool(TEST_PATH_RE.search(path))
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def by_prefix(code, table, default):
|
|
187
|
+
"""First table row whose prefix is the code's whole rule family: "S" matches S602 but not SIM108."""
|
|
188
|
+
for prefix, *mapping in table:
|
|
189
|
+
rest = code[len(prefix):]
|
|
190
|
+
if code.startswith(prefix) and (not rest or rest[0].isdigit() or prefix[-1].isdigit()):
|
|
191
|
+
return tuple(mapping)
|
|
192
|
+
return default
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
"""Request-body models as taint sources: `def create(item: ItemCreate)` in a FastAPI route.
|
|
2
|
+
|
|
3
|
+
A route parameter typed with a Pydantic (or SQLModel) class is the parsed request body, and its text fields are
|
|
4
|
+
request data: `item.name` in a query is as tainted as `request.args["name"]`. Which classes are models, and which
|
|
5
|
+
of their fields hold text, is known only from the project's own class definitions, so the Python files are read
|
|
6
|
+
here and each request-source rule gets one more source naming them. Fields typed int, bool, UUID and the like
|
|
7
|
+
aren't text; a field name that is text in one model and not in another is left out.
|
|
8
|
+
|
|
9
|
+
A field typed with another model is followed one level (`data.table.table_name`), and a model with text fields
|
|
10
|
+
passed whole to a call (`preview(session, data)`) is request data there, so the callee's summary carries it to a
|
|
11
|
+
sink in another file (SQLBot CVE-2026-53556). In that callee the model's other fields are tainted too.
|
|
12
|
+
"""
|
|
13
|
+
import ast
|
|
14
|
+
import re
|
|
15
|
+
|
|
16
|
+
from .base import python_tree
|
|
17
|
+
|
|
18
|
+
MODEL_BASES = {"BaseModel", "pydantic.BaseModel", "SQLModel", "sqlmodel.SQLModel"}
|
|
19
|
+
TEXT_RE = re.compile(r"^((typing\.)?(Optional|List|Annotated)\[str\b.*|(list|set)\[str\]|str( \| None)?|Any)$")
|
|
20
|
+
WRAPPER_RE = re.compile(r"^(?:typing\.)?(?:Optional|List|list|Sequence|set|Set)\[(.*)\]$")
|
|
21
|
+
ROUTE_MARK = "$ROUTE"
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def without_none(annotation):
|
|
25
|
+
"""An annotation without a trailing `| None`."""
|
|
26
|
+
head, bar, tail = annotation.strip().rpartition("|")
|
|
27
|
+
return head.rstrip() if bar and tail.strip() == "None" else annotation.strip()
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def model_named(annotation, models):
|
|
31
|
+
"""The model an annotation names, through Optional[...], List[...] and `| None`, or None."""
|
|
32
|
+
while True:
|
|
33
|
+
annotation = without_none(annotation)
|
|
34
|
+
inner = WRAPPER_RE.match(annotation)
|
|
35
|
+
if not inner:
|
|
36
|
+
return annotation if annotation in models else None
|
|
37
|
+
annotation = inner.group(1)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def class_shape(node):
|
|
41
|
+
"""([a class's bases], {annotated field: annotation})."""
|
|
42
|
+
fields = {stmt.target.id: ast.unparse(stmt.annotation) for stmt in node.body
|
|
43
|
+
if isinstance(stmt, ast.AnnAssign) and isinstance(stmt.target, ast.Name)}
|
|
44
|
+
return [ast.unparse(b) for b in node.bases], fields
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def class_definitions(texts):
|
|
48
|
+
"""{class name: ([its bases], {annotated field: annotation})}, the first definition of each name."""
|
|
49
|
+
classes = {}
|
|
50
|
+
for tree in filter(None, map(python_tree, texts)):
|
|
51
|
+
for node in ast.walk(tree):
|
|
52
|
+
if isinstance(node, ast.ClassDef):
|
|
53
|
+
classes.setdefault(node.name, class_shape(node))
|
|
54
|
+
return classes
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def model_classes(classes):
|
|
58
|
+
"""The classes that are models: a model base, or a base that is a model, at any depth."""
|
|
59
|
+
models = set()
|
|
60
|
+
while more := {name for name, (bases, _) in classes.items()
|
|
61
|
+
if name not in models and any(b in MODEL_BASES or b in models for b in bases)}:
|
|
62
|
+
models |= more
|
|
63
|
+
return models
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def model_annotations(name, classes, models, seen=()):
|
|
67
|
+
"""A model's annotated fields, its model bases' included (its own win)."""
|
|
68
|
+
bases, fields = classes[name]
|
|
69
|
+
inherited = {}
|
|
70
|
+
for base in bases:
|
|
71
|
+
if base in models and base not in seen:
|
|
72
|
+
inherited |= model_annotations(base, classes, models, (*seen, name))
|
|
73
|
+
return inherited | fields
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def model_fields(texts):
|
|
77
|
+
"""{model class: {text field}}, the field names that are non-text in some model, and {model class: {field:
|
|
78
|
+
model}} for fields typed with another model, from Python sources."""
|
|
79
|
+
classes = class_definitions(texts)
|
|
80
|
+
models = model_classes(classes)
|
|
81
|
+
text, other, nested = {}, set(), {}
|
|
82
|
+
for name in models:
|
|
83
|
+
for field, annotation in model_annotations(name, classes, models).items():
|
|
84
|
+
if TEXT_RE.match(annotation):
|
|
85
|
+
text.setdefault(name, set()).add(field)
|
|
86
|
+
continue
|
|
87
|
+
other.add(field)
|
|
88
|
+
if inner := model_named(annotation, models):
|
|
89
|
+
nested.setdefault(name, {})[field] = inner
|
|
90
|
+
return text, other, nested
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def route_patterns(models):
|
|
94
|
+
"""Inside a route function whose parameter $PARAM is typed with one of these models."""
|
|
95
|
+
route = "@$APP.$ROUTE($PATH, ...)\n{}def $VIEW(..., $PARAM: $MODEL, ...):\n ...\n"
|
|
96
|
+
return [
|
|
97
|
+
{"pattern-either": [{"pattern-inside": route.format(a)} for a in ("", "async ")]},
|
|
98
|
+
{"metavariable-regex": {"metavariable": "$ROUTE", "regex": "^(route|get|post|put|patch|delete|api_route)$"}},
|
|
99
|
+
{"metavariable-regex": {"metavariable": "$PATH", "regex": "^[rbuf]*['\"]/"}},
|
|
100
|
+
{"metavariable-regex": {"metavariable": "$MODEL", "regex": f"^({alternation(models)})$"}},
|
|
101
|
+
]
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def alternation(names):
|
|
105
|
+
return "|".join(map(re.escape, sorted(names)))
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def deep_models(direct, nested):
|
|
109
|
+
"""{model: ({field typed with a model that has text}, {those models' text fields})}."""
|
|
110
|
+
deep = {}
|
|
111
|
+
for model, fields in (nested or {}).items():
|
|
112
|
+
if subs := {f: direct[inner] for f, inner in fields.items() if inner in direct}:
|
|
113
|
+
deep[model] = (set(subs), set().union(*subs.values()))
|
|
114
|
+
return deep
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def names_regex(metavariable, names):
|
|
118
|
+
return {"metavariable-regex": {"metavariable": metavariable, "regex": f"^({alternation(names)})$"}}
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def model_sources(text, other, nested=None):
|
|
122
|
+
"""Semgrep taint sources for route parameters typed with these models: their text fields, the text fields of
|
|
123
|
+
their model-typed fields, and the whole model passed to a call. Empty when no model has text."""
|
|
124
|
+
direct = {m: found - other for m, found in text.items() if found - other}
|
|
125
|
+
deep = deep_models(direct, nested)
|
|
126
|
+
sources = []
|
|
127
|
+
if direct:
|
|
128
|
+
sources.append({"patterns": [*route_patterns(direct), {"pattern": "$PARAM.$FIELD"},
|
|
129
|
+
names_regex("$FIELD", set().union(*direct.values()))]})
|
|
130
|
+
if deep:
|
|
131
|
+
sources.append({"patterns": [*route_patterns(deep), {"pattern": "$PARAM.$SUB.$FIELD"},
|
|
132
|
+
names_regex("$SUB", set().union(*(s for s, _ in deep.values()))),
|
|
133
|
+
names_regex("$FIELD", set().union(*(f for _, f in deep.values())))]})
|
|
134
|
+
if direct or deep:
|
|
135
|
+
sources.append({"patterns": [
|
|
136
|
+
*route_patterns({*direct, *deep}),
|
|
137
|
+
{"pattern-either": [{"pattern": "$CALL(..., $PARAM, ...)"}, {"pattern": "$CALL(..., $KW=$PARAM, ...)"}]},
|
|
138
|
+
{"focus-metavariable": "$PARAM"},
|
|
139
|
+
]})
|
|
140
|
+
return sources
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def with_model_sources(rules, texts):
|
|
144
|
+
"""The rules, with the model sources added to every Python taint rule whose sources include route parameters."""
|
|
145
|
+
sources = model_sources(*model_fields(texts))
|
|
146
|
+
if not sources:
|
|
147
|
+
return rules
|
|
148
|
+
return [{**rule, "pattern-sources": [*rule["pattern-sources"], *sources]} if takes_route_sources(rule) else rule
|
|
149
|
+
for rule in rules]
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def takes_route_sources(rule):
|
|
153
|
+
return (rule.get("mode") == "taint" and "python" in rule.get("languages", [])
|
|
154
|
+
and ROUTE_MARK in repr(rule.get("pattern-sources")))
|