kneepad 0.3.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.
kneepad/engine.py ADDED
@@ -0,0 +1,1063 @@
1
+ """The analysis engine: turns a command into a decision.
2
+
3
+ ``Analyzer`` walks a script (recursively through ``bash -c``, ``$(...)``, ``eval``,
4
+ scripts it can read, ``ssh host cmd`` and friends), matches every simple command
5
+ against the footgun database and the code handlers, and produces a ``Decision``:
6
+ allow, ask or deny, plus the snapshots to take first.
7
+
8
+ Design rules:
9
+ * Never execute the command, and never connect to anything.
10
+ * Anything that cannot be analysed (too deep, too large, unreadable SQL file) is
11
+ surfaced as a finding rather than silently allowed.
12
+ * Heuristics may over-ask. They must not over-allow where the cost is data loss.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import fnmatch
18
+ import glob
19
+ import ntpath
20
+ import os
21
+ import re
22
+ import sys
23
+ from dataclasses import dataclass, field
24
+ from typing import Dict, List, Optional, Tuple
25
+
26
+ from . import sqlscan, winshell
27
+ from .argvtools import INTERPRETERS, SHELLS, ParsedArgv, cmd_name, parse_argv, strip_wrappers
28
+ from .config import Config, stronger
29
+ from .rules import ACTION_RANK, Rule, load_default_rules, match_argv, REGEX_INPUT_CAP
30
+ from .shellparse import MAX_DEPTH, MAX_SRC, Cmd, Word, is_assignment, iter_nested, parse
31
+ from .snapshots import SnapshotError, SnapshotPlan, estimate_size, git, git_toplevel, list_git_clean_paths
32
+ from .util import redact, kneepad_home, user_home
33
+
34
+ DOWNLOADERS = frozenset({"curl", "wget", "fetch", "aria2c", "http", "https", "xh"})
35
+ SQL_CLIENTS = frozenset({
36
+ "psql", "mysql", "mariadb", "sqlite3", "sqlcmd", "cockroach", "clickhouse-client", "clickhouse",
37
+ "snowsql", "duckdb", "usql", "pgcli", "mycli", "litecli", "sqlplus", "trino", "presto", "cqlsh",
38
+ "beeline", "spark-sql", "isql", "bq",
39
+ })
40
+ MONGO_CLIENTS = frozenset({"mongosh", "mongo"})
41
+ REDIS_CLIENTS = frozenset({"redis-cli", "valkey-cli", "keydb-cli"})
42
+ PROTECTED_BRANCHES = frozenset({"main", "master", "trunk", "production", "prod", "release"})
43
+ SYSTEM_PREFIXES = ("/bin", "/sbin", "/usr", "/etc", "/lib", "/lib32", "/lib64", "/boot", "/sys",
44
+ "/proc", "/dev", "/var/lib", "/var/log", "/var/spool", "/opt", "/srv",
45
+ # macOS
46
+ "/System", "/Library", "/Applications", "/var/db", "/var/root", "/cores", "/private/etc",
47
+ "/private/var/db", "/private/var/root")
48
+ # Git Bash, MSYS2, Cygwin and WSL expose Windows drives as /c, /mnt/c and so on.
49
+ _MSYS_DRIVE = re.compile(r"(?i)^/(?:mnt/|cygdrive/)?[a-z]/(windows|program files(?: \(x86\))?|programdata|\$recycle\.bin|system volume information)(?:/|$)")
50
+ _MSYS_ROOT = re.compile(r"(?i)^/(?:mnt/|cygdrive/)?[a-z]$")
51
+ CRED_DIRS = (".ssh", ".aws", ".gnupg", ".kube", ".azure", ".config/gcloud", ".docker", ".config/gh", "Library/Keychains")
52
+ CRED_FILE_RE = re.compile(r"^(id_[a-z0-9_]+|credentials|authorized_keys|config|config\.json|.*\.pem|.*\.key|hosts\.yml|.*\.keychain(?:-db)?|.*\.p12|.*\.pfx)$")
53
+ PROTECTED_HOME_DIRS = (".ssh", ".aws", ".gnupg", ".kube", ".kneepad", "Library/Keychains", "Library/LaunchAgents")
54
+ PROTECTED_HOME_FILES = (
55
+ ".netrc", ".npmrc", ".pypirc", ".bashrc", ".bash_profile", ".profile", ".zshrc", ".zprofile",
56
+ ".zshenv", ".gitconfig", ".docker/config.json", ".claude/settings.json",
57
+ ".claude/settings.local.json", ".config/fish/config.fish",
58
+ )
59
+ def _chmod_is_tightening(mode: str) -> bool:
60
+ """True when a chmod mode cannot make a file writable by group or others."""
61
+ if re.fullmatch(r"[0-7]{3,4}", mode):
62
+ m = mode[-3:]
63
+ return (int(m[1]) & 2) == 0 and (int(m[2]) & 2) == 0
64
+ parts = mode.split(",")
65
+ for part in parts:
66
+ mm = re.fullmatch(r"([ugoa]*)([-+=])([rwxXst]*)", part)
67
+ if not mm:
68
+ return False
69
+ who, op, perms = mm.groups()
70
+ if op in "+=" and "w" in perms and (who == "" or set(who) & set("goa")):
71
+ return False
72
+ return True
73
+
74
+
75
+ HARMLESS_DEVICES = frozenset({"/dev/null", "/dev/zero", "/dev/full", "/dev/stdout", "/dev/stderr", "/dev/stdin",
76
+ "/dev/tty", "/dev/random", "/dev/urandom"})
77
+ # Only destructive infrastructure and data rules are escalated by a "production" marker.
78
+ PROD_FAMILIES = frozenset({"database", "kubernetes", "iac", "aws", "gcp", "azure", "digitalocean", "heroku", "fly",
79
+ "railway", "supabase", "vercel", "migrations", "docker"})
80
+ ENV_EXAMPLE_SUFFIXES = (".example", ".sample", ".template", ".dist")
81
+ BLOCK_DEVICE_RE = re.compile(r"^/dev/(?:sd[a-z]|hd[a-z]|vd[a-z]|xvd[a-z]|nvme\d|mmcblk\d|disk\d|rdisk\d|loop\d|md\d|dm-\d)")
82
+ SAFE_FIND_PATTERNS = [
83
+ r"\*\.(?:pyc|pyo|o|class|tmp|swp|swo|orig|rej|log)", r"\*~", r"__pycache__", r"\.DS_Store",
84
+ r"node_modules", r"\*\.egg-info", r"\.pytest_cache", r"\.mypy_cache",
85
+ ]
86
+ RUNNERS = {
87
+ "bundle": {"exec"}, "poetry": {"run"}, "pipenv": {"run"}, "uv": {"run"}, "pdm": {"run"},
88
+ "rye": {"run"}, "pnpm": {"exec", "dlx"}, "yarn": {"exec", "dlx"}, "npm": {"exec"}, "bun": {"x"},
89
+ }
90
+ SQL_KIND_TO_RULE = {
91
+ sqlscan.SQL_DROP_DATABASE: "sql-drop-database", sqlscan.SQL_DROP_TABLE: "sql-drop-table",
92
+ sqlscan.SQL_TRUNCATE: "sql-truncate", sqlscan.SQL_DELETE_NO_WHERE: "sql-delete-no-where",
93
+ sqlscan.SQL_UPDATE_NO_WHERE: "sql-update-no-where", sqlscan.SQL_DROP_COLUMN: "sql-drop-column",
94
+ sqlscan.SQL_DROP_ROLE: "sql-drop-role",
95
+ }
96
+ MAX_SCRIPT_BYTES = 64 * 1024
97
+ _VAR_RE = re.compile(r"\$(?:\{([A-Za-z_][A-Za-z0-9_]*)\}|([A-Za-z_][A-Za-z0-9_]*))")
98
+ _STRING_LITERAL_RE = re.compile(
99
+ r'"""(.*?)"""|\'\'\'(.*?)\'\'\'|"((?:[^"\\\n]|\\.)*)"|\'((?:[^\'\\\n]|\\.)*)\'', re.S
100
+ )
101
+ _CODE_RM_RE = re.compile(r"\brm\s+-[a-zA-Z]*[rR][a-zA-Z]*\s+(?:--\s+)?(?:/|~|\$HOME)(?:\s|['\"]|$|\*|/)")
102
+ _CODE_RMTREE_RE = re.compile(r"""(?:shutil\.rmtree|rimraf|fs\.rmSync|rmtree)\(\s*['"](/|~)['"]""")
103
+
104
+
105
+ @dataclass
106
+ class Finding:
107
+ rule_id: str
108
+ title: str
109
+ severity: str
110
+ action: str
111
+ why: str
112
+ safer: str
113
+ recipe: str = ""
114
+ detail: str = ""
115
+ reversible: str = "no"
116
+ refs: List[str] = field(default_factory=list)
117
+ plan: Optional[SnapshotPlan] = None
118
+ note: str = ""
119
+
120
+ def to_dict(self) -> dict:
121
+ return {
122
+ "rule": self.rule_id, "title": self.title, "severity": self.severity, "action": self.action,
123
+ "detail": self.detail, "why": self.why, "safer": self.safer, "recipe": self.recipe,
124
+ "reversible": self.reversible, "refs": self.refs, "note": self.note,
125
+ "snapshot": self.plan.kind if self.plan else None,
126
+ }
127
+
128
+
129
+ @dataclass
130
+ class Decision:
131
+ action: str = "allow"
132
+ findings: List[Finding] = field(default_factory=list)
133
+ plans: List[SnapshotPlan] = field(default_factory=list)
134
+ notes: List[str] = field(default_factory=list)
135
+ mode: str = "enforce"
136
+
137
+ def to_dict(self) -> dict:
138
+ return {
139
+ "action": self.action, "mode": self.mode,
140
+ "findings": [f.to_dict() for f in self.findings],
141
+ "snapshots": [p.kind for p in self.plans], "notes": self.notes,
142
+ }
143
+
144
+ def reason(self, limit: int = 3) -> str:
145
+ """Human-readable explanation shown to the user (ask) or to the agent (deny)."""
146
+ top = [f for f in self.findings if f.action == self.action] or self.findings
147
+ lines: List[str] = []
148
+ for f in top[:limit]:
149
+ lines.append(f"Kneepad [{f.severity}] {f.title} ({f.rule_id})")
150
+ if f.detail:
151
+ lines.append(f" Matched: {redact(f.detail, 200)}")
152
+ if f.note:
153
+ lines.append(f" Note: {f.note}")
154
+ lines.append(f" Why: {f.why}")
155
+ lines.append(f" Safer: {f.safer}")
156
+ if f.recipe:
157
+ lines.append(f" Back up first: {f.recipe}")
158
+ if len(top) > limit:
159
+ lines.append(f" (+{len(top) - limit} more findings. Run: kneepad check '<command>' for the full list.)")
160
+ if self.action == "deny":
161
+ lines.append("Blocked. If you are sure, run it yourself in a terminal. Do not retry or disguise the command.")
162
+ return "\n".join(lines)
163
+
164
+
165
+ class Analyzer:
166
+ def __init__(
167
+ self,
168
+ rules: Optional[List[Rule]] = None,
169
+ config: Optional[Config] = None,
170
+ cwd: Optional[str] = None,
171
+ env: Optional[Dict[str, str]] = None,
172
+ home: Optional[str] = None,
173
+ platform: Optional[str] = None,
174
+ ) -> None:
175
+ self.rules = rules if rules is not None else load_default_rules()
176
+ self.by_id: Dict[str, Rule] = {r.id: r for r in self.rules}
177
+ self.cfg = config or Config()
178
+ self.plat = platform or sys.platform
179
+ c0 = cwd or os.getcwd()
180
+ h0 = home or user_home()
181
+ # Windows-shaped paths are normalised with ntpath even when we run elsewhere (tests, WSL, Git Bash).
182
+ self.cwd = ntpath.normpath(c0) if winshell.looks_windows(c0) else os.path.abspath(c0)
183
+ self.home = ntpath.normpath(h0) if winshell.looks_windows(h0) else os.path.normpath(h0)
184
+ self.env = dict(env) if env is not None else dict(os.environ)
185
+ self._dsl = [r for r in self.rules if not r.virtual and "raw_regex" not in r.match and r.family != "windows"]
186
+ self._win_dsl = [r for r in self.rules if not r.virtual and "raw_regex" not in r.match and r.family == "windows"]
187
+ self._raw = [r for r in self.rules if not r.virtual and "raw_regex" in r.match]
188
+ self._reset()
189
+
190
+ # ------------------------------------------------------------------ state
191
+ def _reset(self) -> None:
192
+ self.findings: List[Finding] = []
193
+ self.notes: List[str] = []
194
+ self.vars: Dict[str, str] = {}
195
+ self._script_depth = 0
196
+ self._seen: set = set()
197
+
198
+ def emit(self, rule_id: str, detail: str = "", plan: Optional[SnapshotPlan] = None, note: str = "") -> None:
199
+ r = self.by_id[rule_id]
200
+ if rule_id in self.cfg.disable_rules and not r.no_override:
201
+ return
202
+ if self._script_depth > 0 and (r.severity in ("low", "medium") or plan is not None):
203
+ self.notes.append(f"{rule_id} inside a followed script was not enforced (only high and critical findings are)")
204
+ return
205
+ action = r.action
206
+ ov = self.cfg.action_overrides.get(rule_id)
207
+ if ov and not r.no_override:
208
+ action = ov
209
+ esc = self.cfg.escalations.get(rule_id)
210
+ if esc:
211
+ action = stronger(action, esc)
212
+ key = (rule_id, detail)
213
+ if key in self._seen:
214
+ return
215
+ self._seen.add(key)
216
+ if plan is not None:
217
+ plan.rule_id = rule_id
218
+ self.findings.append(Finding(
219
+ rule_id=r.id, title=r.title, severity=r.severity, action=action, why=r.why, safer=r.safer,
220
+ recipe=r.recipe, detail=detail, reversible=r.reversible, refs=list(r.refs), plan=plan, note=note,
221
+ ))
222
+
223
+ # --------------------------------------------------------------- public API
224
+ def analyze_shell(self, command: str) -> Decision:
225
+ command = command.replace("\x00", "") # a NUL ends the command for the shell; analyse the pessimistic reading
226
+ self._reset()
227
+ text = command.lstrip("\ufeff") # editors sometimes prepend a BOM
228
+ if len(text) > MAX_SRC:
229
+ self.emit("analysis-limit-exceeded", f"input is {len(text)} bytes, limit {MAX_SRC}")
230
+ text = text[:MAX_SRC]
231
+ for r in self._raw:
232
+ if re.search(r.match["raw_regex"], text):
233
+ self.emit(r.id, text[:120])
234
+ self._walk(text, 0)
235
+ return self._finish(text)
236
+
237
+ def analyze_write_path(self, path: str) -> Decision:
238
+ self._reset()
239
+ abs_path = self._abs(os.path.expanduser(path) if path.startswith("~") else path)
240
+ reason = self._protected_reason(abs_path)
241
+ if reason:
242
+ self.emit("fs-protected-path-write", f"{abs_path} ({reason})")
243
+ return self._finish(abs_path)
244
+
245
+ def analyze_mcp(self, tool_name: str, tool_input: object) -> Decision:
246
+ self._reset()
247
+ strings: List[Tuple[str, str]] = []
248
+ _collect_strings(tool_input, "", strings, [0])
249
+ lname = tool_name.lower()
250
+ if re.search(r"sql|query|database|\bdb\b|postgres|mysql|sqlite|supabase|neon|planetscale|snowflake|bigquery|execute", lname):
251
+ for _k, s in strings:
252
+ self._scan_sql_like(s)
253
+ if re.search(r"shell|bash|terminal|run_command|exec|command", lname):
254
+ for k, s in strings:
255
+ if k.split(".")[-1].lower() in ("command", "cmd", "script", "code", "args", "input"):
256
+ self._walk(s[:MAX_SRC], 0)
257
+ if re.search(r"mongo", lname):
258
+ for _k, s in strings:
259
+ self._scan_mongo_like(s)
260
+ if re.search(r"redis", lname):
261
+ for _k, s in strings:
262
+ self._scan_redis_like(s)
263
+ return self._finish(" ".join(s for _k, s in strings)[:MAX_SRC])
264
+
265
+ # ------------------------------------------------------------------ finish
266
+ def _finish(self, raw_text: str) -> Decision:
267
+ prod = False
268
+ for pat in self.cfg.prod_markers:
269
+ try:
270
+ if re.search(pat, raw_text):
271
+ prod = True
272
+ break
273
+ except re.error:
274
+ continue
275
+ for f in self.findings:
276
+ r = self.by_id[f.rule_id]
277
+ if prod and f.action == "ask" and f.severity in ("high", "critical") and r.family in PROD_FAMILIES:
278
+ f.action = "deny"
279
+ f.note = (f.note + " " if f.note else "") + "Escalated to deny: the command mentions production."
280
+ for pat in self.cfg.allow_patterns:
281
+ try:
282
+ hit = re.search(pat, raw_text)
283
+ except re.error:
284
+ continue
285
+ if hit:
286
+ for f in self.findings:
287
+ if not self.by_id[f.rule_id].no_override and f.action != "allow":
288
+ f.action = "allow"
289
+ f.note = (f.note + " " if f.note else "") + f"Allowed by allow_patterns {pat!r}."
290
+ action = "allow"
291
+ for f in self.findings:
292
+ action = stronger(action, f.action)
293
+ plans: List[SnapshotPlan] = []
294
+ seen_plans: set = set()
295
+ if action in ("allow", "ask"):
296
+ for f in self.findings:
297
+ if f.plan is not None and f.action in ("allow", "ask"):
298
+ key = (f.plan.kind, f.plan.cwd, f.plan.repo, tuple(f.plan.paths), tuple(f.plan.branches))
299
+ if key not in seen_plans:
300
+ seen_plans.add(key)
301
+ plans.append(f.plan)
302
+ return Decision(action=action, findings=self.findings, plans=plans, notes=self.notes, mode=self.cfg.mode)
303
+
304
+ # ------------------------------------------------------------------- walk
305
+ def _walk(self, src: str, depth: int) -> None:
306
+ if depth > MAX_DEPTH:
307
+ self.emit("analysis-limit-exceeded", f"nesting deeper than {MAX_DEPTH}")
308
+ return
309
+ cmds = parse(src)
310
+ for idx in range(len(cmds)):
311
+ self._cmd(cmds, idx, depth)
312
+ for sub in iter_nested(cmds):
313
+ self._walk(sub, depth + 1)
314
+ winshell.analyze(self, src, depth)
315
+
316
+ def _cmd(self, cmds: List[Cmd], idx: int, depth: int) -> None:
317
+ cmd = cmds[idx]
318
+ for op, target in cmd.redirects:
319
+ if op in (">", ">>", ">|", "&>", "&>>"):
320
+ self._check_redirect(target)
321
+ words = cmd.argv
322
+ if not words:
323
+ return
324
+ if all(is_assignment(w.text) for w in words):
325
+ self._record_assignments(words)
326
+ return
327
+ norm, meta = strip_wrappers(words)
328
+ if meta.get("query") or not norm:
329
+ return
330
+ name0 = cmd_name(norm[0].text)
331
+ if name0 in ("export", "declare", "local", "readonly", "typeset"):
332
+ self._record_assignments(norm[1:])
333
+ return
334
+ pa = parse_argv(norm, meta)
335
+ if pa is None:
336
+ return
337
+ self._analyze_pa(pa, cmd, cmds, idx, depth)
338
+
339
+ def _analyze_words(self, words: List[Word], depth: int) -> None:
340
+ if depth > MAX_DEPTH:
341
+ self.emit("analysis-limit-exceeded", f"nesting deeper than {MAX_DEPTH}")
342
+ return
343
+ norm, meta = strip_wrappers(words)
344
+ if meta.get("query") or not norm:
345
+ return
346
+ pa = parse_argv(norm, meta)
347
+ if pa is not None:
348
+ self._analyze_pa(pa, None, None, -1, depth)
349
+
350
+ def _record_assignments(self, words: List[Word]) -> None:
351
+ for w in words:
352
+ if is_assignment(w.text):
353
+ name, val = w.text.split("=", 1)
354
+ self.vars[name.rstrip("+")] = val
355
+
356
+ # ---------------------------------------------------------- per-command
357
+ def _analyze_pa(self, pa: ParsedArgv, cmd: Optional[Cmd], cmds: Optional[List[Cmd]], idx: int, depth: int) -> None:
358
+ if len(pa.argstr) > REGEX_INPUT_CAP:
359
+ self.emit("cmd-oversized", f"{pa.name}: {len(pa.argstr)} characters of arguments")
360
+ # `tool --help` / `tool --version` as the first argument only prints text for every tool we know.
361
+ # Only the first position is exempt: GNU dd, for one, honours --help solely as argv[1].
362
+ if pa.tokens and pa.tokens[0] in ("--help", "--version") and pa.name not in SHELLS and pa.name not in ("sudo", "env", "xargs", "nohup", "time", "command", "exec"):
363
+ return
364
+ for r in self._dsl:
365
+ if match_argv(r, pa):
366
+ self._emit_dsl(r, pa)
367
+ name = pa.name
368
+ if name == "rm":
369
+ self._h_rm(pa)
370
+ elif name == "find":
371
+ self._h_find(pa, depth)
372
+ elif name == "git":
373
+ self._h_git(pa)
374
+ elif name in ("chmod", "chown", "chgrp"):
375
+ self._h_chmod(pa)
376
+ self._h_writers(pa)
377
+ self._h_pipe_to_shell(pa, cmds, idx)
378
+ stdin_texts, unreadable = self._stdin_texts(cmd, cmds, idx) if cmd is not None else ([], [])
379
+ if name in SHELLS:
380
+ self._h_shell(pa, stdin_texts, depth)
381
+ elif name in ("eval",):
382
+ self._walk(" ".join(pa.tokens), depth + 1)
383
+ elif name in ("source", "."):
384
+ if pa.pos:
385
+ self._follow_script(pa.pos[0], depth)
386
+ elif name == "osascript":
387
+ self._h_osascript(pa, depth)
388
+ elif name in INTERPRETERS:
389
+ self._h_interpreter(pa, stdin_texts)
390
+ elif name in SQL_CLIENTS or name in MONGO_CLIENTS or name in REDIS_CLIENTS:
391
+ self._h_db(pa, stdin_texts, unreadable)
392
+ elif ("/" in pa.raw0 or pa.raw0.startswith(".")) and name not in ("rm",) and pa.raw0 not in (".", ".."):
393
+ self._follow_script(pa.raw0, depth)
394
+ self._h_runners(pa, depth)
395
+
396
+ def _emit_dsl(self, r: Rule, pa: ParsedArgv) -> None:
397
+ detail = " ".join([pa.raw0] + pa.tokens)[:200]
398
+ plan: Optional[SnapshotPlan] = None
399
+ if r.snapshot != "none":
400
+ ok, plan = self._make_plan(r, pa)
401
+ if not ok:
402
+ return
403
+ self.emit(r.id, detail, plan=plan)
404
+
405
+ def _make_plan(self, r: Rule, pa: ParsedArgv) -> Tuple[bool, Optional[SnapshotPlan]]:
406
+ """Return (continue, plan). ``continue`` False means a blocking finding was already emitted."""
407
+ cwd = self._git_cwd(pa)
408
+ top = git_toplevel(cwd) if os.path.isdir(cwd) else None
409
+ if top is None:
410
+ # Not a repository: git itself will refuse to run, so there is nothing to protect.
411
+ return True, None
412
+ if r.snapshot == "git-stash":
413
+ return True, SnapshotPlan("git-stash", cwd, repo=top)
414
+ if r.snapshot == "git-branch":
415
+ return True, SnapshotPlan("git-branch", cwd, repo=top, branches=list(pa.pos[1:]))
416
+ if r.snapshot == "git-clean":
417
+ try:
418
+ after = pa.tokens[pa.tokens.index("clean") + 1:] if "clean" in pa.tokens else []
419
+ paths = list_git_clean_paths(cwd, after)
420
+ except (SnapshotError, OSError, ValueError) as exc:
421
+ self.emit("snapshot-unavailable", f"git clean: {exc}")
422
+ return False, None
423
+ if not paths:
424
+ return True, None
425
+ b, _f, exceeded = estimate_size(paths, self.cfg.snapshot_max_mb * 1024 * 1024, self.cfg.snapshot_max_files)
426
+ if exceeded:
427
+ self.emit("fs-rm-too-large-to-snapshot", "git clean would delete more than the snapshot limit")
428
+ return False, None
429
+ return True, SnapshotPlan("git-clean", cwd, repo=top, paths=paths, est_bytes=b)
430
+ return True, None
431
+
432
+ def _git_cwd(self, pa: ParsedArgv) -> str:
433
+ c = pa.flag_values.get("-C")
434
+ if c:
435
+ return self._abs(c)
436
+ return self.cwd
437
+
438
+ # ------------------------------------------------------------- expansion
439
+ def _abs(self, path: str) -> str:
440
+ if winshell.looks_windows(path) or winshell.looks_windows(self.cwd):
441
+ n = winshell.norm_path(path, self.cwd)
442
+ if n is not None:
443
+ return n
444
+ p = os.path.normpath(path if os.path.isabs(path) else os.path.join(self.cwd, path))
445
+ if p.startswith("//"): # POSIX normpath keeps exactly two leading slashes
446
+ p = "/" + p.lstrip("/")
447
+ return p
448
+
449
+ def _lookup(self, name: str) -> Optional[str]:
450
+ if name in self.vars:
451
+ return self.vars[name]
452
+ if name == "HOME":
453
+ return self.home
454
+ if name == "PWD":
455
+ return self.cwd
456
+ return None
457
+
458
+ def _expand_text(self, text: str, depth: int = 0) -> Tuple[str, bool]:
459
+ out: List[str] = []
460
+ pos = 0
461
+ dynamic = False
462
+ for m in _VAR_RE.finditer(text):
463
+ name = m.group(1) or m.group(2)
464
+ val = self._lookup(name)
465
+ out.append(text[pos:m.start()])
466
+ if val is None:
467
+ dynamic = True
468
+ out.append(m.group(0))
469
+ else:
470
+ if "$" in val or "`" in val:
471
+ if depth < 3:
472
+ val, dyn = self._expand_text(val, depth + 1)
473
+ dynamic = dynamic or dyn
474
+ else:
475
+ dynamic = True
476
+ out.append(val)
477
+ pos = m.end()
478
+ out.append(text[pos:])
479
+ res = "".join(out)
480
+ if "$" in res or "`" in res:
481
+ dynamic = True
482
+ return res, dynamic
483
+
484
+ def _expand_word(self, w: Word) -> Tuple[str, bool]:
485
+ text = w.text
486
+ if w.raw.startswith("~") and (text == "~" or text.startswith("~/")):
487
+ text = self.home + text[1:]
488
+ if not w.has_var:
489
+ return text, False
490
+ return self._expand_text(text)
491
+
492
+ # ---------------------------------------------------------------- rm
493
+ def _ci(self, s: str) -> str:
494
+ """Default macOS and Windows volumes are case-insensitive, so compare lower-cased."""
495
+ return s.lower() if self.plat in ("darwin", "win32") else s
496
+
497
+ def _classify(self, p: str) -> str:
498
+ if winshell.looks_windows(p):
499
+ return winshell.classify(p, self.cwd, self.home)
500
+ if p == "/":
501
+ return "catastrophic"
502
+
503
+ # macOS keeps /etc, /var and /tmp under /private, and temp dirs, project dirs and sometimes homes
504
+ # resolve there. Strip the prefix from the target, the home and the cwd alike, or they never compare equal.
505
+ def unpriv(x: str) -> str:
506
+ if x == "/private" or x.startswith("/private/"):
507
+ return x[len("/private"):] or "/"
508
+ return x
509
+
510
+ p = unpriv(p)
511
+ if p == "/":
512
+ return "catastrophic"
513
+ parts = [x for x in p.split("/") if x]
514
+ if len(parts) == 1 or _MSYS_ROOT.match(p):
515
+ return "catastrophic"
516
+ q = self._ci(p)
517
+ home_dir = unpriv(self.home)
518
+ home = self._ci(home_dir)
519
+ cwd = self._ci(unpriv(self.cwd))
520
+ if q == home or (home != "/" and home.startswith(q + "/")):
521
+ return "catastrophic"
522
+ if cwd == q or cwd.startswith(q + "/"):
523
+ return "ancestor"
524
+ if os.path.basename(p) == ".git":
525
+ return "dotgit"
526
+ for d in CRED_DIRS:
527
+ base = self._ci(os.path.join(home_dir, d))
528
+ if q == base or (q.startswith(base + "/") and CRED_FILE_RE.match(os.path.basename(p))):
529
+ return "creds"
530
+ for pref in SYSTEM_PREFIXES:
531
+ pr = self._ci(pref)
532
+ if q == pr or q.startswith(pr + "/"):
533
+ return "system"
534
+ if _MSYS_DRIVE.match(p):
535
+ return "system"
536
+ if self.plat == "darwin" and q.startswith("/users/") and not (q == home or q.startswith(home + "/")):
537
+ return "system"
538
+ return "normal"
539
+
540
+ def _ignorable(self, p: str) -> bool:
541
+ parts = set(re.split(r"[\\/]", p)) if winshell.looks_windows(p) else set(p.split("/"))
542
+ base = os.path.basename(p)
543
+ return bool(parts & self.cfg.ignore_dirs) or base == ".DS_Store" or base.endswith(".pyc")
544
+
545
+ def _git_recoverable(self, p: str) -> bool:
546
+ """True when ``p`` is tracked by git with no local changes, so git can restore it."""
547
+ d = p if os.path.isdir(p) and not os.path.islink(p) else os.path.dirname(p)
548
+ top = git_toplevel(d)
549
+ if not top:
550
+ return False
551
+ try:
552
+ tracked = git(top, "ls-files", "--", p)
553
+ if tracked.returncode != 0 or not tracked.stdout.strip():
554
+ return False
555
+ status = git(top, "status", "--porcelain", "--ignored", "--", p)
556
+ return status.returncode == 0 and not status.stdout.strip()
557
+ except Exception:
558
+ return False
559
+
560
+ def _h_rm(self, pa: ParsedArgv) -> None:
561
+ recursive = bool({"-r", "-R", "--recursive"} & pa.flags)
562
+ if "--no-preserve-root" in pa.flags:
563
+ self.emit("fs-rm-catastrophic", "--no-preserve-root")
564
+ if pa.meta.get("xargs"):
565
+ self.emit("fs-rm-via-xargs", " ".join([pa.raw0] + pa.tokens)[:160])
566
+ cands: List[str] = []
567
+ for w in pa.pos_words:
568
+ text, dyn = self._expand_word(w)
569
+ if dyn:
570
+ if recursive:
571
+ self.emit("fs-rm-dynamic-target", w.raw or w.text)
572
+ continue
573
+ if text == "":
574
+ continue
575
+ paths = [text]
576
+ if w.glob:
577
+ pat = text if os.path.isabs(text) else os.path.join(self.cwd, text)
578
+ matches = glob.glob(pat)
579
+ if len(matches) > 2000:
580
+ if recursive:
581
+ self.emit("fs-rm-dynamic-target", f"glob {w.raw} matches more than 2000 paths")
582
+ continue
583
+ paths = matches
584
+ if recursive and text in (".*", "./.*"):
585
+ self.emit("fs-rm-ancestor-of-cwd", ".* can match .. on some systems")
586
+ for p in paths:
587
+ self._rm_one(p, recursive, cands)
588
+ seen: set = set()
589
+ need: List[str] = []
590
+ for p in cands:
591
+ if p in seen:
592
+ continue
593
+ seen.add(p)
594
+ if not os.path.lexists(p) or self._ignorable(p) or self._git_recoverable(p):
595
+ continue
596
+ need.append(p)
597
+ if need:
598
+ b, _f, exceeded = estimate_size(need, self.cfg.snapshot_max_mb * 1024 * 1024, self.cfg.snapshot_max_files)
599
+ if exceeded:
600
+ self.emit("fs-rm-too-large-to-snapshot", ", ".join(need)[:160])
601
+ else:
602
+ self.emit("fs-rm-snapshot", ", ".join(need)[:160], plan=SnapshotPlan("files", self.cwd, paths=need, est_bytes=b))
603
+
604
+ def _rm_one(self, p: str, recursive: bool, cands: List[str]) -> None:
605
+ ap = self._abs(p)
606
+ isdir = os.path.isdir(ap) and not os.path.islink(ap)
607
+ kind = self._classify(ap)
608
+ if kind in ("catastrophic", "ancestor", "dotgit") and not recursive and isdir:
609
+ return # rm refuses a directory without -r
610
+ if kind == "catastrophic":
611
+ self.emit("fs-rm-catastrophic", ap)
612
+ elif kind == "ancestor":
613
+ self.emit("fs-rm-ancestor-of-cwd", ap)
614
+ elif kind == "dotgit":
615
+ self.emit("fs-rm-dot-git", ap)
616
+ elif kind == "creds":
617
+ self.emit("fs-rm-credentials-dir", ap)
618
+ elif kind == "system":
619
+ self.emit("fs-rm-system-path", ap)
620
+ else:
621
+ cands.append(ap)
622
+
623
+ # -------------------------------------------------------------- find
624
+ def _h_find(self, pa: ParsedArgv, depth: int) -> None:
625
+ toks = pa.tokens
626
+ names: List[str] = []
627
+ has_delete = False
628
+ for i, t in enumerate(toks):
629
+ if t in ("-name", "-iname", "-path", "-ipath", "-regex") and i + 1 < len(toks):
630
+ names.append(toks[i + 1])
631
+ if t == "-delete":
632
+ has_delete = True
633
+ safe = bool(names) and all(any(re.fullmatch(p, n) for p in SAFE_FIND_PATTERNS) for n in names)
634
+ if has_delete and not safe:
635
+ self.emit("fs-find-delete", " ".join(["find"] + toks)[:200])
636
+ words = pa.words[1:]
637
+ i = 0
638
+ while i < len(toks):
639
+ if toks[i] in ("-exec", "-execdir", "-ok", "-okdir"):
640
+ j = i + 1
641
+ while j < len(toks) and toks[j] not in (";", "+"):
642
+ j += 1
643
+ payload = words[i + 1:j]
644
+ if payload:
645
+ norm, _m = strip_wrappers(payload)
646
+ first = cmd_name(norm[0].text) if norm else ""
647
+ if first in ("rm", "shred", "unlink", "rmdir"):
648
+ if not safe:
649
+ self.emit("fs-find-delete", " ".join(["find"] + toks)[:200])
650
+ else:
651
+ self._analyze_words(payload, depth + 1)
652
+ i = j
653
+ i += 1
654
+
655
+ # --------------------------------------------------------------- git
656
+ def _h_git(self, pa: ParsedArgv) -> None:
657
+ if not pa.pos or pa.pos[0] != "push":
658
+ return
659
+ force = bool({"--force", "-f"} & pa.flags) and not ({"--force-with-lease", "--force-if-includes"} & pa.flags)
660
+ refspecs = pa.pos[2:]
661
+ plus = [r for r in refspecs if r.startswith("+")]
662
+ if plus:
663
+ self.emit("git-push-plus-refspec", " ".join(plus)[:120])
664
+ protected = set(PROTECTED_BRANCHES) | set(self.cfg.protected_branches)
665
+
666
+ def is_protected(b: str) -> bool:
667
+ return b in protected or b.startswith("release/")
668
+
669
+ hit: List[str] = []
670
+ for r in refspecs:
671
+ spec = r.lstrip("+")
672
+ dst = spec.split(":", 1)[1] if ":" in spec else spec
673
+ dst = dst[len("refs/heads/"):] if dst.startswith("refs/heads/") else dst
674
+ if (force or r.startswith("+")) and is_protected(dst):
675
+ hit.append(dst)
676
+ if force and not refspecs and "--all" not in pa.flags and "--mirror" not in pa.flags:
677
+ try:
678
+ r = git(self._git_cwd(pa), "symbolic-ref", "--short", "-q", "HEAD")
679
+ cur = r.stdout.strip() if r.returncode == 0 else ""
680
+ except Exception:
681
+ cur = ""
682
+ if cur and is_protected(cur):
683
+ hit.append(cur)
684
+ if hit:
685
+ self.emit("git-force-push-protected-branch", ", ".join(sorted(set(hit))))
686
+
687
+ # ------------------------------------------------------- chmod / chown
688
+ def _h_chmod(self, pa: ParsedArgv) -> None:
689
+ if not ({"-R", "--recursive"} & pa.flags):
690
+ return
691
+ targets = pa.pos_words[1:] if pa.pos_words else []
692
+ for w in targets:
693
+ text, dyn = self._expand_word(w)
694
+ if dyn or text == "":
695
+ continue
696
+ ap = self._abs(text)
697
+ if self._classify(ap) == "catastrophic" or ap == "/":
698
+ self.emit("fs-chmod-chown-critical", ap)
699
+
700
+ # ----------------------------------------------------- protected writes
701
+ def _protected_reason(self, ap: str) -> Optional[str]:
702
+ if winshell.looks_windows(ap):
703
+ return winshell.protected_reason(ap, self.home, kneepad_home())
704
+ home = self.home
705
+ if ap in HARMLESS_DEVICES or ap.startswith("/dev/fd/"):
706
+ return None
707
+ for pat in self.cfg.allow_write_paths:
708
+ p = os.path.expanduser(pat)
709
+ p = p if os.path.isabs(p) else os.path.join(self.cwd, p)
710
+ if fnmatch.fnmatch(ap, p) or ap == p:
711
+ return None
712
+ c = self._ci(ap)
713
+ for rel in PROTECTED_HOME_DIRS:
714
+ base = self._ci(os.path.join(home, rel))
715
+ if c == base or c.startswith(base + "/"):
716
+ return f"protected directory ~/{rel}"
717
+ sb = self._ci(kneepad_home())
718
+ if c == sb or c.startswith(sb + "/"):
719
+ return "Kneepad's own state"
720
+ for rel in PROTECTED_HOME_FILES:
721
+ if c == self._ci(os.path.join(home, rel)):
722
+ return f"protected file ~/{rel}"
723
+ for pref in SYSTEM_PREFIXES:
724
+ pr = self._ci(pref)
725
+ if c == pr or c.startswith(pr + "/"):
726
+ return "system path"
727
+ parts = [x for x in ap.split("/") if x]
728
+ for i in range(len(parts) - 1):
729
+ pair = (parts[i], parts[i + 1])
730
+ if pair in ((".git", "hooks"), (".git", "config"), (".github", "workflows")):
731
+ return f"{pair[0]}/{pair[1]}"
732
+ if parts[i] == ".claude" and parts[i + 1] in ("settings.json", "settings.local.json"):
733
+ return "agent settings"
734
+ base = os.path.basename(ap)
735
+ if base == ".kneepad.toml":
736
+ return "Kneepad project config"
737
+ if re.match(r"^\.env(\.[A-Za-z0-9_-]+)?$", base) and not base.endswith(ENV_EXAMPLE_SUFFIXES):
738
+ return "environment file with secrets"
739
+ for pat in self.cfg.protected_paths:
740
+ p = os.path.expanduser(pat)
741
+ p = p if os.path.isabs(p) else os.path.join(self.cwd, p)
742
+ if fnmatch.fnmatch(ap, p) or ap == p:
743
+ return f"protected by config pattern {pat}"
744
+ return None
745
+
746
+ def _check_write_word(self, w: Word, skip_system: bool = False) -> None:
747
+ text, dyn = self._expand_word(w)
748
+ if dyn or text == "":
749
+ return
750
+ ap = self._abs(text)
751
+ reason = self._protected_reason(ap)
752
+ if reason and not (skip_system and reason == "system path"):
753
+ self.emit("fs-protected-path-write", f"{ap} ({reason})")
754
+
755
+ def _check_redirect(self, target: Word) -> None:
756
+ text, dyn = self._expand_word(target)
757
+ if dyn or text == "":
758
+ return
759
+ if BLOCK_DEVICE_RE.match(text):
760
+ self.emit("fs-redirect-to-block-device", text)
761
+ return
762
+ self._check_write_word(target)
763
+
764
+ def _h_writers(self, pa: ParsedArgv) -> None:
765
+ name = pa.name
766
+ words: List[Word] = []
767
+ if name == "tee":
768
+ words = list(pa.pos_words)
769
+ elif name in ("cp", "install", "ln", "rsync", "scp"):
770
+ if pa.pos_words:
771
+ words = [pa.pos_words[-1]]
772
+ elif name in ("mv", "rm", "shred", "truncate", "unlink"):
773
+ words = list(pa.pos_words)
774
+ elif name == "sed":
775
+ if any(f.startswith("-i") or f == "--in-place" for f in pa.flags) or any(t.startswith("-i") for t in pa.tokens):
776
+ words = list(pa.pos_words)
777
+ elif name in ("chmod", "chown", "chgrp"):
778
+ words = list(pa.pos_words[1:])
779
+ if name == "chmod" and pa.pos and _chmod_is_tightening(pa.pos[0]):
780
+ words = [] # restricting permissions (e.g. 600, go-rwx) is routine hygiene
781
+ elif name == "dd":
782
+ for t, w in zip(pa.tokens, pa.words[1:]):
783
+ if t.startswith("of="):
784
+ words.append(Word(text=t[3:], raw=t[3:]))
785
+ elif name == "curl":
786
+ for f in ("-o", "--output"):
787
+ if f in pa.flag_values:
788
+ words.append(Word(text=pa.flag_values[f], raw=pa.flag_values[f]))
789
+ elif name == "wget":
790
+ for f in ("-O", "--output-document"):
791
+ if f in pa.flag_values:
792
+ words.append(Word(text=pa.flag_values[f], raw=pa.flag_values[f]))
793
+ for f in ("-t", "--target-directory"):
794
+ if f in pa.flag_values and name in ("cp", "mv", "install", "ln"):
795
+ words.append(Word(text=pa.flag_values[f], raw=pa.flag_values[f]))
796
+ for w in words:
797
+ if name == "dd" or not w.text.startswith("-"):
798
+ self._check_write_word(w, skip_system=name in ("rm", "dd", "shred", "unlink"))
799
+
800
+ # ----------------------------------------------------------- pipelines
801
+ _APPLESCRIPT_SHELL = re.compile(r'(?is)do\s+shell\s+script\s+"((?:[^"\\]|\\.)*)"')
802
+ _JXA_SHELL = re.compile(r"(?is)doShellScript\(\s*(?:\"((?:[^\"\\]|\\.)*)\"|'((?:[^'\\]|\\.)*)')")
803
+
804
+ def _h_osascript(self, pa: ParsedArgv, depth: int) -> None:
805
+ """AppleScript and JXA can run shell commands. Analyse the command strings we can see."""
806
+ scripts: List[str] = []
807
+ toks = pa.tokens
808
+ for i, t in enumerate(toks):
809
+ if t == "-e" and i + 1 < len(toks):
810
+ scripts.append(toks[i + 1])
811
+ text = "\n".join(scripts)
812
+ for m in self._APPLESCRIPT_SHELL.finditer(text):
813
+ self._walk(m.group(1).replace('\\"', '"').replace("\\\\", "\\"), depth + 1)
814
+ for m in self._JXA_SHELL.finditer(text):
815
+ self._walk((m.group(1) or m.group(2) or "").replace("\\\"", '"'), depth + 1)
816
+
817
+ def _h_pipe_to_shell(self, pa: ParsedArgv, cmds: Optional[List[Cmd]], idx: int) -> None:
818
+ name = pa.name
819
+ is_shell = name in SHELLS
820
+ is_interp = name in INTERPRETERS
821
+ if cmds is not None and idx > 0 and cmds[idx].pipe_in and (is_shell or is_interp):
822
+ has_c = any(re.fullmatch(r"-[A-Za-z]*c[A-Za-z]*", t) for t in pa.tokens) if is_shell else False
823
+ reads_stdin = (not pa.pos) or pa.pos == ["-"] or "-s" in pa.flags
824
+ if not has_c and reads_stdin:
825
+ j = idx - 1
826
+ while j >= 0: # walk back through the whole pipeline, e.g. curl | tee f | sh
827
+ prev_norm, _m = strip_wrappers(cmds[j].argv)
828
+ if prev_norm and cmd_name(prev_norm[0].text) in DOWNLOADERS:
829
+ self.emit("net-pipe-to-shell", f"{prev_norm[0].text} ... | {name}")
830
+ break
831
+ if not cmds[j].pipe_in:
832
+ break
833
+ j -= 1
834
+ if is_shell or name in ("eval", "source", "."):
835
+ for w in pa.pos_words:
836
+ for sub in w.subs:
837
+ for c in parse(sub):
838
+ n, _m = strip_wrappers(c.argv)
839
+ if n and cmd_name(n[0].text) in DOWNLOADERS:
840
+ self.emit("net-pipe-to-shell", f"{name} <(...{n[0].text}...)")
841
+ for w in pa.words[1:]:
842
+ for sub in w.subs:
843
+ for c in parse(sub):
844
+ n, _m = strip_wrappers(c.argv)
845
+ if n and cmd_name(n[0].text) in DOWNLOADERS:
846
+ self.emit("net-pipe-to-shell", f"{name} with output of {n[0].text}")
847
+
848
+ # --------------------------------------------------------------- stdin
849
+ def _read_text(self, path: str, limit: int = 2_000_000) -> Optional[str]:
850
+ ap = self._abs(os.path.expanduser(path) if path.startswith("~") else path)
851
+ try:
852
+ if not os.path.isfile(ap) or os.path.getsize(ap) > limit:
853
+ return None
854
+ with open(ap, "rb") as fh:
855
+ data = fh.read(limit)
856
+ except OSError:
857
+ return None
858
+ if b"\0" in data[:1024]:
859
+ return None
860
+ return data.decode("utf-8", errors="replace")
861
+
862
+ def _stdin_texts(self, cmd: Optional[Cmd], cmds: Optional[List[Cmd]], idx: int) -> Tuple[List[str], List[str]]:
863
+ texts: List[str] = []
864
+ unreadable: List[str] = []
865
+ if cmd is None:
866
+ return texts, unreadable
867
+ texts.extend(cmd.heredocs)
868
+ for op, w in cmd.redirects:
869
+ if op == "<<<":
870
+ texts.append(w.text)
871
+ elif op == "<":
872
+ content = self._read_text(w.text)
873
+ if content is None:
874
+ unreadable.append(w.text)
875
+ else:
876
+ texts.append(content)
877
+ if cmd.pipe_in and cmds is not None and idx > 0:
878
+ prev = cmds[idx - 1]
879
+ pn, _m = strip_wrappers(prev.argv)
880
+ if pn:
881
+ name = cmd_name(pn[0].text)
882
+ if name in ("echo", "printf"):
883
+ texts.append(" ".join(w.text for w in pn[1:]))
884
+ elif name == "cat":
885
+ for w in pn[1:]:
886
+ if not w.text.startswith("-"):
887
+ content = self._read_text(w.text)
888
+ if content is not None:
889
+ texts.append(content)
890
+ texts.extend(prev.heredocs)
891
+ return texts, unreadable
892
+
893
+ # ---------------------------------------------------- shells and scripts
894
+ def _h_shell(self, pa: ParsedArgv, stdin_texts: List[str], depth: int) -> None:
895
+ toks = pa.tokens
896
+ payload: Optional[str] = None
897
+ for i, t in enumerate(toks):
898
+ if t.startswith("-") and not t.startswith("--") and "c" in t[1:] and t[1:].isalpha():
899
+ if i + 1 < len(toks):
900
+ payload = toks[i + 1]
901
+ break
902
+ if not t.startswith("-"):
903
+ break
904
+ if payload is not None:
905
+ self._walk(payload, depth + 1)
906
+ elif pa.pos:
907
+ self._follow_script(pa.pos[0], depth)
908
+ for text in stdin_texts:
909
+ self._walk(text, depth + 1)
910
+
911
+ def _follow_script(self, path: str, depth: int) -> None:
912
+ if depth + 1 > MAX_DEPTH:
913
+ self.emit("analysis-limit-exceeded", f"nesting deeper than {MAX_DEPTH}")
914
+ return
915
+ ap = self._abs(os.path.expanduser(path) if path.startswith("~") else path)
916
+ try:
917
+ if not os.path.isfile(ap) or os.path.getsize(ap) > MAX_SCRIPT_BYTES:
918
+ return
919
+ with open(ap, "rb") as fh:
920
+ data = fh.read(MAX_SCRIPT_BYTES)
921
+ except OSError:
922
+ return
923
+ if b"\0" in data[:1024]:
924
+ return
925
+ text = data.decode("utf-8", errors="replace")
926
+ first = text.split("\n", 1)[0]
927
+ if first.startswith("#!"):
928
+ interp = cmd_name(first[2:].strip().split()[-1] if "env" in first else first[2:].strip().split()[0])
929
+ if interp in INTERPRETERS:
930
+ self._script_depth += 1
931
+ try:
932
+ self._scan_code_text(text)
933
+ finally:
934
+ self._script_depth -= 1
935
+ return
936
+ self._script_depth += 1
937
+ try:
938
+ self._walk(text, depth + 1)
939
+ finally:
940
+ self._script_depth -= 1
941
+
942
+ # ---------------------------------------------------------- interpreters
943
+ def _h_interpreter(self, pa: ParsedArgv, stdin_texts: List[str]) -> None:
944
+ toks = pa.tokens
945
+ code: List[str] = []
946
+ for i, t in enumerate(toks):
947
+ if t in ("-c", "-e", "-r", "--eval", "-p", "--print", "-E") and i + 1 < len(toks):
948
+ code.append(toks[i + 1])
949
+ code.extend(stdin_texts)
950
+ if not code and pa.pos:
951
+ script = self._read_text(pa.pos[0], MAX_SCRIPT_BYTES)
952
+ if script is not None:
953
+ self._script_depth += 1
954
+ try:
955
+ self._scan_code_text(script)
956
+ finally:
957
+ self._script_depth -= 1
958
+ for c in code:
959
+ self._scan_code_text(c)
960
+
961
+ def _scan_code_text(self, text: str) -> None:
962
+ text = text[:sqlscan.MAX_TEXT]
963
+ for m in _STRING_LITERAL_RE.finditer(text):
964
+ lit = next((g for g in m.groups() if g), "")
965
+ if lit:
966
+ self._scan_sql_like(lit)
967
+ self._scan_redis_like(lit)
968
+ self._scan_mongo_like(text)
969
+ if _CODE_RM_RE.search(text) or _CODE_RMTREE_RE.search(text):
970
+ self.emit("fs-rm-catastrophic", "code deletes / or ~")
971
+
972
+ def _scan_sql_like(self, text: str) -> None:
973
+ for kind, snippet in sqlscan.scan_sql(text):
974
+ self.emit(SQL_KIND_TO_RULE[kind], snippet)
975
+
976
+ def _scan_mongo_like(self, text: str) -> None:
977
+ for kind, snippet in sqlscan.scan_mongo(text):
978
+ self.emit(kind, snippet)
979
+
980
+ def _scan_redis_like(self, text: str) -> None:
981
+ for kind, snippet in sqlscan.scan_redis(text):
982
+ self.emit(kind, snippet)
983
+
984
+ # ------------------------------------------------------------ db clients
985
+ def _h_db(self, pa: ParsedArgv, stdin_texts: List[str], unreadable: List[str]) -> None:
986
+ name = pa.name
987
+ texts = list(pa.tokens) + list(stdin_texts)
988
+ files: List[str] = []
989
+ if name in ("psql", "cqlsh", "sqlcmd", "usql", "isql"):
990
+ for f in ("-f", "--file", "-i"):
991
+ if f in pa.flag_values:
992
+ files.append(pa.flag_values[f])
993
+ if name in ("mysql", "mariadb", "mongosh", "mongo", "duckdb", "sqlite3"):
994
+ for t in pa.tokens:
995
+ if t.startswith("--file="):
996
+ files.append(t.split("=", 1)[1])
997
+ if name in MONGO_CLIENTS:
998
+ files.extend(p for p in pa.pos if p.endswith(".js"))
999
+ for f in files:
1000
+ content = self._read_text(f)
1001
+ if content is None:
1002
+ self.emit("sql-file-uninspectable", f)
1003
+ else:
1004
+ texts.append(content)
1005
+ for f in unreadable:
1006
+ self.emit("sql-file-uninspectable", f)
1007
+ for t in texts:
1008
+ if name in SQL_CLIENTS:
1009
+ self._scan_sql_like(t)
1010
+ elif name in MONGO_CLIENTS:
1011
+ self._scan_mongo_like(t)
1012
+ elif name in REDIS_CLIENTS:
1013
+ self._scan_redis_like(t)
1014
+
1015
+ # --------------------------------------------------------------- runners
1016
+ def _h_runners(self, pa: ParsedArgv, depth: int) -> None:
1017
+ name = pa.name
1018
+ words = pa.words
1019
+ if name in RUNNERS and pa.pos and pa.pos[0] in RUNNERS[name]:
1020
+ for i, w in enumerate(words[1:], start=1):
1021
+ if w.text == pa.pos[0]:
1022
+ self._analyze_words(words[i + 1:], depth + 1)
1023
+ break
1024
+ elif name == "ssh" and len(pa.pos_idx) >= 1:
1025
+ rest = words[pa.pos_idx[0] + 1:]
1026
+ if rest:
1027
+ self._walk(" ".join(w.text for w in rest), depth + 1)
1028
+ elif name in ("docker", "podman", "docker-compose"):
1029
+ pos = pa.pos
1030
+ for i, p in enumerate(pos[:3]):
1031
+ if p in ("exec", "run") and len(pa.pos_idx) > i + 1:
1032
+ rest = words[pa.pos_idx[i + 1] + 1:]
1033
+ if rest:
1034
+ self._analyze_words(rest, depth + 1)
1035
+ break
1036
+ ep = pa.flag_values.get("--entrypoint")
1037
+ if ep:
1038
+ self._walk(ep, depth + 1)
1039
+ elif name == "kubectl" and pa.pos and pa.pos[0] in ("exec", "run", "debug"):
1040
+ for i, w in enumerate(words[1:], start=1):
1041
+ if w.text == "--":
1042
+ self._analyze_words(words[i + 1:], depth + 1)
1043
+ break
1044
+ elif name == "su":
1045
+ toks = pa.tokens
1046
+ for i, t in enumerate(toks):
1047
+ if t in ("-c", "--command") and i + 1 < len(toks):
1048
+ self._walk(toks[i + 1], depth + 1)
1049
+ break
1050
+
1051
+
1052
+ def _collect_strings(obj: object, path: str, out: List[Tuple[str, str]], budget: List[int]) -> None:
1053
+ if budget[0] > MAX_SRC:
1054
+ return
1055
+ if isinstance(obj, str):
1056
+ budget[0] += len(obj)
1057
+ out.append((path, obj))
1058
+ elif isinstance(obj, dict):
1059
+ for k, v in obj.items():
1060
+ _collect_strings(v, f"{path}.{k}" if path else str(k), out, budget)
1061
+ elif isinstance(obj, (list, tuple)):
1062
+ for i, v in enumerate(obj):
1063
+ _collect_strings(v, f"{path}[{i}]", out, budget)