codeveto 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. codeveto/__init__.py +3 -0
  2. codeveto/__main__.py +8 -0
  3. codeveto/ai/__init__.py +19 -0
  4. codeveto/ai/harness.py +303 -0
  5. codeveto/ai/packets.py +855 -0
  6. codeveto/ai/policy.py +222 -0
  7. codeveto/ai/prompt.py +101 -0
  8. codeveto/ai/providers/__init__.py +178 -0
  9. codeveto/ai/providers/claude.py +247 -0
  10. codeveto/ai/providers/openai_compat.py +246 -0
  11. codeveto/ai/runner.py +293 -0
  12. codeveto/ai/verify.py +324 -0
  13. codeveto/anchor.py +211 -0
  14. codeveto/cli.py +247 -0
  15. codeveto/cli_explain.py +49 -0
  16. codeveto/cli_hook.py +31 -0
  17. codeveto/cli_init.py +254 -0
  18. codeveto/cli_mcp.py +29 -0
  19. codeveto/cli_packets.py +35 -0
  20. codeveto/cli_publish.py +29 -0
  21. codeveto/cli_review.py +362 -0
  22. codeveto/cli_rules.py +78 -0
  23. codeveto/cli_verify.py +47 -0
  24. codeveto/config.py +1229 -0
  25. codeveto/data/README.md +16 -0
  26. codeveto/data/ai-wire.schema.json +53 -0
  27. codeveto/data/prompts/system.md +57 -0
  28. codeveto/data/report-v1.schema.json +268 -0
  29. codeveto/data/templates/forgejo-codeveto.yml +104 -0
  30. codeveto/data/templates/github-codeveto.yml +18 -0
  31. codeveto/embedded.py +311 -0
  32. codeveto/engine.py +1570 -0
  33. codeveto/git.py +1549 -0
  34. codeveto/globs.py +348 -0
  35. codeveto/integrations/__init__.py +1 -0
  36. codeveto/integrations/hooks.py +327 -0
  37. codeveto/integrations/mcp.py +770 -0
  38. codeveto/integrations/mcp_ai.py +77 -0
  39. codeveto/integrations/prepush.py +222 -0
  40. codeveto/jsonsafe.py +60 -0
  41. codeveto/languages.py +539 -0
  42. codeveto/lexers.py +2560 -0
  43. codeveto/model.py +372 -0
  44. codeveto/publish/__init__.py +28 -0
  45. codeveto/publish/action.py +330 -0
  46. codeveto/publish/common.py +84 -0
  47. codeveto/publish/diff.py +208 -0
  48. codeveto/publish/event.py +241 -0
  49. codeveto/publish/forgejo.py +184 -0
  50. codeveto/publish/github.py +380 -0
  51. codeveto/publish/http.py +263 -0
  52. codeveto/publish/pull.py +218 -0
  53. codeveto/publish/untrusted.py +110 -0
  54. codeveto/py.typed +0 -0
  55. codeveto/redact.py +113 -0
  56. codeveto/render/__init__.py +64 -0
  57. codeveto/render/agent.py +43 -0
  58. codeveto/render/github.py +101 -0
  59. codeveto/render/json.py +23 -0
  60. codeveto/render/markdown.py +208 -0
  61. codeveto/render/safe.py +249 -0
  62. codeveto/render/sarif.py +217 -0
  63. codeveto/render/text.py +210 -0
  64. codeveto/report.py +252 -0
  65. codeveto/rules/__init__.py +84 -0
  66. codeveto/rules/agent.py +2972 -0
  67. codeveto/rules/base.py +1026 -0
  68. codeveto/rules/ci.py +1708 -0
  69. codeveto/rules/config.py +493 -0
  70. codeveto/rules/deps.py +1693 -0
  71. codeveto/rules/docker.py +479 -0
  72. codeveto/rules/examples/__init__.py +148 -0
  73. codeveto/rules/examples/agent.py +839 -0
  74. codeveto/rules/examples/ci.py +1046 -0
  75. codeveto/rules/examples/config.py +191 -0
  76. codeveto/rules/examples/deps.py +369 -0
  77. codeveto/rules/examples/docker.py +157 -0
  78. codeveto/rules/examples/go.py +241 -0
  79. codeveto/rules/examples/hygiene.py +466 -0
  80. codeveto/rules/examples/js.py +462 -0
  81. codeveto/rules/examples/python.py +595 -0
  82. codeveto/rules/examples/rust.py +268 -0
  83. codeveto/rules/examples/secrets.py +561 -0
  84. codeveto/rules/examples/security.py +608 -0
  85. codeveto/rules/examples/shell.py +174 -0
  86. codeveto/rules/examples/sql.py +194 -0
  87. codeveto/rules/examples/tests.py +497 -0
  88. codeveto/rules/go.py +328 -0
  89. codeveto/rules/hygiene.py +1094 -0
  90. codeveto/rules/js.py +768 -0
  91. codeveto/rules/python.py +1642 -0
  92. codeveto/rules/rust.py +209 -0
  93. codeveto/rules/secrets.py +1335 -0
  94. codeveto/rules/security.py +3680 -0
  95. codeveto/rules/shell.py +867 -0
  96. codeveto/rules/sql.py +629 -0
  97. codeveto/rules/tests.py +1404 -0
  98. codeveto/schema.py +384 -0
  99. codeveto/statements.py +607 -0
  100. codeveto/worktree.py +1176 -0
  101. codeveto/yamlish.py +1179 -0
  102. codeveto-0.1.0.dist-info/METADATA +253 -0
  103. codeveto-0.1.0.dist-info/RECORD +106 -0
  104. codeveto-0.1.0.dist-info/WHEEL +4 -0
  105. codeveto-0.1.0.dist-info/entry_points.txt +2 -0
  106. codeveto-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,867 @@
