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
@@ -0,0 +1,333 @@
1
+ import ast
2
+ import json
3
+ import re
4
+ import tempfile
5
+ from pathlib import Path
6
+
7
+ from .base import (
8
+ BLOCKER,
9
+ BUG,
10
+ CODE_SMELL,
11
+ CRITICAL,
12
+ HOTSPOT,
13
+ INFO,
14
+ MAJOR,
15
+ MINOR,
16
+ PY,
17
+ VULNERABILITY,
18
+ Analyzer,
19
+ Finding,
20
+ Result,
21
+ ToolError,
22
+ by_prefix,
23
+ is_test_file,
24
+ )
25
+
26
+ # Rule families enabled on top of a project's own ruff config; S (bandit) is left to bandit itself.
27
+ RUFF_EXTEND_SELECT = [
28
+ "B", "SIM", "C4", "PERF", "RET", "ARG", "ERA", "FIX", "PLE", "PLW", "PLR", "PIE", "RUF", "DTZ", "BLE",
29
+ "TRY", "ASYNC", "DJ", "LOG", "G", "INT", "EXE", "T10",
30
+ ]
31
+ # Codes that are noise for whole-repo quality tracking (style nits, or covered by radon/complexipy).
32
+ RUFF_EXTEND_IGNORE = ["PLR2004", "PLR0911", "PLR0912", "PLR0915", "PLR0914", "PLR0917", "TRY003", "RUF012"]
33
+
34
+ RUFF_RULES = [
35
+ ("E9", BLOCKER, BUG),
36
+ ("F82", CRITICAL, BUG),
37
+ ("F63", MAJOR, BUG),
38
+ ("F7", MAJOR, BUG),
39
+ ("PLE", MAJOR, BUG),
40
+ ("ASYNC", MAJOR, BUG),
41
+ ("T10", MAJOR, BUG),
42
+ ("B", MAJOR, BUG),
43
+ ("PLW", MINOR, BUG),
44
+ ("DTZ", MINOR, BUG),
45
+ ("BLE", MINOR, BUG),
46
+ ("S", MAJOR, HOTSPOT),
47
+ ("FIX", INFO, CODE_SMELL),
48
+ ]
49
+
50
+ # Parameters whose names are dictated by a framework (Django views/migrations/signals, pytest fixtures).
51
+ FRAMEWORK_ARGS = {"request", "schema_editor", "apps", "sender", "args", "kwargs", "context", INFO}
52
+ UNUSED_ARG_RE = re.compile(r"`(\w{1,100})`")
53
+
54
+
55
+ def framework_required(code, message, path):
56
+ if not code or not code.startswith("ARG"):
57
+ return False
58
+ if is_test_file(path):
59
+ return True
60
+ match = UNUSED_ARG_RE.search(message)
61
+ return bool(match) and match[1] in FRAMEWORK_ARGS
62
+
63
+
64
+ BANDIT_SEVERITY = {"HIGH": CRITICAL, "MEDIUM": MAJOR, "LOW": MINOR}
65
+ DOWNGRADE = {CRITICAL: MAJOR, MAJOR: MINOR, MINOR: INFO}
66
+
67
+
68
+ def complexity_severity(value, threshold):
69
+ return CRITICAL if value > 2 * threshold else MAJOR
70
+
71
+
72
+ class Ruff(Analyzer):
73
+ name = executable = "ruff"
74
+ extensions = PY
75
+
76
+ def run(self, ctx):
77
+ files = ctx.files_with(PY)
78
+ # --no-fix: a project's own `fix = true` (flaskbb) would otherwise rewrite the files being scanned.
79
+ args = ["check", "--no-fix", "--output-format", "json", "--exit-zero", "--no-cache",
80
+ "--extend-select", ",".join(RUFF_EXTEND_SELECT), "--extend-ignore", ",".join(RUFF_EXTEND_IGNORE),
81
+ *files]
82
+ try:
83
+ out = self.exec(args, ctx)
84
+ except ToolError as e:
85
+ # A repository pinning another ruff (langflow: required-version) stops ruff altogether; its other
86
+ # settings are then ignored rather than losing every finding.
87
+ if "Required version" not in str(e):
88
+ raise
89
+ out = self.exec(["--isolated", *args], ctx)
90
+ result = Result()
91
+ for item in json.loads(out or "[]"):
92
+ code = item.get("code")
93
+ if framework_required(code, item["message"], ctx.rel(item["filename"])):
94
+ continue
95
+ if code is None:
96
+ severity, type_ = BLOCKER, BUG
97
+ rule = "syntax-error"
98
+ else:
99
+ severity, type_ = by_prefix(code, RUFF_RULES, (MINOR, CODE_SMELL))
100
+ rule = code
101
+ result.findings.append(
102
+ Finding(
103
+ "ruff",
104
+ rule,
105
+ severity,
106
+ type_,
107
+ item["message"],
108
+ ctx.rel(item["filename"]),
109
+ item["location"]["row"],
110
+ item.get("end_location", {}).get("row"),
111
+ )
112
+ )
113
+ return result
114
+
115
+
116
+ # B101 (assert) fires on every pytest assertion. B404/B603/B607 flag importing subprocess and calling it with an
117
+ # argument list, which is the safe way to call it; B602/B605 still catch shell=True and os.system.
118
+ BANDIT_SKIPPED = ("B101", "B404", "B603", "B607")
119
+ # random is only a weakness when it makes something an attacker must not guess. The function around the call
120
+ # (its name, docstring and what it stores the value in) says what the number is for.
121
+ SECRET_USE_RE = re.compile(
122
+ r"(?i)\b(?:\w*session[ _]?id\w*|\w*token|token_\w+|\w*secret\w*|\w*passw\w*|pwd|\w*nonce|\w*salt|otp|\w*csrf\w*"
123
+ r"|\w*api_?key\w*|auth|auth_\w+|authenticat\w*|authoriz\w*|cred|credentials?|cipher\w*|(?!crypto\b)\w*crypt\w*"
124
+ # Keys that name a slot rather than a secret (cache_key, sort_key) aren't.
125
+ r"|unpredictable|\w*cookie\w*|\w*remember\w*|(?!\w*(?:cache|sort|dict|map|lookup|group|partition|primary|foreign"
126
+ r"|row|field|column|item|query|storage|bucket|translation|idempotency)_key\b)\w+_key|iv)\b"
127
+ r"|session\s{0,5}\[|\bkey\s{0,5}=[^=\n]{0,80}rand",
128
+ )
129
+ CONTEXT_LINES = 5
130
+ # A weak digest is a weakness where it stores a password (fast to brute-force) or vouches for data against
131
+ # forgery (collisions: signatures, certificates, integrity checks). A token or code derived from a secret, an
132
+ # HMAC or a cache key keeps its secret: preimages of MD5 and SHA-1 are still out of reach (outline's deletion
133
+ # code from the user's JWT secret; TOTP is HMAC-SHA-1 by standard).
134
+ SECURITY_PURPOSE_RE = re.compile(
135
+ r"\b(?:(?=\w*(?:passw|credential|salt))\w+|pwd|passphrase|(?!crypto\b)(?=\w*crypt)\w+"
136
+ r"|(?=(?:\w+_)?(?:cert|verif))\w+|(?=(?:\w+_)?(?:sign(?:ed|er|ing|atures?)?|integrity)\b)\w+)\b", re.IGNORECASE)
137
+
138
+
139
+ def security_purpose(cache, path, line):
140
+ """The code around a finding is about secrets or verification: the innermost Python function, else the
141
+ enclosing function found by indentation, within a window."""
142
+ if path.endswith(".py"):
143
+ text = cache.function_text(path, line)
144
+ else:
145
+ text = enclosing_function_text(cache.lines(path), line, 2 * CONTEXT_LINES)
146
+ return bool(SECURITY_PURPOSE_RE.search(text))
147
+
148
+
149
+ # A line that opens a function: `function f(`, an arrow, or a method `name(...) {` (not if/for/while/switch/catch).
150
+ FUNCTION_HEADER_RE = re.compile(
151
+ r"\bfunction\b|=>|^\s*(async\s+|static\s+|public\s+|private\s+|protected\s+|get\s+|set\s+)*"
152
+ r"(?!(if|for|while|switch|catch|with|return)\b)[\w$]+\s*\(.*\)\s*(?::[^={:]*)?\{\s*$")
153
+
154
+
155
+ def enclosing_function_text(rows, line, limit):
156
+ """The lines of the function around a JS/TS line, by indentation, at most limit lines either side: what a
157
+ neighbouring method does (immich: hashSha1 next to a signature check) isn't this code's purpose. Blocks such as
158
+ if/for are walked through, so the handler's earlier `const password = ...` still counts."""
159
+ i = line - 1
160
+ if not 0 <= i < len(rows):
161
+ return ""
162
+
163
+ def indent(text):
164
+ return len(text) - len(text.lstrip())
165
+
166
+ level, start = indent(rows[i]), i
167
+ # A line that opens a function (`sha1: (b) => createHash('sha1')...`) is its own context, not its siblings'.
168
+ for j in range(i - 1, max(-1, i - 1 - limit), -1) if not FUNCTION_HEADER_RE.search(rows[i]) else ():
169
+ if not rows[j].strip():
170
+ continue
171
+ if indent(rows[j]) < level:
172
+ level = indent(rows[j])
173
+ if FUNCTION_HEADER_RE.search(rows[j]):
174
+ start = j
175
+ break
176
+ start = j
177
+ end = i
178
+ for j in range(i + 1, min(len(rows), i + 1 + limit)):
179
+ if rows[j].strip() and indent(rows[j]) <= level:
180
+ break
181
+ end = j
182
+ return "\n".join(rows[start:end + 1])
183
+
184
+
185
+ def is_random_call(call):
186
+ func = call.func
187
+ return (isinstance(func, ast.Attribute) and isinstance(func.value, ast.Name) and func.value.id == "random") or (
188
+ isinstance(func, ast.Name) and func.id in RANDOM_FUNCTIONS)
189
+
190
+
191
+ def random_function_name(call):
192
+ return call.func.attr if isinstance(call.func, ast.Attribute) else call.func.id
193
+
194
+
195
+ RANDOM_FUNCTIONS = {"random", "randint", "randrange", "choice", "choices", "sample", "shuffle", "uniform",
196
+ "getrandbits", "randbytes", "normalvariate", "gauss", "triangular"}
197
+
198
+
199
+ def passed_as(node, parents):
200
+ """The keyword a node is passed as, looking up through enclosing expressions within its statement, or None."""
201
+ while node in parents and not isinstance(node, ast.stmt):
202
+ if isinstance(parents[node], ast.keyword) and parents[node].arg:
203
+ return parents[node].arg
204
+ node = parents[node]
205
+ return None
206
+
207
+
208
+ class LineCache:
209
+ def __init__(self, root):
210
+ self.root, self.files, self.trees = Path(root), {}, {}
211
+
212
+ def lines(self, path):
213
+ if path not in self.files:
214
+ try:
215
+ self.files[path] = (self.root / path).read_text(errors="replace").splitlines()
216
+ except OSError:
217
+ self.files[path] = []
218
+ return self.files[path]
219
+
220
+ def get(self, path, line):
221
+ rows = self.lines(path)
222
+ return rows[line - 1] if 0 < line <= len(rows) else ""
223
+
224
+ def purpose_text(self, path, line):
225
+ """What a random value on this line is for: the keyword it is passed as (rtt_ms=random.uniform(...) is about
226
+ rtt_ms, whatever else the function does), else the surrounding function."""
227
+ tree = self.tree(path)
228
+ parents = {child: node for node in ast.walk(tree) for child in ast.iter_child_nodes(node)} if tree else {}
229
+ for call in parents:
230
+ if (isinstance(call, ast.Call) and call.lineno == line and is_random_call(call)
231
+ and (keyword := passed_as(call, parents))):
232
+ return keyword
233
+ return self.function_text(path, line)
234
+
235
+ def only_shuffles(self, path, line):
236
+ """random.shuffle() reorders data and makes no value an attacker could guess."""
237
+ calls = [n for n in ast.walk(self.tree(path) or ast.Module(body=[], type_ignores=[]))
238
+ if isinstance(n, ast.Call) and n.lineno == line and is_random_call(n)]
239
+ return bool(calls) and all(random_function_name(c) == "shuffle" for c in calls)
240
+
241
+ def tree(self, path):
242
+ if path not in self.trees:
243
+ try:
244
+ self.trees[path] = ast.parse("\n".join(self.lines(path)))
245
+ except (SyntaxError, ValueError):
246
+ self.trees[path] = None
247
+ return self.trees[path]
248
+
249
+ def function_text(self, path, line):
250
+ """Source of the innermost function around a line, or a few lines either side at module level."""
251
+ around = [n for n in ast.walk(self.tree(path) or ast.Module(body=[], type_ignores=[]))
252
+ if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef))
253
+ and n.lineno <= line <= (n.end_lineno or n.lineno)]
254
+ if around:
255
+ inner = max(around, key=lambda n: n.lineno)
256
+ start, end = inner.lineno, inner.end_lineno or line
257
+ else:
258
+ start, end = max(1, line - CONTEXT_LINES), line + CONTEXT_LINES
259
+ return "\n".join(self.lines(path)[start - 1:end])
260
+
261
+
262
+ class Bandit(Analyzer):
263
+ name = executable = "bandit"
264
+ extensions = PY
265
+
266
+ def run(self, ctx):
267
+ out = self.exec(["-f", "json", "-q", "--exit-zero", "-s", ",".join(BANDIT_SKIPPED), *ctx.files_with(PY)], ctx)
268
+ result = Result()
269
+ source = LineCache(ctx.root)
270
+ for item in json.loads(out)["results"]:
271
+ # random() making a token, key or session id is a definite weakness; elsewhere it's not one at all.
272
+ if item["test_id"] == "B311" and (
273
+ source.only_shuffles(item["filename"], item["line_number"])
274
+ or not SECRET_USE_RE.search(source.purpose_text(item["filename"], item["line_number"]))):
275
+ continue
276
+ type_ = VULNERABILITY if item["test_id"] == "B311" else HOTSPOT
277
+ severity = BANDIT_SEVERITY.get(item["issue_severity"], MINOR)
278
+ if item["issue_confidence"] == "LOW":
279
+ severity = DOWNGRADE[severity]
280
+ # bandit matches API use without following data, so its findings are things to review, not verdicts.
281
+ lines = item.get("line_range") or [item["line_number"]]
282
+ result.findings.append(
283
+ Finding(
284
+ "bandit",
285
+ f"{item['test_id']}:{item['test_name']}",
286
+ severity,
287
+ type_,
288
+ item["issue_text"],
289
+ ctx.rel(item["filename"]),
290
+ item["line_number"],
291
+ max(lines),
292
+ )
293
+ )
294
+ return result
295
+
296
+
297
+ class Radon(Analyzer):
298
+ name = executable = "radon"
299
+ extensions = PY
300
+
301
+ def run(self, ctx):
302
+ files = [str(ctx.root / f) for f in ctx.files_with(PY)]
303
+ threshold = ctx.complexity_threshold
304
+ result = Result()
305
+ # Run outside the repository: radon loads its pyproject.toml's whole [tool] table into configparser, which
306
+ # fails on any value with a "%" (langflow's pytest log format).
307
+ with tempfile.TemporaryDirectory() as cwd:
308
+ cc = self.exec(["cc", "-j", *files], ctx, cwd=cwd)
309
+ mi_out = self.exec(["mi", "-j", *files], ctx, cwd=cwd)
310
+ functions = radon_functions(json.loads(cc))
311
+ result.findings = [radon_finding(ctx, path, b, threshold) for path, b in functions
312
+ if b["complexity"] > threshold]
313
+ result.metrics["complexity_python"] = sum(b["complexity"] for _, b in functions)
314
+ mi = [v["mi"] for v in json.loads(mi_out).values() if "mi" in v]
315
+ if mi:
316
+ result.metrics["maintainability_index"] = round(sum(mi) / len(mi), 1)
317
+ return result
318
+
319
+
320
+ def radon_functions(report):
321
+ """(path, block) for every function and method; files radon couldn't parse map to an error dict."""
322
+ out = []
323
+ for path, blocks in report.items():
324
+ if isinstance(blocks, list):
325
+ out += [(path, b) for b in blocks if b["type"] in ("function", "method")]
326
+ return out
327
+
328
+
329
+ def radon_finding(ctx, path, block, threshold):
330
+ name = f"{block['classname']}.{block['name']}" if block.get("classname") else block["name"]
331
+ return Finding("radon", "cyclomatic-complexity", complexity_severity(block["complexity"], threshold),
332
+ CODE_SMELL, f"{name} has cyclomatic complexity {block['complexity']} (threshold {threshold})",
333
+ ctx.rel(path), block["lineno"], block["endline"])
@@ -0,0 +1,237 @@
1
+ """Give Flask view arguments the type of their URL converter, for Semgrep's taint rules.
2
+
3
+ A Flask view's arguments come from the URL path: `@app.route("/user/<name>") def user(name)`. Only the default,
4
+ `string` and `path` converters pass free text; the others (`int`, `uuid`, `any(a, b)`, and an app's own, usually a
5
+ regex) limit the value. A Semgrep pattern can't tie the converter in the route string to the parameter of the same
6
+ name, so on the copy Semgrep scans such a parameter gets an annotation (`id: int`, `key: uuid.UUID`, `tag: uuid_str`),
7
+ which the request-source rules skip like any typed FastAPI parameter. Only unannotated parameters change, and every
8
+ line keeps its number.
9
+ """
10
+ import ast
11
+ import re
12
+
13
+ from .base import python_tree
14
+
15
+ CONVERTER_RE = re.compile(r"<(\w+)(?:\([^()<>]*\))?:(\w+)>")
16
+ TEXT_CONVERTERS = {"string", "path"}
17
+ TYPES = {"uuid": "uuid.UUID"}
18
+ # Flask-AppBuilder and Flask-Admin route a view class's methods with @expose("/path/<arg>"), imported bare.
19
+ ROUTE_DECORATORS = {"route", "get", "post", "put", "patch", "delete", "expose"}
20
+ BARE_ROUTE_DECORATORS = {"expose"}
21
+
22
+
23
+ def route_path(decorator):
24
+ """The path string of a route decorator (@app.route("/x/<int:id>"), @expose("/x")), else None."""
25
+ if not (isinstance(decorator, ast.Call) and decorator.args and call_name(decorator.func) in ROUTE_DECORATORS):
26
+ return None
27
+ if isinstance(decorator.func, ast.Name) and decorator.func.id not in BARE_ROUTE_DECORATORS:
28
+ return None
29
+ path = decorator.args[0]
30
+ return path.value if isinstance(path, ast.Constant) and isinstance(path.value, str) else None
31
+
32
+
33
+ def converter_types(node):
34
+ """{parameter: annotation} from the converters other than string and path in a function's route decorators."""
35
+ return {name: TYPES.get(converter, converter)
36
+ for path in filter(None, map(route_path, node.decorator_list))
37
+ for converter, name in CONVERTER_RE.findall(path) if converter not in TEXT_CONVERTERS}
38
+
39
+
40
+ def type_route_converters(source):
41
+ """The source with converter-typed view parameters annotated, or None if there are none."""
42
+ if "<" not in source or ":" not in source:
43
+ return None
44
+ try:
45
+ tree = ast.parse(source)
46
+ except (SyntaxError, ValueError):
47
+ return None
48
+ edits = []
49
+ for node in ast.walk(tree):
50
+ if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) or not node.decorator_list:
51
+ continue
52
+ types = converter_types(node)
53
+ edits.extend((arg.lineno, arg.end_col_offset, f": {types[arg.arg]}")
54
+ for arg in node.args.posonlyargs + node.args.args + node.args.kwonlyargs
55
+ if arg.arg in types and arg.annotation is None)
56
+ return annotated(source, edits)
57
+
58
+
59
+ def annotated(source, edits):
60
+ """The source with each (line, column, text) inserted, or None if there are none."""
61
+ if not edits:
62
+ return None
63
+ lines = source.splitlines(keepends=True)
64
+ for row, col, text, *replaced in sorted(edits, reverse=True):
65
+ # ast columns count UTF-8 bytes. An edit may replace that many bytes (a 4-tuple) rather than only insert.
66
+ raw = lines[row - 1].encode()
67
+ lines[row - 1] = (raw[:col] + text.encode() + raw[col + sum(replaced):]).decode()
68
+ return "".join(lines)
69
+
70
+
71
+ # Django routes its URLs in urls.py: path("files/<path:name>", views.serve) or re_path(r"^files/(?P<name>.*)$", serve).
72
+ # A view's arguments past the request come from the URL; those whose converter or regex group lets through free
73
+ # text (str, path, or a group that allows dots or excludes characters, like .* or [^/]+) are marked on the copy
74
+ # Semgrep scans with the annotation URL_TEXT, which the request-source rule matches. <int:pk>, <slug:slug>, [\w-]+
75
+ # and \d+ can't carry a path, quotes or markup, and a view the analysis can't see routed stays unmarked.
76
+ URL_TEXT = "codewatch_url_text"
77
+ DJANGO_ROUTES = {"path", "re_path", "url"}
78
+ PATH_PARAMETER_RE = re.compile(r"<(?:(\w+):)?(\w+)>")
79
+ TEXT_PATH_CONVERTERS = {"", "str", "path"}
80
+ # A group starts at an unescaped "(": `\(?P<` is a literal parenthesis, and starting there read the rest of the route.
81
+ GROUP_RE = re.compile(r"(?<!\\)\(\?P<(\w+)>((?:[^()\\]|\\.|\((?:[^()\\]|\\.)*\))*)\)")
82
+ TEXT_GROUP_RE = re.compile(r"\.|\[\^|\\[SWD]")
83
+
84
+
85
+ def joined_text(node):
86
+ return "".join(part.value for part in node.values if isinstance(part, ast.Constant) and isinstance(part.value, str))
87
+
88
+
89
+ def added_text(node):
90
+ left, right = constant_text(node.left), constant_text(node.right)
91
+ return None if left is None and right is None else (left or "") + (right or "")
92
+
93
+
94
+ def constant_text(node):
95
+ """A route string: a constant, 'constant'.format(...), an f-string's constant parts or constants added."""
96
+ if isinstance(node, ast.Constant):
97
+ return node.value if isinstance(node.value, str) else None
98
+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute) and node.func.attr == "format":
99
+ return constant_text(node.func.value)
100
+ if isinstance(node, ast.JoinedStr):
101
+ return joined_text(node)
102
+ if isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add):
103
+ return added_text(node)
104
+ return None
105
+
106
+
107
+ def call_name(node):
108
+ return node.id if isinstance(node, ast.Name) else node.attr if isinstance(node, ast.Attribute) else None
109
+
110
+
111
+ def django_text_parameters(sources):
112
+ """{view function name: {parameter}} for the URL arguments Django's routes pass as free text, from the
113
+ urlpatterns in sources."""
114
+ views = {}
115
+ for tree in filter(None, (python_tree(source) for source in sources if "urlpatterns" in source)):
116
+ for node in ast.walk(tree):
117
+ if found := route_text_parameters(node):
118
+ views.setdefault(found[0], set()).update(found[1])
119
+ return views
120
+
121
+
122
+ def text_names(route, function):
123
+ """The free-text parameters of a route: path() converters that take text, re_path() groups that match it."""
124
+ if function == "path":
125
+ return {name for converter, name in PATH_PARAMETER_RE.findall(route) if converter in TEXT_PATH_CONVERTERS}
126
+ return {name for name, group in GROUP_RE.findall(route) if TEXT_GROUP_RE.search(group)}
127
+
128
+
129
+ def route_text_parameters(node):
130
+ """(view name, {free-text parameters}) for a path()/re_path() call with both, else None."""
131
+ if not (isinstance(node, ast.Call) and call_name(node.func) in DJANGO_ROUTES and len(node.args) >= 2):
132
+ return None
133
+ route, view = constant_text(node.args[0]), call_name(node.args[1])
134
+ names = text_names(route, call_name(node.func)) if route is not None and view is not None else set()
135
+ return (view, names) if names else None
136
+
137
+
138
+ def mark_url_text(source, views):
139
+ """The source with the free-text URL arguments of the function views in views annotated URL_TEXT, or None."""
140
+ if not views or not any(name in source for name in views):
141
+ return None
142
+ tree = python_tree(source)
143
+ if tree is None:
144
+ return None
145
+ return annotated(source, [edit for node in ast.walk(tree)
146
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name in views
147
+ for edit in url_text_edits(node, views[node.name])])
148
+
149
+
150
+ def url_text_edits(view, names):
151
+ """URL_TEXT annotations for a request view's unannotated parameters among names."""
152
+ arguments = view.args.posonlyargs + view.args.args + view.args.kwonlyargs
153
+ if not arguments or arguments[0].arg != "request":
154
+ return []
155
+ return [(arg.lineno, arg.end_col_offset, f": {URL_TEXT}")
156
+ for arg in arguments[1:] if arg.arg in names and arg.annotation is None]
157
+
158
+
159
+ SCALAR_RE = re.compile(r"^(typing\.)?(Optional\[)?(int|float|bool|(uuid\.)?UUID|(datetime\.)?(date|datetime|time)|"
160
+ r"(decimal\.)?Decimal|uuid_str)\]?$|^(int|float|bool) \| None$")
161
+
162
+
163
+ def scalar_parameters(source):
164
+ """{(function, parameter)} for parameters annotated with a type that can't carry text: int, bool, UUID, a date,
165
+ or (after type_route_converters) a Flask converter other than string and path."""
166
+ source = type_route_converters(source) or source
167
+ try:
168
+ tree = ast.parse(source)
169
+ except (SyntaxError, ValueError):
170
+ return set()
171
+ return {(node.name, arg.arg)
172
+ for node in ast.walk(tree) if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))
173
+ for arg in node.args.posonlyargs + node.args.args + node.args.kwonlyargs
174
+ if arg.annotation is not None and SCALAR_RE.match(ast.unparse(arg.annotation))}
175
+
176
+
177
+ # Django REST framework's routers send /things/<lookup>/ to a ViewSet's detail methods (retrieve, update,
178
+ # partial_update, destroy and @action(detail=True) ones) as the keyword argument lookup_url_kwarg, else lookup_field,
179
+ # else pk, matched by lookup_value_regex: '[^/.]+' unless the class narrows it. That passes markup and quotes, so the
180
+ # argument is marked URL_TEXT like a Django route's free-text argument, unless the class's regex can't carry text
181
+ # (\d+, [0-9a-f-]+). CVAT CVE-2024-47064 (retrieve(self, request, pk: str) into an HttpResponseNotFound).
182
+ VIEWSET_BASE_RE = re.compile(r"(ViewSet|ViewSetMixin)$")
183
+ DETAIL_METHODS = {"retrieve", "update", "partial_update", "destroy"}
184
+
185
+
186
+ def class_constant(cls, name):
187
+ """The string a class body assigns to name, if any."""
188
+ for stmt in cls.body:
189
+ if (isinstance(stmt, ast.Assign) and any(isinstance(t, ast.Name) and t.id == name for t in stmt.targets)
190
+ and isinstance(stmt.value, ast.Constant) and isinstance(stmt.value.value, str)):
191
+ return stmt.value.value
192
+ return None
193
+
194
+
195
+ def viewset_lookup(cls):
196
+ """The URL argument a DRF ViewSet's detail methods receive, or None if it isn't a ViewSet or can't carry text."""
197
+ if not any(VIEWSET_BASE_RE.search(call_name(base) or "") for base in cls.bases):
198
+ return None
199
+ regex = class_constant(cls, "lookup_value_regex")
200
+ if regex is not None and not TEXT_GROUP_RE.search(regex):
201
+ return None
202
+ return class_constant(cls, "lookup_url_kwarg") or class_constant(cls, "lookup_field") or "pk"
203
+
204
+
205
+ def detail_action(method):
206
+ """Whether a ViewSet method takes the object's lookup from the URL: a standard detail method or @action(detail=True)."""
207
+ return method.name in DETAIL_METHODS or any(
208
+ isinstance(d, ast.Call) and call_name(d.func) == "action"
209
+ and any(k.arg == "detail" and isinstance(k.value, ast.Constant) and k.value.value is True for k in d.keywords)
210
+ for d in method.decorator_list)
211
+
212
+
213
+ def lookup_edits(method, lookup):
214
+ """Edits marking a detail method's lookup argument URL_TEXT: an unannotated one, or one annotated str."""
215
+ edits = []
216
+ for arg in (method.args.posonlyargs + method.args.args + method.args.kwonlyargs)[2:]:
217
+ if arg.arg != lookup:
218
+ continue
219
+ if arg.annotation is None:
220
+ edits.append((arg.lineno, arg.end_col_offset, f": {URL_TEXT}"))
221
+ elif isinstance(arg.annotation, ast.Name) and arg.annotation.id == "str" and arg.annotation.lineno == arg.lineno:
222
+ edits.append((arg.lineno, arg.annotation.col_offset, URL_TEXT, len("str")))
223
+ return edits
224
+
225
+
226
+ def mark_viewset_lookups(source):
227
+ """The source with DRF ViewSets' free-text lookup arguments annotated URL_TEXT, or None."""
228
+ if "ViewSet" not in source:
229
+ return None
230
+ tree = python_tree(source)
231
+ if tree is None:
232
+ return None
233
+ edits = [edit for cls in ast.walk(tree) if isinstance(cls, ast.ClassDef) and (lookup := viewset_lookup(cls))
234
+ for method in cls.body
235
+ if isinstance(method, (ast.FunctionDef, ast.AsyncFunctionDef)) and detail_action(method)
236
+ for edit in lookup_edits(method, lookup)]
237
+ return annotated(source, edits)
@@ -0,0 +1,94 @@
1
+ """Rewrite Python slices as tuple indexes (x[a:b] -> x[a, b]) for Semgrep's taint analysis.
2
+
3
+ Semgrep OSS stops tracking taint through a slice, so `bar = param[5:]` loses the request data that flowed into
4
+ it, while `param[5]` keeps it. Scanning a copy with every slice turned into an index keeps the data flow. The copy
5
+ is only ever scanned, never run, and every token stays on its original line, so findings map back unchanged.
6
+ """
7
+ import io
8
+ import keyword
9
+ import tokenize
10
+
11
+ OPENERS, CLOSERS = "([{", ")]}"
12
+ # A "[" after one of these starts a subscript; after anything else (an operator, a keyword, "(") it's a list.
13
+ SUBSCRIPTABLE_TOKENS = {tokenize.NAME, tokenize.STRING, tokenize.NUMBER}
14
+ FSTRING_END = getattr(tokenize, "FSTRING_END", None)
15
+
16
+
17
+ def is_subscript(prev):
18
+ if prev is None:
19
+ return False
20
+ if prev.type == tokenize.NAME:
21
+ return not keyword.iskeyword(prev.string) or prev.string in ("None", "True", "False")
22
+ if prev.type == tokenize.OP:
23
+ return prev.string in (")", "]")
24
+ return prev.type in SUBSCRIPTABLE_TOKENS or prev.type == FSTRING_END
25
+
26
+
27
+ SKIPPED_TOKENS = (tokenize.NL, tokenize.NEWLINE, tokenize.COMMENT, tokenize.INDENT, tokenize.DEDENT)
28
+
29
+
30
+ def is_op(tok, strings):
31
+ return tok.type == tokenize.OP and tok.string in strings
32
+
33
+
34
+ def open_frame(tok, prev):
35
+ return {"subscript": tok.string == "[" and is_subscript(prev), "colons": [], "lambda": False, "last": tok}
36
+
37
+
38
+ def close_frame(stack):
39
+ """The colon edits of the bracket a closer ends: a subscript's, unless a lambda inside it holds the colons."""
40
+ frame = stack.pop() if stack else None
41
+ return frame["colons"] if frame and frame["subscript"] and frame["colons"] and not frame["lambda"] else []
42
+
43
+
44
+ def inner_token(frame, tok):
45
+ """A token inside brackets: a lambda, or a subscript's top-level colon, which becomes ", " (with None for an
46
+ empty bound before it)."""
47
+ if tok.type == tokenize.NAME and tok.string == "lambda":
48
+ frame["lambda"] = True
49
+ elif frame["subscript"] and is_op(tok, ":"):
50
+ empty_before = is_op(frame["last"], ("[", ",", ":"))
51
+ colon = [*tok.start, ":", "None, " if empty_before else ", "]
52
+ frame["colons"].append(colon)
53
+ frame["pending"] = colon
54
+
55
+
56
+ def slice_edits(source):
57
+ """[row, col, old, new] edits turning each top-level ":" of a subscript into ", ", with None for empty bounds."""
58
+ edits, stack, prev = [], [], None
59
+ for tok in tokenize.generate_tokens(io.StringIO(source).readline):
60
+ if tok.type in SKIPPED_TOKENS:
61
+ continue
62
+ if stack and (pending := stack[-1].pop("pending", None)) and is_op(tok, ","):
63
+ # x[:, i] and x[a:, i]: the next comma already separates, so the colon adds no ", " of its own.
64
+ pending[3] = pending[3][:-2]
65
+ if is_op(tok, OPENERS):
66
+ stack.append(open_frame(tok, prev))
67
+ elif is_op(tok, CLOSERS):
68
+ edits += close_frame(stack)
69
+ elif stack:
70
+ inner_token(stack[-1], tok)
71
+ if stack:
72
+ stack[-1]["last"] = tok
73
+ prev = tok
74
+ return edits
75
+
76
+
77
+ def index_slices(source):
78
+ """The source with slices rewritten, or None if it has none (or doesn't tokenize)."""
79
+ if "[" not in source or ":" not in source:
80
+ return None
81
+ try:
82
+ edits = slice_edits(source)
83
+ except (tokenize.TokenError, IndentationError, SyntaxError):
84
+ return None
85
+ if not edits:
86
+ return None
87
+ lines = source.splitlines(keepends=True)
88
+ for row, col, old, new in sorted(edits, reverse=True):
89
+ line = lines[row - 1]
90
+ if line[col:col + len(old)] != old:
91
+ return None
92
+ lines[row - 1] = line[:col] + new + line[col + len(old):]
93
+ return "".join(lines)
94
+