patchloop 0.2.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 (56) hide show
  1. patchloop/__init__.py +23 -0
  2. patchloop/api.py +110 -0
  3. patchloop/build.py +118 -0
  4. patchloop/classify.py +137 -0
  5. patchloop/cli.py +370 -0
  6. patchloop/config.py +148 -0
  7. patchloop/detect.py +133 -0
  8. patchloop/doctor.py +207 -0
  9. patchloop/enrich/__init__.py +66 -0
  10. patchloop/enrich/epss.py +65 -0
  11. patchloop/enrich/kev.py +39 -0
  12. patchloop/fixers/__init__.py +1 -0
  13. patchloop/fixers/base.py +20 -0
  14. patchloop/fixers/js_fix.py +288 -0
  15. patchloop/fixers/poetry_fix.py +144 -0
  16. patchloop/fixers/uv_fix.py +118 -0
  17. patchloop/git_ops.py +171 -0
  18. patchloop/github.py +161 -0
  19. patchloop/hints.py +180 -0
  20. patchloop/images.py +208 -0
  21. patchloop/isolate.py +57 -0
  22. patchloop/js/__init__.py +1 -0
  23. patchloop/js/lockfiles.py +237 -0
  24. patchloop/js/manifest.py +121 -0
  25. patchloop/js/ranges.py +130 -0
  26. patchloop/js/registry.py +67 -0
  27. patchloop/js/yarn.py +189 -0
  28. patchloop/lockgraph.py +181 -0
  29. patchloop/models.py +248 -0
  30. patchloop/plan.py +194 -0
  31. patchloop/pr_body.py +253 -0
  32. patchloop/prioritize.py +38 -0
  33. patchloop/proc.py +71 -0
  34. patchloop/py.typed +0 -0
  35. patchloop/pypi.py +60 -0
  36. patchloop/report/__init__.py +1 -0
  37. patchloop/report/console.py +243 -0
  38. patchloop/report/json_out.py +26 -0
  39. patchloop/report/sarif.py +143 -0
  40. patchloop/runner.py +494 -0
  41. patchloop/scanner.py +214 -0
  42. patchloop/sources/__init__.py +1 -0
  43. patchloop/sources/base.py +5 -0
  44. patchloop/sources/imports.py +292 -0
  45. patchloop/sources/merge.py +113 -0
  46. patchloop/sources/osv.py +255 -0
  47. patchloop/specifiers.py +259 -0
  48. patchloop/validate.py +198 -0
  49. patchloop/versions.py +81 -0
  50. patchloop/workspaces.py +142 -0
  51. patchloop/worktree.py +153 -0
  52. patchloop-0.2.0.dist-info/METADATA +388 -0
  53. patchloop-0.2.0.dist-info/RECORD +56 -0
  54. patchloop-0.2.0.dist-info/WHEEL +4 -0
  55. patchloop-0.2.0.dist-info/entry_points.txt +3 -0
  56. patchloop-0.2.0.dist-info/licenses/LICENSE +21 -0