1
+ """Shell pack (SPEC 6.1, 6.5): bug patterns in shell scripts.
2
+
3
+ ``shell/`` owns ``.sh`` files and shebang scripts (SPEC 6.1); workflow
4
+ ``run:`` blocks belong to ``ci/``. Every rule here also reads the ``RUN``
5
+ commands and heredoc bodies of Dockerfiles (``FileContext.embedded_scripts()``),
6
+ whose ``docker/`` pack has no rules of its own for them.
7
+
8
+ The rules share a small word splitter (:func:`commands`) that reads shell
9
+ the way the shell does as far as these rules need: simple commands with
10
+ their words, each word a list of literal, quoted, ``$VAR``/``${...}`` and
11
+ ``$(...)``/``<(...)`` parts. Comments and heredoc bodies are blanked first
12
+ with the lexer's spans, so text that only mentions a command is never read
13
+ as one. It is a reader, not a parser: unbalanced input stops at the end of
14
+ the text, and every loop moves forward, so it is linear in the text size.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import re
20
+ from collections.abc import Callable, Iterator
21
+ from dataclasses import dataclass, field
22
+
23
+ from codeveto import lexers
24
+ from codeveto.lexers import LexResult
25
+ from codeveto.rules.base import FileContext, Hit, rule
26
+
27
+ # --- Reading shell words -------------------------------------------------------------
28
+
29
+ _SPECIAL_PARAMS = frozenset("@*#?$!-0123456789")
30
+ _OPERATORS = (":-", ":=", ":?", ":+", "-", "=", "?", "+", "%%", "%", "##", "#", "//", "/")
31
+ _OPERATORS += ("^^", "^", ",,", ",", ":")
32
+ _META = frozenset(" \t\n;&|<>()")
33
+ _KEYWORDS = frozenset({"if", "then", "else", "elif", "do", "while", "until", "!", "{", "}", "time"})
34
+ _KEYWORDS |= frozenset({"fi", "done", "esac", "in"})
35
+
36
+
37
+ @dataclass(frozen=True, slots=True)
38
+ class Part:
39
+ """One piece of a word.
40
+
41
+ ``kind`` is ``lit`` (unquoted or double-quoted literal text), ``sq``
42
+ (single-quoted or ``$'...'``), ``var`` (a parameter expansion: ``text`` is
43
+ the name, ``op`` the operator inside ``${...}`` and ``arg`` what follows
44
+ it), ``cmd`` (``$(...)`` or backticks), ``proc`` (``<(...)``/``>(...)``) or
45
+ ``arith`` (``$((...))``). For ``cmd`` and ``proc`` ``text`` is the inner
46
+ script and ``start`` its offset in the scanned text.
47
+ """
48
+
49
+ kind: str
50
+ text: str
51
+ start: int
52
+ op: str = ""
53
+ arg: str = ""
54
+ quoted: bool = False
55
+
56
+
57
+ @dataclass(slots=True)
58
+ class Word:
59
+ start: int
60
+ end: int
61
+ raw: str
62
+ parts: list[Part] = field(default_factory=list)
63
+
64
+ @property
65
+ def literal(self) -> str | None:
66
+ """The word's text if it is made only of literal parts, else ``None``."""
67
+ if all(p.kind in ("lit", "sq") for p in self.parts):
68
+ return "".join(p.text for p in self.parts)
69
+ return None
70
+
71
+ @property
72
+ def flat(self) -> str:
73
+ """Literal parts as text, every expansion as a NUL placeholder."""
74
+ return "".join(p.text if p.kind in ("lit", "sq") else "\0" for p in self.parts)
75
+
76
+
77
+ @dataclass(slots=True)
78
+ class Command:
79
+ """A simple command: its words (assignments included) and what ended it."""
80
+
81
+ words: list[Word]
82
+ sep: str
83
+
84
+
85
+ def _skip_quoted(text: str, i: int, end: int) -> int:
86
+ """Index after the quoted string or escape starting at ``text[i]``."""
87
+ c = text[i]
88
+ if c == "\\":
89
+ return min(i + 2, end)
90
+ if c == "'":
91
+ j = text.find("'", i + 1, end)
92
+ return end if j < 0 else j + 1
93
+ # Double quote or backtick: backslash escapes the next character.
94
+ j = i + 1
95
+ while j < end:
96
+ if text[j] == "\\":
97
+ j += 2
98
+ continue
99
+ if text[j] == c:
100
+ return j + 1
101
+ j += 1
102
+ return end
103
+
104
+
105
+ def _match(text: str, i: int, end: int, opening: str, closing: str) -> int:
106
+ """Index of the ``closing`` that balances the ``opening`` before ``i`` (or ``end``)."""
107
+ depth = 1
108
+ while i < end:
109
+ c = text[i]
110
+ if c in "\\'\"`":
111
+ i = _skip_quoted(text, i, end)
112
+ continue
113
+ if c == opening:
114
+ depth += 1
115
+ elif c == closing:
116
+ depth -= 1
117
+ if depth == 0:
118
+ return i
119
+ i += 1
120
+ return end
121
+
122
+
123
+ def _name_end(text: str, i: int, end: int) -> int:
124
+ j = i
125
+ while j < end and (text[j].isalnum() or text[j] == "_"):
126
+ j += 1
127
+ return j
128
+
129
+
130
+ def _braced(inner: str, start: int, quoted: bool) -> Part:
131
+ """``${...}`` content as a ``var`` part."""
132
+ op = ""
133
+ body = inner
134
+ if body.startswith("#") and len(body) > 1 and body[1] not in "}":
135
+ op, body = "#len", body[1:]
136
+ elif body.startswith("!"):
137
+ op, body = "!", body[1:]
138
+ if body[:1] and (body[0].isalpha() or body[0] == "_"):
139
+ k = _name_end(body, 0, len(body))
140
+ elif body[:1] and body[0] in _SPECIAL_PARAMS:
141
+ k = 1
142
+ else:
143
+ return Part("var", "", start, op="?unknown", quoted=quoted)
144
+ name, rest = body[:k], body[k:]
145
+ if rest.startswith("["):
146
+ close = rest.find("]")
147
+ rest = rest[close + 1 :] if close >= 0 else ""
148
+ if not op:
149
+ for candidate in _OPERATORS:
150
+ if rest.startswith(candidate):
151
+ op, rest = candidate, rest[len(candidate) :]
152
+ break
153
+ return Part("var", name, start, op=op, arg=rest, quoted=quoted)
154
+
155
+
156
+ def _dollar(text: str, i: int, end: int, quoted: bool) -> tuple[Part, int]:
157
+ """The expansion starting at ``text[i] == "$"`` and the index after it."""
158
+ nxt = text[i + 1] if i + 1 < end else ""
159
+ if text.startswith("$((", i, end):
160
+ close = _match(text, i + 3, end, "(", ")")
161
+ after = close + 2 if text.startswith("))", close, end) else min(close + 1, end)
162
+ return Part("arith", text[i + 3 : close], i + 3, quoted=quoted), after
163
+ if nxt == "(":
164
+ close = _match(text, i + 2, end, "(", ")")
165
+ return Part("cmd", text[i + 2 : close], i + 2, quoted=quoted), min(close + 1, end)
166
+ if nxt == "{":
167
+ close = _match(text, i + 2, end, "{", "}")
168
+ return _braced(text[i + 2 : close], i, quoted), min(close + 1, end)
169
+ if nxt and (nxt.isalpha() or nxt == "_"):
170
+ k = _name_end(text, i + 1, end)
171
+ return Part("var", text[i + 1 : k], i, quoted=quoted), k
172
+ if nxt and nxt in _SPECIAL_PARAMS:
173
+ return Part("var", nxt, i, quoted=quoted), i + 2
174
+ if nxt == "'" and not quoted:
175
+ j = i + 2
176
+ while j < end and text[j] != "'":
177
+ j += 2 if text[j] == "\\" else 1
178
+ return Part("sq", text[i + 2 : min(j, end)], i), min(j + 1, end)
179
+ return Part("lit", "$", i, quoted=quoted), i + 1
180
+
181
+
182
+ def _double_quoted(text: str, i: int, end: int, parts: list[Part]) -> int:
183
+ """Parts of the double-quoted string opening at ``text[i]``; index after it."""
184
+ j = i + 1
185
+ buf: list[str] = []
186
+ buf_start = j
187
+
188
+ def flush() -> None:
189
+ if buf:
190
+ parts.append(Part("lit", "".join(buf), buf_start, quoted=True))
191
+ buf.clear()
192
+
193
+ while j < end:
194
+ c = text[j]
195
+ if c == '"':
196
+ flush()
197
+ return j + 1
198
+ if c == "\\" and j + 1 < end:
199
+ if text[j + 1] != "\n":
200
+ buf.append(text[j + 1] if text[j + 1] in '$`"\\' else text[j : j + 2])
201
+ j += 2
202
+ continue
203
+ if c == "$":
204
+ flush()
205
+ part, j = _dollar(text, j, end, True)
206
+ parts.append(part)
207
+ buf_start = j
208
+ continue
209
+ if c == "`":
210
+ flush()
211
+ close = _skip_quoted(text, j, end)
212
+ parts.append(Part("cmd", text[j + 1 : max(close - 1, j + 1)], j + 1, quoted=True))
213
+ j = close
214
+ buf_start = j
215
+ continue
216
+ if not buf:
217
+ buf_start = j
218
+ buf.append(c)
219
+ j += 1
220
+ flush()
221
+ return end
222
+
223
+
224
+ def _word(text: str, i: int, end: int) -> tuple[Word, int]:
225
+ """The word starting at ``text[i]`` (not a metacharacter) and the index after it."""
226
+ start = i
227
+ parts: list[Part] = []
228
+ buf: list[str] = []
229
+ buf_start = i
230
+
231
+ def flush() -> None:
232
+ if buf:
233
+ parts.append(Part("lit", "".join(buf), buf_start))
234
+ buf.clear()
235
+
236
+ while i < end:
237
+ c = text[i]
238
+ if c in "<>" and text.startswith("(", i + 1) and i == start:
239
+ close = _match(text, i + 2, end, "(", ")")
240
+ parts.append(Part("proc", text[i + 2 : close], i + 2))
241
+ i = min(close + 1, end)
242
+ continue
243
+ if c in _META:
244
+ break
245
+ if c == "\\":
246
+ if text.startswith("\n", i + 1):
247
+ i += 2
248
+ continue
249
+ if not buf:
250
+ buf_start = i
251
+ buf.append(text[i + 1 : i + 2])
252
+ i += 2
253
+ continue
254
+ if c == "'":
255
+ flush()
256
+ close = _skip_quoted(text, i, end)
257
+ parts.append(Part("sq", text[i + 1 : max(close - 1, i + 1)], i + 1))
258
+ i = close
259
+ buf_start = i
260
+ continue
261
+ if c == '"':
262
+ flush()
263
+ i = _double_quoted(text, i, end, parts)
264
+ buf_start = i
265
+ continue
266
+ if c == "$":
267
+ flush()
268
+ part, i = _dollar(text, i, end, False)
269
+ parts.append(part)
270
+ buf_start = i
271
+ continue
272
+ if c == "`":
273
+ flush()
274
+ close = _skip_quoted(text, i, end)
275
+ parts.append(Part("cmd", text[i + 1 : max(close - 1, i + 1)], i + 1))
276
+ i = close
277
+ buf_start = i
278
+ continue
279
+ if not buf:
280
+ buf_start = i
281
+ buf.append(c)
282
+ i += 1
283
+ flush()
284
+ return Word(start, i, text[start:i], parts), i
285
+
286
+
287
+ def commands(text: str, start: int = 0, end: int | None = None) -> Iterator[Command]:
288
+ """Simple commands of ``text[start:end]`` in order.
289
+
290
+ Redirections (``> file``, ``2>&1``, ``<<EOF``) are dropped with their
291
+ targets; ``(``, ``)``, newlines and the list and pipeline operators end a
292
+ command, and ``Command.sep`` says which.
293
+ """
294
+ end = len(text) if end is None else end
295
+ i = start
296
+ words: list[Word] = []
297
+ while i < end:
298
+ c = text[i]
299
+ if c in " \t\r":
300
+ i += 1
301
+ continue
302
+ if c == "\\" and text.startswith("\n", i + 1):
303
+ i += 2
304
+ continue
305
+ if c == "#" and not words:
306
+ nl = text.find("\n", i, end)
307
+ i = end if nl < 0 else nl
308
+ continue
309
+ if c in "\n;&|()":
310
+ sep = text[i : i + 2] if text[i : i + 2] in ("&&", "||", ";;", "|&") else c
311
+ if words or sep in ("|", "|&"):
312
+ yield Command(words, sep)
313
+ words = []
314
+ i += len(sep)
315
+ continue
316
+ if c in "<>" and not text.startswith("(", i + 1):
317
+ # A redirection: an fd number before it was read as a word.
318
+ if words and words[-1].end == i and words[-1].raw.isdigit():
319
+ words.pop()
320
+ j = i
321
+ while j < end and text[j] in "<>&|-":
322
+ j += 1
323
+ while j < end and text[j] in " \t":
324
+ j += 1
325
+ if j < end and text[j] not in _META:
326
+ _, j = _word(text, j, end)
327
+ i = max(j, i + 1)
328
+ continue
329
+ word, i = _word(text, i, end)
330
+ words.append(word)
331
+ if words:
332
+ yield Command(words, "")
333
+
334
+
335
+ # --- Command structure --------------------------------------------------------------
336
+
337
+ _WRAPPERS = frozenset({"sudo", "doas", "command", "builtin", "exec", "nohup", "env", "nice"})
338
+ _WRAPPER_ARGS = frozenset({"-u", "-g", "-C", "-h", "-p", "-n"})
339
+ _SHELLS = frozenset({"sh", "bash", "zsh", "dash", "ksh", "ash", "mksh"})
340
+ _DECLARE = frozenset({"local", "export", "readonly", "declare", "typeset"})
341
+
342
+
343
+ def _is_assignment(word: Word) -> str | None:
344
+ """The variable name if ``word`` is ``NAME=value`` (or ``NAME+=``, ``NAME[i]=``)."""
345
+ first = word.parts[0] if word.parts else None
346
+ if first is None or first.kind != "lit" or first.quoted:
347
+ return None
348
+ text = first.text
349
+ k = _name_end(text, 0, len(text))
350
+ if k == 0 or text[0].isdigit():
351
+ return None
352
+ rest = text[k:]
353
+ if rest.startswith("["):
354
+ close = rest.find("]")
355
+ rest = rest[close + 1 :] if close >= 0 else ""
356
+ return text[:k] if rest.startswith(("=", "+=")) else None
357
+
358
+
359
+ def _value_parts(word: Word) -> list[Part]:
360
+ first = word.parts[0]
361
+ eq = first.text.find("=")
362
+ tail = first.text[eq + 1 :]
363
+ head = [Part("lit", tail, first.start + eq + 1)] if tail else []
364
+ return head + word.parts[1:]
365
+
366
+
367
+ def _non_empty(parts: list[Part]) -> bool:
368
+ """Is a value made of ``parts`` certainly non-empty?
369
+
370
+ Any literal character makes it so, as do ``${X:-default}`` with a
371
+ literal default and ``$(mktemp ...)`` or ``$(pwd)``. A bare ``$OTHER`` or
372
+ any other command substitution can be empty.
373
+ """
374
+ for p in parts:
375
+ if p.kind in ("lit", "sq") and p.text:
376
+ return True
377
+ if p.kind == "var" and p.op in (":-", ":=", "-", "=") and p.arg.strip("\"'"):
378
+ return True
379
+ if p.kind == "var" and p.op == "#len":
380
+ return True
381
+ if p.kind == "cmd":
382
+ inner = p.text.strip()
383
+ if inner == "pwd" or inner.startswith("mktemp"):
384
+ return True
385
+ if p.kind == "arith":
386
+ return True
387
+ return False
388
+
389
+
390
+ def split_command(cmd: Command) -> tuple[list[Word], list[Word]]:
391
+ """``(prefix assignments, words from the command name on)``, keywords skipped."""
392
+ words = cmd.words
393
+ i = 0
394
+ while i < len(words) and words[i].literal in _KEYWORDS:
395
+ i += 1
396
+ assigns: list[Word] = []
397
+ while i < len(words) and _is_assignment(words[i]):
398
+ assigns.append(words[i])
399
+ i += 1
400
+ return assigns, words[i:]
401
+
402
+
403
+ def unwrap(words: list[Word]) -> tuple[list[Word], bool]:
404
+ """Words from the real command on, past ``sudo``, ``env`` and similar wrappers.
405
+
406
+ Also says whether ``sudo`` or ``doas`` was among them.
407
+ """
408
+ elevated = False
409
+ i = 0
410
+ while i < len(words):
411
+ name = _basename(words[i].literal or "")
412
+ if name not in _WRAPPERS:
413
+ break
414
+ elevated = elevated or name in ("sudo", "doas")
415
+ i += 1
416
+ while i < len(words):
417
+ lit = words[i].literal or ""
418
+ if name == "env" and _is_assignment(words[i]):
419
+ i += 1
420
+ elif lit.startswith("-") and lit != "-":
421
+ i += 2 if lit in _WRAPPER_ARGS and name in ("sudo", "doas") else 1
422
+ else:
423
+ break
424
+ return words[i:], elevated
425
+
426
+
427
+ def _basename(name: str) -> str:
428
+ return name.rsplit("/", 1)[-1]
429
+
430
+
431
+ def command_name(words: list[Word]) -> str:
432
+ return _basename(words[0].literal or "") if words else ""
433
+
434
+
435
+ # --- Blanking comments and heredoc bodies -------------------------------------------
436
+
437
+
438
+ def code_view(text: str, result: LexResult) -> str:
439
+ """``text`` with comments and heredoc bodies blanked (strings kept), same length."""
440
+ strings, comments = lexers.flatten(result)
441
+ ranges: list[tuple[int, int]] = [(c.start, c.end) for c in comments]
442
+ ranges += [(s.content_start, s.content_end) for s in strings if s.kind == "heredoc"]
443
+ if not ranges:
444
+ return text
445
+ chars = list(text)
446
+ for a, b in ranges:
447
+ for k in range(a, min(b, len(chars))):
448
+ if chars[k] != "\n":
449
+ chars[k] = " "
450
+ return "".join(chars)
451
+
452
+
453
+ @dataclass(frozen=True, slots=True)
454
+ class Script:
455
+ """A shell text to read and where its offsets point in the file."""
456
+
457
+ code: str
458
+ line_of: Callable[[int], int]
459
+ column_of: Callable[[int], int] | None
460
+ start_line: int = 1
461
+
462
+
463
+ def _file_script(ctx: FileContext) -> Script | None:
464
+ text = ctx.new_text
465
+ if not text:
466
+ return None
467
+ index = ctx.line_index
468
+ spans = ctx.spans
469
+ code = code_view(text, spans)
470
+ return Script(code, index.line_of, lambda offset: index.position(offset)[1])
471
+
472
+
473
+ def scripts(ctx: FileContext) -> Iterator[Script]:
474
+ """The shell scripts of ``ctx``: the file itself, or a Dockerfile's ``RUN`` shell."""
475
+ if ctx.language == "shell":
476
+ script = _file_script(ctx)
477
+ if script is not None:
478
+ yield script
479
+ return
480
+ for embedded in ctx.embedded_scripts():
481
+ if embedded.language != "shell" or not embedded.text:
482
+ continue
483
+ result = lexers.lex(embedded.text, "shell")
484
+ yield Script(code_view(embedded.text, result), embedded.line_of, None, embedded.start_line)
485
+
486
+
487
+ def _hit(
488
+ script: Script,
489
+ offset: int,
490
+ *,
491
+ message: str | None = None,
492
+ evidence: str,
493
+ severity: str | None = None,
494
+ ) -> Hit:
495
+ column = script.column_of(offset) if script.column_of is not None else None
496
+ return Hit(
497
+ script.line_of(offset),
498
+ column=column,
499
+ message=message,
500
+ evidence=evidence,
501
+ severity=severity,
502
+ )
503
+
504
+
505
+ # --- shell/rm-rf-variable -------------------------------------------------------------
506
+
507
+ _ALWAYS_SET = frozenset({"HOME", "PWD", "RANDOM", "UID", "EUID", "PPID", "BASHPID", "LINENO"})
508
+ _ALWAYS_SET |= frozenset({"SECONDS", "$", "?", "#", "!"})
509
+ _TEST_GUARDS = frozenset({"-n", "-d", "-e", "-f"})
510
+ _UNSAFE_OPS = frozenset({"", "%", "%%", "#", "##", "/", "//", "^", "^^", ",", ",,", ":+", "+"})
511
+
512
+
513
+ @dataclass(slots=True)
514
+ class _ShellState:
515
+ """What the script established before the current command."""
516
+
517
+ nounset: bool = False
518
+ safe: set[str] = field(default_factory=set) # assigned non-empty or checked
519
+
520
+ def note_set(self, words: list[Word]) -> None:
521
+ args = [w.literal or "" for w in words[1:]]
522
+ for k, arg in enumerate(args):
523
+ if arg.startswith("-") and not arg.startswith("--") and "u" in arg[1:]:
524
+ self.nounset = True
525
+ elif arg.startswith("+") and "u" in arg[1:]:
526
+ self.nounset = False
527
+ elif arg in ("-o", "+o") and k + 1 < len(args) and args[k + 1] == "nounset":
528
+ self.nounset = arg == "-o"
529
+
530
+ def note_assignment(self, word: Word) -> None:
531
+ name = _is_assignment(word)
532
+ if name is None:
533
+ return
534
+ if _non_empty(_value_parts(word)):
535
+ self.safe.add(name)
536
+ else:
537
+ self.safe.discard(name)
538
+
539
+ def note_guards(self, words: list[Word]) -> None:
540
+ """``[ -n "$X" ]`` and ``${X:?}`` make ``X`` checked from here on."""
541
+ for k, word in enumerate(words):
542
+ for part in word.parts:
543
+ if part.kind == "var" and part.op in (":?", "?"):
544
+ self.safe.add(part.text)
545
+ if word.literal in _TEST_GUARDS and k + 1 < len(words):
546
+ nxt = words[k + 1].parts
547
+ if len(nxt) == 1 and nxt[0].kind == "var" and nxt[0].op == "":
548
+ self.safe.add(nxt[0].text)
549
+
550
+ def note_for(self, words: list[Word]) -> None:
551
+ if len(words) >= 2 and words[1].literal:
552
+ self.safe.add(words[1].literal)
553
+
554
+
555
+ def _recursive(words: list[Word]) -> bool:
556
+ for word in words[1:]:
557
+ lit = word.literal
558
+ if lit is None or not lit.startswith("-") or lit == "-":
559
+ continue
560
+ if lit == "--":
561
+ return False
562
+ if lit.startswith("--"):
563
+ if lit == "--recursive":
564
+ return True
565
+ elif "r" in lit or "R" in lit:
566
+ return True
567
+ return False
568
+
569
+
570
+ def _operands(words: list[Word]) -> Iterator[Word]:
571
+ options = True
572
+ for word in words[1:]:
573
+ lit = word.literal
574
+ if options and lit is not None and lit.startswith("-") and lit != "-":
575
+ if lit == "--":
576
+ options = False
577
+ continue
578
+ yield word
579
+
580
+
581
+ def _dangerous_start(word: Word, state: _ShellState) -> Part | None:
582
+ """The expansion a ``rm`` operand starts with when an empty value leaves ``/...``."""
583
+ parts = word.parts
584
+ if len(parts) < 2 or parts[0].kind != "var":
585
+ return None
586
+ var = parts[0]
587
+ after = parts[1]
588
+ if after.kind not in ("lit", "sq") or not after.text.startswith("/"):
589
+ return None
590
+ if var.text in _ALWAYS_SET or var.op in (":?", "?", "#len", "!", "?unknown"):
591
+ return None
592
+ if var.op in (":-", "-", ":=", "="):
593
+ if var.arg.strip("\"'"):
594
+ return None
595
+ elif var.op not in _UNSAFE_OPS:
596
+ return None
597
+ defaulted = var.op in (":-", "-", ":=", "=")
598
+ if state.nounset and not defaulted and var.op not in (":+", "+"):
599
+ return None
600
+ if var.text in state.safe and not defaulted:
601
+ return None
602
+ return var
603
+
604
+
605
+ def _scan_rm(
606
+ script: Script, state: _ShellState, depth: int, start: int = 0, end: int | None = None
607
+ ) -> Iterator[Hit]:
608
+ for cmd in commands(script.code, start, end):
609
+ assigns, words = split_command(cmd)
610
+ for word in assigns:
611
+ state.note_assignment(word)
612
+ words, _ = unwrap(words)
613
+ name = command_name(words)
614
+ state.note_guards(words)
615
+ if name == "set":
616
+ state.note_set(words)
617
+ elif name in _DECLARE:
618
+ for word in words[1:]:
619
+ state.note_assignment(word)
620
+ elif name in ("for", "select"):
621
+ state.note_for(words)
622
+ elif name == "rm" and _recursive(words):
623
+ for word in _operands(words):
624
+ var = _dangerous_start(word, state)
625
+ if var is not None:
626
+ shown = var.text if len(var.text) <= 40 else var.text[:40]
627
+ yield _hit(
628
+ script,
629
+ word.start,
630
+ message=(
631
+ f"rm -r on a path that starts with ${shown}: if it is empty "
632
+ "or unset this deletes from /"
633
+ ),
634
+ evidence=f"rm -r {word.raw[:200]}",
635
+ )
636
+ if depth < 4:
637
+ for word in cmd.words:
638
+ for part in word.parts:
639
+ if part.kind in ("cmd", "proc"):
640
+ yield from _scan_rm(
641
+ script, state, depth + 1, part.start, part.start + len(part.text)
642
+ )
643
+
644
+
645
+ _DOCKER_DEFINE = re.compile(r"^[ \t]*(?:ARG|ENV)[ \t]", re.IGNORECASE)
646
+ _DOCKER_PAIR = re.compile(r"(?<![\w$])([A-Za-z_]\w{0,100})=([^\s$\"']|\"[^\s$\"]|'[^\s']|$)")
647
+ _DOCKER_LEGACY = re.compile(r"^[ \t]*ENV[ \t]+([A-Za-z_]\w{0,100})[ \t]+[^\s$=]", re.IGNORECASE)
648
+
649
+
650
+ def _docker_defaults(ctx: FileContext) -> list[tuple[int, str]]:
651
+ """``(line, name)`` of Dockerfile ARG/ENV variables given a non-empty literal value."""
652
+ out: list[tuple[int, str]] = []
653
+ for stmt in ctx.statements():
654
+ if not _DOCKER_DEFINE.match(stmt.text):
655
+ continue
656
+ legacy = _DOCKER_LEGACY.match(stmt.text)
657
+ if legacy is not None:
658
+ out.append((stmt.start_line, legacy.group(1)))
659
+ continue
660
+ for m in _DOCKER_PAIR.finditer(stmt.text[:4000]):
661
+ if m.group(2):
662
+ out.append((stmt.start_line, m.group(1)))
663
+ return out
664
+
665
+
666
+ @rule(
667
+ id="shell/rm-rf-variable",
668
+ severity="error",
669
+ title="rm -r on a path that starts with an unchecked variable",
670
+ languages={"shell", "dockerfile"},
671
+ rationale=(
672
+ 'When VAR is empty or unset, `rm -rf "$VAR/"*` becomes `rm -rf /*`. The rule '
673
+ "fires when the operand starts with an expansion followed by `/` and nothing "
674
+ "earlier in the script makes the value non-empty: no `set -u` (or `-o nounset`), "
675
+ 'no `${VAR:?}`, no `[ -n "$VAR" ]`/`-d`/`-e`/`-f` test and no assignment of a '
676
+ 'value with a literal part, `$(mktemp ...)` or `$(pwd)`. A bare `rm -rf "$VAR"` '
677
+ "is not reported: an empty operand deletes nothing. Constant paths are fine. "
678
+ "Dockerfile `RUN` commands are read too."
679
+ ),
680
+ hint='Guard the variable: rm -rf "${VAR:?}/"*, or set -u at the top of the script.',
681
+ tags={"shell", "correctness", "data-loss"},
682
+ )
683
+ def rm_rf_variable(ctx: FileContext) -> Iterator[Hit]:
684
+ """``rm -r`` (any spelling of the recursive flag) whose operand is ``$VAR/...``."""
685
+ defined = _docker_defaults(ctx) if ctx.language == "dockerfile" else []
686
+ for script in scripts(ctx):
687
+ state = _ShellState()
688
+ state.safe.update(name for line, name in defined if line < script.start_line)
689
+ if ctx.language == "shell":
690
+ text = ctx.new_text or ""
691
+ head = text.split("\n", 1)[0]
692
+ if head.startswith("#!") and any(
693
+ w.startswith("-") and "u" in w for w in head.split()[1:]
694
+ ):
695
+ state.nounset = True
696
+ yield from _scan_rm(script, state, 0)
697
+
698
+
699
+ # --- shell/curl-pipe-shell ------------------------------------------------------------
700
+
701
+ _FETCHERS = frozenset({"curl", "wget"})
702
+
703
+
704
+ def _url_risk(words: list[Word]) -> str | None:
705
+ """Why the download is worse than plain HTTPS: ``http://`` or a variable URL."""
706
+ variable = False
707
+ for word in words[1:]:
708
+ flat = word.flat
709
+ if flat.startswith("-"):
710
+ continue
711
+ lower = flat.lower()
712
+ if "://" in lower:
713
+ return "over plain http://" if lower.startswith("http://") else None
714
+ if word.parts and word.parts[0].kind == "var":
715
+ variable = True
716
+ return "from a variable URL" if variable else None
717
+
718
+
719
+ def _fetch_in(code: str, part: Part) -> list[Word] | None:
720
+ """The ``curl``/``wget`` command that starts ``inner`` (a substitution's script)."""
721
+ for cmd in commands(code, part.start, part.start + len(part.text)):
722
+ _, words = split_command(cmd)
723
+ words, _ = unwrap(words)
724
+ return words if command_name(words) in _FETCHERS else None
725
+ return None
726
+
727
+
728
+ def _pipe_severity(risk: str | None, elevated: bool) -> str | None:
729
+ """``warning`` for a plain HTTPS download; the rule's ``error`` otherwise."""
730
+ return None if risk or elevated else "warning"
731
+
732
+
733
+ def _pipe_message(risk: str | None, elevated: bool) -> str:
734
+ extra = [r for r in (risk, "into sudo" if elevated else None) if r]
735
+ suffix = f" ({', '.join(extra)})" if extra else ""
736
+ return f"Downloaded script runs in a shell without verification{suffix}"
737
+
738
+
739
+ def _scan_pipes(
740
+ script: Script, depth: int, start: int = 0, end: int | None = None
741
+ ) -> Iterator[Hit]:
742
+ pipeline: list[Command] = []
743
+ for cmd in commands(script.code, start, end):
744
+ pipeline.append(cmd)
745
+ if cmd.sep not in ("|", "|&"):
746
+ yield from _check_pipeline(script, pipeline)
747
+ pipeline = []
748
+ _, words = split_command(cmd)
749
+ words, elevated = unwrap(words)
750
+ name = command_name(words)
751
+ if name in _SHELLS or name in ("source", ".", "eval"):
752
+ for word in words[1:]:
753
+ for part in word.parts:
754
+ if part.kind not in ("proc", "cmd"):
755
+ continue
756
+ if part.kind == "cmd" and name in ("source", "."):
757
+ continue
758
+ fetch = _fetch_in(script.code, part)
759
+ if fetch is None:
760
+ continue
761
+ yield _hit(
762
+ script,
763
+ fetch[0].start,
764
+ message=_pipe_message(_url_risk(fetch), elevated),
765
+ severity=_pipe_severity(_url_risk(fetch), elevated),
766
+ evidence=f"{name} {fetch[0].raw} {' '.join(w.raw for w in fetch[1:])}"[
767
+ :300
768
+ ],
769
+ )
770
+ if depth < 4:
771
+ for word in cmd.words:
772
+ for part in word.parts:
773
+ if part.kind == "cmd":
774
+ yield from _scan_pipes(
775
+ script, depth + 1, part.start, part.start + len(part.text)
776
+ )
777
+ if pipeline:
778
+ yield from _check_pipeline(script, pipeline)
779
+
780
+
781
+ def _check_pipeline(script: Script, pipeline: list[Command]) -> Iterator[Hit]:
782
+ if len(pipeline) < 2:
783
+ return
784
+ fetch: list[Word] | None = None
785
+ for cmd in pipeline:
786
+ _, words = split_command(cmd)
787
+ words, elevated = unwrap(words)
788
+ name = command_name(words)
789
+ if fetch is None:
790
+ if name in _FETCHERS:
791
+ fetch = words
792
+ continue
793
+ if name in _SHELLS:
794
+ yield _hit(
795
+ script,
796
+ fetch[0].start,
797
+ message=_pipe_message(_url_risk(fetch), elevated),
798
+ severity=_pipe_severity(_url_risk(fetch), elevated),
799
+ evidence=" ".join(w.raw for w in fetch)[:300] + f" | {name}",
800
+ )
801
+ return
802
+
803
+
804
+ @rule(
805
+ id="shell/curl-pipe-shell",
806
+ severity="error",
807
+ title="Downloaded script piped into a shell",
808
+ languages={"shell", "dockerfile"},
809
+ rationale=(
810
+ '`curl ... | sh`, `bash <(curl ...)` and `sh -c "$(curl ...)"` run whatever the '
811
+ "server returns, unverified. Same policy as `ci/curl-pipe-shell`: a warning for "
812
+ "an `https://` URL, an error over plain `http://` (anyone on the path can swap "
813
+ "the script), from a variable URL (the source is not reviewable) or into `sudo`. "
814
+ "Shell scripts and Dockerfile `RUN` commands and heredocs are read."
815
+ ),
816
+ hint="Download to a file, verify its checksum or signature, then run it.",
817
+ tags={"shell", "security", "supply-chain"},
818
+ )
819
+ def curl_pipe_shell(ctx: FileContext) -> Iterator[Hit]:
820
+ """A ``curl``/``wget`` pipeline ending in a shell, or a shell fed a download."""
821
+ for script in scripts(ctx):
822
+ yield from _scan_pipes(script, 0)
823
+
824
+
825
+ # --- shell/eval -------------------------------------------------------------------------
826
+
827
+
828
+ @rule(
829
+ id="shell/eval",
830
+ severity="warning",
831
+ title="eval of text built from variables",
832
+ languages={"shell", "dockerfile"},
833
+ rationale=(
834
+ "`eval` parses its arguments as shell code a second time, so any variable in them "
835
+ 'that carries outside input becomes code. `eval "$(tool init)"` with a fixed '
836
+ "command and no variable is the usual idiom and is not reported. Shell scripts "
837
+ "and Dockerfile `RUN` commands and heredocs are read."
838
+ ),
839
+ hint="Call the command directly, use an array for arguments, or printf -v for names.",
840
+ tags={"shell", "security", "cwe-95"},
841
+ )
842
+ def eval_(ctx: FileContext) -> Iterator[Hit]:
843
+ """``eval`` with a parameter expansion among its arguments."""
844
+ for script in scripts(ctx):
845
+ for cmd in commands(script.code):
846
+ _, words = split_command(cmd)
847
+ words, _ = unwrap(words)
848
+ if command_name(words) != "eval" or words[0].literal != "eval":
849
+ continue
850
+ if any(p.kind == "var" for w in words[1:] for p in w.parts):
851
+ yield _hit(
852
+ script,
853
+ words[0].start,
854
+ evidence=" ".join(w.raw for w in words)[:300],
855
+ )
856
+
857
+
858
+ __all__ = [
859
+ "Command",
860
+ "Part",
861
+ "Word",
862
+ "code_view",
863
+ "command_name",
864
+ "commands",
865
+ "split_command",
866
+ "unwrap",
867
+ ]