pubcheck 0.0.2__tar.gz → 0.0.3__tar.gz
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.
- {pubcheck-0.0.2 → pubcheck-0.0.3}/PKG-INFO +5 -2
- {pubcheck-0.0.2 → pubcheck-0.0.3}/README.md +4 -1
- {pubcheck-0.0.2 → pubcheck-0.0.3}/pubcheck/base.py +22 -3
- {pubcheck-0.0.2 → pubcheck-0.0.3}/pubcheck/detectors.py +149 -4
- {pubcheck-0.0.2 → pubcheck-0.0.3}/pubcheck/hold.py +11 -0
- {pubcheck-0.0.2 → pubcheck-0.0.3}/pyproject.toml +1 -1
- {pubcheck-0.0.2 → pubcheck-0.0.3}/tests/test_pubcheck.py +132 -0
- {pubcheck-0.0.2 → pubcheck-0.0.3}/.github/workflows/ci.yml +0 -0
- {pubcheck-0.0.2 → pubcheck-0.0.3}/.gitignore +0 -0
- {pubcheck-0.0.2 → pubcheck-0.0.3}/LICENSE +0 -0
- {pubcheck-0.0.2 → pubcheck-0.0.3}/pubcheck/__init__.py +0 -0
- {pubcheck-0.0.2 → pubcheck-0.0.3}/pubcheck/__main__.py +0 -0
- {pubcheck-0.0.2 → pubcheck-0.0.3}/pubcheck/core.py +0 -0
- {pubcheck-0.0.2 → pubcheck-0.0.3}/pubcheck/correspond.py +0 -0
- {pubcheck-0.0.2 → pubcheck-0.0.3}/pubcheck/sources.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: pubcheck
|
|
3
|
-
Version: 0.0.
|
|
3
|
+
Version: 0.0.3
|
|
4
4
|
Summary: One publication check for every writer: is this text fit for a public repository? Personal names, the owner's own matters, private references, credentials and @mentions, failing closed when nobody is watching.
|
|
5
5
|
Project-URL: Homepage, https://github.com/thorwhalen/pubcheck
|
|
6
6
|
Project-URL: Repository, https://github.com/thorwhalen/pubcheck
|
|
@@ -51,7 +51,7 @@ A private target passes untouched. A public one, or one whose visibility is unkn
|
|
|
51
51
|
- `owner-relation`: the owner's own preferences, corrections or relations ("the operator stated", "my agents");
|
|
52
52
|
- `private-ref`: repos known to be private, private companions, this machine's home folder, and your own `private_patterns`;
|
|
53
53
|
- `session-link`: Claude session links;
|
|
54
|
-
- `credential`: credential-shaped strings (the patterns of `openloops.egress`)
|
|
54
|
+
- `credential`: credential-shaped strings (the patterns of `openloops.egress`), plus what an external secret scanner finds when you set `credential_scanner`;
|
|
55
55
|
- `mention`: `@login` and `@org/team` outside code, for an **unattended** writer only, since a mention notifies a person.
|
|
56
56
|
|
|
57
57
|
## Attended and unattended writers
|
|
@@ -80,6 +80,9 @@ With `hold_repo` set, a held post is filed as an issue in that private repo with
|
|
|
80
80
|
| `private_owner` | `PUBCHECK_PRIVATE_OWNER` | unset: the account whose `<owner>/_<name>` repos are private companions |
|
|
81
81
|
| `private_issues` | `PUBCHECK_PRIVATE_ISSUES` | unset: where context with no companion goes |
|
|
82
82
|
| `private_patterns` | (config only) | none: regexes for private references, such as working folders |
|
|
83
|
+
| `credential_scanner` | `PUBCHECK_CREDENTIAL_SCANNER` | unset: a gitleaks-compatible scanner to run beside the built-in patterns, e.g. `betterleaks` |
|
|
84
|
+
|
|
85
|
+
`credential_scanner` adds the long tail of vendor key formats (betterleaks ships several hundred rules) to the built-in patterns, which stay. The text is piped to `<scanner> stdin` with the report redacted, and live validation is never requested, since checking whether a key works means sending it to its vendor. It runs once per check over the whole post, from a neutral folder, and only from an absolute path outside the current folder. A scanner that is missing or fails is logged as a gap: an attended check carries on with the built-in patterns (and says so once on stderr), an unattended one is `unavailable` and holds the text. A held post whose credential only the scanner found is filed without its text, since the redaction patterns cannot find that credential. `credential_scanner_args` (config only) replaces the argument list for a scanner whose flags differ.
|
|
83
86
|
|
|
84
87
|
## Caches and log
|
|
85
88
|
|
|
@@ -21,7 +21,7 @@ A private target passes untouched. A public one, or one whose visibility is unkn
|
|
|
21
21
|
- `owner-relation`: the owner's own preferences, corrections or relations ("the operator stated", "my agents");
|
|
22
22
|
- `private-ref`: repos known to be private, private companions, this machine's home folder, and your own `private_patterns`;
|
|
23
23
|
- `session-link`: Claude session links;
|
|
24
|
-
- `credential`: credential-shaped strings (the patterns of `openloops.egress`)
|
|
24
|
+
- `credential`: credential-shaped strings (the patterns of `openloops.egress`), plus what an external secret scanner finds when you set `credential_scanner`;
|
|
25
25
|
- `mention`: `@login` and `@org/team` outside code, for an **unattended** writer only, since a mention notifies a person.
|
|
26
26
|
|
|
27
27
|
## Attended and unattended writers
|
|
@@ -50,6 +50,9 @@ With `hold_repo` set, a held post is filed as an issue in that private repo with
|
|
|
50
50
|
| `private_owner` | `PUBCHECK_PRIVATE_OWNER` | unset: the account whose `<owner>/_<name>` repos are private companions |
|
|
51
51
|
| `private_issues` | `PUBCHECK_PRIVATE_ISSUES` | unset: where context with no companion goes |
|
|
52
52
|
| `private_patterns` | (config only) | none: regexes for private references, such as working folders |
|
|
53
|
+
| `credential_scanner` | `PUBCHECK_CREDENTIAL_SCANNER` | unset: a gitleaks-compatible scanner to run beside the built-in patterns, e.g. `betterleaks` |
|
|
54
|
+
|
|
55
|
+
`credential_scanner` adds the long tail of vendor key formats (betterleaks ships several hundred rules) to the built-in patterns, which stay. The text is piped to `<scanner> stdin` with the report redacted, and live validation is never requested, since checking whether a key works means sending it to its vendor. It runs once per check over the whole post, from a neutral folder, and only from an absolute path outside the current folder. A scanner that is missing or fails is logged as a gap: an attended check carries on with the built-in patterns (and says so once on stderr), an unattended one is `unavailable` and holds the text. A held post whose credential only the scanner found is filed without its text, since the redaction patterns cannot find that credential. `credential_scanner_args` (config only) replaces the argument list for a scanner whose flags differ.
|
|
53
56
|
|
|
54
57
|
## Caches and log
|
|
55
58
|
|
|
@@ -52,7 +52,10 @@ CONFIG_FILE = "~/.config/pubcheck/config.toml"
|
|
|
52
52
|
#: (a reference to one is private, and a flag points at the target's companion);
|
|
53
53
|
#: - ``private_issues``: the private repo for context that has no companion;
|
|
54
54
|
#: - ``private_patterns``: more regexes for private references (working folders, the
|
|
55
|
-
#: layout of the operator's machines), on top of this machine's home folder
|
|
55
|
+
#: layout of the operator's machines), on top of this machine's home folder;
|
|
56
|
+
#: - ``credential_scanner``: an external secret scanner to run beside the built-in
|
|
57
|
+
#: credential patterns, e.g. ``betterleaks`` (unset: none is run). See
|
|
58
|
+
#: :func:`pubcheck.detectors.scanner_credential`.
|
|
56
59
|
DFLT_SETTINGS = {
|
|
57
60
|
"hold_repo": None,
|
|
58
61
|
"hold_label": "escalate",
|
|
@@ -60,6 +63,7 @@ DFLT_SETTINGS = {
|
|
|
60
63
|
"private_owner": None,
|
|
61
64
|
"private_issues": None,
|
|
62
65
|
"private_patterns": (),
|
|
66
|
+
"credential_scanner": None,
|
|
63
67
|
}
|
|
64
68
|
#: The environment variable that overrides each setting (``private_patterns``: config only).
|
|
65
69
|
SETTINGS_ENV = {
|
|
@@ -68,6 +72,7 @@ SETTINGS_ENV = {
|
|
|
68
72
|
"budget_seconds": "PUBCHECK_BUDGET_SECONDS",
|
|
69
73
|
"private_owner": "PUBCHECK_PRIVATE_OWNER",
|
|
70
74
|
"private_issues": "PUBCHECK_PRIVATE_ISSUES",
|
|
75
|
+
"credential_scanner": "PUBCHECK_CREDENTIAL_SCANNER",
|
|
71
76
|
}
|
|
72
77
|
|
|
73
78
|
|
|
@@ -83,14 +88,28 @@ class Budget:
|
|
|
83
88
|
return cap
|
|
84
89
|
return min(cap, self.deadline - time.monotonic())
|
|
85
90
|
|
|
86
|
-
def run(
|
|
91
|
+
def run(
|
|
92
|
+
self,
|
|
93
|
+
argv,
|
|
94
|
+
*,
|
|
95
|
+
cap: float = LOOKUP_TIMEOUT,
|
|
96
|
+
stdin: str | None = None,
|
|
97
|
+
env: Mapping | None = None,
|
|
98
|
+
cwd: str | None = None,
|
|
99
|
+
):
|
|
87
100
|
"""``subprocess.run`` within the budget; ``None`` when out of time or on failure."""
|
|
88
101
|
left = self.left(cap)
|
|
89
102
|
if left <= 0.05:
|
|
90
103
|
return None
|
|
91
104
|
try:
|
|
92
105
|
return subprocess.run(
|
|
93
|
-
argv,
|
|
106
|
+
argv,
|
|
107
|
+
capture_output=True,
|
|
108
|
+
text=True,
|
|
109
|
+
timeout=left,
|
|
110
|
+
input=stdin,
|
|
111
|
+
env=env,
|
|
112
|
+
cwd=cwd,
|
|
94
113
|
)
|
|
95
114
|
except (OSError, subprocess.SubprocessError):
|
|
96
115
|
return None
|
|
@@ -17,7 +17,9 @@ and the log never holds it). A credential's term is its pattern name, never the
|
|
|
17
17
|
``private_patterns`` (``ctx["private_patterns"]``, from the settings);
|
|
18
18
|
- ``session-link``: ``claude.ai/code/session_…`` (not on commits, whose session links a
|
|
19
19
|
commit hook strips);
|
|
20
|
-
- ``credential``: a credential-shaped string (:func:`openloops.egress.find_credentials`)
|
|
20
|
+
- ``credential``: a credential-shaped string (:func:`openloops.egress.find_credentials`),
|
|
21
|
+
and, when the operator sets ``credential_scanner``, what that external scanner finds
|
|
22
|
+
(:func:`scanner_credential`);
|
|
21
23
|
- ``mention``: an ``@login`` or ``@org/team`` outside code, which notifies a person:
|
|
22
24
|
sending it is messaging them. Only in :data:`UNATTENDED_DETECTORS`, since an attended
|
|
23
25
|
author chose to notify.
|
|
@@ -33,12 +35,19 @@ and the log never holds it). A credential's term is its pattern name, never the
|
|
|
33
35
|
from __future__ import annotations
|
|
34
36
|
|
|
35
37
|
import getpass
|
|
38
|
+
import json
|
|
36
39
|
import os
|
|
37
40
|
import re
|
|
41
|
+
import shlex
|
|
42
|
+
import shutil
|
|
43
|
+
import sys
|
|
44
|
+
import tempfile
|
|
38
45
|
from collections.abc import Callable, Iterable, Mapping
|
|
39
46
|
from functools import lru_cache
|
|
40
47
|
from pathlib import Path
|
|
41
48
|
|
|
49
|
+
from pubcheck.base import Budget, log_event
|
|
50
|
+
|
|
42
51
|
Finding = tuple[str, str]
|
|
43
52
|
Detector = Callable[[str, Mapping], list]
|
|
44
53
|
|
|
@@ -182,6 +191,139 @@ def credential(text, ctx):
|
|
|
182
191
|
return [("credential", name) for name, _ in find_credentials(text)]
|
|
183
192
|
|
|
184
193
|
|
|
194
|
+
#: The arguments of a gitleaks-compatible scanner's ``stdin`` command (betterleaks 1.x and
|
|
195
|
+
#: gitleaks 8 share them): a JSON report on stdout, the secret redacted, exit 0 on a find.
|
|
196
|
+
#: Never a validation flag: checking whether a credential is live sends it to its vendor.
|
|
197
|
+
SCANNER_ARGS = (
|
|
198
|
+
"stdin",
|
|
199
|
+
"--report-format",
|
|
200
|
+
"json",
|
|
201
|
+
"--report-path",
|
|
202
|
+
"-",
|
|
203
|
+
"--no-banner",
|
|
204
|
+
"--redact",
|
|
205
|
+
"--exit-code",
|
|
206
|
+
"0",
|
|
207
|
+
)
|
|
208
|
+
#: Environment variables that would switch a scanner's live validation on; never passed.
|
|
209
|
+
SCANNER_ENV_DROPPED = ("BETTERLEAKS_VALIDATE", "BETTERLEAKS_ANALYZE")
|
|
210
|
+
#: Seconds the scanner may take, within what is left of the check's budget.
|
|
211
|
+
SCANNER_TIMEOUT = 5.0
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
class ScannerUnavailable(RuntimeError):
|
|
215
|
+
"""A configured scanner did not run; an unattended check must not pass without it."""
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def scanner_credential(text, ctx):
|
|
219
|
+
"""What an external secret scanner finds, named ``<scanner>:<rule id>``.
|
|
220
|
+
|
|
221
|
+
Off unless the operator sets ``credential_scanner`` (``betterleaks`` is the one
|
|
222
|
+
weighed in thorwhalen/pubcheck#3; any gitleaks-compatible ``stdin`` command works,
|
|
223
|
+
with ``credential_scanner_args`` for another argument list). It adds the long tail of
|
|
224
|
+
vendor formats to the built-in :func:`credential`, which stays.
|
|
225
|
+
|
|
226
|
+
It runs once per check, over every text of the post together (``whole_batch``). The
|
|
227
|
+
text goes on stdin, never in argv; the report is redacted; validation is never asked
|
|
228
|
+
for; the scanner runs from a neutral folder, so a repo's own scanner config is not
|
|
229
|
+
read, and only from an absolute path outside the current folder.
|
|
230
|
+
|
|
231
|
+
A scanner that is missing, fails or runs out of time is a gap, logged every time. An
|
|
232
|
+
attended check carries on with the built-in patterns (and says so once on stderr);
|
|
233
|
+
an **unattended** one raises :class:`ScannerUnavailable`, so the check is
|
|
234
|
+
``unavailable`` and the text is held, as any other lookup that cannot be made.
|
|
235
|
+
|
|
236
|
+
>>> scanner_credential("AKIA...", {}) # no scanner configured
|
|
237
|
+
[]
|
|
238
|
+
"""
|
|
239
|
+
conf = ctx.get("settings") or {}
|
|
240
|
+
scanner = conf.get("credential_scanner")
|
|
241
|
+
if not scanner:
|
|
242
|
+
return []
|
|
243
|
+
try:
|
|
244
|
+
report = _run_scanner(scanner, conf, text, ctx)
|
|
245
|
+
except ScannerUnavailable as gap:
|
|
246
|
+
log_event(writer="pubcheck", event="credential_scanner_gap", reason=str(gap))
|
|
247
|
+
if ctx.get("unattended"):
|
|
248
|
+
raise
|
|
249
|
+
_say_once(str(gap))
|
|
250
|
+
return []
|
|
251
|
+
name = Path(scanner).name
|
|
252
|
+
return [
|
|
253
|
+
("credential", f"{name}:{f.get('RuleID') or 'unknown'}")
|
|
254
|
+
for f in report
|
|
255
|
+
if isinstance(f, Mapping)
|
|
256
|
+
]
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
scanner_credential.whole_batch = True
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def _run_scanner(scanner, conf, text, ctx) -> list:
|
|
263
|
+
"""The scanner's findings for ``text``; raises :class:`ScannerUnavailable` on any gap."""
|
|
264
|
+
if not isinstance(scanner, str):
|
|
265
|
+
raise ScannerUnavailable("credential_scanner must be a command name or path")
|
|
266
|
+
args = conf.get("credential_scanner_args") or SCANNER_ARGS
|
|
267
|
+
if isinstance(args, str):
|
|
268
|
+
args = shlex.split(args)
|
|
269
|
+
if not all(isinstance(a, str) for a in args):
|
|
270
|
+
raise ScannerUnavailable("credential_scanner_args must be a list of strings")
|
|
271
|
+
exe = shutil.which(scanner)
|
|
272
|
+
if exe is None:
|
|
273
|
+
raise ScannerUnavailable(f"credential_scanner {scanner!r} not found")
|
|
274
|
+
exe = os.path.realpath(exe)
|
|
275
|
+
here = os.path.realpath(os.getcwd())
|
|
276
|
+
if exe.startswith(here + os.sep):
|
|
277
|
+
raise ScannerUnavailable(
|
|
278
|
+
f"credential_scanner {scanner!r} resolves inside the current folder; refused"
|
|
279
|
+
)
|
|
280
|
+
env = {k: v for k, v in os.environ.items() if k not in SCANNER_ENV_DROPPED}
|
|
281
|
+
budget = ctx.get("budget") or Budget(None)
|
|
282
|
+
done = budget.run(
|
|
283
|
+
[exe, *args], cap=SCANNER_TIMEOUT, stdin=text, env=env, cwd=tempfile.gettempdir()
|
|
284
|
+
)
|
|
285
|
+
if done is None:
|
|
286
|
+
raise ScannerUnavailable(
|
|
287
|
+
f"credential_scanner {scanner!r} failed or ran out of time"
|
|
288
|
+
)
|
|
289
|
+
if done.returncode != 0:
|
|
290
|
+
raise ScannerUnavailable(
|
|
291
|
+
f"credential_scanner {scanner!r} exited {done.returncode}"
|
|
292
|
+
)
|
|
293
|
+
try:
|
|
294
|
+
report = json.loads(done.stdout)
|
|
295
|
+
except ValueError:
|
|
296
|
+
raise ScannerUnavailable(
|
|
297
|
+
f"credential_scanner {scanner!r} printed no JSON report"
|
|
298
|
+
) from None
|
|
299
|
+
if report is None: # Go encodes an empty slice as null
|
|
300
|
+
return []
|
|
301
|
+
if not isinstance(report, list):
|
|
302
|
+
raise ScannerUnavailable(f"credential_scanner {scanner!r} printed no list")
|
|
303
|
+
return report
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def is_scanner_finding(finding) -> bool:
|
|
307
|
+
"""True for a credential an external scanner found (its term is ``<scanner>:<rule>``).
|
|
308
|
+
|
|
309
|
+
The built-in patterns name their findings without a colon, and only they are known
|
|
310
|
+
to :func:`pubcheck.hold.redact`.
|
|
311
|
+
|
|
312
|
+
>>> is_scanner_finding(("credential", "betterleaks:slack-webhook-url"))
|
|
313
|
+
True
|
|
314
|
+
>>> is_scanner_finding(("credential", "github_token"))
|
|
315
|
+
False
|
|
316
|
+
"""
|
|
317
|
+
category, term = finding
|
|
318
|
+
return category == "credential" and ":" in term
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
@lru_cache(maxsize=None)
|
|
322
|
+
def _say_once(why: str) -> None:
|
|
323
|
+
"""Say once per process, on stderr, that an attended check ran without the scanner."""
|
|
324
|
+
print(f"pubcheck: {why}; built-in credential patterns only", file=sys.stderr)
|
|
325
|
+
|
|
326
|
+
|
|
185
327
|
def mention(text, ctx):
|
|
186
328
|
"""``@login`` and ``@org/team`` outside code spans and blocks: each notifies someone."""
|
|
187
329
|
bare = _CODE.sub(" ", text)
|
|
@@ -195,6 +337,7 @@ DETECTORS: tuple[Detector, ...] = (
|
|
|
195
337
|
private_ref,
|
|
196
338
|
session_link,
|
|
197
339
|
credential,
|
|
340
|
+
scanner_credential,
|
|
198
341
|
)
|
|
199
342
|
#: An unattended writer also holds every @mention: nobody chose to notify that person.
|
|
200
343
|
UNATTENDED_DETECTORS: tuple[Detector, ...] = DETECTORS + (mention,)
|
|
@@ -203,9 +346,11 @@ UNATTENDED_DETECTORS: tuple[Detector, ...] = DETECTORS + (mention,)
|
|
|
203
346
|
def findings(texts: Iterable[str], ctx: Mapping, *, detectors=DETECTORS) -> list[Finding]:
|
|
204
347
|
"""``[(category, term)]``, each once, found by ``detectors`` in any of ``texts``."""
|
|
205
348
|
seen: list[Finding] = []
|
|
206
|
-
for text in texts
|
|
207
|
-
|
|
208
|
-
|
|
349
|
+
texts = [re.sub(r"\s+", " ", text or "") for text in texts]
|
|
350
|
+
for detect in detectors:
|
|
351
|
+
# a detector that starts a process sees the whole post once, not text by text
|
|
352
|
+
batches = ["\n".join(texts)] if getattr(detect, "whole_batch", False) else texts
|
|
353
|
+
for text in batches:
|
|
209
354
|
for hit in detect(text, ctx):
|
|
210
355
|
if hit not in seen:
|
|
211
356
|
seen.append(hit)
|
|
@@ -23,6 +23,7 @@ import shutil
|
|
|
23
23
|
from collections.abc import Mapping, Sequence
|
|
24
24
|
|
|
25
25
|
from pubcheck.base import Budget, settings, text_hash
|
|
26
|
+
from pubcheck.detectors import is_scanner_finding
|
|
26
27
|
from pubcheck.core import HINTS, Verdict
|
|
27
28
|
from pubcheck.sources import gh_repo_view
|
|
28
29
|
|
|
@@ -35,6 +36,12 @@ PEM_BLOCK = re.compile(
|
|
|
35
36
|
)
|
|
36
37
|
|
|
37
38
|
|
|
39
|
+
#: What a desk item shows instead of a text whose credential only the scanner found.
|
|
40
|
+
WITHHELD = (
|
|
41
|
+
"[withheld: a secret scanner found a credential here; read the post at its source]"
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
|
|
38
45
|
def redact(text: str) -> str:
|
|
39
46
|
r"""``text`` with every credential-shaped string replaced by its pattern's name.
|
|
40
47
|
|
|
@@ -78,6 +85,10 @@ def hold_body(
|
|
|
78
85
|
if verdict.decision == "flag"
|
|
79
86
|
else [f"- the check was unavailable: {verdict.reason}"]
|
|
80
87
|
)
|
|
88
|
+
if any(is_scanner_finding(f) for f in verdict.findings):
|
|
89
|
+
# a credential only the external scanner knows: redact() cannot find it, so the
|
|
90
|
+
# text is not copied at all
|
|
91
|
+
text, title, more = WITHHELD, (WITHHELD if title else title), ()
|
|
81
92
|
text, title = redact(text), redact(title) if title else title
|
|
82
93
|
also = (
|
|
83
94
|
[f"**Also published with it:** {', '.join(redact(m) for m in more)}", ""]
|
|
@@ -6,7 +6,7 @@ build-backend = "hatchling.build"
|
|
|
6
6
|
|
|
7
7
|
[project]
|
|
8
8
|
name = "pubcheck"
|
|
9
|
-
version = "0.0.
|
|
9
|
+
version = "0.0.3"
|
|
10
10
|
description = "One publication check for every writer: is this text fit for a public repository? Personal names, the owner's own matters, private references, credentials and @mentions, failing closed when nobody is watching."
|
|
11
11
|
readme = "README.md"
|
|
12
12
|
requires-python = ">=3.11"
|
|
@@ -435,3 +435,135 @@ def test_before_send_through_correspond_check(env):
|
|
|
435
435
|
lines, stopped = outbound.check(ref, Draft(text="Ada Quill asked"), dry_run=True,
|
|
436
436
|
before_send=make_before_send())
|
|
437
437
|
assert stopped is not None and stopped.error_kind == "needs_approval"
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
# -- the opt-in external scanner beside the built-in credential patterns (#3) --
|
|
441
|
+
|
|
442
|
+
|
|
443
|
+
@pytest.fixture
|
|
444
|
+
def scan_env(tmp_path, monkeypatch):
|
|
445
|
+
"""A fake scanner on PATH (outside the cwd), and a private state dir for the log."""
|
|
446
|
+
bin_dir, state = tmp_path / "scanbin", tmp_path / "state"
|
|
447
|
+
bin_dir.mkdir()
|
|
448
|
+
monkeypatch.setenv(STATE_DIR_ENV, str(state))
|
|
449
|
+
monkeypatch.setenv("PATH", f"{bin_dir}{os.pathsep}{os.environ['PATH']}")
|
|
450
|
+
(tmp_path / "cwd").mkdir()
|
|
451
|
+
monkeypatch.chdir(tmp_path / "cwd") # the cwd does not hold the scanner
|
|
452
|
+
d._say_once.cache_clear()
|
|
453
|
+
|
|
454
|
+
def make(stdout, *, exit_code=0, sleep=0):
|
|
455
|
+
log = tmp_path / "fakescan.log"
|
|
456
|
+
script = bin_dir / "fakescan"
|
|
457
|
+
script.write_text(
|
|
458
|
+
"#!/usr/bin/env python3\n"
|
|
459
|
+
"import json, os, sys, time\n"
|
|
460
|
+
f"time.sleep({sleep})\n"
|
|
461
|
+
f"open({str(log)!r}, 'a').write(json.dumps({{'argv': sys.argv[1:], "
|
|
462
|
+
"'stdin': sys.stdin.read(), 'cwd': os.getcwd(), "
|
|
463
|
+
"'validate': os.environ.get('BETTERLEAKS_VALIDATE')}) + '\\n')\n"
|
|
464
|
+
f"sys.stdout.write({stdout!r})\n"
|
|
465
|
+
f"sys.exit({exit_code})\n"
|
|
466
|
+
)
|
|
467
|
+
script.chmod(0o755)
|
|
468
|
+
return log
|
|
469
|
+
|
|
470
|
+
make.state = state
|
|
471
|
+
return make
|
|
472
|
+
|
|
473
|
+
|
|
474
|
+
def _ctx(**kw):
|
|
475
|
+
return {"settings": {"credential_scanner": "fakescan"}, **kw}
|
|
476
|
+
|
|
477
|
+
|
|
478
|
+
def test_scanner_is_off_unless_configured():
|
|
479
|
+
assert d.scanner_credential("anything", {"settings": {}}) == []
|
|
480
|
+
assert d.scanner_credential in d.DETECTORS
|
|
481
|
+
|
|
482
|
+
|
|
483
|
+
def test_scanner_findings_are_named_by_rule_and_never_carry_the_secret(
|
|
484
|
+
scan_env, monkeypatch
|
|
485
|
+
):
|
|
486
|
+
log = scan_env(json.dumps([{"RuleID": "slack-webhook-url", "Secret": "REDACTED"}]))
|
|
487
|
+
monkeypatch.setenv("BETTERLEAKS_VALIDATE", "true")
|
|
488
|
+
assert d.scanner_credential("the text", _ctx()) == [
|
|
489
|
+
("credential", "fakescan:slack-webhook-url")
|
|
490
|
+
]
|
|
491
|
+
seen = json.loads(log.read_text())
|
|
492
|
+
assert seen["stdin"] == "the text" # on stdin, never in argv
|
|
493
|
+
assert "the text" not in seen["argv"]
|
|
494
|
+
assert "--redact" in seen["argv"] and "--report-path" in seen["argv"]
|
|
495
|
+
assert not any("valid" in a for a in seen["argv"])
|
|
496
|
+
assert seen["validate"] is None # an inherited switch to live validation is dropped
|
|
497
|
+
assert seen["cwd"] != os.getcwd() # a repo's own scanner config is not picked up
|
|
498
|
+
|
|
499
|
+
|
|
500
|
+
def test_the_scanner_runs_once_per_check_over_every_text(scan_env):
|
|
501
|
+
log = scan_env("[]")
|
|
502
|
+
d.findings(["title", "body", "label-a", "label-b"], _ctx())
|
|
503
|
+
runs = log.read_text().splitlines()
|
|
504
|
+
assert len(runs) == 1 and json.loads(runs[0])["stdin"] == "title\nbody\nlabel-a\nlabel-b"
|
|
505
|
+
|
|
506
|
+
|
|
507
|
+
@pytest.mark.parametrize("stdout", ["[]", "null"])
|
|
508
|
+
def test_an_empty_report_finds_nothing(scan_env, stdout):
|
|
509
|
+
scan_env(stdout)
|
|
510
|
+
assert d.scanner_credential("x", _ctx()) == []
|
|
511
|
+
|
|
512
|
+
|
|
513
|
+
@pytest.mark.parametrize(
|
|
514
|
+
"stdout, exit_code", [("not json", 0), ("", 3), ("42", 0), ("[]", 2)]
|
|
515
|
+
)
|
|
516
|
+
def test_a_failed_scan_is_a_gap_attended_and_a_hold_unattended(
|
|
517
|
+
scan_env, capsys, stdout, exit_code
|
|
518
|
+
):
|
|
519
|
+
scan_env(stdout, exit_code=exit_code)
|
|
520
|
+
assert d.scanner_credential("x", _ctx()) == [] # attended: built-in patterns only
|
|
521
|
+
assert "fakescan" in capsys.readouterr().err
|
|
522
|
+
with pytest.raises(d.ScannerUnavailable):
|
|
523
|
+
d.scanner_credential("x", _ctx(unattended=True))
|
|
524
|
+
events = (scan_env.state / "events.jsonl").read_text().splitlines()
|
|
525
|
+
assert len(events) == 2 and all("credential_scanner_gap" in e for e in events)
|
|
526
|
+
|
|
527
|
+
|
|
528
|
+
def test_a_missing_or_malformed_scanner_setting_is_a_gap(scan_env):
|
|
529
|
+
assert d.scanner_credential("x", {"settings": {"credential_scanner": "nope-xyz"}}) == []
|
|
530
|
+
with pytest.raises(d.ScannerUnavailable):
|
|
531
|
+
d.scanner_credential(
|
|
532
|
+
"x", {"settings": {"credential_scanner": 42}, "unattended": True}
|
|
533
|
+
)
|
|
534
|
+
with pytest.raises(d.ScannerUnavailable):
|
|
535
|
+
d.scanner_credential(
|
|
536
|
+
"x",
|
|
537
|
+
{"settings": {"credential_scanner": "fakescan",
|
|
538
|
+
"credential_scanner_args": [1, 2]}, "unattended": True},
|
|
539
|
+
)
|
|
540
|
+
|
|
541
|
+
|
|
542
|
+
def test_a_scanner_inside_the_current_folder_is_refused(scan_env, tmp_path, monkeypatch):
|
|
543
|
+
local = tmp_path / "repo" / "bin"
|
|
544
|
+
local.mkdir(parents=True)
|
|
545
|
+
(local / "fakescan").write_text("#!/bin/sh\necho []\n")
|
|
546
|
+
(local / "fakescan").chmod(0o755)
|
|
547
|
+
monkeypatch.chdir(tmp_path / "repo")
|
|
548
|
+
monkeypatch.setenv("PATH", f"{local}{os.pathsep}{os.environ['PATH']}")
|
|
549
|
+
with pytest.raises(d.ScannerUnavailable, match="inside the current folder"):
|
|
550
|
+
d.scanner_credential("x", _ctx(unattended=True))
|
|
551
|
+
|
|
552
|
+
|
|
553
|
+
def test_a_hold_never_copies_a_credential_only_the_scanner_found():
|
|
554
|
+
from pubcheck.core import Verdict
|
|
555
|
+
from pubcheck.hold import WITHHELD, hold_body
|
|
556
|
+
|
|
557
|
+
secret = "https://hooks.example.invalid/services/T000/B000/" + "x" * 24
|
|
558
|
+
v = Verdict(decision="flag", findings=[("credential", "fakescan:slack-webhook-url")])
|
|
559
|
+
body = hold_body(v, target="github:o/r", text=f"see {secret}", title=secret, more=[secret])
|
|
560
|
+
assert secret not in body and WITHHELD in body
|
|
561
|
+
|
|
562
|
+
|
|
563
|
+
def test_the_scanner_is_a_setting_with_an_environment_override(monkeypatch):
|
|
564
|
+
from pubcheck.base import settings
|
|
565
|
+
|
|
566
|
+
monkeypatch.setenv("PUBCHECK_CONFIG", "/nonexistent/config.toml")
|
|
567
|
+
assert settings()["credential_scanner"] is None
|
|
568
|
+
monkeypatch.setenv("PUBCHECK_CREDENTIAL_SCANNER", "betterleaks")
|
|
569
|
+
assert settings()["credential_scanner"] == "betterleaks"
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|