patchloop/runner.py ADDED
@@ -0,0 +1,494 @@
1
+ """The `fix` pipeline.
2
+
3
+ detect -> worktree -> PR-branch check -> scan -> plan -> resolve -> baseline test ->
4
+ apply + test + isolate breakers -> changed-files check -> rescan -> classify ->
5
+ commit -> push -> open or update the PR (or, with --no-push, a local branch + body file).
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import re
11
+ import shlex
12
+ import shutil
13
+ from dataclasses import dataclass, field
14
+ from datetime import UTC, date, datetime
15
+ from pathlib import Path
16
+
17
+ from patchloop.build import BuildSpec, ImageCheck, build_image, compare, remove_image
18
+ from patchloop.classify import classify, exit_code
19
+ from patchloop.config import BuildConfig, Config
20
+ from patchloop.detect import detect_project
21
+ from patchloop.fixers.base import LockError
22
+ from patchloop.fixers.js_fix import JsFixer
23
+ from patchloop.fixers.poetry_fix import PoetryFixer
24
+ from patchloop.fixers.uv_fix import UvFixer
25
+ from patchloop.git_ops import (
26
+ TRAILER,
27
+ BranchState,
28
+ GitError,
29
+ branch_state,
30
+ commit,
31
+ foreign_error,
32
+ has_remote,
33
+ push,
34
+ repo_slug,
35
+ same_change,
36
+ set_local_branch,
37
+ )
38
+ from patchloop.github import GhCli, GitHubError, PRHost, PullRequest
39
+ from patchloop.images import Scanner, leak_warning, scan_images
40
+ from patchloop.isolate import isolate_breakers
41
+ from patchloop.js import manifest as js_manifest
42
+ from patchloop.js.lockfiles import read_lock
43
+ from patchloop.js.registry import NpmIndex
44
+ from patchloop.lockgraph import load_graph
45
+ from patchloop.models import (
46
+ JS_MANAGERS,
47
+ MANIFEST,
48
+ ExitCode,
49
+ Finding,
50
+ FixStatus,
51
+ RunReport,
52
+ Severity,
53
+ Upgrade,
54
+ ValidationResult,
55
+ normalize_package,
56
+ )
57
+ from patchloop.plan import Plan, build_plan
58
+ from patchloop.pr_body import BodyInput, render
59
+ from patchloop.pypi import PyPIIndex, ReleaseIndex
60
+ from patchloop.scanner import (
61
+ ScanResult,
62
+ cache_dir,
63
+ image_reports,
64
+ new_run_id,
65
+ prune_runs,
66
+ scan_project,
67
+ )
68
+ from patchloop.specifiers import allows as pyproject_allows
69
+ from patchloop.validate import INSTALL_FAILED, Validator, tool_env
70
+ from patchloop.worktree import Worktree, allowed_files, changed_files, worktree
71
+
72
+
73
+ class FixError(Exception):
74
+ """The run cannot continue; nothing is changed (exit code 2)."""
75
+
76
+
77
+ @dataclass
78
+ class ImageBuilder:
79
+ """Builds the project's image and scans it; removes every image it built."""
80
+
81
+ cfg: BuildConfig
82
+ args: dict[str, str]
83
+ run_id: str
84
+ run_dir: Path
85
+ scanners: list[Scanner]
86
+ platform: str | None = None
87
+ tags: list[str] = field(default_factory=list)
88
+ leaked: set[str] = field(default_factory=set)
89
+
90
+ def tag(self, label: str) -> str:
91
+ return f"patchloop-{self.run_id.lower()}:{label}"
92
+
93
+ def build_and_scan(self, project_dir: Path, label: str) -> list[Path]:
94
+ tag = self.tag(label)
95
+ spec = BuildSpec(
96
+ project_dir / self.cfg.dockerfile, project_dir / self.cfg.context, self.args
97
+ )
98
+ build_image(spec, tag, self.run_dir / "logs" / f"build-{label}.log")
99
+ self.tags.append(tag)
100
+ scans = scan_images(
101
+ [tag], self.scanners, self.run_dir / "images" / label, self.platform, self.args
102
+ )
103
+ for s in scans:
104
+ self.leaked.update(s.leaked)
105
+ return [s.report for s in scans]
106
+
107
+ def image_findings(self, findings: list[Finding], label: str) -> list[Finding]:
108
+ target = f"image:{self.tag(label)}"
109
+ return [f for f in findings if any(h.target == target for h in f.sources)]
110
+
111
+ def cleanup(self) -> None:
112
+ for tag in self.tags:
113
+ remove_image(tag)
114
+
115
+
116
+ @dataclass
117
+ class FixOutcome:
118
+ exit_code: ExitCode
119
+ report: RunReport | None = None
120
+ plan: Plan | None = None
121
+ resolvable: list[Upgrade] = field(default_factory=list)
122
+ blocked: dict[str, str] = field(default_factory=dict)
123
+ kept: list[Upgrade] = field(default_factory=list)
124
+ scan: ScanResult | None = None
125
+ changed: list[str] = field(default_factory=list)
126
+ manifest_changes: dict[str, list[tuple[str, str, str]]] = field(default_factory=dict)
127
+ """package -> (file, old, new) edits to package.json / pyproject.toml."""
128
+ manifest: str = "pyproject.toml"
129
+ worktree_path: Path | None = None
130
+ ref: str = ""
131
+ run_dir: Path | None = None
132
+ test_runs: int = 0
133
+ dry_run: bool = False
134
+ display_name: str = ""
135
+ branch: str = ""
136
+ pr_action: str = "none"
137
+ """created | updated | unchanged | local | none"""
138
+ pr: PullRequest | None = None
139
+ pr_note: str = ""
140
+ commit_sha: str | None = None
141
+ pr_title: str = ""
142
+ body_path: Path | None = None
143
+ warnings: list[str] = field(default_factory=list)
144
+ image_check: ImageCheck | None = None
145
+
146
+
147
+ def _priority(scan: ScanResult) -> dict[str, int]:
148
+ """Most severe package first, so bisection keeps the important upgrades in context."""
149
+ best: dict[str, int] = {}
150
+ for f in scan.shown:
151
+ name = normalize_package(f.package, f.ecosystem)
152
+ best[name] = max(best.get(name, 0), f.severity.rank)
153
+ return best
154
+
155
+
156
+ def pr_branch(cfg: Config, project_rel: str) -> str:
157
+ """The configured branch; by default one per project folder, so a repo holding several
158
+ projects gets one PR for each."""
159
+ if "branch" in cfg.pr.model_fields_set or not project_rel:
160
+ return cfg.pr.branch
161
+ slug = re.sub(r"[^A-Za-z0-9._-]+", "-", project_rel).strip("-.").lower()
162
+ return f"{cfg.pr.branch}-{slug}" if slug else cfg.pr.branch
163
+
164
+
165
+ def run_fix(
166
+ path: Path,
167
+ cfg: Config,
168
+ only: set[Severity] | None = None,
169
+ *,
170
+ dry_run: bool = False,
171
+ push_pr: bool = True,
172
+ keep_worktree: bool = False,
173
+ host: PRHost | None = None,
174
+ index: ReleaseIndex | None = None,
175
+ today: date | None = None,
176
+ imports: list[Path] | None = None,
177
+ build_args: dict[str, str] | None = None,
178
+ ) -> FixOutcome:
179
+ """Run the loop; then commit and open or update the PR (``push_pr``) or a local branch.
180
+
181
+ ``host`` is where the PR lives; by default gh on the repo behind ``origin``.
182
+ """
183
+ origin = detect_project(path, base_branch=cfg.pr.base_branch)
184
+ prune_runs()
185
+ run_id = new_run_id()
186
+ run_dir = cache_dir() / "runs" / run_id
187
+ env = tool_env(run_dir)
188
+ started = datetime.now(UTC)
189
+
190
+ with worktree(origin.root, cfg.pr.base_branch, run_dir / "worktree", keep_worktree) as wt:
191
+ state: BranchState | None = None
192
+ if not dry_run:
193
+ host, state = _preflight(wt, cfg, push_pr, host)
194
+ # Images are scanned once; the rescan maps the same reports onto the fixed lockfile.
195
+ all_imports = [*(imports or []), *image_reports(cfg, run_dir / "images")]
196
+ builder = None
197
+ if cfg.build is not None:
198
+ builder = ImageBuilder(
199
+ cfg.build, build_args or {}, run_id, run_dir,
200
+ list(cfg.image_scanners), cfg.image_platform,
201
+ ) # fmt: skip
202
+ try:
203
+ outcome = _fix_in_worktree(
204
+ wt, cfg, only, run_id, run_dir, env, started, dry_run, index, today,
205
+ all_imports, builder,
206
+ ) # fmt: skip
207
+ finally:
208
+ if builder is not None:
209
+ builder.cleanup()
210
+ for venv in ("venv", "poetry-venvs"): # the bulk of a run folder; logs stay
211
+ shutil.rmtree(run_dir / venv, ignore_errors=True)
212
+ if builder is not None and builder.leaked:
213
+ outcome.warnings.append(leak_warning(builder.leaked))
214
+ outcome.worktree_path = wt.path if keep_worktree else None
215
+ outcome.ref = wt.ref
216
+ outcome.run_dir = run_dir
217
+ outcome.display_name = wt.project_rel or origin.root.name
218
+ outcome.branch = pr_branch(cfg, wt.project_rel)
219
+ if state is not None:
220
+ _publish(outcome, wt, cfg, state, host if push_pr else None)
221
+ return outcome
222
+
223
+
224
+ def _preflight(
225
+ wt: Worktree, cfg: Config, push_pr: bool, host: PRHost | None
226
+ ) -> tuple[PRHost | None, BranchState]:
227
+ """Before any slow work: can we push, and is the PR branch ours to rebuild?"""
228
+ branch = pr_branch(cfg, wt.project_rel)
229
+ if not push_pr:
230
+ state = branch_state(wt.repo_root, branch, wt.commit_sha, remote=False)
231
+ if state.foreign:
232
+ raise foreign_error(state, "local")
233
+ return None, state
234
+ if not has_remote(wt.repo_root):
235
+ raise GitError("the repo has no 'origin' remote to push to; use --no-push")
236
+ if host is None:
237
+ gh = GhCli(cfg.pr.repo or repo_slug(wt.repo_root), cfg.pr.gh_user)
238
+ gh.check_access()
239
+ host = gh
240
+ state = branch_state(wt.repo_root, branch, wt.commit_sha, remote=True, env=host.push_env())
241
+ if state.foreign:
242
+ raise foreign_error(state, "origin")
243
+ return host, state
244
+
245
+
246
+ def _commit_message(outcome: FixOutcome, report: RunReport, title: str) -> str:
247
+ by_key = {f.key: f for f in report.findings_before}
248
+ lines = [title, ""]
249
+ for u in outcome.kept:
250
+ ids = [
251
+ by_key[r.finding_key].advisory_id
252
+ for r in report.results
253
+ if r.status.counts_as_fixed and r.upgrade and r.upgrade.package == u.package
254
+ ]
255
+ if ids:
256
+ lines.append(f"- {u.package} {u.from_version} -> {u.to_version}: {', '.join(ids)}")
257
+ return "\n".join([*lines, "", f"{TRAILER}: {report.run_id}"])
258
+
259
+
260
+ def _publish(
261
+ outcome: FixOutcome, wt: Worktree, cfg: Config, state: BranchState, host: PRHost | None
262
+ ) -> None:
263
+ """Commit the kept upgrades, then push and open / update the PR (or a local branch)."""
264
+ report = outcome.report
265
+ if report is None or outcome.run_dir is None:
266
+ return
267
+ introduced = [r for r in report.results if r.status is FixStatus.INTRODUCED]
268
+ if introduced:
269
+ outcome.pr_note = (
270
+ f"No PR: the upgrades bring in {len(introduced)} new finding(s); see INTRODUCED above."
271
+ )
272
+ return
273
+ if not any(r.status.counts_as_fixed for r in report.results) or not outcome.changed:
274
+ outcome.pr_note = "No PR: nothing was fixed, so there is nothing to commit."
275
+ if host is not None and (pr := host.find_open(state.name)) is not None:
276
+ outcome.pr = pr
277
+ outcome.pr_note += f" The open PatchLoop PR #{pr.number} was left as is."
278
+ return
279
+
280
+ title, text = render(
281
+ BodyInput(
282
+ report=report,
283
+ base_ref=wt.ref,
284
+ manifest_changes=outcome.manifest_changes,
285
+ manifest=outcome.manifest,
286
+ project_rel=wt.project_rel,
287
+ image_check=outcome.image_check,
288
+ )
289
+ )
290
+ body_path = outcome.run_dir / "pr-body.md"
291
+ body_path.write_text(text, "utf-8")
292
+ outcome.body_path = body_path
293
+ outcome.pr_title = title
294
+ sha = commit(wt.path, sorted(outcome.changed), _commit_message(outcome, report, title))
295
+ outcome.commit_sha = sha
296
+
297
+ if host is None:
298
+ set_local_branch(wt.repo_root, state.name, sha)
299
+ outcome.pr_action = "local"
300
+ return
301
+
302
+ if state.sha and same_change(wt.repo_root, state.sha, sha):
303
+ outcome.pr_action = "unchanged"
304
+ outcome.commit_sha = state.sha
305
+ else:
306
+ push(wt.repo_root, sha, state.name, state.sha, host.push_env())
307
+ pushed = "" if outcome.pr_action == "unchanged" else f"'{state.name}' was pushed, but "
308
+ try:
309
+ pr = host.find_open(state.name)
310
+ if pr is not None:
311
+ host.update(pr, title, body_path)
312
+ if outcome.pr_action != "unchanged":
313
+ outcome.pr_action = "updated"
314
+ else:
315
+ pr = host.create(cfg.pr.base_branch, state.name, title, body_path)
316
+ outcome.pr_action = "created"
317
+ outcome.warnings += host.decorate(pr, cfg.pr.labels, cfg.pr.reviewers)
318
+ except GitHubError as exc:
319
+ raise GitHubError(pushed + str(exc)) from exc
320
+ outcome.pr = pr
321
+ report.pr_url = pr.url
322
+ (outcome.run_dir / "report.json").write_text(report.model_dump_json(indent=2), "utf-8")
323
+
324
+
325
+ def _fix_in_worktree(
326
+ wt: Worktree,
327
+ cfg: Config,
328
+ only: set[Severity] | None,
329
+ run_id: str,
330
+ run_dir: Path,
331
+ env: dict[str, str],
332
+ started: datetime,
333
+ dry_run: bool,
334
+ index: ReleaseIndex | None,
335
+ today: date | None,
336
+ imports: list[Path],
337
+ builder: ImageBuilder | None = None,
338
+ ) -> FixOutcome:
339
+ project = detect_project(wt.project_dir, base_branch=cfg.pr.base_branch)
340
+ project.commit_sha = wt.commit_sha
341
+ built_before = builder.build_and_scan(wt.project_dir, "before") if builder else []
342
+ before = scan_project(
343
+ project, cfg, run_id, run_dir / "raw-before", only, today=today,
344
+ imports=[*imports, *built_before],
345
+ ) # fmt: skip
346
+ graph = load_graph(project)
347
+ manifest_texts = [m.read_text(encoding="utf-8") for m in project.manifests()]
348
+ js = project.manager in JS_MANAGERS
349
+ js_lock = read_lock(project.manager, project.lockfile) if js else None
350
+ allows_one = js_manifest.manifest_allows if js else pyproject_allows
351
+
352
+ def allows_all(_text: str, package: str, version: str) -> bool:
353
+ """Every manifest (the root and each workspace member) allows ``version``."""
354
+ return all(allows_one(text, package, version) for text in manifest_texts)
355
+
356
+ plan = build_plan(
357
+ before.shown,
358
+ graph,
359
+ manifest_texts[0],
360
+ project.lockfile,
361
+ index or (NpmIndex(names=js_lock.names) if js_lock else PyPIIndex()),
362
+ cfg.allow_major_upgrades,
363
+ extras=before.below_threshold,
364
+ registry=js_lock.registry if js_lock else None,
365
+ manifest_allows=allows_all,
366
+ )
367
+ rank = _priority(before)
368
+ plan.upgrades.sort(key=lambda u: (-rank.get(u.package, 0), u.package))
369
+
370
+ fixer: UvFixer | PoetryFixer | JsFixer
371
+ if js:
372
+ fixer = JsFixer(
373
+ project.root, project.manager, project.lockfile, graph, env, project.members
374
+ )
375
+ elif project.manager == "poetry":
376
+ fixer = PoetryFixer(project.root, graph, env)
377
+ else:
378
+ fixer = UvFixer(project.root, graph, env, project.members)
379
+ resolvable, blocked = fixer.resolve_each(plan.upgrades)
380
+ if fixer.resolver_errors:
381
+ (run_dir / "logs").mkdir(parents=True, exist_ok=True)
382
+ (run_dir / "logs" / "resolver.log").write_text(
383
+ "".join(f"{pkg}: {msg}\n" for pkg, msg in fixer.resolver_errors.items()), "utf-8"
384
+ )
385
+ outcome = FixOutcome(
386
+ exit_code=ExitCode.OK, plan=plan, resolvable=resolvable, blocked=blocked, scan=before
387
+ )
388
+ if dry_run:
389
+ outcome.dry_run = True
390
+ return outcome
391
+
392
+ validator = Validator(
393
+ project.root, cfg.validation, project.manager, env, run_dir / "logs", project.members
394
+ )
395
+ fixer.restore()
396
+ # Nothing to try: skip the install and test run (and don't fail on tests already broken).
397
+ baseline = validator.run("baseline") if resolvable else None
398
+ if baseline is not None and not baseline.passed:
399
+ if baseline.failed_tests == [INSTALL_FAILED]:
400
+ raise FixError(
401
+ f"installing the project failed on {wt.ref} before any change "
402
+ f"(`{shlex.join(validator.install_cmd)}`). Log: {baseline.log_path}"
403
+ )
404
+ what = ", ".join(baseline.failed_tests) or "tests failed"
405
+ raise FixError(
406
+ f"tests already fail on {wt.ref} before any change ({what}); "
407
+ f"fix them first. Log: {baseline.log_path}"
408
+ )
409
+
410
+ counter = 0
411
+
412
+ def test(upgrades: list[Upgrade]) -> ValidationResult:
413
+ nonlocal counter
414
+ counter += 1
415
+ try:
416
+ fixer.apply(upgrades)
417
+ except LockError:
418
+ return ValidationResult(ran=False, passed=False, failed_tests=["<resolution failed>"])
419
+ return validator.run(f"try-{counter:02d}")
420
+
421
+ if validator.tests_enabled and cfg.validation.isolate_breakers:
422
+ iso = isolate_breakers(resolvable, test)
423
+ kept, breakers, final = iso.kept, iso.breakers, iso.final
424
+ outcome.test_runs = iso.test_runs
425
+ else:
426
+ final = test(resolvable) if resolvable else None
427
+ outcome.test_runs = 1 if resolvable else 0
428
+ if final is not None and not final.passed:
429
+ kept, breakers = [], {u.package: final for u in resolvable}
430
+ else:
431
+ kept, breakers = resolvable, {}
432
+
433
+ fixer.apply(kept) # leave exactly the kept upgrades in place
434
+ outcome.kept = kept
435
+ outcome.manifest = MANIFEST[project.manager]
436
+ outcome.manifest_changes = {
437
+ k: v for k, v in fixer.manifest_changes.items() if k in {u.package for u in kept}
438
+ }
439
+ changed = changed_files(wt)
440
+ expected = [project.lockfile.name, *(project.manifest_label(m) for m in project.manifests())]
441
+ unexpected = sorted(set(changed) - allowed_files(wt, expected))
442
+ if unexpected:
443
+ fixer.restore()
444
+ raise FixError(
445
+ f"files other than {MANIFEST[project.manager]} and the lockfile changed: {unexpected}"
446
+ )
447
+ outcome.changed = changed
448
+
449
+ # Rebuild from the fixed files and scan again: the rebuilt image decides what is gone.
450
+ built_after = built_before
451
+ if builder is not None and kept:
452
+ built_after = builder.build_and_scan(wt.project_dir, "after")
453
+ after = scan_project(
454
+ project, cfg, run_id, run_dir / "raw-after", only, today=today,
455
+ imports=[*imports, *built_after],
456
+ ) # fmt: skip
457
+ if builder is not None:
458
+ after_label = "after" if kept else "before"
459
+ outcome.image_check = compare(
460
+ builder.image_findings(before.findings, "before"),
461
+ builder.image_findings(after.findings, after_label),
462
+ list(cfg.image_scanners),
463
+ )
464
+ # An import finding whose lockfile version is now fixed is gone, as far as the PR goes.
465
+ present = [f for f in after.findings if not f.fixed_in_source]
466
+ present_keys = {f.key for f in present}
467
+ results = classify(
468
+ before.shown,
469
+ before.ignored,
470
+ before.below_threshold,
471
+ plan,
472
+ kept,
473
+ breakers,
474
+ blocked,
475
+ before.findings,
476
+ [f for f in after.shown if f.key in present_keys],
477
+ tests_ran=validator.tests_enabled,
478
+ after_all=present,
479
+ )
480
+ outcome.report = RunReport(
481
+ run_id=run_id,
482
+ repo=wt.repo_root.name,
483
+ commit_sha=wt.commit_sha,
484
+ started_at=started,
485
+ tool_versions=before.tool_versions,
486
+ findings_before=before.findings,
487
+ findings_after=after.findings,
488
+ results=results,
489
+ baseline=baseline,
490
+ final=final,
491
+ )
492
+ outcome.exit_code = exit_code(results)
493
+ (run_dir / "report.json").write_text(outcome.report.model_dump_json(indent=2), "utf-8")
494
+ return outcome
patchloop/scanner.py ADDED
@@ -0,0 +1,214 @@
1
+ """The `scan` pipeline: detect -> collect -> merge -> annotate -> filter."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import shutil
7
+ import uuid
8
+ from dataclasses import dataclass, field
9
+ from datetime import UTC, date, datetime, timedelta
10
+ from pathlib import Path
11
+
12
+ from patchloop.build import BuildSpec, build_image, remove_image
13
+ from patchloop.config import Config, IgnoreRule
14
+ from patchloop.detect import detect_project
15
+ from patchloop.enrich import enrich
16
+ from patchloop.images import leak_warning, scan_images
17
+ from patchloop.lockgraph import load_graph, project_lock_versions
18
+ from patchloop.models import Finding, Project, Severity, ecosystem_of
19
+ from patchloop.prioritize import always_fix, gate_severity, sort_key
20
+ from patchloop.proc import Runner
21
+ from patchloop.sources.imports import load_import
22
+ from patchloop.sources.merge import annotate, merge_findings
23
+ from patchloop.sources.osv import OsvSource
24
+
25
+
26
+ def cache_dir() -> Path:
27
+ base = os.environ.get("XDG_CACHE_HOME")
28
+ return (Path(base) if base else Path.home() / ".cache") / "patchloop"
29
+
30
+
31
+ def osv_db_dir() -> Path:
32
+ """Where the local OSV database lives (PATCHLOOP_OSV_DB overrides; the tests share one)."""
33
+ override = os.environ.get("PATCHLOOP_OSV_DB")
34
+ return Path(override) if override else cache_dir() / "osv-db"
35
+
36
+
37
+ def new_run_id(now: datetime | None = None) -> str:
38
+ stamp = (now or datetime.now(UTC)).strftime("%Y%m%dT%H%M%SZ")
39
+ return f"{stamp}-{uuid.uuid4().hex[:6]}"
40
+
41
+
42
+ KEEP_RUNS = timedelta(days=7)
43
+
44
+
45
+ def prune_runs(now: datetime | None = None) -> None:
46
+ """Delete run folders (logs, reports, raw scanner output) older than KEEP_RUNS."""
47
+ now = now or datetime.now(UTC)
48
+ runs = cache_dir() / "runs"
49
+ if not runs.is_dir():
50
+ return
51
+ for run in runs.iterdir():
52
+ try:
53
+ started = datetime.strptime(run.name[:16], "%Y%m%dT%H%M%SZ").replace(tzinfo=UTC)
54
+ except ValueError:
55
+ continue # not a run folder PatchLoop made
56
+ if now - started > KEEP_RUNS:
57
+ shutil.rmtree(run, ignore_errors=True)
58
+
59
+
60
+ @dataclass
61
+ class ScanResult:
62
+ project: Project
63
+ run_id: str
64
+ raw_dir: Path
65
+ findings: list[Finding]
66
+ """Every merged finding, sorted most severe first."""
67
+ shown: list[Finding] = field(default_factory=list)
68
+ """Findings at or above the threshold and not ignored."""
69
+ ignored: list[tuple[Finding, IgnoreRule]] = field(default_factory=list)
70
+ below_threshold: list[Finding] = field(default_factory=list)
71
+ expired_rules: list[IgnoreRule] = field(default_factory=list)
72
+ tool_versions: dict[str, str] = field(default_factory=dict)
73
+ imports: list[Path] = field(default_factory=list)
74
+ warnings: list[str] = field(default_factory=list)
75
+
76
+
77
+ def _matching_rule(f: Finding, rules: list[IgnoreRule]) -> IgnoreRule | None:
78
+ ids = set(f.aliases)
79
+ return next((r for r in rules if r.id in ids), None)
80
+
81
+
82
+ def apply_filters(
83
+ result: ScanResult,
84
+ cfg: Config,
85
+ only: set[Severity] | None = None,
86
+ today: date | None = None,
87
+ ) -> None:
88
+ today = today or date.today()
89
+ active = [r for r in cfg.ignore if not r.is_expired(today)]
90
+ result.expired_rules = [r for r in cfg.ignore if r.is_expired(today)]
91
+ for f in result.findings:
92
+ rule = _matching_rule(f, active)
93
+ if rule is not None:
94
+ result.ignored.append((f, rule))
95
+ elif not always_fix(f) and (
96
+ (only is not None and gate_severity(f) not in only and f.severity not in only)
97
+ or (only is None and gate_severity(f).rank < cfg.threshold.rank)
98
+ ):
99
+ result.below_threshold.append(f)
100
+ else:
101
+ result.shown.append(f)
102
+
103
+
104
+ def run_scan(
105
+ path: Path,
106
+ cfg: Config,
107
+ only: set[Severity] | None = None,
108
+ run: Runner | None = None,
109
+ today: date | None = None,
110
+ imports: list[Path] | None = None,
111
+ build_args: dict[str, str] | None = None,
112
+ ) -> ScanResult:
113
+ project = detect_project(path, base_branch=cfg.pr.base_branch)
114
+ prune_runs()
115
+ run_id = new_run_id()
116
+ raw = cache_dir() / "runs" / run_id
117
+ all_imports = [*(imports or []), *image_reports(cfg, raw / "images")]
118
+ tag = f"patchloop-{run_id.lower()}:scan"
119
+ built = False
120
+ build_warnings: list[str] = []
121
+ try:
122
+ if cfg.build is not None:
123
+ spec = BuildSpec(
124
+ project.root / cfg.build.dockerfile, project.root / cfg.build.context,
125
+ build_args or {},
126
+ ) # fmt: skip
127
+ build_image(spec, tag, raw / "logs" / "build.log")
128
+ built = True
129
+ scans = scan_images(
130
+ [tag], list(cfg.image_scanners), raw / "images", cfg.image_platform,
131
+ build_args or {},
132
+ ) # fmt: skip
133
+ all_imports += [s.report for s in scans]
134
+ leaked = {n for s in scans for n in s.leaked}
135
+ if leaked:
136
+ build_warnings.append(leak_warning(leaked))
137
+ result = scan_project(project, cfg, run_id, raw, only, run, today, imports=all_imports)
138
+ result.warnings += build_warnings
139
+ return result
140
+ finally:
141
+ if built:
142
+ remove_image(tag)
143
+
144
+
145
+ def image_reports(cfg: Config, out_dir: Path) -> list[Path]:
146
+ """Scan ``cfg.images`` with each of ``cfg.image_scanners``; return the reports."""
147
+ if not cfg.images:
148
+ return []
149
+ scans = scan_images(cfg.images, list(cfg.image_scanners), out_dir, cfg.image_platform)
150
+ return [s.report for s in scans]
151
+
152
+
153
+ def resolve_imports(project_root: Path, cfg: Config, extra: list[Path] | None) -> list[Path]:
154
+ """``imports:`` from patchloop.yml (relative to the project) plus --import files."""
155
+ paths = [p if p.is_absolute() else project_root / p for p in cfg.imports]
156
+ paths += [p.resolve() for p in extra or []]
157
+ return list(dict.fromkeys(p.resolve() for p in paths))
158
+
159
+
160
+ def scan_project(
161
+ project: Project,
162
+ cfg: Config,
163
+ run_id: str,
164
+ raw_dir: Path,
165
+ only: set[Severity] | None = None,
166
+ run: Runner | None = None,
167
+ today: date | None = None,
168
+ *,
169
+ imports: list[Path] | None = None,
170
+ ) -> ScanResult:
171
+ """Collect, merge, annotate and filter findings for an already-detected project."""
172
+ # Imported reports are read first: a bad file fails at once, not after a scan.
173
+ imported: list[Finding] = []
174
+ warnings: list[str] = []
175
+ imported_versions: dict[str, str] = {}
176
+ if imports:
177
+ lock = project_lock_versions(project)
178
+ lock_ecosystem = ecosystem_of(project.manager)
179
+ for path in imports:
180
+ imp = load_import(path, lock, lock_ecosystem)
181
+ imported += imp.findings
182
+ warnings += imp.warnings
183
+ if imp.tool_version:
184
+ imported_versions[imp.tool] = imp.tool_version
185
+ offline_db = osv_db_dir() if cfg.osv_offline else None
186
+ osv = OsvSource(raw_dir, run=run, offline_db=offline_db)
187
+ collected = osv.collect(project) + imported
188
+ findings = merge_findings(collected)
189
+ if cfg.enrich:
190
+ warnings += enrich(findings, cache_dir() / "enrich")
191
+ findings = annotate(findings, load_graph(project))
192
+ findings.sort(key=sort_key)
193
+ result = ScanResult(
194
+ project=project,
195
+ run_id=run_id,
196
+ raw_dir=raw_dir,
197
+ findings=findings,
198
+ imports=list(imports or []),
199
+ warnings=warnings,
200
+ )
201
+ result.tool_versions.update(imported_versions)
202
+ version = next(
203
+ (
204
+ h.tool_version
205
+ for f in findings
206
+ for h in f.sources
207
+ if h.tool == "osv-scanner" and h.tool_version
208
+ ),
209
+ None,
210
+ )
211
+ if version:
212
+ result.tool_versions["osv-scanner"] = version
213
+ apply_filters(result, cfg, only, today)
214
+ return result