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,1335 @@
1
+ """Secrets pack (SPEC 6.1): credentials in the change.
2
+
3
+ Provider tokens are matched by their documented formats (prefixes, lengths,
4
+ alphabets and, for GitHub's classic tokens, the CRC32 checksum), private
5
+ keys by their PEM blocks, and the rest by context: credentials in URLs,
6
+ secret-named assignments, ``.env`` and credential files.
7
+
8
+ Every hit marks the secret with ``Hit.redact`` on each line it occupies, so
9
+ the engine replaces it in every snippet, message and evidence. Messages never
10
+ quote the value and ``evidence`` carries only a short SHA-256 fingerprint of
11
+ it, which is still the hit's identity for the introduced-only filter (a moved
12
+ or re-indented secret is not new; a changed one is).
13
+
14
+ Placeholders (``<your-token>``, ``xxxx``, ``changeme``, ``${VAR}``,
15
+ ``$(cmd)``, ``os.environ[...]``, ``process.env.X``, template syntax) and
16
+ obviously fake values (long runs of one character, ``0123456789``-style
17
+ sequences, too few distinct characters) never fire. Known documentation dummy
18
+ values (canaries: the AWS ``EXAMPLE`` key ID and secret, GitHub's and Stripe's
19
+ documentation tokens, the jwt.io sample) are reported by their provider rule
20
+ as notes.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import base64
26
+ import binascii
27
+ import hashlib
28
+ import itertools
29
+ import math
30
+ import re
31
+ import zlib
32
+ from collections.abc import Callable, Iterator
33
+ from dataclasses import dataclass
34
+
35
+ from codeveto import jsonsafe
36
+ from codeveto.rules.base import FileContext, Hit, rule
37
+
38
+ # --- Shared value checks ----------------------------------------------------------
39
+
40
+
41
+ def _words(text: str) -> tuple[str, ...]:
42
+ return tuple(text.split())
43
+
44
+
45
+ def fingerprint(value: str) -> str:
46
+ """Short SHA-256 of ``value``: identifies a secret without revealing it."""
47
+ data = value.encode("utf-8", "surrogatepass")
48
+ return "sha256:" + hashlib.sha256(data).hexdigest()[:12]
49
+
50
+
51
+ _FAKE_WORDS = _words(
52
+ "example xxxx placeholder your fake dummy sample redacted insert replace token secret"
53
+ )
54
+
55
+
56
+ def _longest_run(value: str) -> int:
57
+ best = run = 1 if value else 0
58
+ for a, b in itertools.pairwise(value):
59
+ run = run + 1 if a == b else 1
60
+ best = max(best, run)
61
+ return best
62
+
63
+
64
+ def _longest_sequence(value: str) -> int:
65
+ """Longest run of consecutive code points (``0123``, ``abcd``, ``DCBA``)."""
66
+ best = 1 if value else 0
67
+ up = down = 1
68
+ for a, b in itertools.pairwise(value):
69
+ up = up + 1 if ord(b) == ord(a) + 1 and b.isalnum() else 1
70
+ down = down + 1 if ord(b) == ord(a) - 1 and b.isalnum() else 1
71
+ best = max(best, up, down)
72
+ return best
73
+
74
+
75
+ def is_fake_token(body: str) -> bool:
76
+ """Is a provider token body an obvious stand-in rather than random material?"""
77
+ lowered = body.lower()
78
+ if any(word in lowered for word in _FAKE_WORDS):
79
+ return True
80
+ if _longest_run(body) >= 6 or _longest_sequence(body) >= 6:
81
+ return True
82
+ if len(body) >= 20:
83
+ kinds = any(c.islower() for c in body) + any(c.isupper() for c in body)
84
+ if kinds + any(c.isdigit() for c in body) < 2:
85
+ return True # one character class: a word, a slug or a number
86
+ return len(set(body)) < min(10, len(body) // 3)
87
+
88
+
89
+ def _mixed(body: str) -> bool:
90
+ """Random base62/base64url material of this length has all three classes."""
91
+ return (
92
+ any(c.islower() for c in body)
93
+ and any(c.isupper() for c in body)
94
+ and any(c.isdigit() for c in body)
95
+ and not is_fake_token(body)
96
+ )
97
+
98
+
99
+ _REFERENCE_MARKERS = _words(
100
+ "${ $( {{ }} <% %> #{ %( os.environ process.env getenv environ[ env( env. secrets. vault: "
101
+ "ssm: arn:aws: op:// keyring encrypted: enc["
102
+ )
103
+
104
+ _PLACEHOLDER_WORDS = _words(
105
+ "example sample placeholder changeme change_me change-me changeit replace your insert "
106
+ "dummy fake redacted fixme todo notreal not_real not-a- mock test xxx *** ..."
107
+ )
108
+
109
+ DEFAULT_WORDS = frozenset(
110
+ _words(
111
+ "password passwd pass pwd secret token admin administrator root guest user username dev "
112
+ "development local localhost postgres postgresql mysql mariadb mongo redis rabbitmq minio "
113
+ "minioadmin none null nil undefined true false default demo foo bar baz foobar qwerty "
114
+ "letmein hunter2 123456 12345678 123456789 password1 password123 secret123 tbd hidden "
115
+ "masked empty unset required optional string"
116
+ )
117
+ )
118
+ """Values that are documentation defaults or local-development stand-ins, not secrets."""
119
+
120
+ _FORMAT_SPEC = re.compile(r"%[-+ #0]{0,3}[0-9]{0,3}[sdvqrx]")
121
+
122
+
123
+ def is_placeholder(value: str) -> bool:
124
+ """Is ``value`` empty, a placeholder, a default word or a reference to a secret?"""
125
+ stripped = value.strip()
126
+ if not stripped:
127
+ return True
128
+ lowered = stripped.lower()
129
+ if stripped[0] == "$" or (stripped[0] in "<[" and stripped[-1] in ">]"):
130
+ return True
131
+ if "{" in stripped and "}" in stripped:
132
+ return True # str.format, Go and Jinja templates
133
+ if any(marker in lowered for marker in _REFERENCE_MARKERS):
134
+ return True
135
+ if any(word in lowered for word in _PLACEHOLDER_WORDS):
136
+ return True
137
+ if _FORMAT_SPEC.search(stripped):
138
+ return True
139
+ if lowered in DEFAULT_WORDS:
140
+ return True
141
+ core = stripped.strip("-_.*#=")
142
+ return len(set(core)) <= 2
143
+
144
+
145
+ def shannon(value: str) -> float:
146
+ """Shannon entropy in bits per character."""
147
+ if not value:
148
+ return 0.0
149
+ counts: dict[str, int] = {}
150
+ for ch in value:
151
+ counts[ch] = counts.get(ch, 0) + 1
152
+ size = len(value)
153
+ return -sum(c / size * math.log2(c / size) for c in counts.values())
154
+
155
+
156
+ def _classes(value: str) -> int:
157
+ lower = any(c.islower() for c in value)
158
+ upper = any(c.isupper() for c in value)
159
+ digit = any(c.isdigit() for c in value)
160
+ other = any(not c.isalnum() for c in value)
161
+ return lower + upper + digit + other
162
+
163
+
164
+ _KNOWN_HASH = re.compile(
165
+ r"\$2[abxy]?\$[0-9]{2}\$|\$argon2(?:id|i|d)\$|\$[156]\$|\$scrypt\$|\$pbkdf2"
166
+ r"|pbkdf2[_:]sha|scrypt:|\{s?sha[0-9]{0,3}\}|(?:sha1|sha224|sha256|sha384|sha512|md5)[:$-]",
167
+ re.IGNORECASE,
168
+ )
169
+
170
+
171
+ def is_known_hash(value: str) -> bool:
172
+ """Is ``value`` a password hash or digest in a known algorithm's notation?"""
173
+ return _KNOWN_HASH.match(value) is not None
174
+
175
+
176
+ _WORD = re.compile(r"[a-z]{4,}|[A-Z][a-z]{3,}|[A-Z]{4,}")
177
+
178
+
179
+ def looks_random(value: str, minimum: int = 12) -> bool:
180
+ """Has ``value`` the length, variety and entropy of generated secret material?
181
+
182
+ Words and identifiers (``user_password``, ``AcmeCheckoutService2``,
183
+ ``checkout-v2,search-beta``) and anything with whitespace are not: at
184
+ most half the value may be letter runs that read like words. A value in
185
+ one letter case must also be at least 20 alphanumeric characters (``-``
186
+ and ``_`` allowed) with a fifth of them digits and 3.5 bits of entropy
187
+ per character, which long hex and base32 tokens have.
188
+ """
189
+ if len(value) < minimum or len(value) > 512 or any(c.isspace() for c in value):
190
+ return False
191
+ if "://" in value or value.startswith(("/", "./", "../", "~/")) or is_known_hash(value):
192
+ return False
193
+ if is_fake_token(value):
194
+ return False
195
+ if sum(len(w) for w in _WORD.findall(value)) * 2 > len(value):
196
+ return False
197
+ entropy = shannon(value)
198
+ mixed_case = any(c.islower() for c in value) and any(c.isupper() for c in value)
199
+ if mixed_case and _classes(value) >= 3:
200
+ return entropy >= 3.0
201
+ core = value.replace("-", "").replace("_", "")
202
+ digits = sum(c.isdigit() for c in core)
203
+ return len(core) >= 20 and core.isalnum() and digits * 5 >= len(core) and entropy >= 3.5
204
+
205
+
206
+ # --- Secret-looking names ---------------------------------------------------------
207
+
208
+ _NAME_KEYWORDS = _words(
209
+ "password passwd passphrase secret token apikey accesskey privatekey authkey signingkey "
210
+ "encryptionkey masterkey credential"
211
+ )
212
+
213
+ _NAME_EXCLUDED = frozenset(
214
+ _words(
215
+ "hash hashed digest checksum fingerprint sha sha1 sha256 sha512 md5 salt url uri path "
216
+ "file filename dir name names field label type types header prefix suffix length len "
217
+ "count max min size regex re pattern format fmt env var id ids endpoint param expiry "
218
+ "expires expiration ttl timeout policy mode kind placeholder example tokenizer tokens "
219
+ "public pub limit usage budget input output validator rule error message msg text help "
220
+ "hint prompt description desc class ref key_id provider store manager source version "
221
+ "location arn slot sentinel reset confirm confirmation strength complexity rotation "
222
+ "refresh_url lifetime enabled required scope scopes permission permissions algorithm "
223
+ "alg issuer audience host port domain region bucket"
224
+ )
225
+ )
226
+
227
+ _CAMEL = re.compile(r"[A-Z]{2,}(?=[A-Z][a-z])|[A-Z]?[a-z]+|[A-Z]+|[0-9]+")
228
+
229
+
230
+ def name_segments(name: str) -> list[str]:
231
+ """Lower-case words of an identifier (snake, kebab, dotted and camel case)."""
232
+ words: list[str] = []
233
+ for part in re.split(r"[^A-Za-z0-9]", name):
234
+ words.extend(w.lower() for w in _CAMEL.findall(part))
235
+ return words
236
+
237
+
238
+ def is_secret_name(name: str) -> bool:
239
+ """Does ``name`` say its value is a secret (and not about one, like ``token_url``)?"""
240
+ segments = name_segments(name)
241
+ if not segments or any(s in _NAME_EXCLUDED for s in segments):
242
+ return False
243
+ joined = "".join(segments)
244
+ return "pwd" in segments or any(k in joined for k in _NAME_KEYWORDS)
245
+
246
+
247
+ _PUBLIC_PREFIXES = _words(
248
+ "VITE_ NEXT_PUBLIC_ REACT_APP_ EXPO_PUBLIC_ NUXT_PUBLIC_ GATSBY_ PUBLIC_ STORYBOOK_"
249
+ )
250
+
251
+
252
+ def is_public_name(name: str) -> bool:
253
+ """Framework prefixes for variables that are shipped to the browser by design."""
254
+ return name.upper().startswith(_PUBLIC_PREFIXES)
255
+
256
+
257
+ # --- Line scanning ----------------------------------------------------------------
258
+
259
+
260
+ def _line_matches(
261
+ ctx: FileContext,
262
+ pattern: re.Pattern[str],
263
+ needles: tuple[str, ...],
264
+ *,
265
+ folded: bool = False,
266
+ ) -> Iterator[tuple[int, str, re.Match[str]]]:
267
+ """``(line, full line, match)`` for each match on a changed line, once per start.
268
+
269
+ A line is searched only when it contains one of ``needles`` (compared in
270
+ lower case when ``folded``). Windows of long lines are searched, and each
271
+ match is redone on the full line at its start, so a token that crosses a
272
+ window edge is matched whole and a match that a window edge cut out of a
273
+ longer token (the lookbehind sees the real line) is dropped.
274
+ """
275
+ seen: set[tuple[int, int]] = set()
276
+ lines = ctx.lines
277
+ for number, text in ctx.changed_lines():
278
+ probe = text.lower() if folded else text
279
+ if needles and not any(n in probe for n in needles):
280
+ continue
281
+ whole = text.at_line_start and text.at_line_end
282
+ full = lines[number - 1]
283
+ for window_match in pattern.finditer(text):
284
+ start = text.offset + window_match.start()
285
+ if (number, start) in seen:
286
+ continue
287
+ seen.add((number, start))
288
+ match = window_match if whole else pattern.match(full, start)
289
+ if match is not None:
290
+ yield number, full, match
291
+
292
+
293
+ @dataclass(frozen=True, slots=True)
294
+ class Token:
295
+ """A provider token found on a changed line (0-based ``start``/``end`` in the line)."""
296
+
297
+ line: int
298
+ start: int
299
+ end: int
300
+ value: str
301
+ full_line: str
302
+
303
+ def hit(self, label: str, *, canary: bool = False) -> Hit:
304
+ """The hit for this token; a known documentation dummy value is only a note."""
305
+ return Hit(
306
+ self.line,
307
+ column=self.start + 1,
308
+ message=f"Documentation dummy {label}" if canary else f"{label} in the change",
309
+ evidence=f"{label} {fingerprint(self.value)}",
310
+ redact=((self.line, self.start + 1, self.end + 1),),
311
+ severity="note" if canary else None,
312
+ )
313
+
314
+
315
+ @dataclass(frozen=True, slots=True)
316
+ class Provider:
317
+ """One provider token format: how to find it and how to tell a real one."""
318
+
319
+ label: str
320
+ pattern: re.Pattern[str]
321
+ needles: tuple[str, ...]
322
+ group: str | int = 0
323
+ """Group of the match that is the secret (redacted and fingerprinted)."""
324
+ valid: Callable[[re.Match[str], str, FileContext, int], bool] = lambda m, line, ctx, n: True
325
+ canary: Callable[[str], bool] = lambda value: False
326
+
327
+ def tokens(self, ctx: FileContext) -> Iterator[tuple[Token, bool]]:
328
+ """``(token, is_canary)`` for every match that is real or a known canary."""
329
+ for number, full, match in _line_matches(ctx, self.pattern, self.needles):
330
+ value = match.group(self.group)
331
+ token = Token(number, match.start(self.group), match.end(self.group), value, full)
332
+ if self.canary(value):
333
+ yield token, True
334
+ elif self.valid(match, full, ctx, number):
335
+ yield token, False
336
+
337
+
338
+ # --- Token formats ----------------------------------------------------------------
339
+
340
+ _BASE62 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
341
+
342
+
343
+ def base62(value: int, width: int) -> str:
344
+ digits = ""
345
+ while value:
346
+ value, rest = divmod(value, 62)
347
+ digits = _BASE62[rest] + digits
348
+ return digits.rjust(width, "0")
349
+
350
+
351
+ def github_checksum_ok(body: str) -> bool:
352
+ """GitHub classic token body: 30 random characters, then base62(CRC32) in 6."""
353
+ return base62(zlib.crc32(body[:30].encode("ascii")), 6) == body[30:]
354
+
355
+
356
+ def _body_not_fake(group: str | int) -> Callable[[re.Match[str], str, FileContext, int], bool]:
357
+ def check(match: re.Match[str], line: str, ctx: FileContext, number: int) -> bool:
358
+ return not is_fake_token(match.group(group))
359
+
360
+ return check
361
+
362
+
363
+ AWS_ACCESS_KEY = Provider(
364
+ label="AWS access key ID",
365
+ pattern=re.compile(r"(?<![A-Za-z0-9])(?:AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16}(?![A-Za-z0-9])"),
366
+ needles=("AKIA", "ASIA", "ABIA", "ACCA"),
367
+ valid=lambda m, line, ctx, n: not is_fake_token(m.group(0)[4:]),
368
+ canary=lambda value: value.endswith("EXAMPLE"),
369
+ )
370
+
371
+ AWS_SECRET_KEY = Provider(
372
+ label="AWS secret access key",
373
+ pattern=re.compile(
374
+ r"(?i)(?:aws[A-Za-z0-9_.-]{0,20}secret[A-Za-z0-9_.-]{0,20}|secret_?access_?key)"
375
+ r"[\"'\]]{0,2}[ \t]{0,5}(?::=|=>|:|=)[ \t]{0,5}[\"']?"
376
+ r"(?P<value>[A-Za-z0-9/+]{40})(?![A-Za-z0-9/+=])"
377
+ ),
378
+ needles=("ecret", "ECRET"),
379
+ group="value",
380
+ valid=lambda m, line, ctx, n: (
381
+ _classes(m.group("value")) >= 3 and not is_fake_token(m.group("value"))
382
+ ),
383
+ canary=lambda value: value.endswith("EXAMPLEKEY"),
384
+ )
385
+
386
+ _GITHUB_DOC_BODIES = frozenset({"16C7e42F292c6912E7710c838347Ae178B4a"})
387
+
388
+ GITHUB_CLASSIC = Provider(
389
+ label="GitHub token",
390
+ pattern=re.compile(r"(?<![A-Za-z0-9_])gh[pousr]_(?P<body>[A-Za-z0-9]{36})(?![A-Za-z0-9_])"),
391
+ needles=("gh",),
392
+ valid=lambda m, line, ctx, n: github_checksum_ok(m.group("body")),
393
+ canary=lambda value: value[4:] in _GITHUB_DOC_BODIES,
394
+ )
395
+
396
+ GITHUB_FINE_GRAINED = Provider(
397
+ label="GitHub fine-grained token",
398
+ pattern=re.compile(
399
+ r"(?<![A-Za-z0-9_])github_pat_(?P<a>[A-Za-z0-9]{22})_(?P<b>[A-Za-z0-9]{59})(?![A-Za-z0-9_])"
400
+ ),
401
+ needles=("github_pat_",),
402
+ valid=lambda m, line, ctx, n: (
403
+ not is_fake_token(m.group("a")) and not is_fake_token(m.group("b"))
404
+ ),
405
+ )
406
+
407
+ GITLAB = Provider(
408
+ label="GitLab token",
409
+ pattern=re.compile(
410
+ r"(?<![A-Za-z0-9_-])(?:(?:glpat|gldt|glrt|glcbt|glft|glimt|glsoat|glffct|glagent|gloas|glptt)-"
411
+ r"|GR1348941)(?P<body>[0-9A-Za-z_-]{20,64})(?:\.[0-9a-z]{2}\.[0-9a-z]{7,9})?(?![0-9A-Za-z_-])"
412
+ ),
413
+ needles=("gl", "GR1348941"),
414
+ valid=_body_not_fake("body"),
415
+ )
416
+
417
+ SLACK_TOKEN = Provider(
418
+ label="Slack token",
419
+ pattern=re.compile(
420
+ r"(?<![A-Za-z0-9.-])(?:"
421
+ r"xox[abposr]-(?:[0-9]-)?(?:[0-9]{8,15}-){1,3}(?P<a>[A-Za-z0-9]{20,64})"
422
+ r"|xox[er](?:\.xox[bp])?-[0-9]-(?P<b>[A-Za-z0-9-]{60,250})"
423
+ r"|xapp-[0-9]-[A-Z0-9]{8,14}-[0-9]{8,15}-(?P<c>[a-f0-9]{32,80})"
424
+ r")(?![A-Za-z0-9-])"
425
+ ),
426
+ needles=("xox", "xapp-"),
427
+ valid=lambda m, line, ctx, n: not is_fake_token(m.group("a") or m.group("b") or m.group("c")),
428
+ )
429
+
430
+ SLACK_WEBHOOK = Provider(
431
+ label="Slack webhook URL",
432
+ pattern=re.compile(
433
+ r"https?://hooks\.slack\.com/(?P<path>"
434
+ r"services/T[A-Z0-9]{8,12}/B[A-Z0-9]{8,12}/(?P<a>[A-Za-z0-9]{24})"
435
+ r"|(?:workflows|triggers)/T[A-Z0-9]{8,12}/A[A-Z0-9]{8,12}/[0-9]{6,20}/(?P<b>[A-Za-z0-9]{32})"
436
+ r")(?![A-Za-z0-9])"
437
+ ),
438
+ needles=("hooks.slack.com",),
439
+ group="path",
440
+ valid=lambda m, line, ctx, n: not is_fake_token(m.group("a") or m.group("b")),
441
+ )
442
+
443
+ _STRIPE_DOC_BODIES = frozenset({"4eC39HqLyjWDarjtT1zdp7dc", "BQokikJOvBiI2HlWgH4olfQ2"})
444
+
445
+ STRIPE_LIVE = Provider(
446
+ label="Stripe live secret key",
447
+ pattern=re.compile(
448
+ r"(?<![A-Za-z0-9_])(?:sk|rk)_live_(?P<body>[0-9A-Za-z]{24,247})(?![0-9A-Za-z_])"
449
+ ),
450
+ needles=("_live_",),
451
+ valid=_body_not_fake("body"),
452
+ canary=lambda value: value[8:] in _STRIPE_DOC_BODIES,
453
+ )
454
+
455
+
456
+ def _not_firebase(match: re.Match[str], line: str, ctx: FileContext, number: int) -> bool:
457
+ """Firebase and other browser API keys are public identifiers by Google's design."""
458
+ if is_fake_token(match.group("body")):
459
+ return False
460
+ prefix = line[: match.start()]
461
+ if any(p in prefix.upper() for p in _PUBLIC_PREFIXES):
462
+ return False
463
+ lines = ctx.lines
464
+ nearby = lines[max(0, number - 21) : number]
465
+ return not any("firebase" in item[:2000].lower() for item in nearby)
466
+
467
+
468
+ GOOGLE_API_KEY = Provider(
469
+ label="Google API key",
470
+ pattern=re.compile(r"(?<![A-Za-z0-9_-])AIza(?P<body>[0-9A-Za-z_-]{35})(?![0-9A-Za-z_-])"),
471
+ needles=("AIza",),
472
+ valid=_not_firebase,
473
+ )
474
+
475
+ OPENAI_KEY = Provider(
476
+ label="OpenAI API key",
477
+ pattern=re.compile(
478
+ r"(?<![A-Za-z0-9_-])sk-(?:(?:proj|svcacct|admin)-(?P<a>[A-Za-z0-9_-]{40,250})"
479
+ r"|(?P<b>[A-Za-z0-9]{20}T3BlbkFJ[A-Za-z0-9]{20}))(?![A-Za-z0-9_-])"
480
+ ),
481
+ needles=("sk-",),
482
+ valid=lambda m, line, ctx, n: _mixed(m.group("a") or m.group("b")),
483
+ )
484
+
485
+ ANTHROPIC_KEY = Provider(
486
+ label="Anthropic API key",
487
+ pattern=re.compile(
488
+ r"(?<![A-Za-z0-9_-])sk-ant-(?:api|admin|oat|ort)[0-9]{2}-(?P<body>[A-Za-z0-9_-]{80,120})"
489
+ r"(?![A-Za-z0-9_-])"
490
+ ),
491
+ needles=("sk-ant-",),
492
+ valid=lambda m, line, ctx, n: _mixed(m.group("body")),
493
+ )
494
+
495
+ NPM_TOKEN = Provider(
496
+ label="npm access token",
497
+ pattern=re.compile(r"(?<![A-Za-z0-9_])npm_(?P<body>[A-Za-z0-9]{36})(?![A-Za-z0-9_])"),
498
+ needles=("npm_",),
499
+ valid=_body_not_fake("body"),
500
+ )
501
+
502
+ PYPI_TOKEN = Provider(
503
+ label="PyPI API token",
504
+ pattern=re.compile(
505
+ r"(?<![A-Za-z0-9_-])pypi-AgE(?:IcHlwaS5vcmc|NdGVzdC5weXBpLm9yZw)(?P<body>[A-Za-z0-9_-]{50,400})"
506
+ r"(?![A-Za-z0-9_-])"
507
+ ),
508
+ needles=("pypi-AgE",),
509
+ valid=_body_not_fake("body"),
510
+ )
511
+
512
+
513
+ def _b64json(segment: str) -> object:
514
+ try:
515
+ raw = base64.urlsafe_b64decode(segment + "=" * (-len(segment) % 4))
516
+ return jsonsafe.loads(raw.decode("utf-8"))
517
+ except (binascii.Error, ValueError, UnicodeDecodeError, RecursionError):
518
+ return None
519
+
520
+
521
+ def _jwt_valid(match: re.Match[str], line: str, ctx: FileContext, number: int) -> bool:
522
+ header = _b64json(match.group("header"))
523
+ payload = _b64json(match.group("payload"))
524
+ if not isinstance(header, dict) or not isinstance(payload, dict):
525
+ return False
526
+ alg = header.get("alg")
527
+ return isinstance(alg, str) and alg.lower() != "none" and not is_fake_token(match.group("sig"))
528
+
529
+
530
+ def _jwt_canary(value: str) -> bool:
531
+ """The jwt.io sample token (``sub`` 1234567890, ``name`` John Doe)."""
532
+ parts = value.split(".")
533
+ payload = _b64json(parts[1]) if len(parts) == 3 else None
534
+ return (
535
+ isinstance(payload, dict)
536
+ and payload.get("sub") == "1234567890"
537
+ and payload.get("name") == "John Doe"
538
+ )
539
+
540
+
541
+ JWT = Provider(
542
+ label="JSON Web Token",
543
+ pattern=re.compile(
544
+ r"(?<![A-Za-z0-9_-])(?P<header>eyJ[A-Za-z0-9_-]{8,1000})\.(?P<payload>eyJ[A-Za-z0-9_-]{4,4000})"
545
+ r"\.(?P<sig>[A-Za-z0-9_-]{16,1000})(?![A-Za-z0-9_.-])"
546
+ ),
547
+ needles=("eyJ",),
548
+ valid=_jwt_valid,
549
+ canary=_jwt_canary,
550
+ )
551
+
552
+ PROVIDERS: dict[str, tuple[Provider, ...]] = {
553
+ "secrets/aws-access-key": (AWS_ACCESS_KEY,),
554
+ "secrets/aws-secret-key": (AWS_SECRET_KEY,),
555
+ "secrets/github-token": (GITHUB_CLASSIC, GITHUB_FINE_GRAINED),
556
+ "secrets/gitlab-token": (GITLAB,),
557
+ "secrets/slack-token": (SLACK_TOKEN,),
558
+ "secrets/slack-webhook": (SLACK_WEBHOOK,),
559
+ "secrets/stripe-live-key": (STRIPE_LIVE,),
560
+ "secrets/google-api-key": (GOOGLE_API_KEY,),
561
+ "secrets/openai-key": (OPENAI_KEY,),
562
+ "secrets/anthropic-key": (ANTHROPIC_KEY,),
563
+ "secrets/npm-token": (NPM_TOKEN,),
564
+ "secrets/pypi-token": (PYPI_TOKEN,),
565
+ "secrets/jwt": (JWT,),
566
+ }
567
+ """Each provider rule and the token formats it reports."""
568
+
569
+
570
+ def _provider_hits(ctx: FileContext, rule_id: str) -> Iterator[Hit]:
571
+ for provider in PROVIDERS[rule_id]:
572
+ for token, canary in provider.tokens(ctx):
573
+ yield token.hit(provider.label, canary=canary)
574
+
575
+
576
+ def _provider_spans(ctx: FileContext) -> dict[int, list[tuple[int, int]]]:
577
+ """Changed-line spans that a provider rule already reports (canaries included)."""
578
+ spans: dict[int, list[tuple[int, int]]] = {}
579
+ for providers in PROVIDERS.values():
580
+ for provider in providers:
581
+ for number, _, match in _line_matches(ctx, provider.pattern, provider.needles):
582
+ spans.setdefault(number, []).append(match.span())
583
+ return spans
584
+
585
+
586
+ # --- Private keys -----------------------------------------------------------------
587
+
588
+ _PEM_BEGIN = re.compile(
589
+ r"-----BEGIN (?P<label>(?:[A-Z0-9]{2,12} ){0,3}PRIVATE KEY(?: BLOCK)?)-----"
590
+ )
591
+ _PEM_HEADER = re.compile(r"[A-Za-z][A-Za-z-]{1,30}: ")
592
+ _BASE64_LINE = re.compile(r"=?[A-Za-z0-9+/]{1,16384}={0,3}") # PGP checksums start with =
593
+ _BASE64_CHARS = frozenset("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=")
594
+ _PEM_MAX_LINES = 400
595
+ _PEM_MIN_BODY = 64
596
+ _DECORATION = " \t\"'`+,;()\\"
597
+ # Comment leaders a key pasted into a comment block carries on every line: none of
598
+ # them is base64 except "//", which therefore needs whitespace (or nothing) after it.
599
+ _COMMENT_LEADERS = ("<!--", "/*", "--", "#", ";", "*")
600
+ _COMMENT_CLOSERS = ("*/", "-->")
601
+
602
+
603
+ def _content_span(line: str) -> tuple[int, int]:
604
+ """Span of a body line without string syntax and comment leaders around it.
605
+
606
+ Removed: quotes, ``\\n`` escapes, ``+`` concatenation, a trailing comma or
607
+ backslash, and one comment leader (``#``, ``//``, ``/*``, ``*``, ``;``,
608
+ ``--``, ``<!--``) with a closing ``*/`` or ``-->``.
609
+ """
610
+ lo, hi = 0, len(line)
611
+ changed = True
612
+ while changed and lo < hi:
613
+ changed = False
614
+ for suffix in ("\\n", "\\r", "\n", "\r", *_COMMENT_CLOSERS):
615
+ if line.endswith(suffix, lo, hi):
616
+ hi -= len(suffix)
617
+ changed = True
618
+ while hi > lo and line[hi - 1] in _DECORATION:
619
+ hi -= 1
620
+ changed = True
621
+ while lo < hi and line[lo] in " \t":
622
+ lo += 1
623
+ if line.startswith("//", lo, hi) and (lo + 2 == hi or line[lo + 2] in " \t"):
624
+ lo += 2
625
+ else:
626
+ for leader in _COMMENT_LEADERS:
627
+ if line.startswith(leader, lo, hi):
628
+ lo += len(leader)
629
+ break
630
+ while lo < hi and line[lo] in _DECORATION:
631
+ lo += 1
632
+ return lo, hi
633
+
634
+
635
+ def _body_core(line: str) -> tuple[int, int] | None:
636
+ """Span of the base64 content of a key body line, or ``None`` if it is not one.
637
+
638
+ The content may be wrapped in string syntax or a comment (see
639
+ :func:`_content_span`).
640
+ """
641
+ lo, hi = _content_span(line)
642
+ if lo < hi and line[lo] == "b" and hi - lo > 1 and line[lo + 1] in "\"'":
643
+ lo += 2
644
+ if lo >= hi:
645
+ return None
646
+ if _BASE64_LINE.fullmatch(line, lo, hi) is None:
647
+ return None
648
+ return lo, hi
649
+
650
+
651
+ def _plausible_key(body: str) -> bool:
652
+ if len(body) < _PEM_MIN_BODY or len(set(body)) < 20:
653
+ return False
654
+ lowered = body.lower()
655
+ return not any(w in lowered for w in ("example", "placeholder", "yourkey", "redacted"))
656
+
657
+
658
+ @dataclass(frozen=True, slots=True)
659
+ class KeyBlock:
660
+ """A private key block: BEGIN line, last line and the redact span of each body line."""
661
+
662
+ label: str
663
+ begin: int
664
+ column: int
665
+ end: int
666
+ spans: tuple[tuple[int, int, int], ...]
667
+ body: str
668
+
669
+ def hit(self, message: str) -> Hit:
670
+ return Hit(
671
+ self.begin,
672
+ end_line=self.end if self.end > self.begin else None,
673
+ column=self.column,
674
+ message=message,
675
+ evidence=f"{self.label} {fingerprint(self.body)}",
676
+ redact=self.spans,
677
+ )
678
+
679
+
680
+ def _single_line_key(number: int, line: str, match: re.Match[str], end_at: int) -> KeyBlock | None:
681
+ raw = line[match.end() : end_at]
682
+ body = raw
683
+ for escape in ("\\n", "\\r", "\\"):
684
+ body = body.replace(escape, "")
685
+ body = "".join(body.split())
686
+ if not body or not set(body) <= _BASE64_CHARS or not _plausible_key(body):
687
+ return None
688
+ return KeyBlock(
689
+ match.group("label"),
690
+ number,
691
+ match.start() + 1,
692
+ number,
693
+ ((number, match.end() + 1, end_at + 1),),
694
+ body,
695
+ )
696
+
697
+
698
+ def _multi_line_key(
699
+ lines: tuple[str, ...], number: int, match: re.Match[str], end_marker: str
700
+ ) -> KeyBlock | None:
701
+ spans: list[tuple[int, int, int]] = []
702
+ parts: list[str] = []
703
+ last = number
704
+ ended = False
705
+ for index in range(number, min(len(lines), number + _PEM_MAX_LINES)):
706
+ line = lines[index]
707
+ current = index + 1
708
+ if end_marker in line:
709
+ last, ended = current, True
710
+ break
711
+ if "-----BEGIN " in line:
712
+ break
713
+ lo, hi = _content_span(line)
714
+ if lo >= hi:
715
+ continue # a blank line, or a bare comment leader
716
+ if not parts and _PEM_HEADER.match(line, lo, hi):
717
+ continue # Proc-Type, DEK-Info, Version, Comment
718
+ core = _body_core(line)
719
+ if core is None:
720
+ return None
721
+ lo, hi = core
722
+ spans.append((current, lo + 1, hi + 1))
723
+ parts.append(line[lo:hi])
724
+ last = current
725
+ body = "".join(parts)
726
+ if not _plausible_key(body) or (not ended and len(body) < 4 * _PEM_MIN_BODY):
727
+ return None
728
+ return KeyBlock(match.group("label"), number, match.start() + 1, last, tuple(spans), body)
729
+
730
+
731
+ def private_key_blocks(lines: tuple[str, ...]) -> Iterator[KeyBlock]:
732
+ """Every PEM or PGP private key block with real key material in ``lines``.
733
+
734
+ A block's body is base64 lines (optionally wrapped in string syntax), or
735
+ the text between the markers on one line with ``\\n`` escapes (JSON
736
+ service-account files). Headers alone, ``...`` bodies and placeholders are
737
+ not keys.
738
+ """
739
+ for index, line in enumerate(lines):
740
+ if "PRIVATE KEY" not in line:
741
+ continue
742
+ number = index + 1
743
+ pos = line.find("-----BEGIN ")
744
+ while pos >= 0:
745
+ match = _PEM_BEGIN.match(line, pos)
746
+ if match is not None:
747
+ end_marker = f"-----END {match.group('label')}-----"
748
+ end_at = line.find(end_marker, match.end())
749
+ if end_at >= 0:
750
+ block = _single_line_key(number, line, match, end_at)
751
+ else:
752
+ block = _multi_line_key(lines, number, match, end_marker)
753
+ if block is not None:
754
+ yield block
755
+ pos = line.find("-----BEGIN ", pos + 1)
756
+
757
+
758
+ # --- URL credentials --------------------------------------------------------------
759
+
760
+ URL_CREDENTIALS = re.compile(
761
+ r"(?<![A-Za-z0-9+.-])(?P<scheme>[A-Za-z][A-Za-z0-9+.-]{1,20})://"
762
+ r"(?P<user>[^\s:/@?#\"'`<>]{0,128}):(?P<password>[^\s/@?#\"'`<>]{1,256})"
763
+ r"@(?P<host>\[[0-9A-Fa-f:.]{2,45}\]|[A-Za-z0-9._~-]{1,253})"
764
+ )
765
+
766
+ _LOCAL_HOSTS = frozenset(
767
+ {
768
+ "localhost",
769
+ "127.0.0.1",
770
+ "0.0.0.0", # noqa: S104 (a host name to recognise, not a bind)
771
+ "[::1]",
772
+ "host.docker.internal",
773
+ }
774
+ )
775
+ _EXAMPLE_SUFFIXES = (".local", ".localhost", ".test", ".example", ".invalid")
776
+ _EXAMPLE_DOMAINS = ("example.com", "example.org", "example.net")
777
+
778
+
779
+ def _local_or_example(host: str) -> bool:
780
+ host = host.lower().rstrip(".")
781
+ if host in _LOCAL_HOSTS or host.startswith("127."):
782
+ return True
783
+ if host.endswith(_EXAMPLE_SUFFIXES):
784
+ return True
785
+ return any(host == d or host.endswith("." + d) for d in _EXAMPLE_DOMAINS)
786
+
787
+
788
+ def real_url_password(match: re.Match[str], strict_hosts: bool = True) -> bool:
789
+ """Is the password of a ``scheme://user:password@host`` match a real literal?"""
790
+ user, password, host = match.group("user"), match.group("password"), match.group("host")
791
+ if is_placeholder(password) or password == user or user.lower() == "anonymous":
792
+ return False # anonymous FTP-style logins take an e-mail address, not a secret
793
+ if password.isdigit() and len(password) <= 5:
794
+ return False # host:port, not a password
795
+ if not strict_hosts:
796
+ return True
797
+ if _local_or_example(host):
798
+ return False
799
+ if "." not in host and not host.startswith("["):
800
+ # A single-label host is a compose or cluster service name: local
801
+ # development defaults are common there, real secrets are strong.
802
+ return looks_random(password)
803
+ return True
804
+
805
+
806
+ # --- Assignments ------------------------------------------------------------------
807
+
808
+ _ASSIGNMENT = re.compile(
809
+ r"(?<![A-Za-z0-9_])[\"']?(?P<name>[A-Za-z_][A-Za-z0-9_.-]{0,80})[\"']?\]?"
810
+ r"[ \t]{0,3}(?::[ \t]{0,3}[A-Za-z_&*\[(][A-Za-z0-9_\[\]., |&<>'*()]{0,40}?[ \t]{0,3}(?==))?"
811
+ r"(?::=|=>|=|:)[ \t]{0,5}"
812
+ r"(?:(?P<q>[\"'`])(?P<quoted>[^\"'`\r\n]{1,512})(?P=q)|(?P<bare>[^\s\"'`,;#]{1,512})(?=[\s,;#]|$))"
813
+ )
814
+ _NAME_NEEDLES = ("pass", "pwd", "secret", "token", "key", "credential")
815
+ _UNQUOTED_LANGUAGES = frozenset({"yaml", "text", "shell", "dockerfile"})
816
+
817
+
818
+ def _assignment_value(match: re.Match[str], language: str) -> tuple[str, int, int] | None:
819
+ if match.group("quoted") is not None:
820
+ return match.group("quoted"), match.start("quoted"), match.end("quoted")
821
+ if language not in _UNQUOTED_LANGUAGES:
822
+ return None # a bare word in code is a reference, not a literal
823
+ return match.group("bare"), match.start("bare"), match.end("bare")
824
+
825
+
826
+ # --- Credential and .env files ----------------------------------------------------
827
+
828
+ _TEMPLATE_SUFFIXES = (".example", ".sample", ".template", ".dist")
829
+
830
+
831
+ def _basename(path: str) -> str:
832
+ return path.rsplit("/", 1)[-1]
833
+
834
+
835
+ def is_template_path(path: str) -> bool:
836
+ return _basename(path).lower().endswith(_TEMPLATE_SUFFIXES)
837
+
838
+
839
+ def is_env_file(path: str) -> bool:
840
+ """``.env``, ``.env.*`` and ``*.env``, but not templates or encrypted vaults."""
841
+ name = _basename(path)
842
+ if is_template_path(path) or name in (".env.vault", ".envrc"):
843
+ return False
844
+ return name == ".env" or name.startswith(".env.") or (name.endswith(".env") and name != ".env")
845
+
846
+
847
+ _CREDENTIAL_NAMES = frozenset(
848
+ {
849
+ ".netrc",
850
+ "_netrc",
851
+ ".pypirc",
852
+ ".npmrc",
853
+ ".yarnrc",
854
+ ".yarnrc.yml",
855
+ ".git-credentials",
856
+ "credentials",
857
+ ".credentials",
858
+ "credentials.json",
859
+ "credentials.yml",
860
+ "credentials.yaml",
861
+ "credentials.toml",
862
+ "credentials.ini",
863
+ }
864
+ )
865
+ _KEY_NAMES = frozenset(
866
+ {"id_rsa", "id_dsa", "id_ecdsa", "id_ed25519", "id_ecdsa_sk", "id_ed25519_sk"}
867
+ )
868
+ _KEY_SUFFIXES = (".pem", ".key", ".ppk")
869
+
870
+
871
+ def credential_kind(path: str) -> str | None:
872
+ """Which credential file format ``path`` is (``None`` for any other file)."""
873
+ if is_template_path(path):
874
+ return None
875
+ name = _basename(path)
876
+ lowered = name.lower()
877
+ if lowered in _CREDENTIAL_NAMES:
878
+ return lowered.lstrip("_").lstrip(".") if lowered != "_netrc" else "netrc"
879
+ if lowered.startswith("client_secret") and lowered.endswith(".json"):
880
+ return "credentials.json"
881
+ if lowered in _KEY_NAMES or lowered.endswith(_KEY_SUFFIXES):
882
+ return "key"
883
+ return None
884
+
885
+
886
+ _ENV_LINE = re.compile(
887
+ r"[ \t]{0,20}(?:export[ \t]{1,5})?(?P<key>[A-Za-z_][A-Za-z0-9_.-]{0,100})"
888
+ r"[ \t]{0,5}[=:][ \t]{0,5}"
889
+ )
890
+ _INI_LINE = re.compile(
891
+ r"[ \t]{0,20}(?P<key>[A-Za-z_][A-Za-z0-9_. -]{0,100}?)[ \t]{0,5}[=:][ \t]{0,5}"
892
+ )
893
+ _NETRC_PASSWORD = re.compile(r"(?:^|[ \t])(?:password|passwd)[ \t]{1,20}(?P<value>[^\s]{1,512})")
894
+ _NPM_AUTH = re.compile(
895
+ r"(?:^|[ \t:])(?P<key>_authToken|_auth|_password|npmAuthToken|npmAuthIdent)"
896
+ r"[ \t]{0,5}[=:][ \t]{0,5}"
897
+ )
898
+ _JSON_PAIR = re.compile(
899
+ r"[\"'](?P<key>[A-Za-z_][A-Za-z0-9_.-]{0,80})[\"'][ \t]{0,5}:[ \t]{0,5}"
900
+ r"\"(?P<value>(?:[^\"\\\r\n]|\\.){1,8000})\""
901
+ )
902
+
903
+
904
+ def _value_span(line: str, start: int) -> tuple[int, int] | None:
905
+ """Span of the value starting at ``start``: quoted, or bare up to an inline comment."""
906
+ rest = line[start:]
907
+ if not rest.strip():
908
+ return None
909
+ if rest[0] in "\"'":
910
+ close = rest.find(rest[0], 1)
911
+ end = len(line.rstrip("\r")) if close < 0 else start + close
912
+ return (start + 1, end) if end > start + 1 else None
913
+ hi = len(line.rstrip("\r\n"))
914
+ for marker in (" #", "\t#", " ;"):
915
+ cut = line.find(marker, start)
916
+ if cut >= 0:
917
+ hi = min(hi, cut)
918
+ while hi > start and line[hi - 1] in " \t":
919
+ hi -= 1
920
+ return (start, hi) if hi > start else None
921
+
922
+
923
+ def _env_secret(key: str, value: str) -> bool:
924
+ """Does a ``.env`` entry hold a real secret (and not a setting or a placeholder)?"""
925
+ if is_placeholder(value) or is_public_name(key) or is_fake_token(value):
926
+ return False
927
+ url = URL_CREDENTIALS.search(value)
928
+ if url is not None:
929
+ return real_url_password(url, strict_hosts=False)
930
+ if "://" in value:
931
+ return False
932
+ if is_secret_name(key):
933
+ short_number = value.isdigit() and len(value) < 8
934
+ return len(value) >= 6 and not short_number and not is_known_hash(value)
935
+ if any(s in _NAME_EXCLUDED or s in _REVISION_WORDS for s in name_segments(key)):
936
+ return False # BUILD_ID, GIT_SHA, RELEASE_COMMITISH: not secrets however random
937
+ return looks_random(value, minimum=20)
938
+
939
+
940
+ # Names of Git revisions and releases, whose values (commit IDs) look random but are public.
941
+ # Only for keys that are not secret names: GIT_COMMIT_TOKEN is still a token.
942
+ _REVISION_WORDS = frozenset({"commit", "commitish", "committish", "rev", "revision", "tag"})
943
+
944
+
945
+ def _credential_secret(key: str, value: str) -> bool:
946
+ """Does a credential-file entry hold a literal secret?"""
947
+ if is_placeholder(value) or is_fake_token(value):
948
+ return False
949
+ lowered = key.lower().strip()
950
+ if lowered in (
951
+ "aws_secret_access_key",
952
+ "aws_session_token",
953
+ "_authtoken",
954
+ "_auth",
955
+ "_password",
956
+ ):
957
+ return True
958
+ if lowered in ("npmauthtoken", "npmauthident", "client_secret", "refresh_token", "private_key"):
959
+ return True
960
+ return is_secret_name(key)
961
+
962
+
963
+ # --- Rules ------------------------------------------------------------------------
964
+
965
+ _PROVIDER_HINT = (
966
+ "Revoke the credential at the provider now (it is in the Git history), then load it "
967
+ "from a secret store or an environment variable."
968
+ )
969
+
970
+
971
+ @rule(
972
+ id="secrets/private-key",
973
+ severity="error",
974
+ title="Private key",
975
+ rationale=(
976
+ "A committed private key is compromised for good: anyone with the history can "
977
+ "impersonate its owner, decrypt traffic or sign as them. A header alone or a "
978
+ "placeholder body is not reported."
979
+ ),
980
+ hint=(
981
+ "Remove the key, rotate it, and load keys from a secret store or a file outside "
982
+ "the repository."
983
+ ),
984
+ tags={"secrets", "cwe-798"},
985
+ )
986
+ def private_key(ctx: FileContext) -> Iterator[Hit]:
987
+ """A PEM (RSA, EC, DSA, OpenSSH, PKCS#8, encrypted) or PGP private key block.
988
+
989
+ The hit spans the block from its BEGIN line; every body line is redacted.
990
+ """
991
+ if not ctx.added_lines:
992
+ return
993
+ for block in private_key_blocks(ctx.lines):
994
+ yield block.hit(f"Private key ({block.label}) in the change")
995
+
996
+
997
+ def _provider_rule(rule_id: str, title: str, rationale: str, severity: str = "error") -> None:
998
+ def check(ctx: FileContext) -> Iterator[Hit]:
999
+ return _provider_hits(ctx, rule_id)
1000
+
1001
+ check.__name__ = rule_id.split("/", 1)[1].replace("-", "_")
1002
+ check.__doc__ = rationale
1003
+ rule(
1004
+ id=rule_id,
1005
+ severity=severity, # type: ignore[arg-type]
1006
+ title=title,
1007
+ rationale=rationale,
1008
+ hint=_PROVIDER_HINT,
1009
+ tags={"secrets", "cwe-798"},
1010
+ )(check)
1011
+
1012
+
1013
+ _provider_rule(
1014
+ "secrets/aws-access-key",
1015
+ "AWS access key ID",
1016
+ "An AKIA/ASIA access key ID names a live AWS credential and is usually committed next to "
1017
+ "its secret. The documentation IDs ending in EXAMPLE are canaries and only a note.",
1018
+ )
1019
+ _provider_rule(
1020
+ "secrets/aws-secret-key",
1021
+ "AWS secret access key",
1022
+ "A 40-character secret assigned to an AWS secret access key name grants the key's AWS "
1023
+ "permissions. The documentation secret ending in EXAMPLEKEY is a canary and only a note.",
1024
+ )
1025
+ _provider_rule(
1026
+ "secrets/github-token",
1027
+ "GitHub token",
1028
+ "A GitHub personal access, OAuth, app or refresh token gives repository and API access. "
1029
+ "Classic tokens (ghp_, gho_, ghu_, ghs_, ghr_) must carry a valid CRC32 checksum, so "
1030
+ "hand-typed fakes are not reported; fine-grained github_pat_ tokens are checked by shape. "
1031
+ "GitHub's documentation token is a canary and only a note.",
1032
+ )
1033
+ _provider_rule(
1034
+ "secrets/gitlab-token",
1035
+ "GitLab token",
1036
+ "A GitLab personal, deploy, runner, CI job, feed, OAuth or trigger token gives access to "
1037
+ "projects, registries or runners.",
1038
+ )
1039
+ _provider_rule(
1040
+ "secrets/slack-token",
1041
+ "Slack token",
1042
+ "A Slack bot, user, app-level or refresh token can read and post as the workspace app.",
1043
+ )
1044
+ _provider_rule(
1045
+ "secrets/slack-webhook",
1046
+ "Slack webhook URL",
1047
+ "Anyone with an incoming-webhook URL can post into its channel; the path is the secret.",
1048
+ )
1049
+ _provider_rule(
1050
+ "secrets/stripe-live-key",
1051
+ "Stripe live secret key",
1052
+ "A live secret or restricted Stripe key moves real money. Test keys (sk_test_) and "
1053
+ "publishable keys (pk_) are not reported; Stripe's documentation sample bodies are "
1054
+ "canaries and only a note.",
1055
+ )
1056
+ _provider_rule(
1057
+ "secrets/google-api-key",
1058
+ "Google API key",
1059
+ "A Google API key bills its project and may unlock restricted APIs. Keys in Firebase "
1060
+ "configuration or browser-exposed variables (VITE_, NEXT_PUBLIC_ and the like) are public "
1061
+ "by design and are not reported.",
1062
+ )
1063
+ _provider_rule(
1064
+ "secrets/openai-key",
1065
+ "OpenAI API key",
1066
+ "An OpenAI project, service-account, admin or legacy key bills the organisation and "
1067
+ "exposes its data.",
1068
+ )
1069
+ _provider_rule(
1070
+ "secrets/anthropic-key",
1071
+ "Anthropic API key",
1072
+ "An Anthropic API, admin or OAuth key bills the organisation and exposes its workspaces.",
1073
+ )
1074
+ _provider_rule(
1075
+ "secrets/npm-token",
1076
+ "npm access token",
1077
+ "An npm token can publish packages under the owner's name: a supply-chain compromise.",
1078
+ )
1079
+ _provider_rule(
1080
+ "secrets/pypi-token",
1081
+ "PyPI API token",
1082
+ "A PyPI (or TestPyPI) macaroon token can upload releases of the owner's projects.",
1083
+ )
1084
+ _provider_rule(
1085
+ "secrets/jwt",
1086
+ "JSON Web Token",
1087
+ "A signed JWT is a bearer credential until it expires, and expiry is often far away or "
1088
+ "absent. It may also be a harmless fixture, so this is a warning; the jwt.io sample is a "
1089
+ "canary and only a note.",
1090
+ severity="warning",
1091
+ )
1092
+
1093
+
1094
+ _NOTE_CLASSES = frozenset({"test", "docs"})
1095
+ """Classes where fixtures and samples are common: heuristic rules report less there."""
1096
+
1097
+
1098
+ @rule(
1099
+ id="secrets/url-credentials",
1100
+ severity="error",
1101
+ title="Credentials in a URL",
1102
+ rationale=(
1103
+ "A password or token in a URL's user-info part travels into logs, shell history and "
1104
+ "error reports. Placeholders, references (${VAR}, $VAR, {password}, %s), a password equal "
1105
+ "to the user name, anonymous logins, documentation defaults and loopback or example hosts "
1106
+ "are not reported; on a single-label service host (a compose or cluster name) only a "
1107
+ "strong password is. In test and documentation files, where URL fixtures and samples are "
1108
+ "common, a hit is a warning."
1109
+ ),
1110
+ hint="Pass the password separately (an environment variable, a secret store, a .netrc).",
1111
+ tags={"secrets", "cwe-798"},
1112
+ )
1113
+ def url_credentials(ctx: FileContext) -> Iterator[Hit]:
1114
+ """``scheme://user:password@host`` with a literal, non-placeholder password."""
1115
+ covered: dict[int, list[tuple[int, int]]] | None = None
1116
+ for number, _, match in _line_matches(ctx, URL_CREDENTIALS, ("@",)):
1117
+ if not real_url_password(match):
1118
+ continue
1119
+ value = match.group("password")
1120
+ start, end = match.span("password")
1121
+ if covered is None:
1122
+ covered = _provider_spans(ctx)
1123
+ if any(lo < end and start < hi for lo, hi in covered.get(number, ())):
1124
+ continue # a provider token in the URL: its own rule reports it
1125
+ yield Hit(
1126
+ number,
1127
+ column=match.start() + 1,
1128
+ message=f"Password in a {match.group('scheme')} URL",
1129
+ evidence=f"url-password {fingerprint(value)}",
1130
+ redact=((number, match.start("password") + 1, match.end("password") + 1),),
1131
+ severity="warning" if ctx.file_class in _NOTE_CLASSES else None,
1132
+ )
1133
+
1134
+
1135
+ @rule(
1136
+ id="secrets/generic-assignment",
1137
+ severity="warning",
1138
+ title="Secret-looking value assigned to a secret name",
1139
+ rationale=(
1140
+ "A literal with the length and entropy of generated key material, assigned to a name "
1141
+ "like password, secret, token or api_key, is most likely a real credential. Empty "
1142
+ "strings, placeholders, references, password hashes, words and identifiers are not "
1143
+ "reported, nor are values a provider rule, .env or credential-file rule already "
1144
+ "reports. In test and documentation files and in-file test regions, where fixtures are "
1145
+ "common, a hit is only a note."
1146
+ ),
1147
+ hint="Load the value from the environment or a secret store, and rotate it if it was real.",
1148
+ tags={"secrets", "cwe-798"},
1149
+ )
1150
+ def generic_assignment(ctx: FileContext) -> Iterator[Hit]:
1151
+ """``name = "value"`` (``name: value`` in YAML, INI and shell) with a random literal."""
1152
+ if is_env_file(ctx.path) or credential_kind(ctx.path) is not None:
1153
+ return
1154
+ covered: dict[int, list[tuple[int, int]]] | None = None
1155
+ for number, _, match in _line_matches(ctx, _ASSIGNMENT, _NAME_NEEDLES, folded=True):
1156
+ if not is_secret_name(match.group("name")):
1157
+ continue
1158
+ found = _assignment_value(match, ctx.language)
1159
+ if found is None:
1160
+ continue
1161
+ value, start, end = found
1162
+ if is_placeholder(value) or not looks_random(value):
1163
+ continue
1164
+ if covered is None:
1165
+ covered = _provider_spans(ctx)
1166
+ if any(lo < end and start < hi for lo, hi in covered.get(number, ())):
1167
+ continue
1168
+ fixture = ctx.file_class in _NOTE_CLASSES or ctx.in_test_region(number)
1169
+ yield Hit(
1170
+ number,
1171
+ column=start + 1,
1172
+ message="Secret-looking literal assigned to a secret name",
1173
+ evidence=f"assignment {fingerprint(value)}",
1174
+ redact=((number, start + 1, end + 1),),
1175
+ severity="note" if fixture else None,
1176
+ )
1177
+
1178
+
1179
+ @rule(
1180
+ id="secrets/env-file",
1181
+ severity="error",
1182
+ title=".env file with real secrets",
1183
+ scope="file",
1184
+ rationale=(
1185
+ "A committed .env file is meant to stay on one machine; a real secret in it is leaked "
1186
+ "to everyone with the history. Templates (*.example, *.sample, *.template, *.dist) are "
1187
+ "not checked, and settings, placeholders, references and browser-exposed variables "
1188
+ "(VITE_, NEXT_PUBLIC_ and the like) are fine: only a secret-named key with a literal "
1189
+ "value, a random-looking value or a URL with a password is reported."
1190
+ ),
1191
+ hint=(
1192
+ "Remove the file from Git (add it to .gitignore), rotate the values and commit a "
1193
+ ".env.example instead."
1194
+ ),
1195
+ tags={"secrets", "cwe-798"},
1196
+ )
1197
+ def env_file(ctx: FileContext) -> Iterator[Hit]:
1198
+ """Each changed ``KEY=value`` line of a ``.env`` file whose value is a real secret."""
1199
+ if not is_env_file(ctx.path) or not ctx.new_text or not ctx.added_lines:
1200
+ return
1201
+ lines = ctx.lines
1202
+ keys: set[int] | None = None
1203
+ for number in sorted(ctx.added_lines):
1204
+ if number > len(lines):
1205
+ continue
1206
+ line = lines[number - 1]
1207
+ if line.lstrip().startswith("#"):
1208
+ continue
1209
+ match = _ENV_LINE.match(line[:4000])
1210
+ if match is None:
1211
+ continue
1212
+ span = _value_span(line, match.end())
1213
+ if span is None:
1214
+ continue
1215
+ lo, hi = span
1216
+ key, value = match.group("key"), line[lo:hi]
1217
+ if "-----BEGIN " in value:
1218
+ if keys is None:
1219
+ keys = {block.begin for block in private_key_blocks(lines)}
1220
+ if number not in keys:
1221
+ continue # a key header with a placeholder body
1222
+ elif not _env_secret(key, value):
1223
+ continue
1224
+ yield Hit(
1225
+ number,
1226
+ column=lo + 1,
1227
+ message=f"Secret value for {key} in a .env file",
1228
+ evidence=f"env {fingerprint(value)}",
1229
+ redact=((number, lo + 1, hi + 1),),
1230
+ )
1231
+
1232
+
1233
+ def _credential_values(
1234
+ kind: str, lines: tuple[str, ...], number: int
1235
+ ) -> Iterator[tuple[int, int, str]]:
1236
+ """``(start, end, key)`` of the literal secret values on line ``number``."""
1237
+ line = lines[number - 1][:8000]
1238
+ if kind == "netrc":
1239
+ for match in _NETRC_PASSWORD.finditer(line):
1240
+ yield match.start("value"), match.end("value"), "password"
1241
+ return
1242
+ if kind == "git-credentials":
1243
+ for match in URL_CREDENTIALS.finditer(line):
1244
+ if real_url_password(match, strict_hosts=False):
1245
+ yield match.start("password"), match.end("password"), "password"
1246
+ return
1247
+ if kind in ("npmrc", "yarnrc", "yarnrc.yml"):
1248
+ for match in _NPM_AUTH.finditer(line):
1249
+ span = _value_span(line, match.end())
1250
+ if span is not None:
1251
+ yield span[0], span[1], match.group("key")
1252
+ return
1253
+ if kind == "credentials.json":
1254
+ for match in _JSON_PAIR.finditer(line):
1255
+ yield match.start("value"), match.end("value"), match.group("key")
1256
+ return
1257
+ if line.lstrip().startswith(("#", ";", "[")):
1258
+ return
1259
+ match = _INI_LINE.match(line)
1260
+ if match is not None:
1261
+ span = _value_span(line, match.end())
1262
+ if span is not None:
1263
+ yield span[0], span[1], match.group("key")
1264
+
1265
+
1266
+ _PUTTY_PRIVATE = re.compile(r"Private-Lines:[ \t]{0,5}(?P<count>[0-9]{1,3})[ \t]{0,5}$")
1267
+
1268
+
1269
+ def _putty_blocks(lines: tuple[str, ...]) -> Iterator[KeyBlock]:
1270
+ for index, line in enumerate(lines):
1271
+ match = _PUTTY_PRIVATE.match(line.rstrip("\r"))
1272
+ if match is None:
1273
+ continue
1274
+ count = int(match.group("count"))
1275
+ body_lines = lines[index + 1 : index + 1 + count]
1276
+ spans = tuple(
1277
+ (index + 2 + k, 1, len(text.rstrip("\r")) + 1)
1278
+ for k, text in enumerate(body_lines)
1279
+ if text.rstrip("\r")
1280
+ )
1281
+ body = "".join(t.strip() for t in body_lines)
1282
+ if spans and _plausible_key(body) and set(body) <= _BASE64_CHARS:
1283
+ yield KeyBlock(
1284
+ "PuTTY private key", index + 1, 1, index + 1 + len(body_lines), spans, body
1285
+ )
1286
+
1287
+
1288
+ @rule(
1289
+ id="secrets/credentials-file",
1290
+ severity="error",
1291
+ title="Credential file with real secrets",
1292
+ scope="file",
1293
+ rationale=(
1294
+ "Files like .netrc, .pypirc, .npmrc, .git-credentials, AWS credentials, Google "
1295
+ "credentials.json and private key files exist to hold secrets; committed with literal "
1296
+ "values they leak them. Templates (*.example, *.sample, *.template, *.dist) and files "
1297
+ "with only placeholders or references (${NPM_TOKEN}) are fine; a .pem holding only "
1298
+ "certificates is not a key file."
1299
+ ),
1300
+ hint=(
1301
+ "Remove the file from Git, rotate what it held, and keep it in the home directory "
1302
+ "or a secret store."
1303
+ ),
1304
+ tags={"secrets", "cwe-798"},
1305
+ )
1306
+ def credentials_file(ctx: FileContext) -> Iterator[Hit]:
1307
+ """Each changed line of a credential file that holds a literal secret value."""
1308
+ kind = credential_kind(ctx.path)
1309
+ if kind is None or not ctx.new_text or not ctx.added_lines:
1310
+ return
1311
+ lines = ctx.lines
1312
+ name = _basename(ctx.path)
1313
+ if kind == "key":
1314
+ for block in (*private_key_blocks(lines), *_putty_blocks(lines)):
1315
+ yield block.hit(f"Private key in {name}")
1316
+ return
1317
+ for number in sorted(ctx.added_lines):
1318
+ if number > len(lines):
1319
+ continue
1320
+ for lo, hi, key in _credential_values(kind, lines, number):
1321
+ value = lines[number - 1][lo:hi]
1322
+ if kind in ("netrc", "git-credentials"):
1323
+ if is_placeholder(value):
1324
+ continue
1325
+ elif not _credential_secret(key, value):
1326
+ continue
1327
+ if "-----BEGIN " in value and not any(True for _ in private_key_blocks((value,))):
1328
+ continue # a private_key field with a placeholder body
1329
+ yield Hit(
1330
+ number,
1331
+ column=lo + 1,
1332
+ message=f"Secret value for {key.strip()} in {name}",
1333
+ evidence=f"credential {fingerprint(value)}",
1334
+ redact=((number, lo + 1, hi + 1),),
1335
+ )