codefactory-cli 0.20.1__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 (61) hide show
  1. codefactory/__init__.py +3 -0
  2. codefactory/__main__.py +5 -0
  3. codefactory/accept.py +68 -0
  4. codefactory/analyzers/__init__.py +55 -0
  5. codefactory/analyzers/generic.py +392 -0
  6. codefactory/analyzers/parallel.py +113 -0
  7. codefactory/analyzers/python.py +279 -0
  8. codefactory/analyzers/python_parse.py +402 -0
  9. codefactory/analyzers/treewalk.py +299 -0
  10. codefactory/analyzers/ts_helper.js +483 -0
  11. codefactory/analyzers/typescript.py +118 -0
  12. codefactory/apple.py +80 -0
  13. codefactory/audit.py +227 -0
  14. codefactory/baseline.py +58 -0
  15. codefactory/brief.py +330 -0
  16. codefactory/cache.py +93 -0
  17. codefactory/checks.py +608 -0
  18. codefactory/cli.py +782 -0
  19. codefactory/config.py +157 -0
  20. codefactory/coverage.py +104 -0
  21. codefactory/deps.py +182 -0
  22. codefactory/diff.py +197 -0
  23. codefactory/efficiency.py +250 -0
  24. codefactory/flags.py +263 -0
  25. codefactory/graph.py +95 -0
  26. codefactory/hotspots.py +344 -0
  27. codefactory/infra.py +242 -0
  28. codefactory/intent.py +106 -0
  29. codefactory/layers.py +143 -0
  30. codefactory/org.py +131 -0
  31. codefactory/owners.py +72 -0
  32. codefactory/patch.py +81 -0
  33. codefactory/paths.py +93 -0
  34. codefactory/plan.py +476 -0
  35. codefactory/privacy.py +221 -0
  36. codefactory/profile.py +667 -0
  37. codefactory/rerank.py +161 -0
  38. codefactory/review.py +1504 -0
  39. codefactory/rules.py +50 -0
  40. codefactory/sarif.py +661 -0
  41. codefactory/sbom.py +78 -0
  42. codefactory/security.py +537 -0
  43. codefactory/similar.py +199 -0
  44. codefactory/skill.py +144 -0
  45. codefactory/skill_template/SKILL.md +68 -0
  46. codefactory/skill_template/__init__.py +0 -0
  47. codefactory/sqlgraph.py +109 -0
  48. codefactory/suppress.py +92 -0
  49. codefactory/taint.py +439 -0
  50. codefactory/trace.py +72 -0
  51. codefactory/viewer/__init__.py +19 -0
  52. codefactory/viewer/dashboard.html +43 -0
  53. codefactory/viewer/factory.css +61 -0
  54. codefactory/viewer/factory.js +665 -0
  55. codefactory/viewer/template.html +47 -0
  56. codefactory_cli-0.20.1.dist-info/METADATA +250 -0
  57. codefactory_cli-0.20.1.dist-info/RECORD +61 -0
  58. codefactory_cli-0.20.1.dist-info/WHEEL +5 -0
  59. codefactory_cli-0.20.1.dist-info/entry_points.txt +2 -0
  60. codefactory_cli-0.20.1.dist-info/licenses/LICENSE +21 -0
  61. codefactory_cli-0.20.1.dist-info/top_level.txt +1 -0
