buckthorn 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.
buckthorn/__init__.py ADDED
@@ -0,0 +1 @@
1
+ """Buckthorn: static checks for Python packages. Nothing it reads is installed, imported or run."""
buckthorn/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from buckthorn.cli import main
2
+
3
+ raise SystemExit(main())
buckthorn/cli.py ADDED
@@ -0,0 +1,613 @@
1
+ """Command line: buckthorn scan <artifacts>, check <lockfile or MCP config>, diff, env <venv>,
2
+ hf <repo>.
3
+
4
+ Exit codes: 0 clean, 1 flagged (or not_verified, unless --allow-not-verified),
5
+ 2 a usage or input error.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import contextlib
12
+ import fnmatch
13
+ import glob
14
+ import hashlib
15
+ import io
16
+ import json
17
+ import os
18
+ import posixpath
19
+ import re
20
+ import sys
21
+ from datetime import UTC, datetime
22
+ from importlib.metadata import version
23
+ from pathlib import Path
24
+
25
+ from buckthorn import hf, lock, mcp_config
26
+ from buckthorn.env import scan_env
27
+ from buckthorn.findings import COVERAGE_RULE_IDS, Finding, Result, Severity, new_findings
28
+ from buckthorn.scan import ARTIFACT_SUFFIXES, CALL_TIME, scan_artifact, split_artifact_name
29
+
30
+ _SEVERITY_ORDER = list(Severity)
31
+
32
+
33
+ class InputError(Exception):
34
+ """Bad input from the caller: reported on stderr, exit code 2."""
35
+
36
+
37
+ def main(argv: list[str] | None = None) -> int:
38
+ # A name the console cannot encode (cp1252 on Windows) is escaped, not a crash.
39
+ for stream in (sys.stdout, sys.stderr):
40
+ if isinstance(stream, io.TextIOWrapper):
41
+ stream.reconfigure(errors="backslashreplace")
42
+ parser = argparse.ArgumentParser(
43
+ prog="buckthorn",
44
+ description=(
45
+ "Static checks for Python and npm packages. Nothing is installed, imported or run."
46
+ ),
47
+ )
48
+ parser.add_argument("--version", action="version", version=f"buckthorn {version('buckthorn')}")
49
+ sub = parser.add_subparsers(dest="command", required=True)
50
+ scan = sub.add_parser(
51
+ "scan",
52
+ help="scan wheels, sdists and npm tarballs, folders of them, or a model folder's code",
53
+ )
54
+ scan.add_argument(
55
+ "target", type=Path, nargs="+", help="a .whl, .tar.gz, .tgz or .zip, or a folder"
56
+ )
57
+ _add_report_arguments(scan)
58
+ check = sub.add_parser(
59
+ "check",
60
+ help="fetch every artifact a lockfile pins, or the PyPI packages an MCP config "
61
+ "would install, from PyPI, check each hash, scan them",
62
+ )
63
+ check.add_argument(
64
+ "lockfile",
65
+ type=Path,
66
+ nargs="+",
67
+ help="requirements.txt with hashes, uv.lock, poetry.lock, or an agent's MCP config "
68
+ "(.mcp.json, mcp.json, claude_desktop_config.json)",
69
+ )
70
+ check.add_argument(
71
+ "--cache-dir",
72
+ type=Path,
73
+ metavar="DIR",
74
+ help="keep downloads here between runs (default: a temporary folder, removed after)",
75
+ )
76
+ check.add_argument(
77
+ "--all-files",
78
+ action="store_true",
79
+ help="check every pinned file, not only the one this machine would install",
80
+ )
81
+ _add_report_arguments(check)
82
+ diff = sub.add_parser("diff", help="report only what an upgrade adds")
83
+ diff.add_argument("old", help="the version you have: a wheel or sdist, or name==version")
84
+ diff.add_argument("new", help="the version you are moving to, the same way")
85
+ diff.add_argument("--cache-dir", type=Path, metavar="DIR", help="keep downloads here")
86
+ _add_report_arguments(diff)
87
+ env = sub.add_parser("env", help="scan an installed environment in place")
88
+ env.add_argument("path", type=Path, help="a virtualenv, or a site-packages folder")
89
+ _add_report_arguments(env)
90
+ hub = sub.add_parser(
91
+ "hf", help="read the code a Hugging Face model repo runs at load with trust_remote_code"
92
+ )
93
+ hub.add_argument("repo", nargs="+", help="org/name, or org/name@commit to pin it")
94
+ _add_report_arguments(hub)
95
+ sub.add_parser("mcp", help="run a stdio MCP server so a coding agent can check packages")
96
+ args = parser.parse_args(argv)
97
+ if args.command == "mcp":
98
+ # The SDK is an optional extra, imported here and nowhere else: every other
99
+ # command must work without it.
100
+ try:
101
+ import mcp # noqa: F401
102
+ except ImportError:
103
+ print('buckthorn: the MCP server needs: pip install "buckthorn[mcp]"', file=sys.stderr)
104
+ return 2
105
+ from buckthorn.mcp_server import serve
106
+
107
+ serve()
108
+ return 0
109
+ try:
110
+ allow = _load_allowlist(args.allowlist) if args.allowlist else []
111
+ if args.command == "check":
112
+ results = [
113
+ result
114
+ for path in args.lockfile
115
+ for result in _check_lockfile(path, args.cache_dir, args.all_files)
116
+ ]
117
+ elif args.command == "diff":
118
+ results = [_diff(args.old, args.new, args.cache_dir)]
119
+ elif args.command == "env":
120
+ results = _env(args.path)
121
+ elif args.command == "hf":
122
+ results = [_hf(spec) for spec in args.repo]
123
+ else:
124
+ results = [scan_file(path) for path in artifacts(args.target)]
125
+ except InputError as exc:
126
+ print(f"buckthorn: {exc}", file=sys.stderr)
127
+ return 2
128
+ if args.receipt:
129
+ try:
130
+ statement = _receipt(results, args.command)
131
+ except InputError as exc:
132
+ print(f"buckthorn: {exc}", file=sys.stderr)
133
+ return 2
134
+ try:
135
+ _write(args.receipt, json.dumps(statement, indent=2))
136
+ except OSError as exc:
137
+ print(f"buckthorn: could not write {args.receipt}: {exc}", file=sys.stderr)
138
+ return 2
139
+ _apply_allowlist(results, allow)
140
+ if args.write_allowlist:
141
+ accepted = _baseline(results)
142
+ try:
143
+ text = json.dumps({"allow": allow + accepted}, indent=2) + "\n"
144
+ _write(args.write_allowlist, text)
145
+ except OSError as exc:
146
+ print(f"buckthorn: could not write {args.write_allowlist}: {exc}", file=sys.stderr)
147
+ return 2
148
+ _apply_allowlist(results, accepted)
149
+ left = sum(
150
+ f.severity != Severity.INFO and f.rule_id not in COVERAGE_RULE_IDS
151
+ for r in results
152
+ for f in r.findings
153
+ )
154
+ if left:
155
+ print(
156
+ f"buckthorn: {left} finding{'s' if left > 1 else ''} not tied to a package "
157
+ "version could not be accepted and still count",
158
+ file=sys.stderr,
159
+ )
160
+ return _report(results, args)
161
+
162
+
163
+ def json_report(results: list[Result]) -> dict:
164
+ """The --format json report; the MCP tools return the same."""
165
+ return {
166
+ "schema_version": 1, # raised when a key changes meaning or goes away
167
+ "tool": "buckthorn",
168
+ "version": version("buckthorn"),
169
+ "verdict": _overall(results),
170
+ "artifacts": [
171
+ {
172
+ "path": r.path,
173
+ "sha256": r.sha256,
174
+ "verdict": r.verdict,
175
+ "findings": [f.to_dict() for f in _ordered(r.findings)],
176
+ "allowed": [f.to_dict() | {"reason": why} for f, why in r.allowed],
177
+ }
178
+ for r in results
179
+ ],
180
+ }
181
+
182
+
183
+ RECEIPT_PREDICATE = "https://hedgerow.dev/buckthorn/scan-receipt/v1"
184
+
185
+
186
+ def _receipt(results: list[Result], command: str) -> dict:
187
+ """An in-toto Statement of what the scanner found in each artifact, by hash.
188
+
189
+ Same shape as Hayward's receipts. Taken before the allowlist, so acceptance
190
+ decisions stay apart from what was seen. Only artifacts whose bytes were read
191
+ are subjects: a pin that was never downloaded names a hash nobody looked at.
192
+ InputError for diff (it reports what is new, not what an artifact holds), env
193
+ (installed files have no artifact hash), and two artifacts with one name.
194
+ """
195
+ if command in ("diff", "env", "hf"):
196
+ raise InputError(f"--receipt is for scan and check, not {command}")
197
+ if any(Path(r.path).is_dir() for r in results): # a model folder has no artifact hash
198
+ raise InputError("--receipt is for wheels and sdists, not a model folder")
199
+ subjects, artifacts = [], {}
200
+ for r in results:
201
+ never_read = any(f.rule_id in ("BKT-LOCK-002", "BKT-LOCK-003") for f in r.findings)
202
+ if not r.sha256 or never_read:
203
+ continue
204
+ name = Path(r.path).name
205
+ if name in artifacts:
206
+ if {"name": name, "digest": {"sha256": r.sha256}} in subjects:
207
+ continue # one artifact reached twice, as two MCP servers running one package
208
+ raise InputError(f"two artifacts are named {name}; a receipt needs unique names")
209
+ subjects.append({"name": name, "digest": {"sha256": r.sha256}})
210
+ artifacts[name] = {
211
+ "verdict": r.verdict,
212
+ "rules": sorted({f.rule_id for f in r.findings if f.rule_id not in COVERAGE_RULE_IDS}),
213
+ "coverage_gaps": sorted(
214
+ {f.rule_id for f in r.findings if f.rule_id in COVERAGE_RULE_IDS}
215
+ ),
216
+ }
217
+ return {
218
+ "_type": "https://in-toto.io/Statement/v1",
219
+ "subject": subjects,
220
+ "predicateType": RECEIPT_PREDICATE,
221
+ "predicate": {
222
+ "scanner": {"name": "buckthorn", "version": version("buckthorn")},
223
+ "scanned": datetime.now(UTC).isoformat(timespec="seconds"),
224
+ "note": "Analysis evidence: what Buckthorn found in each artifact, identified by "
225
+ "hash. It is not a safety certificate.",
226
+ "artifacts": artifacts,
227
+ },
228
+ }
229
+
230
+
231
+ def _load_allowlist(path: Path) -> list[dict[str, str]]:
232
+ """Entries of {"allow": [...]}: rule and package required, file and version optional,
233
+ and a reason always. Coverage gaps cannot be allowed: they mean nothing was read."""
234
+ try:
235
+ entries = json.loads(path.read_text(encoding="utf-8"))["allow"]
236
+ except (OSError, ValueError, KeyError, TypeError) as exc:
237
+ raise InputError(f"allowlist {path}: {exc}") from exc
238
+ if not isinstance(entries, list):
239
+ raise InputError(f"allowlist {path}: 'allow' must be a list")
240
+ for n, entry in enumerate(entries, 1):
241
+ if not isinstance(entry, dict) or not all(
242
+ isinstance(entry.get(key), str) and entry[key].strip()
243
+ for key in ("rule", "package", "reason")
244
+ ):
245
+ raise InputError(f"allowlist {path}: entry {n} needs a rule, a package and a reason")
246
+ if entry["rule"] in COVERAGE_RULE_IDS:
247
+ raise InputError(f"allowlist {path}: entry {n}: {entry['rule']} cannot be allowed")
248
+ return entries
249
+
250
+
251
+ def _package_of(result: Result) -> tuple[str, str]:
252
+ """Package and version a result is named for, or ("", "").
253
+
254
+ Only results named for a package can be allowed: name==version (env, pins)
255
+ or an artifact file. Anything else, like the env's unowned files, never matches.
256
+ """
257
+ if "==" in result.path:
258
+ package, _, release = result.path.partition("==")
259
+ elif result.path.lower().endswith(ARTIFACT_SUFFIXES):
260
+ package, release = split_artifact_name(Path(result.path).name)
261
+ elif "@" in result.path: # a Hub repo at a commit: org/name@sha
262
+ package, _, release = result.path.partition("@")
263
+ else:
264
+ package, release = "", ""
265
+ return package, release
266
+
267
+
268
+ def _allow_file(finding: Finding, release: str) -> str:
269
+ """The finding's file with the version folder taken out, as allowlist globs match.
270
+ "." and ".." are resolved first: pkg/tests/../x.py installs as pkg/x.py."""
271
+ file = posixpath.normpath(finding.file_path)
272
+ first, sep, rest = file.partition("/")
273
+ return first.replace(f"-{release}", "") + sep + rest if release else file
274
+
275
+
276
+ def _baseline(results: list[Result]) -> list[dict[str, str]]:
277
+ """Allowlist entries for every finding left after --allowlist, pinned to its version,
278
+ for --write-allowlist. Coverage gaps and info notes are never written."""
279
+ reason = (
280
+ f"accepted as found by buckthorn {version('buckthorn')} on "
281
+ f"{datetime.now(UTC).date().isoformat()}; review before trusting"
282
+ )
283
+ entries: list[dict[str, str]] = []
284
+ for result in results:
285
+ package, release = _package_of(result)
286
+ if not package:
287
+ continue
288
+ for finding in result.findings:
289
+ if finding.severity == Severity.INFO or finding.rule_id in COVERAGE_RULE_IDS:
290
+ continue
291
+ if "@" in result.path and "@" in finding.file_path:
292
+ continue # code fetched from another repo's main branch is never allowed
293
+ entry = {"rule": finding.rule_id, "package": package}
294
+ if release:
295
+ entry["version"] = release
296
+ # The file is matched as a glob: a name from the package must match only itself.
297
+ entry |= {"file": glob.escape(_allow_file(finding, release)), "reason": reason}
298
+ if entry not in entries:
299
+ entries.append(entry)
300
+ return entries
301
+
302
+
303
+ def _apply_allowlist(results: list[Result], entries: list[dict[str, str]]) -> None:
304
+ for result in results:
305
+ package, release = _package_of(result)
306
+ kept = []
307
+ for finding in result.findings:
308
+ file = _allow_file(finding, release)
309
+ reason = next(
310
+ (
311
+ e["reason"]
312
+ for e in entries
313
+ if e["rule"] == finding.rule_id
314
+ and package
315
+ and _same_package(e["package"], package, result.path)
316
+ and e.get("version", release) == release
317
+ and fnmatch.fnmatchcase(file, e.get("file", "*"))
318
+ # code fetched from another repo's main branch is never allowed
319
+ and not ("@" in result.path and "@" in finding.file_path)
320
+ ),
321
+ None,
322
+ )
323
+ if reason is None:
324
+ kept.append(finding)
325
+ else:
326
+ result.allowed.append((finding, reason))
327
+ result.findings = kept
328
+
329
+
330
+ def _same_package(entry: str, package: str, path: str) -> bool:
331
+ """PyPI folds -_. and case together; npm names are taken as written."""
332
+ if path.lower().endswith(".tgz"):
333
+ return entry == package
334
+ return re.sub(r"[-_.]+", "-", entry).lower() == re.sub(r"[-_.]+", "-", package).lower()
335
+
336
+
337
+ def _env(path: Path) -> list[Result]:
338
+ try:
339
+ return scan_env(path)
340
+ except (ValueError, OSError) as exc: # not an environment, or a folder we cannot list
341
+ raise InputError(str(exc)) from exc
342
+
343
+
344
+ def _hf(spec: str) -> Result:
345
+ try:
346
+ return hf.scan_repo(spec)
347
+ except ValueError as exc: # a malformed repo id
348
+ raise InputError(f"{spec}: {exc}") from exc
349
+
350
+
351
+ def _diff(old_arg: str, new_arg: str, cache_dir: Path | None) -> Result:
352
+ """The new version's findings that the old version does not have."""
353
+ old, old_version = _resolve(old_arg, cache_dir)
354
+ new, new_version = _resolve(new_arg, cache_dir)
355
+ findings = new_findings(old.findings, new.findings, old_version, new_version)
356
+ if old.path.endswith(".whl") and not new.path.endswith(".whl"):
357
+ message = (
358
+ f"{old.path} installed as a wheel; {new.path} is an sdist, "
359
+ "so installing it now builds from source and runs install-time code"
360
+ )
361
+ findings.append(Finding("BKT-DIFF-001", message, Severity.MEDIUM, new.path))
362
+ return Result(new.path, new.sha256, findings)
363
+
364
+
365
+ def _resolve(arg: str, cache_dir: Path | None) -> tuple[Result, str]:
366
+ """Scan a local artifact, or fetch name==version from PyPI. Also returns the version."""
367
+ path = Path(arg)
368
+ if path.is_file():
369
+ return scan_file(path), split_artifact_name(path.name)[1]
370
+ if "==" not in arg:
371
+ raise InputError(f"{arg}: no such file, and not name==version")
372
+ name, _, version = arg.partition("==")
373
+ try:
374
+ return lock.scan_release(
375
+ name.strip(), version.strip(), cache_dir=cache_dir
376
+ ), version.strip()
377
+ except lock.FetchError as exc:
378
+ raise InputError(f"{arg}: {exc}") from exc
379
+
380
+
381
+ def _check_lockfile(path: Path, cache_dir: Path | None, all_files: bool) -> list[Result]:
382
+ if not path.is_file():
383
+ raise InputError(f"{path}: no such file")
384
+
385
+ def progress(name: str) -> None:
386
+ print(_printable(name), file=sys.stderr) # MCP config keys are not checked names
387
+
388
+ try:
389
+ servers = mcp_config.servers(path.read_text(encoding="utf-8"))
390
+ if servers is not None:
391
+ results = mcp_config.check(servers, cache_dir=cache_dir, progress=progress)
392
+ else:
393
+ results = lock.check(path, cache_dir=cache_dir, all_files=all_files, progress=progress)
394
+ except (ValueError, UnicodeDecodeError) as exc: # unknown name, or TOML that will not parse
395
+ raise InputError(f"{path}: {exc}") from exc
396
+ for result in results:
397
+ result.source = str(path)
398
+ return results
399
+
400
+
401
+ def _add_report_arguments(parser: argparse.ArgumentParser) -> None:
402
+ parser.add_argument("-f", "--format", choices=("text", "json", "sarif"), default="text")
403
+ parser.add_argument(
404
+ "-o", "--output", type=Path, metavar="FILE", help="write the report here, not to stdout"
405
+ )
406
+ parser.add_argument(
407
+ "--allowlist",
408
+ type=Path,
409
+ metavar="FILE",
410
+ help="JSON file of findings you have reviewed and accept, each with a reason",
411
+ )
412
+ parser.add_argument(
413
+ "--write-allowlist",
414
+ type=Path,
415
+ metavar="FILE",
416
+ help="accept every finding of this run: write it to FILE (with any --allowlist "
417
+ "entries), pinned to its version. Review the file before you commit it",
418
+ )
419
+ parser.add_argument(
420
+ "--receipt",
421
+ type=Path,
422
+ metavar="FILE",
423
+ help="also write an unsigned in-toto scan receipt: each artifact's hash and what "
424
+ "was found, before --allowlist",
425
+ )
426
+ parser.add_argument(
427
+ "--allow-not-verified",
428
+ action="store_true",
429
+ help="exit 0 when something could not be fully read (default: treat it as flagged)",
430
+ )
431
+
432
+
433
+ def artifacts(targets: list[Path]) -> list[Path]:
434
+ paths: list[Path] = []
435
+ for target in targets:
436
+ if target.is_dir():
437
+ found = sorted(
438
+ p
439
+ for p in target.iterdir()
440
+ if p.is_file() and p.name.lower().endswith(ARTIFACT_SUFFIXES)
441
+ )
442
+ if not found and hf.is_model_folder(target):
443
+ paths.append(target) # a model repo: its remote code is read
444
+ continue
445
+ if not found:
446
+ raise InputError(f"{target}: no wheels or sdists in this folder")
447
+ paths.extend(found)
448
+ elif target.is_file():
449
+ paths.append(target)
450
+ else:
451
+ raise InputError(f"{target}: no such file or folder")
452
+ return paths
453
+
454
+
455
+ def scan_file(path: Path) -> Result:
456
+ if path.is_dir():
457
+ return hf.scan_folder(path)
458
+ digest = hashlib.sha256()
459
+ with path.open("rb") as fh:
460
+ for chunk in iter(lambda: fh.read(1 << 20), b""):
461
+ digest.update(chunk)
462
+ return Result(str(path), digest.hexdigest(), scan_artifact(path))
463
+
464
+
465
+ def _overall(results: list[Result]) -> str:
466
+ verdicts = {r.verdict for r in results}
467
+ for name in ("flagged", "not_verified"):
468
+ if name in verdicts:
469
+ return name
470
+ return "clean"
471
+
472
+
473
+ def _report(results: list[Result], args: argparse.Namespace, to_file: bool = False) -> int:
474
+ overall = _overall(results)
475
+ if args.output and not to_file:
476
+ report = io.StringIO()
477
+ with contextlib.redirect_stdout(report):
478
+ code = _report(results, args, to_file=True)
479
+ try:
480
+ _write(args.output, report.getvalue())
481
+ except OSError as exc:
482
+ print(f"buckthorn: could not write {args.output}: {exc}", file=sys.stderr)
483
+ return 2
484
+ print(f"{overall}: report written to {args.output}")
485
+ return code
486
+ if args.format == "sarif":
487
+ print(json.dumps(_sarif(results, args), indent=2))
488
+ elif args.format == "json":
489
+ print(json.dumps(json_report(results), indent=2))
490
+ else:
491
+ hidden = 0
492
+ for r in results:
493
+ print(f"{_printable(r.path)}: {r.verdict}")
494
+ for f in _ordered(r.findings):
495
+ # Info notes are context, not verdicts; JSON keeps them. Coverage gaps always show.
496
+ if f.severity == Severity.INFO and f.rule_id not in COVERAGE_RULE_IDS:
497
+ hidden += 1
498
+ continue
499
+ where, message = _printable(_where(f)), _printable(f.message)
500
+ print(f" {f.severity.value:<8} {f.rule_id:<16} {where} {message}")
501
+ counts = {
502
+ v: sum(r.verdict == v for r in results) for v in ("clean", "flagged", "not_verified")
503
+ }
504
+ summary = ", ".join(f"{n} {v}" for v, n in counts.items() if n)
505
+ print(f"\n{len(results)} scanned: {summary}")
506
+ if counts["clean"] and args.command in ("scan", "check", "env") and not CALL_TIME:
507
+ print(
508
+ "clean: nothing flagged in what runs at install, at start-up or at import. "
509
+ "Code that only runs when you call it is not read."
510
+ )
511
+ if hidden:
512
+ print(
513
+ f"{hidden} info note{'s' if hidden > 1 else ''} hidden (--format json shows them)"
514
+ )
515
+ # Unpinned servers and dependencies are info (most configs have them), so count
516
+ # them where they show. A normal tree would otherwise hide behind "info notes".
517
+ unpinned = sum(f.rule_id == "BKT-MCP-002" for r in results for f in r.findings)
518
+ if unpinned:
519
+ s = "s" if unpinned > 1 else ""
520
+ print(f"{unpinned} server{s} not pinned to a version (BKT-MCP-002)")
521
+ floating = sum(f.rule_id == "BKT-MCP-007" for r in results for f in r.findings)
522
+ if floating:
523
+ word = "dependency" if floating == 1 else "dependencies"
524
+ print(f"{floating} {word} not pinned to a version (BKT-MCP-007)")
525
+ allowed = sum(len(r.allowed) for r in results)
526
+ if allowed:
527
+ print(f"{allowed} finding{'s' if allowed > 1 else ''} allowed by the allowlist")
528
+ if overall == "flagged" or (overall == "not_verified" and not args.allow_not_verified):
529
+ return 1
530
+ return 0
531
+
532
+
533
+ _SARIF_LEVELS = {
534
+ Severity.CRITICAL: "error",
535
+ Severity.HIGH: "error",
536
+ Severity.MEDIUM: "warning",
537
+ Severity.LOW: "note",
538
+ }
539
+
540
+
541
+ _RULES_URL = "https://github.com/hedgerow-dev/buckthorn/blob/main/docs/rules.md"
542
+
543
+
544
+ def _where(f: Finding) -> str:
545
+ line = f.metadata.get("line") or (f.metadata.get("lines") or [None])[0]
546
+ return f"{f.file_path}:{line}" if line else f.file_path
547
+
548
+
549
+ def _sarif(results: list[Result], args: argparse.Namespace) -> dict:
550
+ """SARIF 2.1.0 for code scanning. Info notes are left out; coverage gaps stay in.
551
+
552
+ Findings sit inside archives, so each points at the artifact, or for `check`
553
+ at its lockfile (the file in the repository), with the inner path in the message.
554
+ """
555
+ rules: set[str] = set()
556
+ sarif_results = []
557
+ for r in results:
558
+ uri = r.source or r.path
559
+ for f in _ordered(r.findings):
560
+ gap = f.rule_id in COVERAGE_RULE_IDS
561
+ if f.severity == Severity.INFO and not gap:
562
+ continue
563
+ rules.add(f.rule_id)
564
+ # Every finding in an artifact shares its location, so code scanning
565
+ # tells them apart by this, not by line.
566
+ key = "\0".join((f.rule_id, r.path, f.file_path, f.message))
567
+ sarif_results.append(
568
+ {
569
+ "ruleId": f.rule_id,
570
+ "level": "warning" if gap else _SARIF_LEVELS[f.severity],
571
+ "message": {"text": f"{r.path}: {_where(f)}: {f.message}"},
572
+ "locations": [{"physicalLocation": {"artifactLocation": {"uri": uri}}}],
573
+ "partialFingerprints": {
574
+ "buckthorn/v1": hashlib.sha256(key.encode()).hexdigest()
575
+ },
576
+ }
577
+ )
578
+ driver = {
579
+ "name": "buckthorn",
580
+ "version": version("buckthorn"),
581
+ "rules": [
582
+ {"id": i, "shortDescription": {"text": i}, "helpUri": _RULES_URL} for i in sorted(rules)
583
+ ],
584
+ }
585
+ return {
586
+ "$schema": "https://json.schemastore.org/sarif-2.1.0.json",
587
+ "version": "2.1.0",
588
+ "runs": [{"tool": {"driver": driver}, "results": sarif_results}],
589
+ }
590
+
591
+
592
+ def _printable(text: str) -> str:
593
+ """Control characters escaped: names come from the packages being checked, and a
594
+ carriage return or terminal escape in one could make a flagged line read clean, and a
595
+ direction mark (U+202E) can make one name read as another. A leading "::" is escaped
596
+ too: GitHub Actions reads such a line as a workflow command."""
597
+ controls = r"[\x00-\x1f\x7f-\x9f\u061c\u200e\u200f\u2028\u2029\u202a-\u202e\u2066-\u2069]"
598
+ text = re.sub(controls, lambda m: repr(m.group())[1:-1], text)
599
+ return re.sub(r"^(\s*):", r"\1\\x3a", text) if text.lstrip().startswith("::") else text
600
+
601
+
602
+ def _write(path: Path, text: str) -> None:
603
+ """Never through a symlink: the Action's default report path is in the checkout it checks."""
604
+ nofollow = getattr(os, "O_NOFOLLOW", 0)
605
+ if not nofollow and os.path.islink(path): # Windows has no O_NOFOLLOW: check first
606
+ raise OSError(f"{path} is a symlink")
607
+ flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC | nofollow
608
+ with open(os.open(path, flags, 0o666), "w", encoding="utf-8") as fh:
609
+ fh.write(text)
610
+
611
+
612
+ def _ordered(findings: list[Finding]) -> list[Finding]:
613
+ return sorted(findings, key=lambda f: (_SEVERITY_ORDER.index(f.severity), f.file_path))