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/__init__.py ADDED
@@ -0,0 +1,23 @@
1
+ """PatchLoop: scan -> prioritize -> fix -> test -> rescan -> one PR."""
2
+
3
+ from importlib.metadata import PackageNotFoundError, version
4
+ from typing import TYPE_CHECKING
5
+
6
+ if TYPE_CHECKING: # the real import happens on first use, in __getattr__ below
7
+ from patchloop.api import fix, scan
8
+
9
+ try:
10
+ __version__ = version("patchloop")
11
+ except PackageNotFoundError: # pragma: no cover - running from a source tree without install
12
+ __version__ = "0.0.0"
13
+
14
+ __all__ = ["__version__", "fix", "scan"]
15
+
16
+
17
+ def __getattr__(name: str) -> object:
18
+ # `from patchloop import scan, fix`, loaded on first use so `import patchloop` stays light.
19
+ if name in ("scan", "fix"):
20
+ from patchloop import api
21
+
22
+ return getattr(api, name)
23
+ raise AttributeError(f"module 'patchloop' has no attribute {name!r}")
patchloop/api.py ADDED
@@ -0,0 +1,110 @@
1
+ """Use PatchLoop from Python code instead of the command line.
2
+
3
+ from patchloop import scan, fix
4
+
5
+ result = scan("path/to/project", min_severity="MEDIUM")
6
+ for finding in result.shown:
7
+ print(finding.package, finding.installed_version, finding.advisory_id)
8
+
9
+ outcome = fix("path/to/project", push=False) # commit to a local branch only
10
+ print(outcome.exit_code, outcome.report.results if outcome.report else [])
11
+
12
+ Both take the same settings as ``patchloop.yml`` (as a :class:`Config`, a dict, or read from
13
+ the project folder) and return the same models the CLI uses. Nothing is printed.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ from pathlib import Path
19
+ from typing import Any
20
+
21
+ from patchloop.build import resolve_build_args
22
+ from patchloop.config import BuildConfig, Config, load_config
23
+ from patchloop.images import parse_scanners
24
+ from patchloop.models import Severity
25
+ from patchloop.runner import FixOutcome, run_fix
26
+ from patchloop.scanner import ScanResult, resolve_imports, run_scan
27
+
28
+
29
+ def _config(
30
+ path: Path,
31
+ config: Config | dict[str, Any] | None,
32
+ min_severity: str | None,
33
+ images: list[str] | None,
34
+ scanners: str | None,
35
+ build: bool,
36
+ ) -> Config:
37
+ if isinstance(config, Config):
38
+ cfg = config
39
+ elif isinstance(config, dict):
40
+ cfg = Config.model_validate(config)
41
+ else:
42
+ cfg = load_config(path)
43
+ update: dict[str, Any] = {}
44
+ if min_severity is not None:
45
+ update["severity_threshold"] = Severity(min_severity.upper()).value
46
+ if images:
47
+ update["images"] = list(dict.fromkeys([*cfg.images, *images]))
48
+ if scanners is not None:
49
+ update["image_scanners"] = parse_scanners(scanners)
50
+ if build and cfg.build is None:
51
+ update["build"] = BuildConfig()
52
+ return cfg.model_copy(update=update) if update else cfg
53
+
54
+
55
+ def _build_args(cfg: Config, given: list[str] | None) -> dict[str, str]:
56
+ if cfg.build is None:
57
+ if given:
58
+ raise ValueError("build_args need build=True (or `build:` in patchloop.yml)")
59
+ return {}
60
+ return resolve_build_args(cfg.build.args, given or [])
61
+
62
+
63
+ def scan(
64
+ path: str | Path = ".",
65
+ *,
66
+ config: Config | dict[str, Any] | None = None,
67
+ min_severity: str | None = None,
68
+ imports: list[str | Path] | None = None,
69
+ images: list[str] | None = None,
70
+ scanners: str | None = None,
71
+ build: bool = False,
72
+ build_args: list[str] | None = None,
73
+ ) -> ScanResult:
74
+ """Find vulnerable dependencies. Changes nothing in the project."""
75
+ root = Path(path).resolve()
76
+ cfg = _config(root, config, min_severity, images, scanners, build)
77
+ args = _build_args(cfg, build_args)
78
+ extra = [Path(p) for p in imports or []]
79
+ return run_scan(root, cfg, imports=resolve_imports(root, cfg, extra), build_args=args)
80
+
81
+
82
+ def fix(
83
+ path: str | Path = ".",
84
+ *,
85
+ config: Config | dict[str, Any] | None = None,
86
+ min_severity: str | None = None,
87
+ push: bool = True,
88
+ dry_run: bool = False,
89
+ imports: list[str | Path] | None = None,
90
+ images: list[str] | None = None,
91
+ scanners: str | None = None,
92
+ build: bool = False,
93
+ build_args: list[str] | None = None,
94
+ ) -> FixOutcome:
95
+ """Upgrade, test, rescan; then open or update the PR (``push``) or commit locally."""
96
+ root = Path(path).resolve()
97
+ cfg = _config(root, config, min_severity, images, scanners, build)
98
+ args = _build_args(cfg, build_args)
99
+ extra = [Path(p) for p in imports or []]
100
+ return run_fix(
101
+ root,
102
+ cfg,
103
+ dry_run=dry_run,
104
+ push_pr=push,
105
+ imports=resolve_imports(root, cfg, extra),
106
+ build_args=args,
107
+ )
108
+
109
+
110
+ __all__ = ["Config", "FixOutcome", "ScanResult", "fix", "scan"]
patchloop/build.py ADDED
@@ -0,0 +1,118 @@
1
+ """Build the project's container image with Docker, so it can be scanned before and after a fix.
2
+
3
+ Build-arg values never reach a command line, a log or a report: each value is put in the
4
+ build process's environment and Docker is given only ``--build-arg NAME``, which makes it
5
+ read the value from there. The build log is kept in the run folder with any value that
6
+ still shows up replaced by ``***``.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import contextlib
12
+ import os
13
+ from collections import Counter
14
+ from dataclasses import dataclass, field
15
+ from pathlib import Path
16
+
17
+ from patchloop import proc
18
+ from patchloop.images import MIN_SECRET_LEN
19
+ from patchloop.models import Finding, Severity
20
+ from patchloop.proc import ToolNotFoundError, ToolTimeoutError
21
+
22
+ BUILD_TIMEOUT_S = 3600
23
+
24
+
25
+ class BuildError(Exception):
26
+ """docker build failed; the message names the log."""
27
+
28
+
29
+ @dataclass(frozen=True)
30
+ class BuildSpec:
31
+ dockerfile: Path
32
+ context: Path
33
+ args: dict[str, str] = field(default_factory=dict)
34
+ """NAME -> value. Values are secrets until proven otherwise."""
35
+
36
+
37
+ def resolve_build_args(names: list[str], cli: list[str]) -> dict[str, str]:
38
+ """Config names (values from the environment) plus ``NAME=VALUE`` / ``NAME`` from the CLI."""
39
+ out: dict[str, str] = {}
40
+ for item in [*names, *cli]:
41
+ name, sep, value = item.partition("=")
42
+ name = name.strip()
43
+ if not name:
44
+ continue
45
+ if sep:
46
+ out[name] = value
47
+ elif name in os.environ:
48
+ out[name] = os.environ[name]
49
+ else:
50
+ raise BuildError(f"build arg {name} has no value: set it in the environment")
51
+ return out
52
+
53
+
54
+ def _redact(text: str, values: list[str]) -> str:
55
+ for v in sorted((v for v in values if len(v) >= MIN_SECRET_LEN), key=len, reverse=True):
56
+ text = text.replace(v, "***")
57
+ return text
58
+
59
+
60
+ def build_image(spec: BuildSpec, tag: str, log: Path) -> None:
61
+ if not spec.dockerfile.is_file():
62
+ raise BuildError(f"no Dockerfile at {spec.dockerfile}")
63
+ cmd = ["docker", "build", "--progress", "plain", "-f", str(spec.dockerfile), "-t", tag]
64
+ for name in spec.args:
65
+ cmd += ["--build-arg", name]
66
+ cmd.append(str(spec.context))
67
+ env = {**os.environ, **spec.args, "DOCKER_BUILDKIT": "1"}
68
+ try:
69
+ result = proc.run(cmd, timeout=BUILD_TIMEOUT_S, env=env)
70
+ except ToolNotFoundError as exc:
71
+ raise BuildError("docker is not installed; it is needed for --build") from exc
72
+ except ToolTimeoutError as exc:
73
+ raise BuildError(f"docker build timed out after {BUILD_TIMEOUT_S // 60} min") from exc
74
+ log.parent.mkdir(parents=True, exist_ok=True)
75
+ secrets = list(spec.args.values())
76
+ log.write_text(_redact(result.stdout + result.stderr, secrets), "utf-8")
77
+ if not result.ok:
78
+ raise BuildError(f"docker build failed (exit {result.returncode}); log: {log}")
79
+
80
+
81
+ def remove_image(tag: str) -> None:
82
+ with contextlib.suppress(ToolNotFoundError, ToolTimeoutError):
83
+ proc.run(["docker", "image", "rm", "--force", tag], timeout=120)
84
+
85
+
86
+ @dataclass
87
+ class ImageCheck:
88
+ """Findings in the built image before and after the fix."""
89
+
90
+ scanners: list[str]
91
+ before: Counter[Severity] = field(default_factory=Counter)
92
+ after: Counter[Severity] = field(default_factory=Counter)
93
+ gone: list[str] = field(default_factory=list)
94
+ """'package advisory' of findings in the first image and not in the rebuilt one."""
95
+
96
+ @property
97
+ def total_before(self) -> int:
98
+ return sum(self.before.values())
99
+
100
+ @property
101
+ def total_after(self) -> int:
102
+ return sum(self.after.values())
103
+
104
+
105
+ def _issues(findings: list[Finding]) -> dict[tuple[str, str], Severity]:
106
+ return {(f.package, f.advisory_id): f.severity for f in findings}
107
+
108
+
109
+ def compare(before: list[Finding], after: list[Finding], scanners: list[str]) -> ImageCheck:
110
+ b, a = _issues(before), _issues(after)
111
+ after_ids = {(pkg, alias) for f in after for alias in f.aliases for pkg in [f.package]}
112
+ check = ImageCheck(scanners=scanners)
113
+ check.before.update(b.values())
114
+ check.after.update(a.values())
115
+ for f in before:
116
+ if not any((f.package, alias) in after_ids for alias in f.aliases):
117
+ check.gone.append(f"{f.package} {f.advisory_id}")
118
+ return check
patchloop/classify.py ADDED
@@ -0,0 +1,137 @@
1
+ """Give every finding exactly one result state."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from patchloop.config import IgnoreRule
6
+ from patchloop.models import (
7
+ ExitCode,
8
+ Finding,
9
+ FixResult,
10
+ FixStatus,
11
+ Upgrade,
12
+ ValidationResult,
13
+ normalize_package,
14
+ )
15
+ from patchloop.plan import Plan
16
+
17
+
18
+ def same_issue(a: Finding, b: Finding) -> bool:
19
+ """Same package and overlapping advisory IDs. The version is deliberately ignored."""
20
+ return (
21
+ a.ecosystem == b.ecosystem
22
+ and normalize_package(a.package, a.ecosystem) == normalize_package(b.package, b.ecosystem)
23
+ and bool(set(a.aliases) & set(b.aliases))
24
+ )
25
+
26
+
27
+ def _tests_note(result: ValidationResult) -> str:
28
+ names = ", ".join(result.failed_tests) or "tests failed"
29
+ return f"breaks tests: {names}"
30
+
31
+
32
+ def classify(
33
+ shown: list[Finding],
34
+ ignored: list[tuple[Finding, IgnoreRule]],
35
+ below_threshold: list[Finding],
36
+ plan: Plan,
37
+ kept: list[Upgrade],
38
+ breakers: dict[str, ValidationResult],
39
+ blocked: dict[str, str],
40
+ before_all: list[Finding],
41
+ after_shown: list[Finding],
42
+ tests_ran: bool,
43
+ *,
44
+ after_all: list[Finding] | None = None,
45
+ ) -> list[FixResult]:
46
+ """``after_*`` must already exclude findings the lockfile now fixes (fixed_in_source)."""
47
+ results: list[FixResult] = []
48
+ planned = {u.package: u for u in plan.upgrades}
49
+ applied = {u.package: u for u in kept}
50
+ # npm can install one package at several versions: match the upgrade for this version.
51
+ planned_at = {(u.package, u.from_version): u for u in plan.upgrades}
52
+ applied_at = {(u.package, u.from_version): u for u in kept}
53
+ fixed_status = FixStatus.FIXED_AND_VALIDATED if tests_ran else FixStatus.FIXED_NOT_TESTED
54
+ after_everything = after_all if after_all is not None else after_shown
55
+ for f, rule in ignored:
56
+ results.append(
57
+ FixResult(
58
+ finding_key=f.key,
59
+ status=FixStatus.SKIPPED,
60
+ note=f"ignored in config until {rule.expires}: {rule.reason}",
61
+ )
62
+ )
63
+ for f in below_threshold:
64
+ up = applied.get(normalize_package(f.package, f.ecosystem))
65
+ rode = up is not None and f.key in up.finding_keys
66
+ if rode and not any(same_issue(f, a) for a in after_everything):
67
+ results.append(
68
+ FixResult(
69
+ finding_key=f.key,
70
+ status=fixed_status,
71
+ upgrade=up,
72
+ note="below the threshold; fixed by the same upgrade",
73
+ )
74
+ )
75
+ else:
76
+ results.append(
77
+ FixResult(
78
+ finding_key=f.key, status=FixStatus.SKIPPED, note="below severity threshold"
79
+ )
80
+ )
81
+
82
+ for f in shown:
83
+ pkg = normalize_package(f.package, f.ecosystem)
84
+ at = (pkg, f.installed_version)
85
+ upgrade = applied_at.get(at) or planned_at.get(at) or applied.get(pkg) or planned.get(pkg)
86
+ if f.fixed_in_source:
87
+ status, note = (
88
+ FixStatus.FIXED_IN_SOURCE,
89
+ f"the lockfile already has {f.installed_version}; rebuild the image",
90
+ )
91
+ elif not f.in_lockfile:
92
+ status, note = FixStatus.OUT_OF_SCOPE, "needs a base-image or Dockerfile change"
93
+ elif f.key in plan.no_fix:
94
+ status, note = FixStatus.NO_SAFE_FIX, plan.no_fix[f.key]
95
+ elif upgrade is None:
96
+ status, note = FixStatus.NO_SAFE_FIX, "no upgrade was planned"
97
+ elif at not in applied_at and pkg in breakers:
98
+ status, note = FixStatus.FIXED_BUT_TESTS_FAILED, _tests_note(breakers[pkg])
99
+ elif at not in applied_at and pkg in blocked:
100
+ status, note = FixStatus.STILL_PRESENT, blocked[pkg]
101
+ elif pkg in applied:
102
+ # Other copies of the package (npm: several versions) may still be vulnerable;
103
+ # only a copy at a version this upgrade did not replace counts against it.
104
+ others = {u.from_version for u in plan.upgrades if u.package == pkg} - {
105
+ upgrade.from_version
106
+ }
107
+ if any(same_issue(f, a) and a.installed_version not in others for a in after_shown):
108
+ status, note = (
109
+ FixStatus.STILL_PRESENT,
110
+ f"still reported after upgrading to {upgrade.to_version}",
111
+ )
112
+ else:
113
+ status, note = fixed_status, ""
114
+ if upgrade.method == "parent-upgrade":
115
+ note = f"upgraded together with {', '.join(upgrade.parents)}"
116
+ else:
117
+ status, note = FixStatus.STILL_PRESENT, "upgrade was not applied"
118
+ results.append(FixResult(finding_key=f.key, status=status, upgrade=upgrade, note=note))
119
+
120
+ for a in after_shown:
121
+ if not any(same_issue(a, b) for b in before_all):
122
+ results.append(
123
+ FixResult(
124
+ finding_key=a.key,
125
+ status=FixStatus.INTRODUCED,
126
+ note=f"{a.package} {a.installed_version} is affected by {a.advisory_id} "
127
+ "after the upgrades",
128
+ )
129
+ )
130
+ return results
131
+
132
+
133
+ def exit_code(results: list[FixResult]) -> ExitCode:
134
+ remaining = [
135
+ r for r in results if r.status not in (FixStatus.SKIPPED,) and not r.status.counts_as_fixed
136
+ ]
137
+ return ExitCode.FINDINGS_REMAIN if remaining else ExitCode.OK