codefactory/checks.py ADDED
@@ -0,0 +1,608 @@
1
+ # codefactory: ignore-file secret, eval, shell, tls_off, raw_html, plain_http, swallowed, debug_on, cors_any, insecure_cookie, jwt_unverified, weak_cipher, weak_hash, weak_random, secret_key_literal, sensitive_storage — the patterns themselves # noqa: E501
2
+ """Repository and source checks for the review: security, reliability, delivery, dependencies, docs, testing.
3
+
4
+ Pattern checks read the source text (any comment style, both languages); repository checks read manifests and CI
5
+ files. Each returns Evidence: where (file:line), what was seen, and a short excerpt, so a reader can verify it.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import os
12
+ import re
13
+ from collections import deque
14
+ from dataclasses import dataclass, field
15
+ from pathlib import Path
16
+
17
+ from .brief import View
18
+ from .intent import interp_safe, push_skip_explained, safe_names, swallow_intent
19
+ from .paths import is_test
20
+ from .suppress import MARK
21
+ from .suppress import _parse as parse_mark
22
+
23
+ SRC_EXT = (
24
+ ".py", ".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".mts", ".cts",
25
+ ".go", ".java", ".kt", ".kts", ".swift", ".rs", ".c", ".h", ".cc", ".cpp", ".hpp", ".cs", ".rb", ".php", ".scala",
26
+ ".dart", ".lua", ".ex", ".exs", ".m", ".mm", ".sh",
27
+ ) # fmt: skip
28
+
29
+
30
+ @dataclass
31
+ class Evidence:
32
+ file: str
33
+ line: int
34
+ text: str # the line, trimmed
35
+
36
+ def at(self) -> str:
37
+ return f"{self.file}:{self.line}" if self.line else self.file
38
+
39
+
40
+ @dataclass
41
+ class Check:
42
+ key: str
43
+ hits: list[Evidence] = field(default_factory=list)
44
+ data: dict = field(default_factory=dict)
45
+
46
+
47
+ # ---- source patterns ------------------------------------------------------------------------------------------------
48
+
49
+ PATTERNS: dict[str, list[re.Pattern]] = {
50
+ "secret": [
51
+ # a key block: the header ends its line, or key data follows it in a string. Not a sentence about one
52
+ # ("wrapped within -----BEGIN … END-----") or a format check (`starts_with("-----BEGIN PRIVATE KEY-----")`)
53
+ re.compile(
54
+ r"-----BEGIN (?:RSA |EC |OPENSSH |DSA )?PRIVATE KEY-----[ \t]*$|"
55
+ r"-----BEGIN (?:RSA |EC |OPENSSH |DSA )?PRIVATE KEY-----(?:\\r)?\\n[A-Za-z0-9+/=]{16,}"
56
+ ),
57
+ re.compile(r"\bAKIA[0-9A-Z]{16}\b"),
58
+ re.compile(r"\b(?:ghp|gho|ghu|ghs)_[A-Za-z0-9]{36}\b"),
59
+ re.compile(r"\bxox[abpr]-[A-Za-z0-9-]{10,}"),
60
+ re.compile(r"\bsk_live_[A-Za-z0-9]{16,}"),
61
+ re.compile(r"\bAIza[0-9A-Za-z_-]{35}\b"),
62
+ re.compile(
63
+ r"""(?i)\b\w*(?:api[_-]?key|secret|token|passw(?:or)?d|auth)\w*\s*[:=]\s*['"](?=[^'"]*\d)[A-Za-z0-9+/_\-]{20,}['"]"""
64
+ ),
65
+ ],
66
+ "eval": [
67
+ re.compile(r"(?<![\w.])eval\s*\("),
68
+ re.compile(r"\bnew\s+Function\s*\("),
69
+ re.compile(r"(?<![\w.])exec\s*\(\s*[^)]"),
70
+ re.compile(r"\bpickle\.loads?\s*\("),
71
+ re.compile(r"\byaml\.load\s*\((?![^)]*SafeLoader)"),
72
+ ],
73
+ "shell": [
74
+ re.compile(r"shell\s*=\s*True"),
75
+ re.compile(r"\bos\.system\s*\((?!\s*[\"'][^\"'{}%]*[\"']\s*\))"), # not a fixed command: os.system("clear")
76
+ re.compile(r"\bexecSync\s*\(\s*`[^`]*\$\{"),
77
+ re.compile(r"\bchild_process\b.*\bexec\s*\("),
78
+ re.compile(r"(?<![\w.])(?:system|exec|spawn|IO\.popen|shell_exec|passthru)\s*\(?\s*\"[^\"]*(?:#|\$)\{"),
79
+ re.compile(r"`[^`]*#\{[^}]+\}[^`]*`|%x[({][^)}]*#\{"),
80
+ re.compile(r"(?<![\w.])exec(?:Sync)?\s*\(\s*(?:`[^`]*\$\{|[\"'][^\"']*[\"']\s*\+)"), # child_process exec()
81
+ re.compile(r"exec\.Command(?:Context)?\((?:\s*ctx\s*,)?\s*\"(?:ba|z)?sh\"\s*,\s*\"-c\"\s*,(?!\s*\"[^\"]*\"\s*\))"), # Go
82
+ ],
83
+ "tls_off": [
84
+ re.compile(r"verify\s*=\s*False"),
85
+ re.compile(r"rejectUnauthorized\s*:\s*false"),
86
+ re.compile(r"NODE_TLS_REJECT_UNAUTHORIZED"),
87
+ re.compile(r"ssl\._create_unverified_context"),
88
+ re.compile(r"CERT_NONE"),
89
+ re.compile(r"InsecureSkipVerify:\s*true"), # Go
90
+ ],
91
+ "raw_html": [
92
+ re.compile(r"dangerouslySetInnerHTML"),
93
+ re.compile(r"\.innerHTML\s*=(?!=)(?!\s*(?:\"\"|''|``)\s*;?\s*$)"), # not clearing it: `el.innerHTML = ""`
94
+ re.compile(r"\bv-html\b"),
95
+ re.compile(r"\{[{%][^}%\n]*\|\s*safe\b"), # a template's `{{ x | safe }}`, not `allow|safe` in a regex
96
+ re.compile(r"\bmark_safe\s*\("),
97
+ ],
98
+ "plain_http": [
99
+ re.compile(
100
+ r"""['"`]http://(?!localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\]|schemas\.|www\.w3\.org|xmlns)[a-z0-9][^'"`\s]*""", re.I
101
+ )
102
+ ],
103
+ "swallowed": [
104
+ re.compile(r"catch\s*(?:\([^)]*\))?\s*\{\s*\}"),
105
+ re.compile(r"\.catch\(\s*\(\s*\)\s*=>\s*(?:\{\s*\}|undefined|null)\s*\)"),
106
+ re.compile(r"except(?:\s+[\w.(), ]+)?\s*:\s*pass\b"),
107
+ ],
108
+ }
109
+ PATTERNS.update(
110
+ {
111
+ "debug_on": [
112
+ re.compile(r"^\s*DEBUG\s*=\s*True\b"),
113
+ re.compile(r"\.run\([^)]*debug\s*=\s*True"),
114
+ re.compile(r"\bapp\.debug\s*=\s*True"),
115
+ re.compile(r"FLASK_DEBUG\s*=\s*['\"]?1"),
116
+ ],
117
+ "cors_any": [
118
+ re.compile(r"allow_origins\s*=\s*\[\s*['\"]\*['\"]"),
119
+ re.compile(r"CORS_(?:ALLOW_ALL_ORIGINS|ORIGIN_ALLOW_ALL)\s*=\s*True"),
120
+ re.compile(r"Access-Control-Allow-Origin['\"]\s*[,:]\s*['\"]\*"),
121
+ re.compile(r"\borigin\s*:\s*['\"]\*['\"]"),
122
+ re.compile(r"(?<![\w.])CORS\(\s*app\s*\)"),
123
+ re.compile(r"(?<![\w.])cors\(\s*\)"),
124
+ ],
125
+ "insecure_cookie": [
126
+ re.compile(r"(?:SESSION|CSRF)_COOKIE_(?:SECURE|HTTPONLY)\s*=\s*False"),
127
+ re.compile(r"(?:secure|httponly)\s*=\s*False"),
128
+ re.compile(r"(?:httpOnly|secure)\s*:\s*false"),
129
+ ],
130
+ "jwt_unverified": [
131
+ re.compile(r"verify_(?:signature|exp)['\"]?\s*:\s*False"),
132
+ re.compile(r"jwt\.decode\([^)]*verify\s*=\s*False"),
133
+ re.compile(r"algorithms?\s*[:=]\s*\[?\s*['\"]none['\"]", re.I),
134
+ re.compile(r"ignoreExpiration\s*:\s*true"),
135
+ ],
136
+ "weak_cipher": [
137
+ re.compile(r"AES\.MODE_ECB|/ECB/|['\"]aes-\d+-ecb['\"]", re.I),
138
+ re.compile(r"\b(?:DES|DES3|RC4|ARC4|Blowfish)\.new\(|createCipheriv\(\s*['\"](?:des|rc4|bf)", re.I),
139
+ ],
140
+ "weak_hash": [
141
+ re.compile(r"hashlib\.(?:md5|sha1)\(|createHash\(\s*['\"](?:md5|sha1)['\"]"),
142
+ re.compile(r"MessageDigest\.getInstance\(\s*\"(?:MD5|SHA-?1)\""),
143
+ re.compile(r"\b(?:md5|sha1)\.(?:Sum|New)\(|\bInsecure\.(?:MD5|SHA1)\b|\bDigest::(?:MD5|SHA1)\b"),
144
+ ],
145
+ "weak_random": [
146
+ re.compile(r"(?<![\w.])random\.(?:random|randint|choice|choices|getrandbits|randrange)\("),
147
+ re.compile(r"Math\.random\(\)"),
148
+ # Go's math/rand (crypto/rand has none of these): rand.Intn, rand.Int63, rand.Uint64…
149
+ re.compile(r"(?<![\w.])rand\.(?:Intn|Int63n?|Int31n?|Uint32|Uint64|Float64|Perm|Shuffle)\("),
150
+ ],
151
+ "secret_key_literal": [
152
+ re.compile(r"^\s*(?:SECRET_KEY|JWT_SECRET(?:_KEY)?|SESSION_SECRET)\s*=\s*['\"][^'\"]{6,}['\"]"),
153
+ re.compile(r"\bapp\.secret_key\s*=\s*['\"][^'\"]{6,}['\"]"),
154
+ ],
155
+ "sensitive_storage": [
156
+ re.compile(
157
+ r"(?:AsyncStorage|localStorage|sessionStorage)\.setItem\(\s*['\"`][^'\"`]*"
158
+ r"(?:token|password|passwd|secret|jwt|credential|api_?key)",
159
+ re.I,
160
+ ),
161
+ ],
162
+ }
163
+ )
164
+ # Single patterns that mean something else in other languages: Python's exec() runs code; JavaScript's exec() is
165
+ # child_process (a shell) and Ruby's and PHP's replace or start a process.
166
+ ONLY_IN = {
167
+ PATTERNS["eval"][2]: (".py",),
168
+ PATTERNS["shell"][-2]: (".js", ".jsx", ".ts", ".tsx", ".mjs", ".cjs"),
169
+ PATTERNS["shell"][-1]: (".go",),
170
+ }
171
+ COMMENT_LINE = re.compile(r"\s*(?:#|//|\*|/\*|<!--|--\s)")
172
+ # words that say a credential-looking value isn't real ("xoxb-not-a-real-token", "sk_test_fake…", "<your key>")
173
+ PLACEHOLDER = r"(?i)example|placeholder|dummy|xxxx|your[_-]|changeme|<|not[-_ ]?a[-_ ]?real|fake|redacted|sample|mock"
174
+ # Checks for built-ins only some languages have: Go's eval() or Java's exec() are ordinary functions.
175
+ LANG_ONLY = {
176
+ "eval": (".py", ".js", ".jsx", ".ts", ".tsx", ".mjs", ".cjs", ".rb", ".php"),
177
+ "shell": (".py", ".js", ".jsx", ".ts", ".tsx", ".mjs", ".cjs", ".rb", ".php", ".go"),
178
+ }
179
+ # In tests, keys are fixtures (a PEM block in an example, "secret = 'xxxx…'"): only real credential formats count there,
180
+ # because a live AWS, GitHub, Slack, Stripe or Google key in a test is as leaked as anywhere else.
181
+ VENDOR_SECRETS = PATTERNS["secret"][1:6]
182
+ # Lines that only count when they're about something security-sensitive: an md5 for a cache key or Math.random() for a
183
+ # chart colour is fine; for a password, a token or a session it isn't.
184
+ CONTEXT = {
185
+ "insecure_cookie": re.compile(r"cookie|session|csrf", re.I),
186
+ "weak_hash": re.compile(
187
+ r"passw|pwd|secret|signature|\bsign\(|hmac|credential|otp|salt|"
188
+ r"(?:access|refresh|reset|auth|csrf|session|api|bearer)[_ -]?(?:token|key)",
189
+ re.I,
190
+ ),
191
+ # a bare "token" is too vague (a draft id, a list key): it needs to be named for what it guards
192
+ "weak_random": re.compile(
193
+ r"(?:access|refresh|reset|auth|csrf|session|api|invite|verif\w*|bearer|login|magic)[_ -]?(?:token|key|code|id)|"
194
+ r"secret|passw|otp|nonce|salt|csrf",
195
+ re.I,
196
+ ),
197
+ }
198
+ SQL_CALL = re.compile(
199
+ r"(?:execute|executemany|executescript|query|raw|getAllAsync|getFirstAsync|runAsync|execAsync|"
200
+ r"prepareAsync|getAllSync|runSync|executeQuery|executeUpdate|prepareStatement|createQuery|createNativeQuery|"
201
+ r"Query|QueryRow|QueryContext|QueryRowContext|Exec|ExecContext|find_by_sql|where|whereRaw|order|having|joins|"
202
+ r"exec_query|select_all|select_rows)\s*\(\s*"
203
+ r"(f['\"]|`|\"[^\"]*\"\s*(?:%|\+|\.format)|'[^']*'\s*(?:%|\+|\.format)|\"[^\"]*#\{|fmt\.Sprintf\(\s*[\"`][^\"`]*%[sv]|"
204
+ r"\"[^\"]*\$\{?[A-Za-z_])"
205
+ )
206
+ HOST = re.compile(r"""['"`]https?://([a-z0-9.-]+\.[a-z]{2,})(?::\d+)?[/'"`?]""", re.I)
207
+ SQL_WORD = re.compile(r"\b(SELECT|INSERT|UPDATE|DELETE|CREATE|DROP|ALTER|WHERE|FROM)\b", re.I)
208
+ INTERP = re.compile(r"\$\{([^}]+)\}|\{([^}:!]+)[^}]*\}")
209
+ CONSTANT = re.compile(r"^[A-Z0-9_]+$|^\w+\.length$|^\w+\.map\(\(\) => ['\"]\?['\"]\)\.join\(['\"], ?['\"]\)$")
210
+
211
+
212
+ # One search per group over the whole file first: most files match none, and then no line is scanned for it.
213
+ def _group(pats: list[re.Pattern]) -> re.Pattern:
214
+ """The patterns as one alternation, each keeping its own case-insensitivity."""
215
+ parts = []
216
+ for p in pats:
217
+ body = p.pattern[4:] if p.pattern.startswith("(?i)") else p.pattern
218
+ insensitive = p.pattern.startswith("(?i)") or p.flags & re.I
219
+ parts.append(f"(?i:{body})" if insensitive else f"(?:{body})")
220
+ return re.compile("|".join(parts), re.M) # over a whole file: ^ means the start of any line
221
+
222
+
223
+ ANY = {k: _group(pats) for k, pats in PATTERNS.items()}
224
+ SQL_HINT = re.compile(
225
+ r"execute|query|raw|Async|Sync\s*\(|Query|Exec|Statement|find_by_sql|\.(?:where|whereRaw|order|having|joins|select_all|select_rows)\s*\("
226
+ )
227
+ DOLLAR_LANGS = (".kt", ".kts", ".dart", ".php", ".groovy", ".scala")
228
+ WEAK_CONTEXT_FROM_FUNCTION = ("weak_random", "weak_hash") # a token made in new_reset_token() is about a token
229
+ FUNC_HEADER = re.compile(r"^\s*(?:async\s+)?(?:def|func|function|fun|fn)\s+(\w+)|^\s*(?:export\s+)?(?:public|private|static)\b")
230
+
231
+
232
+ def _excerpt(line: str) -> str:
233
+ t = line.strip()
234
+ return t if len(t) <= 140 else t[:137] + "…"
235
+
236
+
237
+ def _ignored(lines: list[str], i: int, key: str, file_kinds: set[str] | None) -> bool:
238
+ """`codefactory: ignore <check>` on the line or the one above, or `ignore-file` for the file (no kinds = all)."""
239
+ if file_kinds is not None and (not file_kinds or key in file_kinds):
240
+ return True
241
+ for ln in (i, i - 1):
242
+ if 1 <= ln <= len(lines) and (m := MARK.search(lines[ln - 1])) and not m.group(1):
243
+ kinds, _ = parse_mark(m.group(2))
244
+ if not kinds or key in kinds:
245
+ return True
246
+ return False
247
+
248
+
249
+ CHECK_KEYS = [
250
+ *PATTERNS,
251
+ "sql_built",
252
+ "module_state",
253
+ "fetch_no_timeout",
254
+ "hosts",
255
+ "error_boundary",
256
+ "swallowed_ok",
257
+ "go_server_timeout",
258
+ ]
259
+
260
+
261
+ def source_files(root: Path, graph: dict) -> list[str]:
262
+ """Every source file to run line checks on: the graph's, plus any on disk the analyzers couldn't read (TypeScript
263
+ without Node.js, other languages without the language pack). A credential in a file nobody could parse is still a
264
+ credential."""
265
+ from .config import load_config
266
+
267
+ seen = {f["id"] for f in graph["files"]}
268
+ skip = set(load_config(root).ignore)
269
+ out = set(seen)
270
+ for dirpath, dirnames, filenames in os.walk(root):
271
+ dirnames[:] = [d for d in dirnames if d not in skip and not d.startswith(".") and not d.endswith(".egg-info")]
272
+ for name in filenames:
273
+ if name.endswith(SRC_EXT) and not name.endswith((".min.js", ".d.ts")):
274
+ out.add(Path(dirpath, name).relative_to(root).as_posix())
275
+ return sorted(out)
276
+
277
+
278
+ def scan_sources(root: Path, files: list[str]) -> dict[str, Check]:
279
+ """Every source file's pattern hits, in parallel and cached per file (see analyzers/parallel)."""
280
+ from .analyzers import parallel
281
+
282
+ items = [(fid, (str(root), fid)) for fid in files if fid.endswith(SRC_EXT)]
283
+ per_file = parallel.run(root, "checks", items, _scan_one, tool="checks")
284
+ out = {k: Check(k) for k in CHECK_KEYS}
285
+ for fid in files:
286
+ for key, got in per_file.get(fid, {}).items():
287
+ out[key].hits += [Evidence(fid, line, text) for line, text in got["hits"]]
288
+ for k, v in got["data"].items():
289
+ out[key].data.setdefault(k, v) # hosts: the first file that uses each
290
+ return out
291
+
292
+
293
+ def _scan_one(root: str, fid: str) -> dict:
294
+ found = _scan(Path(root), [fid])
295
+ return {k: {"hits": [[e.line, e.text] for e in c.hits], "data": c.data} for k, c in found.items() if c.hits or c.data}
296
+
297
+
298
+ def _scan(root: Path, files: list[str]) -> dict[str, Check]:
299
+ keys = [
300
+ *PATTERNS,
301
+ "sql_built",
302
+ "module_state",
303
+ "fetch_no_timeout",
304
+ "hosts",
305
+ "error_boundary",
306
+ "swallowed_ok",
307
+ "go_server_timeout",
308
+ ]
309
+ out = {k: Check(k) for k in keys}
310
+ for fid in files:
311
+ if not fid.endswith(SRC_EXT):
312
+ continue
313
+ try:
314
+ text = (root / fid).read_text(encoding="utf-8", errors="replace")
315
+ except OSError:
316
+ continue
317
+ test = is_test(fid)
318
+ lines = text.splitlines()
319
+ marks = [parse_mark(m.group(2))[0] for ln in lines if (m := MARK.search(ln)) and m.group(1)]
320
+ file_kinds = set().union(*marks) if marks and all(marks) else (set() if marks else None)
321
+
322
+ def hit(key: str, i: int, lines=lines, file_kinds=file_kinds) -> bool: # bound to this file's lines
323
+ return not _ignored(lines, i, key, file_kinds)
324
+
325
+ present = {
326
+ k: (VENDOR_SECRETS if test and k == "secret" else v)
327
+ for k, v in PATTERNS.items()
328
+ if (not test or k == "secret") and (k not in LANG_ONLY or fid.endswith(LANG_ONLY[k])) and ANY[k].search(text)
329
+ }
330
+ sql_here = not test and SQL_HINT.search(text) is not None
331
+ hosts_here = not test and "://" in text
332
+ boundary_here = re.search(r"ErrorBoundary|componentDidCatch|getDerivedStateFromError", text) is not None
333
+ state_here = not test and fid.endswith((".ts", ".tsx", ".js", ".jsx", ".mjs")) and "let " in text
334
+
335
+ for i, line in enumerate(lines, 1):
336
+ if len(line) > 2000: # minified or data
337
+ continue
338
+ for key, pats in present.items(): # tests: only secrets (a test may do anything; a leaked key is leaked)
339
+ if key != "secret" and COMMENT_LINE.match(line):
340
+ continue # prose about a pattern ("mark_safe() it at the end") isn't the code; a key is leaked anywhere
341
+ if any(p.search(line) and (p not in ONLY_IN or fid.endswith(ONLY_IN[p])) for p in pats) and hit(key, i):
342
+ if key == "raw_html" and re.search(r"mark_safe\(.*\bsettings\.[A-Z_]+", line):
343
+ continue # the site's own configuration, not user data
344
+ if key == "plain_http" and re.match(r"\s*(?:\*|//|#|/\*)", line): # an example in a doc comment
345
+ continue
346
+ if key in CONTEXT and not CONTEXT[key].search(line):
347
+ header = next((h for h in reversed(lines[max(0, i - 7) : i - 1]) if FUNC_HEADER.match(h)), "")
348
+ if key not in WEAK_CONTEXT_FROM_FUNCTION or not CONTEXT[key].search(header):
349
+ continue
350
+ if key == "secret" and re.search(PLACEHOLDER, line):
351
+ continue
352
+ if key == "swallowed" and (why := swallow_intent(line, lines[i - 2] if i > 1 else "")):
353
+ out["swallowed_ok"].hits.append(Evidence(fid, i, why)) # deliberate: counted, not reported
354
+ continue
355
+ out[key].hits.append(Evidence(fid, i, _excerpt(line)))
356
+ if sql_here and (m := SQL_CALL.search(line)) and hit("sql_built", i):
357
+ stmt = " ".join(lines[i - 1 : i + 4])
358
+ if SQL_WORD.search(stmt):
359
+ py_format = not m.group(1).startswith("`") # {name}: Python f-strings (and Ruby's #{name})
360
+ start = m.end() - 1 if m.group(1).endswith("#{") else m.end() # keep Ruby's brace
361
+ body = stmt[start : start + 600]
362
+ if not py_format: # just this template literal, not the code after it
363
+ body = re.split(r"(?<!\\)`", body, maxsplit=1)[0]
364
+ names = [a or (b if py_format else "") for a, b in INTERP.findall(body)]
365
+ names = [n for n in names if n]
366
+ if m.group(1).endswith("#{"): # Ruby: #{params[:email]} (a colon is fine inside)
367
+ names = re.findall(r"\{([^}]+)\}", body.split('"')[0])
368
+ dollar = m.group(1).startswith('"') and "$" in m.group(1) and "#{" not in m.group(1)
369
+ if dollar: # "$name" is interpolation in Kotlin, Dart, PHP, Groovy and Scala, not elsewhere
370
+ if not fid.endswith(DOLLAR_LANGS):
371
+ continue
372
+ names += re.findall(r"\$\{?([A-Za-z_][\w.]*)", stmt[m.start(1) : m.start(1) + 600].split('"')[1])
373
+ safe = safe_names(lines, i)
374
+ risky = [n for n in names if not CONSTANT.match(n.strip()) and not interp_safe(n, safe)]
375
+ sprintf = m.group(1).startswith("fmt.") # %s / %v pasted in; %d can't carry SQL
376
+ concat = m.group(1).endswith("+")
377
+ if concat: # "… id = " + id: risky unless every value joined in is a number
378
+ joined = re.findall(r"(?:^|\+)\s*([A-Za-z_$][\w$.]*(?:\(\))?)\s*(?=\+|\)|,|$)", body.split(";")[0])
379
+ concat = not joined or any(not interp_safe(n, safe) for n in joined)
380
+ if risky or sprintf or concat or m.group(1).endswith("%") or ".format" in m.group(1):
381
+ out["sql_built"].hits.append(Evidence(fid, i, _excerpt(line)))
382
+ out["sql_built"].data.setdefault(f"{fid}:{i}", risky[:4])
383
+ if hosts_here and "://" in line and not re.match(r"\s*(//|#|\*|/\*)", line): # used, not just mentioned
384
+ for host in HOST.findall(line):
385
+ if host not in out["hosts"].data and not re.search(r"example\.|localhost|w3\.org|schema", host):
386
+ out["hosts"].data[host] = f"{fid}:{i}"
387
+ if boundary_here and re.search(r"ErrorBoundary|componentDidCatch|getDerivedStateFromError", line):
388
+ out["error_boundary"].hits.append(Evidence(fid, i, _excerpt(line)))
389
+ if state_here and re.match(r"^(?:export\s+)?let\s+\w+", line) and hit("module_state", i):
390
+ out["module_state"].hits.append(Evidence(fid, i, _excerpt(line)))
391
+ if (
392
+ not test
393
+ and fid.endswith((".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs")) # the web's fetch; elsewhere it's any name
394
+ and re.search(r"(?<![\w.])fetch\s*\(", text)
395
+ and not re.search(r"\bsignal\b|AbortSignal\.timeout|timeout", text)
396
+ ):
397
+ ln = next(i for i, text in enumerate(lines, 1) if re.search(r"(?<![\w.])fetch\s*\(", text))
398
+ out["fetch_no_timeout"].hits.append(Evidence(fid, ln, _excerpt(lines[ln - 1])))
399
+ if not test and fid.endswith(".go"): # the default client never times out
400
+ server = next(
401
+ (m for m in re.finditer(r"\bhttp\.ListenAndServe(?:TLS)?\(|&?http\.Server\{", text)
402
+ if not COMMENT_LINE.match(lines[text.count("\n", 0, m.start())])),
403
+ None,
404
+ ) # fmt: skip
405
+ if server and not re.search(r"ReadHeaderTimeout|ReadTimeout|TimeoutHandler", text):
406
+ ln = text.count("\n", 0, server.start()) + 1
407
+ if hit("go_server_timeout", ln):
408
+ out["go_server_timeout"].hits.append(Evidence(fid, ln, _excerpt(lines[ln - 1])))
409
+ for i, line in enumerate(lines, 1):
410
+ code = line.split("//", 1)[0]
411
+ if re.search(r"\bhttp\.(?:Get|Post|Head|PostForm)\(", code) and hit("fetch_no_timeout", i):
412
+ out["fetch_no_timeout"].hits.append(Evidence(fid, i, _excerpt(line)))
413
+ if not test and fid.endswith(".py"):
414
+ for i, line in enumerate(lines, 1):
415
+ if (
416
+ i < len(lines)
417
+ and re.match(r"\s*except\s*(?:\(?\s*(?:Exception|BaseException)\b[^:#]*)?:\s*$", line) # broad only
418
+ and lines[i].strip() == "pass"
419
+ and not swallow_intent(line + " " + lines[i], lines[i - 2] if i > 1 else "")
420
+ and hit("swallowed", i)
421
+ ):
422
+ out["swallowed"].hits.append(Evidence(fid, i, _excerpt(line + " " + lines[i].strip())))
423
+ if re.search(r"\brequests\.(get|post|put|patch|delete|head)\s*\(", line) and "timeout" not in " ".join(
424
+ lines[i - 1 : i + 3]
425
+ ):
426
+ out["fetch_no_timeout"].hits.append(Evidence(fid, i, _excerpt(line)))
427
+ if re.match(r"^\s+global\s+\w+", line):
428
+ out["module_state"].hits.append(Evidence(fid, i, _excerpt(line)))
429
+ return out
430
+
431
+
432
+ # ---- repository ----------------------------------------------------------------------------------------------------
433
+
434
+ CI_FILES = [
435
+ ".github/workflows",
436
+ ".gitlab-ci.yml",
437
+ ".circleci",
438
+ "azure-pipelines.yml",
439
+ "Jenkinsfile",
440
+ ".travis.yml",
441
+ "bitbucket-pipelines.yml",
442
+ ".buildkite",
443
+ ]
444
+ LOCKS = [
445
+ "package-lock.json",
446
+ "yarn.lock",
447
+ "pnpm-lock.yaml",
448
+ "bun.lockb",
449
+ "bun.lock",
450
+ "poetry.lock",
451
+ "uv.lock",
452
+ "Pipfile.lock",
453
+ "requirements.lock",
454
+ "Cargo.lock",
455
+ "go.sum",
456
+ ]
457
+
458
+
459
+ def _python_deps(pyproject: str) -> list[str]:
460
+ """Package names a pyproject.toml depends on (project and optional dependencies, Poetry's tables)."""
461
+ import tomllib
462
+
463
+ try:
464
+ data = tomllib.loads(pyproject)
465
+ except ValueError:
466
+ return []
467
+ project = data.get("project", {})
468
+ specs = list(project.get("dependencies", []))
469
+ for group in project.get("optional-dependencies", {}).values():
470
+ specs += group
471
+ poetry = data.get("tool", {}).get("poetry", {})
472
+ specs += list(poetry.get("dependencies", {})) + list(poetry.get("dev-dependencies", {}))
473
+ return [re.split(r"[\s<>=!~\[;@]", s, maxsplit=1)[0].lower() for s in specs if isinstance(s, str) and s]
474
+
475
+
476
+ def _holds_secret(env: Path) -> bool:
477
+ """An env file with a real value for a secret-looking key (a template with `APP_KEY=` empty isn't a leak)."""
478
+ try:
479
+ text = env.read_text(encoding="utf-8", errors="replace")
480
+ except OSError:
481
+ return False
482
+ for m in re.finditer(
483
+ r"^\s*(?:export\s+)?(\w*(?:KEY|SECRET|TOKEN|PASSWORD|PASSWD|PWD|CREDENTIAL)\w*)[ \t]*=[ \t]*(.*)$", text, re.M | re.I
484
+ ):
485
+ value = m.group(2).strip().strip("'\"")
486
+ if len(value) >= 6 and not re.search(PLACEHOLDER + r"|^\$\{?\w+|changethis|secret$|password$", value, re.I):
487
+ return True
488
+ return False
489
+
490
+
491
+ def scan_repo(root: Path) -> dict:
492
+ info: dict = {
493
+ "ci": [],
494
+ "ci_steps": set(),
495
+ "ci_on_push": False,
496
+ "locks": [],
497
+ "manifests": [],
498
+ "floating": [],
499
+ "unpinned_py": [],
500
+ "runtime_pin": [],
501
+ "readme": None,
502
+ "license": None,
503
+ "env_files": [],
504
+ "frameworks": set(),
505
+ "deps": {},
506
+ "deploy": [],
507
+ }
508
+ for c in CI_FILES:
509
+ p = root / c
510
+ if p.is_dir():
511
+ info["ci"] += [str(f.relative_to(root)).replace("\\", "/") for f in sorted(p.glob("*.y*ml"))]
512
+ elif p.is_file():
513
+ info["ci"].append(c)
514
+ for f in info["ci"]:
515
+ try:
516
+ t = (root / f).read_text(encoding="utf-8", errors="replace").lower()
517
+ except OSError:
518
+ continue
519
+ for step, words in {
520
+ "tests": ["test", "pytest", "jest", "vitest", "unittest"],
521
+ "lint": ["lint", "ruff", "flake8", "eslint"],
522
+ "typecheck": ["tsc", "mypy", "pyright", "typecheck"],
523
+ "build": ["build"],
524
+ }.items():
525
+ if any(w in t for w in words):
526
+ info["ci_steps"].add(step)
527
+ if re.search(r"\bpush\s*:", t) or re.search(r"on:\s*\[?\s*push", t) or push_skip_explained(t):
528
+ info["ci_on_push"] = True # runs on push, or says why it deliberately doesn't
529
+ info["locks"] = [name for name in LOCKS if (root / name).exists()]
530
+ pkg = root / "package.json"
531
+ if pkg.is_file():
532
+ info["manifests"].append("package.json")
533
+ try:
534
+ data = json.loads(pkg.read_text(encoding="utf-8"))
535
+ except ValueError:
536
+ data = {}
537
+ deps = {**data.get("dependencies", {}), **data.get("devDependencies", {})}
538
+ info["deps"].update(deps)
539
+ info["floating"] = [
540
+ f"{k}@{v}" for k, v in deps.items() if v in ("*", "latest", "") or v.startswith(("git", "http", "github:"))
541
+ ]
542
+ if "engines" in data:
543
+ info["runtime_pin"].append("package.json engines")
544
+ for name, fw in (
545
+ ("react-native", "React Native"),
546
+ ("expo", "Expo"),
547
+ ("react", "React"),
548
+ ("next", "Next.js"),
549
+ ("vue", "Vue"),
550
+ ("express", "Express"),
551
+ ("@nestjs/core", "NestJS"),
552
+ ("svelte", "Svelte"),
553
+ ):
554
+ if name in deps:
555
+ info["frameworks"].add(fw)
556
+ info["deploy"] += [k for k in data.get("scripts", {}) if re.search(r"deploy|release|publish|ota", k)]
557
+ for req in ("requirements.txt", "requirements-dev.txt"):
558
+ p = root / req
559
+ if p.is_file():
560
+ info["manifests"].append(req)
561
+ for line in p.read_text(encoding="utf-8", errors="replace").splitlines():
562
+ s = line.split("#")[0].strip()
563
+ if s and not s.startswith("-") and "==" not in s and "@" not in s:
564
+ info["unpinned_py"].append(s)
565
+ if s and not s.startswith("-"):
566
+ info["deps"][re.split(r"[\s<>=!~\[;@]", s, maxsplit=1)[0].lower()] = ""
567
+ if (root / "pyproject.toml").is_file():
568
+ info["manifests"].append("pyproject.toml")
569
+ t = (root / "pyproject.toml").read_text(encoding="utf-8", errors="replace")
570
+ info["deps"].update({name: "" for name in _python_deps(t)})
571
+ for name, fw in (("django", "Django"), ("flask", "Flask"), ("fastapi", "FastAPI"), ("sqlalchemy", "SQLAlchemy")):
572
+ if re.search(rf"\b{name}\b", t, re.I):
573
+ info["frameworks"].add(fw)
574
+ if "requires-python" in t:
575
+ info["runtime_pin"].append("requires-python")
576
+ for f in (".nvmrc", ".node-version", ".python-version", ".tool-versions", "runtime.txt"):
577
+ if (root / f).exists():
578
+ info["runtime_pin"].append(f)
579
+ info["readme"] = next((f for f in ("README.md", "README.rst", "README.txt", "README") if (root / f).exists()), None)
580
+ info["license"] = next((f for f in ("LICENSE", "LICENSE.md", "LICENSE.txt", "COPYING") if (root / f).exists()), None)
581
+ info["env_files"] = [
582
+ p.name
583
+ for p in root.glob(".env*")
584
+ if p.is_file() and not p.name.endswith((".example", ".sample", ".template", ".dist")) and _holds_secret(p)
585
+ ]
586
+ if info["readme"]:
587
+ t = (root / info["readme"]).read_text(encoding="utf-8", errors="replace").lower()
588
+ info["readme_run"] = bool(re.search(r"install|npm |pip |yarn |make |cargo |go run|docker", t))
589
+ return info
590
+
591
+
592
+ # ---- testing -------------------------------------------------------------------------------------------------------
593
+
594
+
595
+ def test_reach(v: View) -> set[str]:
596
+ """Functions a test calls or hands on (a callback), directly or through others."""
597
+ out_edges: dict[str, list[str]] = {}
598
+ for e in v.g["edges"]:
599
+ if e["kind"] in ("call", "ref"):
600
+ out_edges.setdefault(e["src"], []).append(e["dst"])
601
+ start = [fid for fid, f in v.fn.items() if is_test(f["file"])]
602
+ seen, q = set(start), deque(start)
603
+ while q:
604
+ for nxt in out_edges.get(q.popleft(), []):
605
+ if nxt not in seen:
606
+ seen.add(nxt)
607
+ q.append(nxt)
608
+ return seen