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
codeveto/rules/ci.py ADDED
@@ -0,0 +1,1708 @@
1
+ """CI pack (SPEC 6.1): GitHub Actions, Forgejo and Gitea workflows and composite actions.
2
+
3
+ Workflow structure comes from ``FileContext.yaml`` (the bounded ``yamlish``
4
+ reader) and ``run:`` scripts from ``FileContext.embedded_scripts()``, lexed
5
+ as shell where the step's shell is a POSIX shell. Nothing here regexes the
6
+ raw YAML for structure. A file ``yamlish`` cannot read fully is already
7
+ ``partial`` (the engine reports that); rules check what it did read.
8
+
9
+ Most rules are ``line`` rules with ``evidence``: the engine runs them on the
10
+ old side too and drops findings that already existed, so editing a line next
11
+ to old debt does not re-report it. ``ci/*`` findings cannot be ignored inline
12
+ (SPEC 7.3), so the ``error`` rules are deliberately narrow.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import bisect
18
+ import re
19
+ from collections.abc import Iterator
20
+ from dataclasses import dataclass
21
+
22
+ from codeveto import lexers
23
+ from codeveto.embedded import Embedded
24
+ from codeveto.lexers import CommentSpan, StringSpan
25
+ from codeveto.model import FileStatus
26
+ from codeveto.rules.base import FileContext, Hit, rule
27
+ from codeveto.yamlish import YamlMap, YamlNode, YamlResult, YamlScalar, YamlSeq
28
+
29
+ _WORKFLOW = {"workflow"}
30
+ _YAML = {"yaml"}
31
+
32
+ # --- Workflow model -------------------------------------------------------------------
33
+
34
+
35
+ @dataclass(frozen=True, slots=True)
36
+ class Step:
37
+ """One step of a job or of a composite action."""
38
+
39
+ node: YamlMap
40
+ line: int
41
+ uses: YamlScalar | None
42
+ run: YamlScalar | None
43
+ with_: YamlMap | None
44
+ env: YamlMap | None
45
+ cond: str
46
+
47
+
48
+ @dataclass(frozen=True, slots=True)
49
+ class Job:
50
+ """One job (``id`` is ``""`` for the steps of a composite action)."""
51
+
52
+ id: str
53
+ line: int
54
+ end_line: int
55
+ node: YamlMap
56
+ steps: tuple[Step, ...]
57
+ env: YamlMap | None
58
+ cond: str
59
+
60
+
61
+ @dataclass(frozen=True, slots=True)
62
+ class Workflow:
63
+ """One YAML document of a workflow or action file."""
64
+
65
+ root: YamlMap
66
+ triggers: tuple[tuple[str, int], ...]
67
+ jobs: tuple[Job, ...]
68
+ env: YamlMap | None
69
+ is_action: bool
70
+
71
+ def has_trigger(self, *names: str) -> bool:
72
+ return any(name in names for name, _ in self.triggers)
73
+
74
+
75
+ def _scalar(node: YamlNode | None) -> YamlScalar | None:
76
+ return node if isinstance(node, YamlScalar) else None
77
+
78
+
79
+ def _map(node: YamlNode | None) -> YamlMap | None:
80
+ return node if isinstance(node, YamlMap) else None
81
+
82
+
83
+ def _text(node: YamlNode | None) -> str:
84
+ scalar = _scalar(node)
85
+ return scalar.value if scalar is not None else ""
86
+
87
+
88
+ def _triggers(node: YamlNode | None, line: int) -> tuple[tuple[str, int], ...]:
89
+ if isinstance(node, YamlScalar):
90
+ return ((node.value.strip(), node.start_line),) if node.value.strip() else ()
91
+ if isinstance(node, YamlSeq):
92
+ return tuple(
93
+ (item.value.strip(), item.start_line)
94
+ for item in node.items
95
+ if isinstance(item, YamlScalar) and item.value.strip()
96
+ )
97
+ if isinstance(node, YamlMap):
98
+ return tuple((e.key_text, e.key_line) for e in node.entries)
99
+ return ()
100
+
101
+
102
+ def _steps(node: YamlNode | None) -> tuple[Step, ...]:
103
+ if not isinstance(node, YamlSeq):
104
+ return ()
105
+ out: list[Step] = []
106
+ for item in node.items:
107
+ step = _map(item)
108
+ if step is None:
109
+ continue
110
+ out.append(
111
+ Step(
112
+ node=step,
113
+ line=step.start_line,
114
+ uses=_scalar(step.get("uses")),
115
+ run=_scalar(step.get("run")),
116
+ with_=_map(step.get("with")),
117
+ env=_map(step.get("env")),
118
+ cond=_text(step.get("if")),
119
+ )
120
+ )
121
+ return tuple(out)
122
+
123
+
124
+ def workflows(result: YamlResult | None) -> Iterator[Workflow]:
125
+ """The workflow or action documents ``yamlish`` could read."""
126
+ if result is None:
127
+ return
128
+ for document in result.documents:
129
+ root = _map(document.root)
130
+ if root is None:
131
+ continue
132
+ on = root.entry("on")
133
+ triggers = _triggers(on.value, on.key_line) if on is not None else ()
134
+ jobs: list[Job] = []
135
+ jobs_map = _map(root.get("jobs"))
136
+ if jobs_map is not None:
137
+ for entry in jobs_map.entries:
138
+ job = _map(entry.value)
139
+ if job is None:
140
+ continue
141
+ jobs.append(
142
+ Job(
143
+ id=entry.key_text,
144
+ line=entry.key_line,
145
+ end_line=job.end_line,
146
+ node=job,
147
+ steps=_steps(job.get("steps")),
148
+ env=_map(job.get("env")),
149
+ cond=_text(job.get("if")),
150
+ )
151
+ )
152
+ runs = _map(root.get("runs"))
153
+ is_action = runs is not None and jobs_map is None
154
+ if runs is not None and jobs_map is None:
155
+ jobs.append(
156
+ Job(
157
+ id="",
158
+ line=root.entry("runs").key_line, # type: ignore[union-attr]
159
+ end_line=runs.end_line,
160
+ node=runs,
161
+ steps=_steps(runs.get("steps")),
162
+ env=None,
163
+ cond="",
164
+ )
165
+ )
166
+ yield Workflow(
167
+ root=root,
168
+ triggers=triggers,
169
+ jobs=tuple(jobs),
170
+ env=_map(root.get("env")),
171
+ is_action=is_action,
172
+ )
173
+
174
+
175
+ def _column(ctx: FileContext, line: int, needle: str) -> int | None:
176
+ if not needle or line > len(ctx.lines):
177
+ return None
178
+ index = ctx.lines[line - 1].find(needle)
179
+ return index + 1 if index >= 0 else None
180
+
181
+
182
+ def _action_name(uses: str) -> str:
183
+ """``owner/repo[/path]`` of a ``uses:`` value, lower-cased, without ``@ref`` or host."""
184
+ name = uses.strip().split("@", 1)[0].strip().lower()
185
+ for prefix in ("https://", "http://"):
186
+ if name.startswith(prefix):
187
+ name = name[len(prefix) :].split("/", 1)[-1]
188
+ return name.rstrip("/")
189
+
190
+
191
+ def _is_action(step: Step, name: str) -> bool:
192
+ return step.uses is not None and _action_name(step.uses.value) == name
193
+
194
+
195
+ # --- Expressions ----------------------------------------------------------------------
196
+
197
+ _EXPR_OPEN = "${{"
198
+ _EXPR_CLOSE = "}}"
199
+ _MAX_EXPR = 2000
200
+
201
+
202
+ @dataclass(frozen=True, slots=True)
203
+ class Expr:
204
+ start: int
205
+ end: int
206
+ inner: str
207
+
208
+
209
+ def expressions(text: str) -> Iterator[Expr]:
210
+ """Each ``${{ ... }}`` in ``text`` (an unterminated one runs to the end)."""
211
+ pos = 0
212
+ while True:
213
+ start = text.find(_EXPR_OPEN, pos)
214
+ if start < 0:
215
+ return
216
+ close = text.find(_EXPR_CLOSE, start + 3, start + 3 + _MAX_EXPR)
217
+ end = len(text) if close < 0 else close + 2
218
+ yield Expr(start, end, text[start + 3 : end - 2 if close >= 0 else end])
219
+ pos = end
220
+
221
+
222
+ _INDEX = re.compile(r"\[\s{0,3}(?:'([^'\]]{1,100})'|\"([^\"\]]{1,100})\"|(\*|[0-9]{1,6}))\s{0,3}\]")
223
+ _STRING_LITERAL = re.compile(r"'[^']{0,500}'")
224
+ _NOT_TEXT = re.compile(r"==|!=|<|>|&&|!")
225
+ _CALL = re.compile(r"([A-Za-z_][A-Za-z0-9_]{0,50})\s{0,5}\(")
226
+ _TEXT_FUNCTIONS = frozenset({"tojson", "fromjson", "format", "join"})
227
+
228
+
229
+ def _normalize(inner: str) -> str:
230
+ """``a['b'][0]`` as ``a.b.*`` so one pattern covers both spellings."""
231
+
232
+ def repl(m: re.Match[str]) -> str:
233
+ name = m.group(1) or m.group(2)
234
+ return "." + name if name else ".*"
235
+
236
+ return _INDEX.sub(repl, inner)
237
+
238
+
239
+ def yields_text(inner: str) -> bool:
240
+ """Does the expression evaluate to text taken from its operands?
241
+
242
+ A comparison, ``&&``, ``!`` or a call other than ``toJSON``,
243
+ ``fromJSON``, ``format`` and ``join`` makes it a condition or a derived
244
+ value (``contains(...)`` is a boolean); those are not injectable.
245
+ """
246
+ code = _STRING_LITERAL.sub("''", inner)
247
+ if _NOT_TEXT.search(code):
248
+ return False
249
+ return all(m.group(1).lower() in _TEXT_FUNCTIONS for m in _CALL.finditer(code))
250
+
251
+
252
+ _CONTEXT_REF = re.compile(
253
+ r"(?<![A-Za-z0-9_.])(?:github|gitea|forgejo|forge)\.((?:event|head_ref)(?:\.[A-Za-z0-9_*-]{1,64}){0,8})"
254
+ )
255
+ _UNTRUSTED = re.compile(
256
+ r"event\.(?:issue|pull_request|discussion)\.(?:title|body)"
257
+ r"|event\.(?:comment|review|review_comment)\.body"
258
+ r"|event\.pull_request\.head\.(?:ref|label)"
259
+ r"|head_ref"
260
+ r"|event\.(?:[a-z_]{1,40}\.)?head_commit\.(?:message|author(?:\.[a-z_]{1,20})?)"
261
+ r"|event\.commits(?:\.\*|\.[0-9]{1,6})?(?:\.(?:message|author|committer)(?:\.[a-z_]{1,20})?)?"
262
+ r"|event\.pages(?:\.\*|\.[0-9]{1,6})?\.page_name"
263
+ r"|event\.workflow_run\.head_branch"
264
+ )
265
+
266
+
267
+ def untrusted_refs(inner: str) -> list[str]:
268
+ """Attacker-controlled contexts the expression puts into its text, as ``github.<path>``."""
269
+ if not yields_text(inner):
270
+ return []
271
+ found: list[str] = []
272
+ for m in _CONTEXT_REF.finditer(_normalize(inner)):
273
+ path = m.group(1)
274
+ if _UNTRUSTED.fullmatch(path):
275
+ found.append("github." + path)
276
+ return found
277
+
278
+
279
+ _SECRET_REF = re.compile(
280
+ r"(?<![A-Za-z0-9_.])(?:secrets\.([A-Za-z_][A-Za-z0-9_-]{0,100})|github\.(token)\b)"
281
+ )
282
+
283
+
284
+ def secret_refs(inner: str) -> list[str]:
285
+ """``secrets.NAME`` (and ``github.token``) the expression puts into its text."""
286
+ if not yields_text(inner):
287
+ return []
288
+ out = []
289
+ for m in _SECRET_REF.finditer(_normalize(inner)):
290
+ out.append("secrets." + m.group(1) if m.group(1) else "github.token")
291
+ return out
292
+
293
+
294
+ def _env_taint(*envs: YamlMap | None, refs: object) -> dict[str, str]:
295
+ """Env names bound to an expression with a matching context, to that context."""
296
+ found: dict[str, str] = {}
297
+ for env in envs:
298
+ if env is None:
299
+ continue
300
+ for entry in env.entries:
301
+ value = _scalar(entry.value)
302
+ if value is None:
303
+ continue
304
+ for expr in expressions(value.value):
305
+ hits = refs(expr.inner) # type: ignore[operator]
306
+ if hits:
307
+ found[entry.key_text] = hits[0]
308
+ break
309
+ return found
310
+
311
+
312
+ # --- Shell scripts --------------------------------------------------------------------
313
+
314
+
315
+ @dataclass(frozen=True, slots=True)
316
+ class Segment:
317
+ """One simple command of a script: ``work[start:end]``, and what follows it."""
318
+
319
+ start: int
320
+ end: int
321
+ sep: str
322
+ words: tuple[tuple[int, int], ...]
323
+
324
+
325
+ class Script:
326
+ """A ``run:`` script lexed as shell, with ``${{ }}`` expressions held aside.
327
+
328
+ ``work`` is the text with each expression replaced by ``Q`` characters
329
+ of the same length (so the lexer sees a plain word and offsets stay);
330
+ ``masked`` is ``work`` with string and comment interiors blanked.
331
+ """
332
+
333
+ def __init__(self, embedded: Embedded) -> None:
334
+ text = embedded.text
335
+ self.embedded = embedded
336
+ self.text = text
337
+ self.exprs = tuple(expressions(text))
338
+ work = list(text)
339
+ for e in self.exprs:
340
+ for i in range(e.start, e.end):
341
+ if work[i] not in "\r\n":
342
+ work[i] = "Q"
343
+ self.work = "".join(work)
344
+ self.lex = lexers.lex(self.work, "shell")
345
+ self.masked = lexers.mask(self.work, self.lex)
346
+ strings, comments = lexers.flatten(self.lex)
347
+ self._spans: list[StringSpan | CommentSpan] = sorted(
348
+ [*strings, *comments], key=lambda s: s.start
349
+ )
350
+ self._starts = [s.start for s in self._spans]
351
+ reach = 0
352
+ self._reach: list[int] = []
353
+ for span in self._spans:
354
+ reach = max(reach, span.end)
355
+ self._reach.append(reach)
356
+ top = [s for s in self.lex.spans if isinstance(s, StringSpan)]
357
+ self._top = [(s.start, s.end) for s in top]
358
+ self._top_starts = [s.start for s in top]
359
+ self.heredocs = [s for s in strings if s.kind == "heredoc"]
360
+ self.segments = tuple(self._split())
361
+
362
+ def line_of(self, offset: int) -> int:
363
+ return self.embedded.line_of(offset)
364
+
365
+ def in_string(self, pos: int) -> bool:
366
+ k = bisect.bisect_right(self._top_starts, pos) - 1
367
+ return k >= 0 and self._top[k][0] <= pos < self._top[k][1]
368
+
369
+ def context(self, pos: int) -> str:
370
+ """``code``, ``comment``, ``expanded`` (inside a string, expanded) or ``literal``."""
371
+ k = bisect.bisect_right(self._starts, pos) - 1
372
+ inner: StringSpan | CommentSpan | None = None
373
+ while k >= 0 and self._reach[k] > pos:
374
+ span = self._spans[k]
375
+ if span.start <= pos < span.end:
376
+ inner = span # the containing span that starts last is the innermost
377
+ break
378
+ k -= 1
379
+ if inner is None:
380
+ return "code"
381
+ if isinstance(inner, CommentSpan):
382
+ return "comment"
383
+ if any(i.start <= pos + 2 and pos < i.end for i in inner.interpolations):
384
+ return "expanded"
385
+ return "literal"
386
+
387
+ def var_refs(self, start: int = 0, end: int | None = None) -> Iterator[tuple[int, str]]:
388
+ """``(offset, name)`` of each ``$NAME``/``${NAME}`` the shell expands."""
389
+ end = len(self.work) if end is None else end
390
+ for m in _VAR.finditer(self.work, start, end):
391
+ if self.context(m.start()) in ("code", "expanded"):
392
+ yield m.start(), m.group(1) or m.group(2)
393
+
394
+ def word(self, span: tuple[int, int]) -> str:
395
+ return _unquote(self.work[span[0] : span[1]])
396
+
397
+ def _words(self, start: int, end: int) -> tuple[tuple[int, int], ...]:
398
+ words: list[tuple[int, int]] = []
399
+ i = start
400
+ masked = self.masked
401
+ while i < end:
402
+ while i < end and masked[i] in " \t\r\n" and not self.in_string(i):
403
+ i += 1
404
+ if i >= end:
405
+ break
406
+ j = i
407
+ while j < end and not (masked[j] in " \t\r\n" and not self.in_string(j)):
408
+ j += 1
409
+ words.append((i, j))
410
+ i = j
411
+ return tuple(words)
412
+
413
+ def _split(self) -> Iterator[Segment]:
414
+ masked = self.masked
415
+ n = len(masked)
416
+ start = i = 0
417
+ while i < n:
418
+ c = masked[i]
419
+ sep = ""
420
+ width = 1
421
+ if c == "\\" and i + 1 < n:
422
+ i += 2
423
+ continue
424
+ if c in "\n;()`":
425
+ sep = c
426
+ elif c == "|":
427
+ if masked.startswith("||", i):
428
+ sep, width = "||", 2
429
+ else:
430
+ sep, width = "|", 2 if masked.startswith("|&", i) else 1
431
+ elif c == "&":
432
+ if masked.startswith("&&", i):
433
+ sep, width = "&&", 2
434
+ elif not (i + 1 < n and masked[i + 1] == ">") and not (
435
+ i > 0 and masked[i - 1] in "<>"
436
+ ):
437
+ sep = "&"
438
+ if sep and not self.in_string(i):
439
+ yield Segment(start, i, sep, self._words(start, i))
440
+ start = i + width
441
+ i += width if sep else 1
442
+ if start < n:
443
+ yield Segment(start, n, "", self._words(start, n))
444
+
445
+
446
+ _VAR = re.compile(r"\$(?:\{([A-Za-z_][A-Za-z0-9_]{0,100})|([A-Za-z_][A-Za-z0-9_]{0,100}))")
447
+ _ASSIGNMENT = re.compile(r"[A-Za-z_][A-Za-z0-9_]{0,100}=")
448
+ _PREFIX_WORDS = frozenset(
449
+ {"command", "builtin", "exec", "nohup", "time", "!", "{", "then", "do", "else", "elif", "if"}
450
+ | {"while", "until", "xargs"}
451
+ )
452
+ _SUDO_ARG_OPTIONS = frozenset({"-u", "-g", "-h", "-p", "-C", "-D", "-r", "-t", "-U"})
453
+
454
+
455
+ def _unquote(word: str) -> str:
456
+ return word.replace('"', "").replace("'", "").lstrip("\\")
457
+
458
+
459
+ @dataclass(frozen=True, slots=True)
460
+ class Command:
461
+ """The command word of a segment: its name, argument words and whether sudo ran it."""
462
+
463
+ name: str
464
+ index: int
465
+ args: tuple[str, ...]
466
+ sudo: bool
467
+
468
+
469
+ def command(script: Script, seg: Segment) -> Command | None:
470
+ words = [script.word(w) for w in seg.words]
471
+ i = 0
472
+ sudo = False
473
+ while i < len(words):
474
+ w = words[i]
475
+ if _ASSIGNMENT.match(w) or w in _PREFIX_WORDS:
476
+ i += 1
477
+ elif w in ("sudo", "doas"):
478
+ sudo = True
479
+ i += 1
480
+ while i < len(words) and words[i].startswith("-"):
481
+ i += 2 if words[i] in _SUDO_ARG_OPTIONS else 1
482
+ elif w == "env":
483
+ i += 1
484
+ while i < len(words) and (words[i].startswith("-") or _ASSIGNMENT.match(words[i])):
485
+ i += 1
486
+ else:
487
+ name = w.rsplit("/", 1)[-1]
488
+ return Command(name, i, tuple(words[i + 1 :]), sudo)
489
+ return None
490
+
491
+
492
+ def shell_scripts(ctx: FileContext) -> Iterator[Script]:
493
+ """The ``run:`` scripts of the file that run in a POSIX shell."""
494
+ for embedded in ctx.embedded_scripts():
495
+ if embedded.source == "workflow-run" and embedded.language == "shell":
496
+ yield Script(embedded)
497
+
498
+
499
+ def _scripts_by_line(ctx: FileContext) -> dict[int, Embedded]:
500
+ return {e.start_line: e for e in ctx.embedded_scripts() if e.source == "workflow-run"}
501
+
502
+
503
+ def _run_start(run: YamlScalar) -> int:
504
+ return run.line_map[0][1] if run.line_map else run.start_line
505
+
506
+
507
+ def _offset_line(scalar: YamlScalar, offset: int) -> int:
508
+ return scalar.line_of(offset)
509
+
510
+
511
+ # --- untrusted-checkout -------------------------------------------------------------
512
+
513
+ _HEAD_REF = re.compile(
514
+ r"(?<![A-Za-z0-9_.])(?:github|gitea|forgejo|forge)\.(?:"
515
+ r"event\.pull_request\.head\.(?:sha|ref)"
516
+ r"|head_ref"
517
+ r"|event\.workflow_run\.head_(?:sha|branch)"
518
+ r"|event\.workflow_run\.head_commit\.id"
519
+ r")\b"
520
+ r"|refs/pull/[^/\s]{1,80}/(?:merge|head)"
521
+ )
522
+ _PULL_REF = re.compile(r"(?<![A-Za-z0-9_-])(?:refs/)?pull/[^/\s]{1,80}/(merge|head)\b")
523
+ _API_HEAD = re.compile(
524
+ r"(?<![A-Za-z0-9_.])steps\.[A-Za-z0-9_-]{1,100}\.outputs\.[A-Za-z0-9_.*-]{0,200}"
525
+ )
526
+ _PRIVILEGED = ("pull_request_target", "workflow_run", "issue_comment")
527
+ _HEAD_REPO = re.compile(
528
+ r"(?<![A-Za-z0-9_.])github\.event\.(?:pull_request\.head\.repo\.full_name"
529
+ r"|workflow_run\.head_repository\.full_name)\b"
530
+ )
531
+ _RUN_CHECKOUT = re.compile(
532
+ r"\bgh\s{1,10}pr\s{1,10}checkout\b"
533
+ r"|\bgit\s{1,10}(?:fetch|checkout|switch|reset|pull)\b[^\n;&|]{0,300}"
534
+ r"(?:(?<![A-Za-z0-9_-])pull/[^/\s]{1,80}/(?:head|merge)\b|QQQ)"
535
+ )
536
+ _SAME_REPO_GUARD = re.compile(
537
+ r"head\.repo\.full_name\s{0,5}==\s{0,5}github\.repository\b"
538
+ r"|github\.repository\s{0,5}==\s{0,5}github\.event\.pull_request\.head\.repo\.full_name"
539
+ r"|head\.repo\.fork\s{0,5}==\s{0,5}false"
540
+ r"|!\s{0,5}github\.event\.pull_request\.head\.repo\.fork\b"
541
+ )
542
+ _BUILD_ACTIONS = frozenset(
543
+ {
544
+ "docker/build-push-action",
545
+ "github/codeql-action/autobuild",
546
+ "cypress-io/github-action",
547
+ "bahmutov/npm-install",
548
+ "pre-commit/action",
549
+ "goreleaser/goreleaser-action",
550
+ "gradle/gradle-build-action",
551
+ "borales/actions-yarn",
552
+ "actions-rs/cargo",
553
+ }
554
+ )
555
+
556
+
557
+ def _head_checkout(step: Step) -> tuple[int, str, str] | None:
558
+ """``(line, evidence, path)`` when an ``actions/checkout`` step checks out the PR head."""
559
+ if not _is_action(step, "actions/checkout") or step.with_ is None:
560
+ return None
561
+ path = _text(step.with_.get("path")).strip()
562
+ for key, pattern in (("ref", _HEAD_REF), ("repository", _HEAD_REPO)):
563
+ value = _scalar(step.with_.get(key))
564
+ if value is None:
565
+ continue
566
+ for expr in expressions(value.value):
567
+ m = pattern.search(_normalize(expr.inner))
568
+ if m is not None:
569
+ return value.start_line, m.group(), path
570
+ if key == "ref" and _api_head(expr.inner):
571
+ return value.start_line, "pull request head from the API", path
572
+ if key == "ref":
573
+ plain = value.value
574
+ for expr in reversed(list(expressions(plain))):
575
+ plain = plain[: expr.start] + "N" + plain[expr.end :]
576
+ m = _PULL_REF.search(plain)
577
+ if m is not None:
578
+ return value.start_line, "refs/pull/*/" + m.group(1), path
579
+ return None
580
+
581
+
582
+ def _api_head(inner: str) -> bool:
583
+ """Does the expression read a PR head ref or SHA from an earlier step (the PR API)?"""
584
+ normalized = _normalize(inner)
585
+ m = _API_HEAD.search(normalized)
586
+ return m is not None and "head" in normalized[m.start() :].lower()
587
+
588
+
589
+ def _runs_code(step: Step, path: str) -> bool:
590
+ """Does this later step run code, from ``path`` when the head went to a subdirectory?"""
591
+ if step.run is not None and step.run.value.strip():
592
+ if not path or path in (".", "./"):
593
+ return True
594
+ return path.strip("./") in step.run.value or (
595
+ step.node.entry("working-directory") is not None
596
+ and path.strip("./") in _text(step.node.get("working-directory"))
597
+ )
598
+ if step.uses is None:
599
+ return False
600
+ name = _action_name(step.uses.value)
601
+ if step.uses.value.strip().startswith("./"):
602
+ return True
603
+ if name in _BUILD_ACTIONS:
604
+ return True
605
+ return (
606
+ name == "ruby/setup-ruby"
607
+ and step.with_ is not None
608
+ and _text(step.with_.get("bundler-cache")).strip().lower() == "true"
609
+ )
610
+
611
+
612
+ @rule(
613
+ id="ci/untrusted-checkout",
614
+ severity="error",
615
+ title="Privileged workflow runs code from the pull request head",
616
+ languages=_YAML,
617
+ classes=_WORKFLOW,
618
+ rationale=(
619
+ "pull_request_target, workflow_run and issue_comment jobs run with the base "
620
+ "repository's secrets and a write token. Checking out the pull request head and then "
621
+ "running a script, build or install from it lets anyone who opens a pull request run "
622
+ "code with those privileges."
623
+ ),
624
+ hint=(
625
+ "Run untrusted code in a pull_request workflow without secrets, or check out the head "
626
+ "only as data (no later run step) and pass results through artifacts."
627
+ ),
628
+ tags={"ci", "security", "supply-chain"},
629
+ )
630
+ def untrusted_checkout(ctx: FileContext) -> Iterator[Hit]:
631
+ """A head checkout followed by code execution in a privileged workflow.
632
+
633
+ Heuristic: the workflow is triggered by ``pull_request_target``,
634
+ ``workflow_run`` or ``issue_comment`` (a comment on a pull request runs
635
+ in the base context); a job checks out the head (``actions/checkout``
636
+ with ``ref`` set to ``github.event.pull_request.head.sha``/``head.ref``,
637
+ ``github.head_ref``, ``[refs/]pull/*/merge|head`` (also built from
638
+ ``github.event.issue.number``), the ``workflow_run`` head, or a head ref
639
+ or SHA an earlier step read from the PR API (``steps.<id>.outputs``
640
+ naming ``head``), or ``repository`` set to the head repository; or a
641
+ ``run`` step with ``gh pr checkout`` or a ``git fetch``/``checkout`` of
642
+ a pull ref or head expression); and a later step of the same job runs code: any
643
+ ``run`` step (one that names the checkout's ``path`` when the head went
644
+ to a subdirectory), a local ``./`` action, or a known build or install
645
+ action. A head checkout with no later execution is reported as a
646
+ ``warning`` (data only, still worth a look); a job or step guarded by a
647
+ same-repository ``if:`` (``head.repo.full_name == github.repository``,
648
+ ``head.repo.fork == false``) is not reported.
649
+ """
650
+ for wf in workflows(ctx.yaml):
651
+ if not wf.has_trigger(*_PRIVILEGED):
652
+ continue
653
+ for job in wf.jobs:
654
+ if _SAME_REPO_GUARD.search(job.cond):
655
+ continue
656
+ for i, step in enumerate(job.steps):
657
+ if _SAME_REPO_GUARD.search(step.cond):
658
+ continue
659
+ later = job.steps[i + 1 :]
660
+ found = _head_checkout(step)
661
+ if found is not None:
662
+ line, evidence, path = found
663
+ runs = any(_runs_code(s, path) for s in later)
664
+ elif step.run is not None:
665
+ in_run = _run_head_checkout(step.run)
666
+ if in_run is None:
667
+ continue
668
+ line, evidence, end = in_run
669
+ rest = step.run.value[end:].split("\n")[1:]
670
+ runs = any(row.strip() for row in rest) or any(_runs_code(s, "") for s in later)
671
+ else:
672
+ continue
673
+ if runs:
674
+ message = (
675
+ f"Pull request head ({evidence}) checked out and run with base "
676
+ "repository privileges"
677
+ )
678
+ else:
679
+ message = (
680
+ f"Pull request head ({evidence}) checked out in a privileged workflow; "
681
+ "make sure nothing runs it"
682
+ )
683
+ yield Hit(
684
+ line,
685
+ column=_column(ctx, line, evidence),
686
+ evidence=f"checkout {evidence}",
687
+ message=message,
688
+ severity=None if runs else "warning",
689
+ )
690
+
691
+
692
+ def _run_head_checkout(run: YamlScalar) -> tuple[int, str, int] | None:
693
+ text = run.value
694
+ work = list(text)
695
+ head = False
696
+ for e in expressions(text):
697
+ # Head expressions become QQQ...; others a space-free word, so that
698
+ # pull/${{ github.event.issue.number }}/head reads as one ref.
699
+ is_head = bool(_HEAD_REF.search(_normalize(e.inner))) or _api_head(e.inner)
700
+ head = head or is_head
701
+ for i in range(e.start, e.end):
702
+ work[i] = "Q" if is_head else "N"
703
+ joined = "".join(work)
704
+ for m in _RUN_CHECKOUT.finditer(joined):
705
+ if "QQQ" in m.group() and not head:
706
+ continue
707
+ line = _offset_line(run, m.start())
708
+ evidence = "gh pr checkout" if m.group().startswith("gh") else "git pull ref"
709
+ return line, evidence, m.end()
710
+ return None
711
+
712
+
713
+ # --- script-injection --------------------------------------------------------------
714
+
715
+
716
+ _ENV_FILE = re.compile(
717
+ r"(?:>{1,2}\s{0,5}[\"']?|\btee\b[^|;&\n]{0,200}?[\"']?)\$\{?(GITHUB_(?:ENV|OUTPUT|PATH))\b"
718
+ )
719
+
720
+
721
+ @rule(
722
+ id="ci/script-injection",
723
+ severity="error",
724
+ title="Untrusted event text expanded into a script",
725
+ languages=_YAML,
726
+ classes=_WORKFLOW,
727
+ rationale=(
728
+ "${{ }} expressions are pasted into the script text before the shell runs it, so an "
729
+ "issue title, comment, branch name or commit message containing $(...) or a quote runs "
730
+ "as code in the job. Writing such text to $GITHUB_ENV, $GITHUB_OUTPUT or $GITHUB_PATH "
731
+ "lets a newline in it set variables or the PATH for every later step."
732
+ ),
733
+ hint=(
734
+ 'Pass the value through env: (NAME: ${{ github.event.issue.title }}) and use "$NAME" '
735
+ "in the script; never write it to $GITHUB_ENV, $GITHUB_OUTPUT or $GITHUB_PATH."
736
+ ),
737
+ tags={"ci", "security", "cwe-78"},
738
+ )
739
+ def script_injection(ctx: FileContext) -> Iterator[Hit]:
740
+ """Attacker-controlled contexts reaching a script.
741
+
742
+ Contexts: issue, pull request and discussion ``title``/``body``, comment,
743
+ review and review comment ``body``, ``pull_request.head.ref``/``label``,
744
+ ``github.head_ref``, ``head_commit.message``/``author``, ``commits.*``
745
+ messages and authors, ``pages.*.page_name`` and
746
+ ``workflow_run.head_branch`` (``github.``, ``gitea.``, ``forgejo.`` and
747
+ ``forge.`` prefixes, dotted or bracket form). Sinks: a ``${{ }}`` in a
748
+ ``run:`` value or in ``actions/github-script``'s ``script``, and a write
749
+ to ``$GITHUB_ENV``/``$GITHUB_OUTPUT``/``$GITHUB_PATH`` (``>>``/``>`` or
750
+ ``tee``, heredoc bodies included) of a shell variable that ``env:``
751
+ binds to such a context. Expressions that only test the value
752
+ (``==``, ``!``, ``&&``, ``contains()`` and other calls besides
753
+ ``toJSON``/``fromJSON``/``format``/``join``) are not text and not
754
+ reported. A ``{ ...; } >> $GITHUB_ENV`` group is not followed.
755
+ """
756
+ scripts = _scripts_by_line(ctx)
757
+ for wf in workflows(ctx.yaml):
758
+ for job in wf.jobs:
759
+ for step in job.steps:
760
+ sinks: list[YamlScalar] = []
761
+ if step.run is not None:
762
+ sinks.append(step.run)
763
+ if _is_action(step, "actions/github-script") and step.with_ is not None:
764
+ script = _scalar(step.with_.get("script"))
765
+ if script is not None:
766
+ sinks.append(script)
767
+ for sink in sinks:
768
+ for expr in expressions(sink.value):
769
+ for ref in untrusted_refs(expr.inner):
770
+ line = _offset_line(sink, expr.start)
771
+ yield Hit(
772
+ line,
773
+ column=_column(ctx, line, sink.value[expr.start : expr.end]),
774
+ evidence=ref,
775
+ message=f"{ref} is expanded into the script text",
776
+ )
777
+ break
778
+ if step.run is None:
779
+ continue
780
+ embedded = scripts.get(_run_start(step.run))
781
+ if embedded is None or embedded.language != "shell":
782
+ continue
783
+ tainted = _env_taint(wf.env, job.env, step.env, refs=untrusted_refs)
784
+ if tainted:
785
+ yield from _env_file_writes(Script(embedded), tainted)
786
+
787
+
788
+ def _env_file_writes(script: Script, tainted: dict[str, str]) -> Iterator[Hit]:
789
+ heredocs = sorted(script.heredocs, key=lambda s: s.start)
790
+ for seg in script.segments:
791
+ m = _ENV_FILE.search(script.work, seg.start, seg.end)
792
+ if m is None:
793
+ continue
794
+ regions = [(seg.start, seg.end)]
795
+ if "<<" in script.masked[seg.start : seg.end]:
796
+ regions.extend((h.start, h.end) for h in heredocs if seg.end <= h.start <= seg.end + 2)
797
+ for lo, hi in regions:
798
+ for offset, name in script.var_refs(lo, hi):
799
+ if name in tainted:
800
+ ref = tainted[name]
801
+ yield Hit(
802
+ script.line_of(offset),
803
+ evidence=f"{ref} -> {m.group(1)}",
804
+ message=f"{ref} (via ${name}) is written to ${m.group(1)}",
805
+ )
806
+ break
807
+
808
+
809
+ # --- untrusted-artifact --------------------------------------------------------------
810
+
811
+ _WORKSPACE_PATHS = frozenset({"", ".", "./", "${{ github.workspace }}", "${{github.workspace}}"})
812
+
813
+
814
+ @rule(
815
+ id="ci/untrusted-artifact",
816
+ severity="error",
817
+ title="Artifact from the triggering run unpacked into the workspace and run",
818
+ languages=_YAML,
819
+ classes=_WORKFLOW,
820
+ rationale=(
821
+ "A workflow_run job runs with secrets and a write token, but the artifacts of the run "
822
+ "that triggered it were produced by pull request code. Unpacking them over the "
823
+ "workspace and then running anything lets the pull request replace the scripts and "
824
+ "files that run."
825
+ ),
826
+ hint=(
827
+ "Download the artifact into a dedicated directory (path: ${{ runner.temp }}/artifact), "
828
+ "treat its content as untrusted data and never execute it."
829
+ ),
830
+ tags={"ci", "security", "supply-chain"},
831
+ )
832
+ def untrusted_artifact(ctx: FileContext) -> Iterator[Hit]:
833
+ """A ``workflow_run`` job downloads the triggering run's artifacts into the workspace.
834
+
835
+ The download is ``actions/download-artifact`` with a ``run-id`` input
836
+ (another run's artifacts) or ``dawidd6/action-download-artifact``; it
837
+ lands in the workspace when ``path`` is unset, ``.`` or
838
+ ``${{ github.workspace }}``; and a later step of the job runs code (a
839
+ ``run`` step, a local ``./`` action or a known build action). Downloads
840
+ into a dedicated directory, and ``github-script`` API downloads, are not
841
+ reported.
842
+ """
843
+ for wf in workflows(ctx.yaml):
844
+ if not wf.has_trigger("workflow_run"):
845
+ continue
846
+ for job in wf.jobs:
847
+ for i, step in enumerate(job.steps):
848
+ if step.uses is None:
849
+ continue
850
+ name = _action_name(step.uses.value)
851
+ with_ = step.with_ or YamlMap((), step.line, step.line)
852
+ if name == "actions/download-artifact":
853
+ if with_.entry("run-id") is None:
854
+ continue
855
+ elif name != "dawidd6/action-download-artifact":
856
+ continue
857
+ path = _text(with_.get("path")).strip()
858
+ if path not in _WORKSPACE_PATHS:
859
+ continue
860
+ if any(_runs_code(s, "") for s in job.steps[i + 1 :]):
861
+ line = step.uses.start_line
862
+ yield Hit(
863
+ line,
864
+ column=_column(ctx, line, step.uses.value),
865
+ evidence=f"{name} into the workspace",
866
+ message="Artifact of the triggering run is unpacked into the workspace "
867
+ "before code runs",
868
+ )
869
+
870
+
871
+ # --- write-all-permissions ----------------------------------------------------------
872
+
873
+
874
+ def _permission_entries(wf: Workflow) -> Iterator[tuple[str, YamlNode | None, int]]:
875
+ entry = wf.root.entry("permissions")
876
+ if entry is not None:
877
+ yield "workflow", entry.value, entry.key_line
878
+ for job in wf.jobs:
879
+ if job.id:
880
+ entry = job.node.entry("permissions")
881
+ if entry is not None:
882
+ yield f"job {job.id}", entry.value, entry.key_line
883
+
884
+
885
+ @rule(
886
+ id="ci/write-all-permissions",
887
+ severity="error",
888
+ title="Workflow token granted write-all",
889
+ languages=_YAML,
890
+ classes=_WORKFLOW,
891
+ rationale=(
892
+ "permissions: write-all gives the job's token write access to code, releases, packages, "
893
+ "issues and more, so any compromised step or dependency can push to the repository."
894
+ ),
895
+ hint="List only the scopes the job needs, for example permissions: { contents: read }.",
896
+ tags={"ci", "security", "least-privilege"},
897
+ )
898
+ def write_all_permissions(ctx: FileContext) -> Iterator[Hit]:
899
+ """``permissions: write-all`` at workflow or job level."""
900
+ for wf in workflows(ctx.yaml):
901
+ for _where, value, _key_line in _permission_entries(wf):
902
+ scalar = _scalar(value)
903
+ if scalar is not None and scalar.value.strip().lower() == "write-all":
904
+ line = scalar.start_line
905
+ yield Hit(
906
+ line,
907
+ column=_column(ctx, line, scalar.value.strip()),
908
+ evidence="permissions: write-all",
909
+ )
910
+
911
+
912
+ # --- secret-echo ---------------------------------------------------------------------
913
+
914
+ _LOGGING_PIPES = frozenset({"base64", "base32", "basenc", "xxd", "od", "hexdump", "rev", "tee"})
915
+ _REDIRECT = re.compile(r"([0-9]?)>{1,2}\s{0,5}(&?)")
916
+
917
+
918
+ def _stdout_redirected(masked: str) -> bool:
919
+ return any(m.group(1) in ("", "1") and not m.group(2) for m in _REDIRECT.finditer(masked))
920
+
921
+
922
+ @rule(
923
+ id="ci/secret-echo",
924
+ severity="error",
925
+ title="Secret printed to the job log",
926
+ languages=_YAML,
927
+ classes=_WORKFLOW,
928
+ rationale=(
929
+ "Log masking only hides the exact secret value; printed secrets leak through encoded, "
930
+ "split or multi-line forms, and anyone who can read the logs can read them."
931
+ ),
932
+ hint="Pass the secret to the command that needs it (env or stdin), never print it.",
933
+ tags={"ci", "security", "secrets"},
934
+ )
935
+ def secret_echo(ctx: FileContext) -> Iterator[Hit]:
936
+ """``echo``/``printf`` of a secret to standard output in a shell ``run`` step.
937
+
938
+ The secret is a ``${{ secrets.NAME }}`` (or ``github.token``) expression
939
+ in the command, or a ``$NAME`` that ``env:`` binds to one. Reported when
940
+ the command's standard output is not redirected to a file and is not
941
+ piped, or is piped into an encoder or ``tee`` (``base64``, ``xxd``,
942
+ ``rev`` and the like), which defeats log masking. ``::add-mask::``
943
+ commands are not reported.
944
+ """
945
+ scripts = _scripts_by_line(ctx)
946
+ for wf in workflows(ctx.yaml):
947
+ for job in wf.jobs:
948
+ for step in job.steps:
949
+ if step.run is None:
950
+ continue
951
+ embedded = scripts.get(_run_start(step.run))
952
+ if embedded is None or embedded.language != "shell":
953
+ continue
954
+ script = Script(embedded)
955
+ tainted = _env_taint(wf.env, job.env, step.env, refs=secret_refs)
956
+ yield from _secret_echoes(script, tainted)
957
+
958
+
959
+ def _secret_echoes(script: Script, tainted: dict[str, str]) -> Iterator[Hit]:
960
+ segments = script.segments
961
+ for k, seg in enumerate(segments):
962
+ cmd = command(script, seg)
963
+ if cmd is None or cmd.name not in ("echo", "printf"):
964
+ continue
965
+ if "::add-mask::" in script.text[seg.start : seg.end]:
966
+ continue
967
+ found: tuple[int, str] | None = None
968
+ for expr in script.exprs:
969
+ if seg.start <= expr.start < seg.end:
970
+ refs = secret_refs(expr.inner)
971
+ if refs:
972
+ found = (expr.start, refs[0])
973
+ break
974
+ if found is None:
975
+ for offset, name in script.var_refs(seg.start, seg.end):
976
+ if name in tainted:
977
+ found = (offset, tainted[name])
978
+ break
979
+ if found is None or _stdout_redirected(script.masked[seg.start : seg.end]):
980
+ continue
981
+ if seg.sep == "|":
982
+ nxt = command(script, segments[k + 1]) if k + 1 < len(segments) else None
983
+ if nxt is None or nxt.name not in _LOGGING_PIPES:
984
+ continue
985
+ yield Hit(
986
+ script.line_of(found[0]),
987
+ evidence=f"{cmd.name} {found[1]}",
988
+ message=f"{found[1]} is printed to the job log",
989
+ )
990
+
991
+
992
+ # --- curl-pipe-shell -----------------------------------------------------------------
993
+
994
+ _FETCHERS = frozenset({"curl", "wget"})
995
+ _SHELLS = frozenset({"sh", "bash", "zsh", "dash", "ksh", "ash", "mksh"})
996
+ _INTERPRETERS = _SHELLS | {"python", "python3", "perl", "ruby", "node"}
997
+ _SUBST_EXEC = re.compile(
998
+ r"(?<![A-Za-z0-9_./-])(?:(?:ba|z|da|k)?sh|source|eval|\.)\s{1,10}(?:-[A-Za-z]{1,4}\s{1,10}){0,3}"
999
+ r"(?:<\(|[\"']?\$\()\s{0,5}(?:sudo\s{1,5})?(curl|wget)\b"
1000
+ )
1001
+
1002
+
1003
+ @dataclass(frozen=True, slots=True)
1004
+ class PipeFinding:
1005
+ """A download run by a shell: where, its identity, and whether it is the strong case."""
1006
+
1007
+ offset: int
1008
+ evidence: str
1009
+ message: str
1010
+ strong: bool
1011
+
1012
+
1013
+ def curl_pipe_findings(script: Script) -> Iterator[PipeFinding]:
1014
+ """Each download piped or substituted into a shell in ``script``.
1015
+
1016
+ Shared policy for workflow ``run`` scripts: a ``curl``/``wget``
1017
+ pipeline whose later command is a shell or script interpreter reading
1018
+ the download (not one given ``-c``/``-e`` code), and ``sh <(curl ...)``,
1019
+ ``sh -c "$(curl ...)"``, ``source <(curl ...)`` and
1020
+ ``eval "$(curl ...)"``. ``strong`` when the URL is plain ``http://``,
1021
+ no literal URL is given but a variable or expression is, or the shell
1022
+ runs under ``sudo``.
1023
+ """
1024
+ segments = script.segments
1025
+ k = 0
1026
+ while k < len(segments):
1027
+ group = [segments[k]]
1028
+ while group[-1].sep == "|" and k + 1 < len(segments):
1029
+ k += 1
1030
+ group.append(segments[k])
1031
+ k += 1
1032
+ first = command(script, group[0])
1033
+ if first is None or first.name not in _FETCHERS or len(group) < 2:
1034
+ continue
1035
+ for seg in group[1:]:
1036
+ cmd = command(script, seg)
1037
+ if cmd is None or cmd.name.rstrip("0123456789.") not in _INTERPRETERS:
1038
+ continue
1039
+ if any(a in ("-c", "-e") for a in cmd.args):
1040
+ continue
1041
+ notes = _fetch_notes(first.args, sudo=cmd.sudo)
1042
+ yield PipeFinding(
1043
+ group[0].words[first.index][0],
1044
+ f"{first.name} | {cmd.name}",
1045
+ f"Download piped into {'sudo ' if cmd.sudo else ''}{cmd.name}{_detail(notes)}",
1046
+ bool(notes),
1047
+ )
1048
+ break
1049
+ for m in _SUBST_EXEC.finditer(script.work):
1050
+ if script.context(m.start()) != "code":
1051
+ continue
1052
+ stop = script.work.find("\n", m.end())
1053
+ rest = script.work[m.end() : stop if stop >= 0 else len(script.work)]
1054
+ args = tuple(_unquote(w).rstrip(")") for w in rest.split())
1055
+ notes = _fetch_notes(args, sudo="sudo" in script.work[m.start() : m.end()])
1056
+ yield PipeFinding(
1057
+ m.start(),
1058
+ f"{m.group(1)} substituted into a shell",
1059
+ f"Download substituted into a shell{_detail(notes)}",
1060
+ bool(notes),
1061
+ )
1062
+
1063
+
1064
+ def _fetch_notes(args: tuple[str, ...], *, sudo: bool) -> list[str]:
1065
+ urls = [a for a in args if "://" in a]
1066
+ notes = []
1067
+ if any(a.lower().startswith("http://") for a in urls):
1068
+ notes.append("over plain http")
1069
+ elif not urls and any("$" in a or "QQQ" in a for a in args):
1070
+ notes.append("from a variable URL")
1071
+ if sudo:
1072
+ notes.append("as root")
1073
+ return notes
1074
+
1075
+
1076
+ def _detail(notes: list[str]) -> str:
1077
+ return f" ({', '.join(notes)})" if notes else ""
1078
+
1079
+
1080
+ @rule(
1081
+ id="ci/curl-pipe-shell",
1082
+ severity="error",
1083
+ title="Downloaded script piped into a shell",
1084
+ languages=_YAML,
1085
+ classes=_WORKFLOW,
1086
+ rationale=(
1087
+ "curl | sh runs whatever the server returns at that moment, unverified, with the job's "
1088
+ "token and secrets; a compromised or spoofed host owns the job. Over plain http, from a "
1089
+ "variable URL or under sudo the risk is higher."
1090
+ ),
1091
+ hint=(
1092
+ "Download to a file, verify a pinned checksum or signature, then run it; or use a "
1093
+ "pinned action or package instead."
1094
+ ),
1095
+ tags={"ci", "security", "supply-chain"},
1096
+ )
1097
+ def curl_pipe_shell(ctx: FileContext) -> Iterator[Hit]:
1098
+ """See :func:`curl_pipe_findings`; shell ``run`` steps of workflows and actions.
1099
+
1100
+ ``error`` for plain ``http://``, a variable URL or ``sudo``; ``warning``
1101
+ for a literal ``https://`` URL.
1102
+ """
1103
+ for script in shell_scripts(ctx):
1104
+ for found in curl_pipe_findings(script):
1105
+ yield Hit(
1106
+ script.line_of(found.offset),
1107
+ evidence=found.evidence,
1108
+ message=found.message,
1109
+ severity=None if found.strong else "warning",
1110
+ )
1111
+
1112
+
1113
+ # --- unpinned-action / unpinned-image -------------------------------------------------
1114
+
1115
+ _FULL_SHA = re.compile(r"[0-9a-f]{40}(?:[0-9a-f]{24})?")
1116
+ _IMAGE_DIGEST = re.compile(r"@sha256:[0-9a-f]{64}\Z")
1117
+
1118
+
1119
+ def _uses_nodes(wf: Workflow) -> Iterator[YamlScalar]:
1120
+ for job in wf.jobs:
1121
+ if job.id:
1122
+ uses = _scalar(job.node.get("uses"))
1123
+ if uses is not None:
1124
+ yield uses
1125
+ for step in job.steps:
1126
+ if step.uses is not None:
1127
+ yield step.uses
1128
+
1129
+
1130
+ @rule(
1131
+ id="ci/unpinned-action",
1132
+ severity="warning",
1133
+ title="Action not pinned to a commit SHA",
1134
+ languages=_YAML,
1135
+ classes=_WORKFLOW,
1136
+ rationale=(
1137
+ "Tags and branches can be moved: whoever controls the action's repository can change "
1138
+ "the code that runs in this workflow, with its secrets and token, without any change "
1139
+ "here."
1140
+ ),
1141
+ hint="Pin to the full 40-character commit SHA and keep the version in a comment.",
1142
+ tags={"ci", "supply-chain"},
1143
+ )
1144
+ def unpinned_action(ctx: FileContext) -> Iterator[Hit]:
1145
+ """A step or reusable-workflow ``uses:`` without a full commit SHA.
1146
+
1147
+ First-party ``actions/*`` count too. Local ``./`` actions are pinned by
1148
+ the repository itself; ``docker://`` references are images, left to
1149
+ ``ci/unpinned-image``. Expressions are not judged.
1150
+ """
1151
+ for wf in workflows(ctx.yaml):
1152
+ for uses in _uses_nodes(wf):
1153
+ value = uses.value.strip()
1154
+ if not value or value.startswith(("./", "docker://")) or "${{" in value:
1155
+ continue
1156
+ ref = value.rsplit("@", 1)[1] if "@" in value else ""
1157
+ if _FULL_SHA.fullmatch(ref.strip()):
1158
+ continue
1159
+ line = uses.start_line
1160
+ yield Hit(
1161
+ line,
1162
+ column=_column(ctx, line, value),
1163
+ evidence=value,
1164
+ message=f"{value} is not pinned to a commit SHA",
1165
+ )
1166
+
1167
+
1168
+ def _images(wf: Workflow) -> Iterator[YamlScalar]:
1169
+ for job in wf.jobs:
1170
+ if job.id:
1171
+ container = job.node.get("container")
1172
+ if isinstance(container, YamlScalar):
1173
+ yield container
1174
+ elif isinstance(container, YamlMap) and _scalar(container.get("image")):
1175
+ yield _scalar(container.get("image")) # type: ignore[misc]
1176
+ services = _map(job.node.get("services"))
1177
+ if services is not None:
1178
+ for entry in services.entries:
1179
+ service = entry.value
1180
+ if isinstance(service, YamlScalar):
1181
+ yield service
1182
+ elif isinstance(service, YamlMap) and _scalar(service.get("image")):
1183
+ yield _scalar(service.get("image")) # type: ignore[misc]
1184
+ else:
1185
+ image = _scalar(job.node.get("image"))
1186
+ if image is not None and image.value.strip().startswith("docker://"):
1187
+ yield image
1188
+ for step in job.steps:
1189
+ if step.uses is not None and step.uses.value.strip().startswith("docker://"):
1190
+ yield step.uses
1191
+
1192
+
1193
+ @rule(
1194
+ id="ci/unpinned-image",
1195
+ severity="warning",
1196
+ title="Container image not pinned to a digest",
1197
+ languages=_YAML,
1198
+ classes=_WORKFLOW,
1199
+ rationale=(
1200
+ "An image tag can be re-pushed: whoever controls the registry repository can change "
1201
+ "what runs in the job without any change here."
1202
+ ),
1203
+ hint="Reference the image by digest (image@sha256:...) and keep the tag in a comment.",
1204
+ tags={"ci", "supply-chain"},
1205
+ )
1206
+ def unpinned_image(ctx: FileContext) -> Iterator[Hit]:
1207
+ """``container``, ``services`` and ``docker://`` images without an ``@sha256:`` digest.
1208
+
1209
+ Images given by an expression and Dockerfile-built action images are
1210
+ not judged.
1211
+ """
1212
+ for wf in workflows(ctx.yaml):
1213
+ for node in _images(wf):
1214
+ value = node.value.strip()
1215
+ if not value or "${{" in value or _IMAGE_DIGEST.search(value):
1216
+ continue
1217
+ line = node.start_line
1218
+ yield Hit(
1219
+ line,
1220
+ column=_column(ctx, line, value),
1221
+ evidence=value,
1222
+ message=f"{value.removeprefix('docker://')} is not pinned to a digest",
1223
+ )
1224
+
1225
+
1226
+ # --- persist-credentials / secrets-inherit / self-hosted-pr / continue-on-error -------
1227
+
1228
+
1229
+ @rule(
1230
+ id="ci/persist-credentials",
1231
+ severity="warning",
1232
+ title="Checkout keeps the token in the Git config",
1233
+ languages=_YAML,
1234
+ classes=_WORKFLOW,
1235
+ rationale=(
1236
+ "actions/checkout stores the job's token in .git/config unless persist-credentials is "
1237
+ "false; every later step, and any artifact that includes the checkout, can read it."
1238
+ ),
1239
+ hint="Set with: persist-credentials: false unless a later step must push.",
1240
+ tags={"ci", "security", "secrets"},
1241
+ )
1242
+ def persist_credentials(ctx: FileContext) -> Iterator[Hit]:
1243
+ """An ``actions/checkout`` step without ``persist-credentials: false``."""
1244
+ for wf in workflows(ctx.yaml):
1245
+ for job in wf.jobs:
1246
+ for step in job.steps:
1247
+ if not _is_action(step, "actions/checkout") or step.uses is None:
1248
+ continue
1249
+ setting = _scalar(step.with_.get("persist-credentials")) if step.with_ else None
1250
+ if setting is not None and setting.value.strip().lower() == "false":
1251
+ continue
1252
+ node = setting if setting is not None else step.uses
1253
+ yield Hit(
1254
+ node.start_line,
1255
+ column=_column(ctx, node.start_line, node.value.strip()),
1256
+ evidence="actions/checkout persist-credentials",
1257
+ )
1258
+
1259
+
1260
+ @rule(
1261
+ id="ci/secrets-inherit",
1262
+ severity="warning",
1263
+ title="Reusable workflow inherits every secret",
1264
+ languages=_YAML,
1265
+ classes=_WORKFLOW,
1266
+ rationale=(
1267
+ "secrets: inherit hands the called workflow every secret of the repository and "
1268
+ "organization, not only the ones it needs."
1269
+ ),
1270
+ hint="Pass the secrets the called workflow needs explicitly under secrets:.",
1271
+ tags={"ci", "security", "secrets"},
1272
+ )
1273
+ def secrets_inherit(ctx: FileContext) -> Iterator[Hit]:
1274
+ """``secrets: inherit`` on a job that calls a reusable workflow."""
1275
+ for wf in workflows(ctx.yaml):
1276
+ for job in wf.jobs:
1277
+ if not job.id:
1278
+ continue
1279
+ value = _scalar(job.node.get("secrets"))
1280
+ if value is not None and value.value.strip().lower() == "inherit":
1281
+ yield Hit(
1282
+ value.start_line,
1283
+ column=_column(ctx, value.start_line, "inherit"),
1284
+ evidence="secrets: inherit",
1285
+ )
1286
+
1287
+
1288
+ def _self_hosted(node: YamlNode | None) -> YamlNode | None:
1289
+ """The node naming ``self-hosted`` in a ``runs-on`` value, if any."""
1290
+ if isinstance(node, YamlScalar):
1291
+ return node if node.value.strip().lower() == "self-hosted" else None
1292
+ if isinstance(node, YamlSeq):
1293
+ for item in node.items:
1294
+ if isinstance(item, YamlScalar) and item.value.strip().lower() == "self-hosted":
1295
+ return item
1296
+ return None
1297
+ if isinstance(node, YamlMap):
1298
+ return _self_hosted(node.get("labels"))
1299
+ return None
1300
+
1301
+
1302
+ _PR_TRIGGERS = ("pull_request", "pull_request_target")
1303
+
1304
+
1305
+ @rule(
1306
+ id="ci/self-hosted-pr",
1307
+ severity="warning",
1308
+ title="Pull request jobs run on a self-hosted runner",
1309
+ languages=_YAML,
1310
+ classes=_WORKFLOW,
1311
+ rationale=(
1312
+ "A pull request from a fork can run its own code on a self-hosted runner; unless the "
1313
+ "runner is ephemeral and isolated, that code can persist on the machine and reach "
1314
+ "later jobs, secrets and the internal network."
1315
+ ),
1316
+ hint=(
1317
+ "Run pull request jobs on hosted or ephemeral runners, or require approval for "
1318
+ "outside contributors."
1319
+ ),
1320
+ tags={"ci", "security"},
1321
+ )
1322
+ def self_hosted_pr(ctx: FileContext) -> Iterator[Hit]:
1323
+ """A ``runs-on`` with the ``self-hosted`` label in a pull-request-triggered workflow.
1324
+
1325
+ Reported at the label and at the pull request trigger, so adding either
1326
+ is a new finding. Runner names given by an expression are not judged.
1327
+ """
1328
+ for wf in workflows(ctx.yaml):
1329
+ triggers = [(name, line) for name, line in wf.triggers if name in _PR_TRIGGERS]
1330
+ if not triggers:
1331
+ continue
1332
+ labels = [
1333
+ node for job in wf.jobs if job.id for node in [_self_hosted(job.node.get("runs-on"))]
1334
+ ]
1335
+ labels = [n for n in labels if n is not None]
1336
+ if not labels:
1337
+ continue
1338
+ for node in labels:
1339
+ yield Hit(
1340
+ node.start_line,
1341
+ column=_column(ctx, node.start_line, "self-hosted"),
1342
+ evidence=f"self-hosted on {triggers[0][0]}",
1343
+ )
1344
+ for name, line in triggers:
1345
+ yield Hit(line, column=_column(ctx, line, name), evidence=f"{name} on self-hosted")
1346
+
1347
+
1348
+ @rule(
1349
+ id="ci/continue-on-error",
1350
+ severity="warning",
1351
+ title="Failures are ignored",
1352
+ languages=_YAML,
1353
+ classes=_WORKFLOW,
1354
+ rationale=(
1355
+ "continue-on-error: true lets the job or step fail while the workflow still reports "
1356
+ "success, so a broken check can pass unnoticed."
1357
+ ),
1358
+ hint="Remove it, or limit it to an experimental matrix entry with an expression.",
1359
+ tags={"ci", "quality"},
1360
+ )
1361
+ def continue_on_error(ctx: FileContext) -> Iterator[Hit]:
1362
+ """A literal ``continue-on-error: true`` on a job or step (expressions are not judged)."""
1363
+ for wf in workflows(ctx.yaml):
1364
+ for job in wf.jobs:
1365
+ nodes = (
1366
+ [job.node, *(s.node for s in job.steps)] if job.id else [s.node for s in job.steps]
1367
+ )
1368
+ for node in nodes:
1369
+ value = _scalar(node.get("continue-on-error"))
1370
+ if value is not None and _literal_bool(value.value) == "true":
1371
+ yield Hit(
1372
+ value.start_line,
1373
+ column=_column(ctx, value.start_line, "continue-on-error"),
1374
+ evidence="continue-on-error: true",
1375
+ )
1376
+
1377
+
1378
+ def _literal_bool(value: str) -> str:
1379
+ text = value.strip().lower()
1380
+ if text.startswith("${{") and text.endswith("}}"):
1381
+ text = text[3:-2].strip()
1382
+ return text
1383
+
1384
+
1385
+ # --- disabled-check ------------------------------------------------------------------
1386
+
1387
+ _CHECK_TOOLS = frozenset(
1388
+ {
1389
+ "pytest",
1390
+ "py.test",
1391
+ "tox",
1392
+ "nox",
1393
+ "unittest",
1394
+ "ruff",
1395
+ "flake8",
1396
+ "pylint",
1397
+ "mypy",
1398
+ "pyright",
1399
+ "black",
1400
+ "isort",
1401
+ "bandit",
1402
+ "jest",
1403
+ "vitest",
1404
+ "mocha",
1405
+ "ava",
1406
+ "playwright",
1407
+ "cypress",
1408
+ "eslint",
1409
+ "prettier",
1410
+ "tsc",
1411
+ "stylelint",
1412
+ "biome",
1413
+ "golangci-lint",
1414
+ "staticcheck",
1415
+ "govulncheck",
1416
+ "shellcheck",
1417
+ "hadolint",
1418
+ "actionlint",
1419
+ "codeveto",
1420
+ "semgrep",
1421
+ "trivy",
1422
+ "rspec",
1423
+ "rubocop",
1424
+ "phpunit",
1425
+ "phpstan",
1426
+ "psalm",
1427
+ "ctest",
1428
+ }
1429
+ )
1430
+ _CHECK_SCRIPTS = re.compile(
1431
+ r"(?:test|tests|lint|check|typecheck|type-check|types|verify|audit|e2e|format:check)"
1432
+ r"(?::[A-Za-z0-9_-]{1,40})?"
1433
+ )
1434
+ _SUBCOMMANDS = {
1435
+ "cargo": frozenset({"test", "clippy", "fmt", "check", "audit", "deny", "nextest"}),
1436
+ "go": frozenset({"test", "vet"}),
1437
+ "make": frozenset({"test", "check", "lint", "ci", "verify"}),
1438
+ "gradle": frozenset({"test", "check"}),
1439
+ "./gradlew": frozenset({"test", "check"}),
1440
+ "gradlew": frozenset({"test", "check"}),
1441
+ "mvn": frozenset({"test", "verify"}),
1442
+ "dotnet": frozenset({"test"}),
1443
+ }
1444
+ _RUNNERS = frozenset({"uv", "poetry", "pipenv", "hatch", "pdm", "rye"})
1445
+ _NODE_PMS = frozenset({"npm", "pnpm", "yarn", "bun"})
1446
+
1447
+
1448
+ def _is_check(words: tuple[str, ...], depth: int = 0) -> bool:
1449
+ if not words or depth > 3:
1450
+ return False
1451
+ head = words[0].rsplit("/", 1)[-1]
1452
+ rest = words[1:]
1453
+ if head in _CHECK_TOOLS:
1454
+ return True
1455
+ if head in _SUBCOMMANDS:
1456
+ return bool(rest) and rest[0] in _SUBCOMMANDS[head]
1457
+ if head in _NODE_PMS:
1458
+ args = [a for a in rest if not a.startswith("-")]
1459
+ if args and args[0] in ("run", "run-script"):
1460
+ args = args[1:]
1461
+ return bool(args) and bool(_CHECK_SCRIPTS.fullmatch(args[0]))
1462
+ if head in ("npx", "pnpx", "bunx"):
1463
+ return _is_check(tuple(a for a in rest if not a.startswith("-")), depth + 1)
1464
+ if head in _RUNNERS and rest and rest[0] == "run":
1465
+ return _is_check(tuple(a for a in rest[1:] if not a.startswith("-")), depth + 1)
1466
+ if head.rstrip("0123456789.") in ("python", "py") and len(rest) >= 2 and rest[0] == "-m":
1467
+ return _is_check(rest[1:], depth + 1)
1468
+ return False
1469
+
1470
+
1471
+ def _neutralized(script: Script, seg: Segment, nxt: Segment | None) -> bool:
1472
+ if seg.sep != "||" or nxt is None:
1473
+ return False
1474
+ cmd = command(script, nxt)
1475
+ if cmd is None:
1476
+ return False
1477
+ return cmd.name in ("true", ":") or (cmd.name == "exit" and cmd.args[:1] == ("0",))
1478
+
1479
+
1480
+ @rule(
1481
+ id="ci/disabled-check",
1482
+ severity="warning",
1483
+ title="Check disabled or its failure ignored",
1484
+ languages=_YAML,
1485
+ classes=_WORKFLOW,
1486
+ rationale=(
1487
+ "A job or step under if: false never runs, a test or lint command followed by "
1488
+ "|| true can never fail, and git --no-verify skips the repository's hooks: the check "
1489
+ "still looks present but no longer protects anything."
1490
+ ),
1491
+ hint="Fix or remove the check deliberately instead of switching it off in place.",
1492
+ tags={"ci", "quality"},
1493
+ )
1494
+ def disabled_check(ctx: FileContext) -> Iterator[Hit]:
1495
+ """``if: false`` jobs and steps, ``<check> || true`` and ``git ... --no-verify``.
1496
+
1497
+ A check is a known test, lint, type or security tool, ``npm test`` and
1498
+ ``npm run <test|lint|check|...>`` (pnpm, yarn, bun), ``cargo
1499
+ test|clippy``, ``go test|vet``, ``make test|check|lint``, and the same
1500
+ under ``npx``, ``uv run``, ``poetry run`` or ``python -m``. ``|| true``,
1501
+ ``|| :`` and ``|| exit 0`` neutralize it.
1502
+ """
1503
+ for wf in workflows(ctx.yaml):
1504
+ for job in wf.jobs:
1505
+ nodes = (
1506
+ [job.node, *(s.node for s in job.steps)] if job.id else [s.node for s in job.steps]
1507
+ )
1508
+ for node in nodes:
1509
+ cond = _scalar(node.get("if"))
1510
+ if cond is not None and _literal_bool(cond.value) in ("false", "0"):
1511
+ yield Hit(
1512
+ cond.start_line,
1513
+ column=_column(ctx, cond.start_line, "if"),
1514
+ evidence="if: false",
1515
+ message="Job or step disabled with if: false",
1516
+ )
1517
+ for script in shell_scripts(ctx):
1518
+ segments = script.segments
1519
+ for k, seg in enumerate(segments):
1520
+ cmd = command(script, seg)
1521
+ if cmd is None:
1522
+ continue
1523
+ words = (cmd.name, *cmd.args)
1524
+ nxt = segments[k + 1] if k + 1 < len(segments) else None
1525
+ if _is_check(words) and _neutralized(script, seg, nxt):
1526
+ yield Hit(
1527
+ script.line_of(seg.words[cmd.index][0]),
1528
+ evidence=f"{' '.join(words[:3])} || true",
1529
+ message=f"Failure of {cmd.name} is ignored",
1530
+ )
1531
+ elif cmd.name == "git" and "--no-verify" in cmd.args:
1532
+ yield Hit(
1533
+ script.line_of(seg.words[cmd.index][0]),
1534
+ evidence="git --no-verify",
1535
+ message="git --no-verify skips the repository's hooks",
1536
+ )
1537
+
1538
+
1539
+ # --- dangerous-trigger -----------------------------------------------------------------
1540
+
1541
+ _DANGEROUS = ("pull_request_target", "workflow_run")
1542
+
1543
+
1544
+ @rule(
1545
+ id="ci/dangerous-trigger",
1546
+ severity="warning",
1547
+ title="Privileged trigger for untrusted events",
1548
+ languages=_YAML,
1549
+ classes=_WORKFLOW,
1550
+ rationale=(
1551
+ "pull_request_target and workflow_run run with the base repository's secrets and a "
1552
+ "write token in response to events anyone can cause; any use of the pull request's "
1553
+ "code, branch name or artifacts in such a workflow needs careful review."
1554
+ ),
1555
+ hint=(
1556
+ "Prefer pull_request; if a privileged trigger is needed, never check out or run the "
1557
+ "pull request's code and keep permissions minimal."
1558
+ ),
1559
+ tags={"ci", "security"},
1560
+ )
1561
+ def dangerous_trigger(ctx: FileContext) -> Iterator[Hit]:
1562
+ """A ``pull_request_target`` or ``workflow_run`` trigger."""
1563
+ for wf in workflows(ctx.yaml):
1564
+ for name, line in wf.triggers:
1565
+ if name in _DANGEROUS:
1566
+ yield Hit(line, column=_column(ctx, line, name), evidence=name)
1567
+
1568
+
1569
+ # --- git-hooks-changed -----------------------------------------------------------------
1570
+
1571
+ _HOOK_DIRS = (".githooks/", ".git-hooks/", ".husky/")
1572
+ _HOOK_FILES = frozenset(
1573
+ {
1574
+ "lefthook.yml",
1575
+ "lefthook.yaml",
1576
+ ".lefthook.yml",
1577
+ ".lefthook.yaml",
1578
+ "lefthook-local.yml",
1579
+ ".lefthook-local.yml",
1580
+ ".pre-commit-config.yaml",
1581
+ ".pre-commit-config.yml",
1582
+ ".simple-git-hooks.json",
1583
+ ".simple-git-hooks.js",
1584
+ ".simple-git-hooks.cjs",
1585
+ "simple-git-hooks.json",
1586
+ ".overcommit.yml",
1587
+ ".huskyrc",
1588
+ ".huskyrc.json",
1589
+ ".huskyrc.js",
1590
+ }
1591
+ )
1592
+
1593
+
1594
+ def is_hook_path(path: str) -> bool:
1595
+ name = path.rsplit("/", 1)[-1]
1596
+ if name in _HOOK_FILES:
1597
+ return True
1598
+ padded = "/" + path
1599
+ return any("/" + d in padded for d in _HOOK_DIRS)
1600
+
1601
+
1602
+ def _file_hit(ctx: FileContext, message: str) -> Hit:
1603
+ change = ctx.change
1604
+ if change.status is not FileStatus.MODIFIED or "mode-change" in change.flags:
1605
+ return Hit(None, message=message)
1606
+ return Hit(1, end_line=max(len(ctx.lines), 1), message=message)
1607
+
1608
+
1609
+ @rule(
1610
+ id="ci/git-hooks-changed",
1611
+ severity="warning",
1612
+ title="Git hook configuration changed",
1613
+ scope="file",
1614
+ rationale=(
1615
+ "Git hooks and hook managers (Husky, lefthook, pre-commit) run code on every "
1616
+ "contributor's machine at commit and push time."
1617
+ ),
1618
+ hint="Review the hook commands as code that runs on developer machines.",
1619
+ tags={"ci", "security"},
1620
+ )
1621
+ def git_hooks_changed(ctx: FileContext) -> Iterator[Hit]:
1622
+ """A file under ``.githooks/``, ``.git-hooks/`` or ``.husky/``, or a hook-manager config."""
1623
+ if is_hook_path(ctx.path) or (ctx.old_path is not None and is_hook_path(ctx.old_path)):
1624
+ yield _file_hit(ctx, "Git hook configuration changed")
1625
+
1626
+
1627
+ # --- default-permissions / workflow-changed ------------------------------------------------
1628
+
1629
+
1630
+ def _uncovered_jobs(result: YamlResult | None) -> dict[str, Job]:
1631
+ out: dict[str, Job] = {}
1632
+ for wf in workflows(result):
1633
+ if wf.is_action or wf.root.entry("permissions") is not None:
1634
+ continue
1635
+ for job in wf.jobs:
1636
+ if job.id and job.node.entry("permissions") is None:
1637
+ out.setdefault(job.id, job)
1638
+ return out
1639
+
1640
+
1641
+ @rule(
1642
+ id="ci/default-permissions",
1643
+ severity="note",
1644
+ title="Job runs with the default token permissions",
1645
+ scope="file",
1646
+ languages=_YAML,
1647
+ classes=_WORKFLOW,
1648
+ rationale=(
1649
+ "Without a permissions: block the token gets the repository's default, which is "
1650
+ "read-write in many repositories and organizations."
1651
+ ),
1652
+ hint="Add permissions: { contents: read } at the top and widen it per job as needed.",
1653
+ tags={"ci", "least-privilege"},
1654
+ )
1655
+ def default_permissions(ctx: FileContext) -> Iterator[Hit]:
1656
+ """A GitHub workflow job newly left without ``permissions`` (workflow or job level).
1657
+
1658
+ Compared with the old side: reported when the file is added, a job is
1659
+ added without permissions, or the permissions that covered a job were
1660
+ removed. Forgejo and Gitea workflows are not reported.
1661
+ """
1662
+ if not ctx.path.startswith(".github/workflows/"):
1663
+ return
1664
+ new = _uncovered_jobs(ctx.yaml)
1665
+ if not new:
1666
+ return
1667
+ old = _uncovered_jobs(ctx.old_yaml) if ctx.old_text is not None else {}
1668
+ if ctx.old_text is not None and ctx.old_yaml is not None and ctx.old_yaml.unsupported:
1669
+ return
1670
+ fresh = [job for job_id, job in new.items() if job_id not in old]
1671
+ if not fresh:
1672
+ return
1673
+ changed = ctx.added_lines | ctx.deletion_points
1674
+ anchored = False
1675
+ for job in fresh:
1676
+ if any(job.line <= n <= job.end_line for n in changed):
1677
+ anchored = True
1678
+ yield Hit(
1679
+ job.line,
1680
+ end_line=job.end_line,
1681
+ message=f"Job {job.id} has no permissions: block",
1682
+ )
1683
+ if not anchored:
1684
+ yield Hit(
1685
+ 1,
1686
+ end_line=max(len(ctx.lines), 1),
1687
+ message="Jobs lost their permissions: block",
1688
+ )
1689
+
1690
+
1691
+ @rule(
1692
+ id="ci/workflow-changed",
1693
+ severity="note",
1694
+ title="CI workflow changed",
1695
+ scope="file",
1696
+ languages=_YAML,
1697
+ classes=_WORKFLOW,
1698
+ rationale=(
1699
+ "Workflows decide what runs with the repository's secrets and which checks gate a "
1700
+ "merge; every change to them deserves a look."
1701
+ ),
1702
+ hint="Review the workflow change like code that runs with production credentials.",
1703
+ tags={"ci"},
1704
+ )
1705
+ def workflow_changed(ctx: FileContext) -> Iterator[Hit]:
1706
+ """Any change to a workflow or action file."""
1707
+ kind = "Action" if ctx.path.rsplit("/", 1)[-1].startswith("action.") else "Workflow"
1708
+ yield _file_hit(ctx, f"{kind} {ctx.change.status.value}")