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
@@ -0,0 +1,344 @@
1
+ """Where change happens, from git history: the code that is both complex and changed often (hotspots), files that
2
+ change together without importing each other (hidden coupling), and code only one person changes.
3
+
4
+ The idea is behavioural code analysis (Adam Tornhill's "Your Code as a Crime Scene"): of all the debt in a codebase,
5
+ the part that costs money is the part people keep working in. A long function nobody has touched in two years is a
6
+ curiosity; one changed every week is where bugs and slow reviews come from. Findings in hotspots are ranked first.
7
+
8
+ One `git log` over the last 12 months (at most 5,000 commits, 60 seconds), read once per review. Merges and commits
9
+ touching more than 50 files (formatting, renames, vendoring) don't count. Bots (Dependabot, Renovate…) count as
10
+ changes but not as people, so "only one person changes this" isn't fooled by them. An AI assistant's commits count
11
+ for whoever commits under that name: someone drove them.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import json
17
+ import re
18
+ import subprocess
19
+ import time
20
+ from collections import Counter
21
+ from dataclasses import dataclass, field
22
+ from pathlib import Path
23
+
24
+ from .paths import is_test
25
+
26
+ MONTHS = 12
27
+ MAX_COMMITS = 5000
28
+ BIG_COMMIT = 50 # files: past this a commit is a sweep (formatting, renames), not a change to the code's behaviour
29
+ BOTS = re.compile(r"\[bot\]|dependabot|renovate|github-actions|pre-commit-ci|snyk-bot|greenkeeper", re.I)
30
+
31
+
32
+ @dataclass
33
+ class FileHistory:
34
+ path: str
35
+ commits: int = 0
36
+ recent: int = 0 # commits in the last 3 months
37
+ churn: int = 0 # lines added + deleted
38
+ authors: Counter = field(default_factory=Counter) # person -> commits (bots excluded)
39
+ last: int = 0 # epoch seconds
40
+
41
+
42
+ @dataclass
43
+ class History:
44
+ files: dict[str, FileHistory] = field(default_factory=dict)
45
+ pairs: Counter = field(default_factory=Counter) # (a, b) -> commits changing both
46
+ commits: int = 0
47
+ people: Counter = field(default_factory=Counter)
48
+ first: int = 0
49
+ last: int = 0
50
+ note: str = "" # why history is missing or partial
51
+
52
+
53
+ @dataclass
54
+ class Hotspot:
55
+ path: str
56
+ commits: int
57
+ recent: int
58
+ churn: int
59
+ complexity: int # decision points in the file's functions
60
+ loc: int
61
+ score: float # 0-1: change frequency x complexity, relative to this repository
62
+ top_author_share: float
63
+ people: int
64
+
65
+
66
+ @dataclass
67
+ class Coupling:
68
+ a: str
69
+ b: str
70
+ together: int
71
+ share: float # of the less-changed file's commits, how many also changed the other
72
+ linked: bool # one imports the other
73
+
74
+
75
+ def _person(name: str) -> str:
76
+ return re.sub(r"[^a-z0-9]", "", name.lower())
77
+
78
+
79
+ def read(root: Path, months: int = MONTHS, max_commits: int = MAX_COMMITS, timeout: int = 60) -> History:
80
+ """The history, from a cache keyed by the HEAD commit (the log only changes when HEAD does), else from git."""
81
+ try:
82
+ head = subprocess.run(["git", "-C", str(root), "rev-parse", "HEAD", "--show-prefix"], capture_output=True,
83
+ text=True, timeout=10).stdout.split() # fmt: skip
84
+ except (OSError, subprocess.SubprocessError):
85
+ head = []
86
+ key = f"{'/'.join(head)}|{months}|{max_commits}|{time.strftime('%Y-%m-%d')}" if head else "" # a day later, the window moves
87
+ path = root / ".codefactory" / "history.json"
88
+ if key:
89
+ try:
90
+ data = json.loads(path.read_text(encoding="utf-8"))
91
+ if data.get("key") == key:
92
+ return _from_json(data["history"])
93
+ except (OSError, ValueError, KeyError, TypeError):
94
+ pass
95
+ h = _read(root, months, max_commits, timeout)
96
+ if key and h.commits:
97
+ try:
98
+ path.parent.mkdir(exist_ok=True)
99
+ path.write_text(json.dumps({"key": key, "history": _to_json(h)}), encoding="utf-8")
100
+ except OSError:
101
+ pass # read-only checkout
102
+ return h
103
+
104
+
105
+ def _to_json(h: History) -> dict:
106
+ return {"files": {p: [f.commits, f.recent, f.churn, dict(f.authors), f.last] for p, f in h.files.items()},
107
+ "pairs": [[a, b, n] for (a, b), n in h.pairs.items()], "commits": h.commits, "people": dict(h.people),
108
+ "first": h.first, "last": h.last, "note": h.note} # fmt: skip
109
+
110
+
111
+ def _from_json(d: dict) -> History:
112
+ h = History(commits=d["commits"], people=Counter(d["people"]), first=d["first"], last=d["last"], note=d["note"])
113
+ h.files = {p: FileHistory(p, c, r, ch, Counter(a), last) for p, (c, r, ch, a, last) in d["files"].items()}
114
+ h.pairs = Counter({(a, b): n for a, b, n in d["pairs"]})
115
+ return h
116
+
117
+
118
+ def _read(root: Path, months: int, max_commits: int, timeout: int) -> History:
119
+ h = History()
120
+ git = ["git", "-C", str(root)]
121
+ try:
122
+ inside = subprocess.run([*git, "rev-parse", "--is-inside-work-tree"], capture_output=True, text=True, timeout=10)
123
+ if inside.stdout.strip() != "true":
124
+ h.note = "not a git repository: no history to read"
125
+ return h
126
+ if subprocess.run([*git, "rev-parse", "--is-shallow-repository"], capture_output=True, text=True,
127
+ timeout=10).stdout.strip() == "true": # fmt: skip
128
+ # partial only if the clone stops inside the window (`--shallow-since` older than it is complete enough)
129
+ oldest = subprocess.run([*git, "log", "--reverse", "--format=%at", "--max-parents=0"], capture_output=True,
130
+ text=True, timeout=30).stdout.split() # fmt: skip
131
+ if not oldest or int(oldest[0]) > time.time() - months * 30.5 * 86400:
132
+ h.note = "a shallow clone (CI checks out one commit by default): history is partial; `fetch-depth: 0` reads all"
133
+ proc = subprocess.run(
134
+ [*git, "log", "--no-merges", "--no-renames", "--numstat", f"--since={months}.months", f"-n{max_commits}",
135
+ "--format=%x1e%aN%x1f%at", "--relative", "--", "."], # this folder's history, its paths relative to it
136
+ capture_output=True, text=True, timeout=timeout, encoding="utf-8", errors="replace",
137
+ ) # fmt: skip
138
+ except (OSError, subprocess.SubprocessError):
139
+ h.note = "git isn't available or took too long: history not read"
140
+ return h
141
+ recent_cut = time.time() - 90 * 86400
142
+ for block in proc.stdout.split("\x1e")[1:]:
143
+ head, _, body = block.partition("\n")
144
+ name, _, ts = head.partition("\x1f")
145
+ try:
146
+ when = int(ts)
147
+ except ValueError:
148
+ continue
149
+ changed = []
150
+ for line in body.splitlines():
151
+ parts = line.split("\t")
152
+ if len(parts) == 3:
153
+ added, deleted, path = parts
154
+ lines = (int(added) if added.isdigit() else 0) + (int(deleted) if deleted.isdigit() else 0)
155
+ changed.append((path, lines))
156
+ if not changed or len(changed) > BIG_COMMIT:
157
+ continue
158
+ h.commits += 1
159
+ h.first = min(h.first or when, when)
160
+ h.last = max(h.last, when)
161
+ person = None if BOTS.search(name) else _person(name)
162
+ if person:
163
+ h.people[person] += 1
164
+ for path, lines in changed:
165
+ fh = h.files.setdefault(path, FileHistory(path))
166
+ fh.commits += 1
167
+ fh.churn += lines
168
+ fh.recent += when >= recent_cut
169
+ fh.last = max(fh.last, when)
170
+ if person:
171
+ fh.authors[person] += 1
172
+ paths = sorted({p for p, _ in changed})
173
+ if 2 <= len(paths) <= 30:
174
+ for i, a in enumerate(paths):
175
+ for b in paths[i + 1 :]:
176
+ h.pairs[(a, b)] += 1
177
+ if h.commits >= max_commits:
178
+ h.note = h.note or f"read the latest {max_commits:,} commits only"
179
+ return h
180
+
181
+
182
+ GENERATED = re.compile(
183
+ r"(?:^|[/_.-])generated[_.-]|(?:^|/)(?:vendor|vendored|third_party|external)/|"
184
+ r"(?:^|/)(?:jquery|datatables|bootstrap|lodash|moment|chart|d3|highlight)(?:[.-][\w.-]*)?\.js$|"
185
+ r"(?:^|/)(?:generated|__generated__|gen)/|\.(?:gen|generated|g|pb|pb\.gw)\.\w+$|_pb2(?:_grpc)?\.py$|\.pb\.go$|"
186
+ r"(?:^|/)(?:openapi|swagger)[\w.-]*\.(?:ts|js|py)$|\.min\.js$"
187
+ )
188
+
189
+
190
+ def generated(path: str) -> bool:
191
+ """Made by a tool: it changes when its source does, and nobody untangles it by hand."""
192
+ return bool(GENERATED.search(path))
193
+
194
+
195
+ def hotspots(h: History, g: dict, limit: int = 10) -> list[Hotspot]:
196
+ """Source files that are both complex and changed often, most costly first."""
197
+ code = {f["id"]: f for f in g["files"] if not is_test(f["id"])}
198
+ complexity: Counter = Counter()
199
+ for fn in g["functions"]:
200
+ if fn["file"] in code and fn["kind"] != "module":
201
+ complexity[fn["file"]] += max(1, fn.get("branches", 0))
202
+ rows = [(path, fh) for path, fh in h.files.items() if path in code and fh.commits >= 3 and not generated(path)]
203
+ if not rows:
204
+ return []
205
+ top_commits = max(fh.commits for _, fh in rows)
206
+ top_complexity = max((complexity[p] or code[p]["loc"] // 10 or 1) for p, _ in rows)
207
+ out = []
208
+ for path, fh in rows:
209
+ cx = complexity[path] or code[path]["loc"] // 10 or 1
210
+ score = (fh.commits / top_commits) * (cx / top_complexity)
211
+ total = sum(fh.authors.values())
212
+ out.append(Hotspot(path, fh.commits, fh.recent, fh.churn, cx, code[path]["loc"], round(score, 3),
213
+ (fh.authors.most_common(1)[0][1] / total) if total else 0.0, len(fh.authors))) # fmt: skip
214
+ out.sort(key=lambda x: (-x.score, -x.commits))
215
+ return [x for x in out if x.score >= 0.05][:limit]
216
+
217
+
218
+ PACKAGE_LANGS = (".go", ".kt", ".java", ".scala", ".swift", ".cs", ".rs") # .rs: sibling modules of one crate
219
+ # translations change together by design: adding a string touches every language
220
+ TRANSLATIONS = re.compile(r"(?:^|/)(?:i18n|l10n|locales?|translations?|lang)/", re.I)
221
+
222
+
223
+ def _same_package(a: str, b: str) -> bool:
224
+ """Go, Kotlin, Java, Swift… files in one folder share a package (or module) and use each other without imports."""
225
+ return a.rsplit("/", 1)[0] == b.rsplit("/", 1)[0] and a.endswith(PACKAGE_LANGS) and b.endswith(PACKAGE_LANGS)
226
+
227
+
228
+ def coupling(h: History, g: dict, limit: int = 8) -> list[Coupling]:
229
+ """Pairs of files that keep changing in the same commits. Those with no import between them are hidden coupling:
230
+ a change in one needs a change in the other, and nothing in the code says so."""
231
+ from .checks import SRC_EXT
232
+
233
+ known = {f["id"] for f in g["files"]} | {p for p in h.files if p.endswith(SRC_EXT)} # parsed or not
234
+ imports = set()
235
+ file_of = {fn["id"]: fn["file"] for fn in g["functions"]}
236
+ for e in g["edges"]:
237
+ a, b = file_of.get(e["src"], e["src"]), file_of.get(e["dst"], e["dst"])
238
+ if a != b:
239
+ imports.add((a, b))
240
+ imports.add((b, a))
241
+ loc = {f["id"]: f["loc"] for f in g["files"]}
242
+ magnets = {p for p, fh in h.files.items() if fh.commits >= max(6, h.commits // 2) or loc.get(p, 99) <= 15}
243
+ out = []
244
+ for (a, b), together in h.pairs.items():
245
+ if together < 4 or a not in known or b not in known:
246
+ continue
247
+ if (is_test(a) or is_test(b) or a in magnets or b in magnets or generated(a) or generated(b)
248
+ or TRANSLATIONS.search(a) or TRANSLATIONS.search(b)): # fmt: skip
249
+ continue # tests change with their code by design; version files change with everything
250
+ fewer = min(h.files[a].commits, h.files[b].commits)
251
+ share = together / fewer if fewer else 0
252
+ if share >= 0.6:
253
+ out.append(Coupling(a, b, together, round(share, 2), (a, b) in imports or _same_package(a, b)))
254
+ out.sort(key=lambda c: (c.linked, -c.together, -c.share))
255
+ return out[:limit]
256
+
257
+
258
+ def knowledge(h: History, g: dict, limit: int = 8) -> list[tuple[str, str, float, int]]:
259
+ """Busy files almost only one person changes: (path, person, share, commits). Only meaningful with a team."""
260
+ if len([p for p, n in h.people.items() if n >= 3]) < 3:
261
+ return []
262
+ code = {f["id"] for f in g["files"] if not is_test(f["id"])}
263
+ out = []
264
+ for path, fh in h.files.items():
265
+ total = sum(fh.authors.values())
266
+ if path in code and total >= 6:
267
+ person, n = fh.authors.most_common(1)[0]
268
+ if n / total >= 0.85:
269
+ out.append((path, person, round(n / total, 2), total))
270
+ return sorted(out, key=lambda x: -x[3])[:limit]
271
+
272
+
273
+ @dataclass
274
+ class Summary:
275
+ history: History
276
+ hot: list[Hotspot]
277
+ coupled: list[Coupling]
278
+ owners: list[tuple[str, str, float, int]]
279
+
280
+ def by_path(self) -> dict[str, Hotspot]:
281
+ return {x.path: x for x in self.hot}
282
+
283
+
284
+ def analyze(root: Path, g: dict) -> Summary:
285
+ h = read(root)
286
+ return Summary(h, hotspots(h, g), coupling(h, g), knowledge(h, g))
287
+
288
+
289
+ FRONT = (".js", ".jsx", ".ts", ".tsx", ".vue", ".svelte", ".mjs", ".dart", ".swift", ".kt")
290
+
291
+
292
+ def _side(path: str) -> str:
293
+ """Which side of an API a file is on, roughly: browser/app code, or everything else (the server)."""
294
+ return "front" if path.endswith(FRONT) and not re.search(r"(?:^|/)(?:server|api|backend|functions)/", path) else "back"
295
+
296
+
297
+ def _span(h: History) -> str:
298
+ if not h.commits:
299
+ return ""
300
+ return f"{time.strftime('%Y-%m-%d', time.gmtime(h.first))} to {time.strftime('%Y-%m-%d', time.gmtime(h.last))}"
301
+
302
+
303
+ def markdown(s: Summary, findings_by_file: dict[str, list[str]] | None = None) -> list[str]:
304
+ h = s.history
305
+ if not h.commits:
306
+ return [f"No history read ({h.note or 'no commits in the last 12 months'}).", ""]
307
+ people = len(h.people)
308
+ out = [
309
+ f"From {h.commits:,} commits ({_span(h)}, {people} {'person' if people == 1 else 'people'}"
310
+ + (f"; {h.note}" if h.note else "")
311
+ + "). A hotspot is code that is both complex and changed often: of all the debt here, it's the part that costs "
312
+ "time every week.",
313
+ "",
314
+ ]
315
+ findings_by_file = findings_by_file or {}
316
+ if s.hot:
317
+ out += ["| Hotspot | Changes (last 3 months) | Lines changed | Complexity | Findings here |", "|---|--:|--:|--:|---|"]
318
+ for x in s.hot:
319
+ found = findings_by_file.get(x.path, [])
320
+ out.append(
321
+ f"| `{x.path}` | {x.commits} ({x.recent}) | {x.churn:,} | {x.complexity} | "
322
+ f"{', '.join(found[:3]) + (f' +{len(found) - 3}' if len(found) > 3 else '') if found else '-'} |"
323
+ )
324
+ out.append("")
325
+ else:
326
+ out += ["No hotspots: no file is both complex and changed often.", ""]
327
+ hidden = [c for c in s.coupled if not c.linked]
328
+ if hidden:
329
+ out += ["**Change together, but neither imports the other** (a change in one needs the other, and nothing says so):", ""]
330
+ out += [f"- `{c.a}` + `{c.b}`: {c.together} commits together ({c.share:.0%} of the rarer one's)" for c in hidden[:6]]
331
+ if any(_side(c.a) != _side(c.b) for c in hidden[:6]):
332
+ out.append(
333
+ "- Front-end and back-end files move together: a contract kept by hand. Generating the client (or its "
334
+ "types) from the API's schema (OpenAPI, GraphQL, a shared types package) makes a broken change fail the "
335
+ "build instead of a user's screen."
336
+ )
337
+ out.append("")
338
+ if s.owners:
339
+ out += ["**Busy code only one person changes** (if they're away, nobody knows it):", ""]
340
+ out += [f"- `{p}`: {share:.0%} of {n} changes by {who}" for p, who, share, n in s.owners]
341
+ out.append("")
342
+ elif people == 1:
343
+ out += ["One person makes every change, so who-knows-what isn't measured.", ""]
344
+ return out
codefactory/infra.py ADDED
@@ -0,0 +1,242 @@
1
+ """Files that aren't application code but decide how it's built, shipped and served: shell scripts and Makefiles,
2
+ docker-compose and Kubernetes YAML, Pkl and other configuration, HTML pages, and patch files.
3
+
4
+ - Credentials written into any of them (the source-code secret patterns, applied to config files too).
5
+ - Shell (scripts, and Makefile recipes, which are shell): piping a download into a shell, `rm -rf` on a variable that
6
+ can be empty, `eval` of a variable, and scripts that carry on after a failing command (no `set -e`).
7
+ - docker-compose: privileged containers, the host's network, databases published on every interface, passwords
8
+ written into `environment:`.
9
+ - Kubernetes: privileged or root containers, the host's network or filesystem, Secrets committed with their values.
10
+ - HTML: scripts, styles and frames loaded over plain HTTP, third-party scripts without integrity hashes, forms that
11
+ post over plain HTTP.
12
+ - Pkl and other configuration: plain-HTTP URLs to packages and services.
13
+
14
+ Line checks with the exact line, like the source checks; the same `codefactory: ignore` comments silence them.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import os
20
+ import re
21
+ from pathlib import Path
22
+
23
+ from .checks import PATTERNS, PLACEHOLDER, VENDOR_SECRETS, Check, Evidence
24
+ from .paths import is_test
25
+ from .suppress import MARK
26
+
27
+ SKIP = {"node_modules", ".git", ".codefactory", ".venv", "venv", "dist", "build", "vendor", "Pods", ".expo", "coverage",
28
+ "__pycache__", "site-packages", "target", ".next", ".nuxt"} # fmt: skip
29
+ CONFIG_EXT = (".yml", ".yaml", ".pkl", ".toml", ".ini", ".cfg", ".conf", ".properties", ".tf", ".tfvars", ".hcl")
30
+ HTML_EXT = (".html", ".htm")
31
+ SHELL_EXT = (".sh", ".bash", ".zsh")
32
+ PATCH_EXT = (".diff", ".patch")
33
+ MAKEFILES = ("Makefile", "makefile", "GNUmakefile")
34
+ MAX_BYTES = 1_000_000
35
+
36
+ KEYS = ("config_secret", "shell_pipe", "shell_rm_var", "shell_eval", "compose_privileged",
37
+ "compose_exposed", "compose_secret", "k8s_privileged", "k8s_host", "k8s_secret", "html_mixed",
38
+ "html_no_sri", "config_http") # fmt: skip
39
+
40
+ # ---- shell
41
+ PIPE_TO_SHELL = re.compile(r"\b(?:curl|wget)\b[^|#\n]*\|\s*(?:sudo\s+(?:-\w+\s+)*)?(?:ba|z|da)?sh\b")
42
+ # `rm -rf "$DIR/"`, a Make variable `$(BUILD)/` or a recipe's `$$OUT/`: empty, it's `rm -rf /`
43
+ RM_VAR = re.compile(
44
+ r"\brm\s+-(?:[a-zA-Z]*r[a-zA-Z]*f|[a-zA-Z]*f[a-zA-Z]*r)[a-zA-Z]*\s+[\"']?\$\$?(?:\{(\w+)\}|\((\w+)\)|(\w+))[\"']?/"
45
+ )
46
+ SHELL_EVAL = re.compile(r"^\s*eval\s+[\"']?\$(?!\()") # not `eval "$(ssh-agent -s)"`: a trusted command's output
47
+ # credentials without quotes, as config files write them: `PASSWORD = s3cr3t…`, `password: hunter2…`, `api.key=…`
48
+ UNQUOTED_SECRET = re.compile(
49
+ r"^\s*(?:export\s+)?[\w.-]*(?:password|passwd|secret|token|api[_.-]?key|private[_.-]?key)[\w.-]*\s*(?::|\??=|:=)\s*"
50
+ r"(?=[^\s'\"]*\d)([^\s'\"$#{(%][^\s#]{7,})\s*$",
51
+ re.I,
52
+ )
53
+ # (no "missing set -e" check: whether scripts should use it is a debated choice, and most handle errors on purpose)
54
+ HARNESS = re.compile(r"(?:^|/)(?:examples?|samples?|demos?|e2e|playwright|cypress|fixtures|testdata)/", re.I)
55
+ # ---- compose / kubernetes
56
+ DB_PORTS = {"5432": "PostgreSQL", "3306": "MySQL", "6379": "Redis", "27017": "MongoDB", "9200": "Elasticsearch",
57
+ "5672": "RabbitMQ", "11211": "Memcached", "1433": "SQL Server", "9042": "Cassandra"} # fmt: skip
58
+ PORT = re.compile(r"^\s*-\s*[\"']?(?:(\d+\.\d+\.\d+\.\d+|\[?::1?\]?):)?(\d+):(\d+)[\"']?\s*$")
59
+ ENV_SECRET = re.compile(
60
+ r"^\s*-?\s*[\"']?(\w*(?:PASSWORD|PASSWD|SECRET|TOKEN|API_?KEY|PRIVATE_KEY)\w*)[\"']?\s*[:=]\s*(.+)$", re.I
61
+ )
62
+ # ---- html
63
+ TAG_SRC = re.compile(r"<(script|link|iframe|img|form)\b[^>]*?\b(?:src|href|action)\s*=\s*[\"'](http://[^\"']+)[\"'][^>]*>", re.I)
64
+ CDN_SCRIPT = re.compile(
65
+ r"<script\b[^>]*\bsrc\s*=\s*[\"'](?:https:)?//(?!(?:localhost|127\.0\.0\.1))([^/\"']+)[^\"']*[\"'][^>]*>", re.I
66
+ )
67
+ LOCAL_HOST = re.compile(
68
+ r"http://(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\]|www\.w3\.org|schemas\.|[^/\"']*\.local\b|example\.)"
69
+ )
70
+ HTTP_URL = re.compile(
71
+ r"""["'`(\s]http://(?!localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\]|www\.w3\.org|schemas\.|example\.|"""
72
+ r"""json-schema\.org|[\w.-]*\.(?:local|svc|internal)(?=[/:"'`\s]|$))[a-z0-9][^"'`\s)]*""",
73
+ re.I,
74
+ )
75
+
76
+
77
+ def files(root: Path, ignore: set[str] | None = None) -> list[str]:
78
+ skip = SKIP | set(ignore or ())
79
+ out = []
80
+ for dirpath, dirnames, filenames in os.walk(root):
81
+ dirnames[:] = sorted(d for d in dirnames if d not in skip and not (d.startswith(".") and d != ".github"))
82
+ for name in sorted(filenames):
83
+ if name.endswith(CONFIG_EXT + HTML_EXT + SHELL_EXT + PATCH_EXT) or name in MAKEFILES or name.endswith(".mk"):
84
+ out.append(Path(dirpath, name).relative_to(root).as_posix())
85
+ return out
86
+
87
+
88
+ def _read(root: Path, rel: str) -> list[str]:
89
+ try:
90
+ path = root / rel
91
+ if path.stat().st_size > MAX_BYTES:
92
+ return []
93
+ return path.read_text(encoding="utf-8", errors="replace").splitlines()
94
+ except OSError:
95
+ return []
96
+
97
+
98
+ def _quiet(lines: list[str], i: int, key: str) -> bool:
99
+ """A `codefactory: ignore` on this line or the one above, naming this kind (or none)."""
100
+ for ln in (lines[i - 1], lines[i - 2] if i > 1 else ""):
101
+ m = MARK.search(ln)
102
+ if m and (not m.group(2).strip() or key in m.group(2) or not re.match(r"\s*[a-z_]", m.group(2))):
103
+ return True
104
+ return False
105
+
106
+
107
+ def _hit(out: dict, key: str, rel: str, lines: list[str], i: int, text: str | None = None) -> None:
108
+ if not _quiet(lines, i, key):
109
+ out[key].hits.append(Evidence(rel, i, (text or lines[i - 1].strip())[:140]))
110
+
111
+
112
+ def _secrets(rel: str, lines: list[str], out: dict, unquoted: bool = True) -> None:
113
+ pats = VENDOR_SECRETS if is_test(rel) else PATTERNS["secret"]
114
+ patch = rel.endswith(PATCH_EXT)
115
+ for i, ln in enumerate(lines, 1):
116
+ if len(ln) > 2000 or (patch and not ln.startswith("+")):
117
+ continue
118
+ body = ln[1:] if patch else ln
119
+ if re.search(PLACEHOLDER, body) or re.search(r"\$\{\{|\$\{|\{\{|\$\(", body):
120
+ continue
121
+ if any(p.search(body) for p in pats) or (unquoted and not is_test(rel) and UNQUOTED_SECRET.match(body)):
122
+ _hit(out, "config_secret", rel, lines, i, f"{body.split('=')[0].split(':')[0].strip()[:60]} = ********")
123
+
124
+
125
+ def shell(rel: str, lines: list[str], out: dict, makefile: bool = False) -> None:
126
+ """Shell scripts, and the recipes of a Makefile (each recipe line runs in a shell)."""
127
+ text = "\n".join(lines)
128
+ # `set -u` (or `#!/bin/sh -eu`): an unset variable stops the script before `rm -rf "$X/"` can run
129
+ guarded = re.search(r"^\s*set\s+-[a-zA-Z]*u|set -o nounset|^#!\S+\s+-[a-zA-Z]*u", text, re.M)
130
+ for i, ln in enumerate(lines, 1):
131
+ code = ln.split(" #", 1)[0] if not makefile else ln
132
+ if makefile and not ln.startswith("\t"):
133
+ continue
134
+ if re.match(r"\s*#", code):
135
+ continue
136
+ if PIPE_TO_SHELL.search(re.sub(r"'[^']*'|\"[^\"]*\"", "''", code)): # not inside a message: echo 'curl … | sh'
137
+ _hit(out, "shell_pipe", rel, lines, i)
138
+ m = RM_VAR.search(code)
139
+ name = m and (m.group(1) or m.group(2) or m.group(3))
140
+ if m and not guarded and not re.search(rf"\$\{{{name}:[?]", code):
141
+ _hit(out, "shell_rm_var", rel, lines, i)
142
+ if SHELL_EVAL.search(code):
143
+ _hit(out, "shell_eval", rel, lines, i)
144
+
145
+
146
+ def compose(rel: str, lines: list[str], out: dict) -> None:
147
+ in_ports = False
148
+ for i, ln in enumerate(lines, 1):
149
+ s = ln.strip()
150
+ if re.match(r"privileged:\s*true\b", s):
151
+ _hit(out, "compose_privileged", rel, lines, i)
152
+ if re.match(r"network_mode:\s*[\"']?host\b", s):
153
+ _hit(out, "compose_privileged", rel, lines, i)
154
+ if re.match(r"ports:\s*$", s):
155
+ in_ports = True
156
+ continue
157
+ if in_ports:
158
+ m = PORT.match(ln)
159
+ if m:
160
+ host_ip, inside = m.group(1), m.group(3)
161
+ if inside in DB_PORTS and not (host_ip or "").startswith(("127.", "[::1]", "::1")):
162
+ _hit(out, "compose_exposed", rel, lines, i, f"{s} ({DB_PORTS[inside]} on every interface)")
163
+ elif s and not s.startswith("#"):
164
+ in_ports = False
165
+ m = ENV_SECRET.match(ln)
166
+ if m:
167
+ value = m.group(2).strip().strip("'\"")
168
+ if (len(value) >= 6 and not m.group(1).upper().endswith("_FILE") and not value.startswith("/")
169
+ and not re.search(PLACEHOLDER + r"|^\$|changethis|^secret$|^password$", value, re.I)): # fmt: skip
170
+ _hit(out, "compose_secret", rel, lines, i, f"{m.group(1)}: {'*' * 8}")
171
+
172
+
173
+ def kubernetes(rel: str, lines: list[str], out: dict) -> None:
174
+ text = "\n".join(lines)
175
+ starts = [0] + [m.end() for m in re.finditer(r"^---[ \t]*\n", text, re.M)]
176
+ for begin, end in zip(starts, [*starts[1:], len(text)], strict=True): # each YAML document
177
+ doc = text[begin:end]
178
+ if re.search(r"^kind:\s*Secret\s*$", doc, re.M) and re.search(r"^(?:data|stringData):\s*\n\s+\w+:\s*\S", doc, re.M):
179
+ name = re.search(r"^\s+name:\s*(\S+)", doc, re.M) # point at the Secret's name: that's what to look up
180
+ at = begin + (name.start(1) if name else doc.find("kind:"))
181
+ label = f"Secret {name.group(1)}" if name else "a Secret"
182
+ _hit(out, "k8s_secret", rel, lines, text.count("\n", 0, at) + 1, f"{label} with its values in the repository")
183
+ for i, ln in enumerate(lines, 1):
184
+ s = ln.strip()
185
+ if re.match(r"(?:privileged|allowPrivilegeEscalation):\s*true\b", s) or re.match(r"runAsUser:\s*0\b", s):
186
+ _hit(out, "k8s_privileged", rel, lines, i)
187
+ if re.match(r"(?:hostNetwork|hostPID|hostIPC):\s*true\b", s) or re.match(r"hostPath:\s*$", s):
188
+ _hit(out, "k8s_host", rel, lines, i)
189
+
190
+
191
+ def html(rel: str, lines: list[str], out: dict) -> None:
192
+ for i, ln in enumerate(lines, 1):
193
+ for m in TAG_SRC.finditer(ln):
194
+ if not LOCAL_HOST.match(m.group(2)):
195
+ _hit(out, "html_mixed", rel, lines, i)
196
+ for m in CDN_SCRIPT.finditer(ln):
197
+ if "integrity=" not in m.group(0).lower():
198
+ _hit(out, "html_no_sri", rel, lines, i, f"<script src=…{m.group(1)}…> without integrity=")
199
+
200
+
201
+ def config_http(rel: str, lines: list[str], out: dict) -> None:
202
+ for i, ln in enumerate(lines, 1):
203
+ if re.match(r"\s*(?:#|//|;)", ln):
204
+ continue
205
+ if HTTP_URL.search(ln) and re.search(r"url|uri|endpoint|host|server|registry|repo|source|amends|import|"
206
+ r"package|mirror|proxy|base|api|href", ln, re.I): # fmt: skip
207
+ _hit(out, "config_http", rel, lines, i)
208
+
209
+
210
+ def scan(root: Path, ignore: set[str] | None = None) -> dict[str, Check]:
211
+ out = {k: Check(k) for k in KEYS}
212
+ for rel in files(root, ignore):
213
+ lines = _read(root, rel)
214
+ if not lines:
215
+ continue
216
+ name = rel.rsplit("/", 1)[-1]
217
+ test = is_test(rel)
218
+ head = "\n".join(lines[:400])
219
+ compose_file = name.endswith((".yml", ".yaml")) and (
220
+ re.search(r"^services:\s*$", head, re.M) or re.search(r"^kind:\s*Secret\s*$", head, re.M)
221
+ ) # compose passwords and Kubernetes Secrets have their own findings
222
+ if not name.endswith(SHELL_EXT): # scripts are source: the source check covers their credentials
223
+ _secrets(rel, lines, out, unquoted=not compose_file) # compose passwords have their own finding
224
+ if test or rel.startswith(".github/workflows/") or HARNESS.search(rel):
225
+ continue # tests, demos and e2e harnesses may do anything; workflows have their own checks (audit.py)
226
+ if name.endswith(SHELL_EXT):
227
+ shell(rel, lines, out)
228
+ elif name in MAKEFILES or name.endswith(".mk"):
229
+ shell(rel, lines, out, makefile=True)
230
+ elif name.endswith((".yml", ".yaml")):
231
+ text = "\n".join(lines[:400])
232
+ if re.search(r"^services:\s*$", text, re.M):
233
+ compose(rel, lines, out)
234
+ if re.search(r"^apiVersion:\s*\S", text, re.M) and re.search(r"^kind:\s*\S", text, re.M):
235
+ kubernetes(rel, lines, out)
236
+ elif name.endswith(HTML_EXT):
237
+ html(rel, lines, out)
238
+ if name.endswith((".pkl", ".toml", ".ini", ".cfg", ".conf", ".properties", ".tf", ".hcl")):
239
+ config_http(rel, lines, out)
240
+ from .paths import drop_ignored
241
+
242
+ return drop_ignored(out, root)