stackparity 1.0.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.
- stackparity/__init__.py +17 -0
- stackparity/_engine/agents/investigator.py +294 -0
- stackparity/_engine/agents/memory_agent.py +37 -0
- stackparity/_engine/agents/pipeline_agent.py +152 -0
- stackparity/_engine/agents/remediation_agent.py +248 -0
- stackparity/_engine/agents/runtime.py +177 -0
- stackparity/_engine/agents/specialists.py +709 -0
- stackparity/_engine/agents/suspicious_change_agent.py +1275 -0
- stackparity/_engine/cli/__init__.py +2 -0
- stackparity/_engine/cli/main.py +1252 -0
- stackparity/_engine/cli/remediate.py +461 -0
- stackparity/_engine/cli/term.py +44 -0
- stackparity/_engine/config/__init__.py +0 -0
- stackparity/_engine/config/constants.py +88 -0
- stackparity/_engine/config/loader.py +155 -0
- stackparity/_engine/config/settings.py +108 -0
- stackparity/_engine/containers/__init__.py +12 -0
- stackparity/_engine/containers/discovery.py +143 -0
- stackparity/_engine/containers/models.py +72 -0
- stackparity/_engine/containers/trivy_image_scanner.py +165 -0
- stackparity/_engine/core/__init__.py +0 -0
- stackparity/_engine/core/capabilities.py +107 -0
- stackparity/_engine/core/finding_schema.py +305 -0
- stackparity/_engine/core/git_manager.py +206 -0
- stackparity/_engine/core/http.py +64 -0
- stackparity/_engine/core/models.py +109 -0
- stackparity/_engine/core/netpolicy.py +242 -0
- stackparity/_engine/core/plugins.py +43 -0
- stackparity/_engine/core/repository_inspector.py +243 -0
- stackparity/_engine/core/safe_env.py +48 -0
- stackparity/_engine/core/scan_orchestrator.py +289 -0
- stackparity/_engine/core/scan_state.py +58 -0
- stackparity/_engine/core/url_validator.py +135 -0
- stackparity/_engine/ecosystems/__init__.py +1 -0
- stackparity/_engine/ecosystems/registry.py +138 -0
- stackparity/_engine/evidence/__init__.py +1 -0
- stackparity/_engine/evidence/store.py +65 -0
- stackparity/_engine/explainability/__init__.py +0 -0
- stackparity/_engine/explainability/evidence_formatter.py +30 -0
- stackparity/_engine/explainability/explanation_engine.py +132 -0
- stackparity/_engine/explainability/explanation_validator.py +54 -0
- stackparity/_engine/explainability/prompt_templates.py +18 -0
- stackparity/_engine/graph/__init__.py +0 -0
- stackparity/_engine/graph/dependency_tracer.py +86 -0
- stackparity/_engine/graph/graph_builder.py +165 -0
- stackparity/_engine/graph/graph_diff.py +57 -0
- stackparity/_engine/graph/graph_exporter.py +194 -0
- stackparity/_engine/graph/graph_validator.py +46 -0
- stackparity/_engine/graph/impact_analyzer.py +23 -0
- stackparity/_engine/graph/tree_view.py +185 -0
- stackparity/_engine/intel/__init__.py +0 -0
- stackparity/_engine/intel/epss.py +53 -0
- stackparity/_engine/llm/__init__.py +1 -0
- stackparity/_engine/llm/client.py +138 -0
- stackparity/_engine/monitor/__init__.py +0 -0
- stackparity/_engine/monitor/watch.py +171 -0
- stackparity/_engine/non_cve/__init__.py +7 -0
- stackparity/_engine/non_cve/base.py +62 -0
- stackparity/_engine/non_cve/iac.py +144 -0
- stackparity/_engine/non_cve/sast.py +272 -0
- stackparity/_engine/non_cve/supply_chain.py +147 -0
- stackparity/_engine/orchestration/__init__.py +1 -0
- stackparity/_engine/orchestration/pipeline.py +279 -0
- stackparity/_engine/orchestration/supervisor.py +167 -0
- stackparity/_engine/pipeline_analysis/__init__.py +0 -0
- stackparity/_engine/pipeline_analysis/analyzer.py +90 -0
- stackparity/_engine/pipeline_analysis/ci.py +189 -0
- stackparity/_engine/pipeline_analysis/ci_adapters/__init__.py +24 -0
- stackparity/_engine/pipeline_analysis/ci_adapters/azure_pipelines.py +221 -0
- stackparity/_engine/pipeline_analysis/ci_adapters/base.py +239 -0
- stackparity/_engine/pipeline_analysis/ci_adapters/circleci.py +176 -0
- stackparity/_engine/pipeline_analysis/ci_adapters/github_actions.py +356 -0
- stackparity/_engine/pipeline_analysis/ci_adapters/gitlab_ci.py +268 -0
- stackparity/_engine/pipeline_analysis/ci_adapters/jenkins.py +180 -0
- stackparity/_engine/pipeline_analysis/ci_adapters/registry.py +80 -0
- stackparity/_engine/pipeline_analysis/ci_models.py +72 -0
- stackparity/_engine/pipeline_analysis/dockerfile.py +235 -0
- stackparity/_engine/pipeline_analysis/eol.py +62 -0
- stackparity/_engine/pipeline_analysis/models.py +37 -0
- stackparity/_engine/policy/__init__.py +0 -0
- stackparity/_engine/policy/engine.py +216 -0
- stackparity/_engine/policy/resources/default.yaml +56 -0
- stackparity/_engine/policy/resources/strict.yaml +35 -0
- stackparity/_engine/reachability/__init__.py +0 -0
- stackparity/_engine/reachability/app_reachability.py +186 -0
- stackparity/_engine/reachability/scanners.py +215 -0
- stackparity/_engine/remediation/__init__.py +0 -0
- stackparity/_engine/remediation/adapters.py +198 -0
- stackparity/_engine/remediation/apply_local.py +309 -0
- stackparity/_engine/remediation/code_fixes.py +383 -0
- stackparity/_engine/remediation/compat.py +156 -0
- stackparity/_engine/remediation/container_plan.py +127 -0
- stackparity/_engine/remediation/delivery.py +31 -0
- stackparity/_engine/remediation/export.py +44 -0
- stackparity/_engine/remediation/lifecycle.py +623 -0
- stackparity/_engine/remediation/local_trial.py +358 -0
- stackparity/_engine/remediation/patchers.py +215 -0
- stackparity/_engine/remediation/planner.py +285 -0
- stackparity/_engine/remediation/pr_template_engine.py +234 -0
- stackparity/_engine/remediation/reachability_impact.py +147 -0
- stackparity/_engine/remediation/versions.py +92 -0
- stackparity/_engine/remediation/whatif.py +64 -0
- stackparity/_engine/remediation/worktree_pr.py +434 -0
- stackparity/_engine/reporting/__init__.py +0 -0
- stackparity/_engine/reporting/counts.py +63 -0
- stackparity/_engine/reporting/fix_pdf.py +343 -0
- stackparity/_engine/reporting/fix_report.py +135 -0
- stackparity/_engine/reporting/json_exporter.py +61 -0
- stackparity/_engine/reporting/report_generator.py +200 -0
- stackparity/_engine/reporting/sarif.py +71 -0
- stackparity/_engine/reporting/vex.py +57 -0
- stackparity/_engine/reporting/view.py +166 -0
- stackparity/_engine/risk_analysis/__init__.py +0 -0
- stackparity/_engine/risk_analysis/contextual_scorer.py +253 -0
- stackparity/_engine/risk_analysis/evidence_collector.py +62 -0
- stackparity/_engine/risk_analysis/evidence_normalizer.py +37 -0
- stackparity/_engine/risk_analysis/finding_correlator.py +90 -0
- stackparity/_engine/risk_analysis/function_impact.py +184 -0
- stackparity/_engine/risk_analysis/production_context.py +252 -0
- stackparity/_engine/risk_analysis/risk_rules.py +81 -0
- stackparity/_engine/risk_analysis/risk_scorer.py +390 -0
- stackparity/_engine/sandbox/__init__.py +0 -0
- stackparity/_engine/sandbox/runner.py +142 -0
- stackparity/_engine/sbom/__init__.py +0 -0
- stackparity/_engine/sbom/adapters/__init__.py +19 -0
- stackparity/_engine/sbom/adapters/builtin.py +29 -0
- stackparity/_engine/sbom/adapters/syft.py +26 -0
- stackparity/_engine/sbom/adapters/trivy.py +76 -0
- stackparity/_engine/sbom/builtin_generator.py +227 -0
- stackparity/_engine/sbom/cyclonedx_validator.py +166 -0
- stackparity/_engine/sbom/exporters.py +153 -0
- stackparity/_engine/sbom/fusion/__init__.py +5 -0
- stackparity/_engine/sbom/fusion/engine.py +315 -0
- stackparity/_engine/sbom/fusion/hashes.py +47 -0
- stackparity/_engine/sbom/fusion/ledger.py +96 -0
- stackparity/_engine/sbom/fusion/registries.py +271 -0
- stackparity/_engine/sbom/fusion/resolver.py +143 -0
- stackparity/_engine/sbom/fusion/writer.py +114 -0
- stackparity/_engine/sbom/lockfile_analyzer.py +114 -0
- stackparity/_engine/sbom/merge.py +71 -0
- stackparity/_engine/sbom/package_extractors/common.py +104 -0
- stackparity/_engine/sbom/package_extractors/manifests.py +101 -0
- stackparity/_engine/sbom/package_extractors/npm.py +206 -0
- stackparity/_engine/sbom/package_extractors/others.py +267 -0
- stackparity/_engine/sbom/package_extractors/python.py +143 -0
- stackparity/_engine/sbom/quality_analyzer.py +191 -0
- stackparity/_engine/sbom/scanner_engine.py +98 -0
- stackparity/_engine/sbom/syft_runner.py +100 -0
- stackparity/_engine/sbom/tool_locator.py +69 -0
- stackparity/_engine/sbom/trivy_runner.py +82 -0
- stackparity/_engine/storage/__init__.py +0 -0
- stackparity/_engine/storage/cache.py +56 -0
- stackparity/_engine/storage/database.py +295 -0
- stackparity/_engine/storage/memory.py +146 -0
- stackparity/_engine/suspicious_changes/__init__.py +12 -0
- stackparity/_engine/suspicious_changes/analyzer.py +1022 -0
- stackparity/_engine/suspicious_changes/change_correlation.py +861 -0
- stackparity/_engine/suspicious_changes/lifecycle_script_detector.py +263 -0
- stackparity/_engine/suspicious_changes/lockfile_change_detector.py +316 -0
- stackparity/_engine/suspicious_changes/manifest_diff_detector.py +251 -0
- stackparity/_engine/suspicious_changes/package_risk.py +78 -0
- stackparity/_engine/suspicious_changes/popular_packages.py +94 -0
- stackparity/_engine/suspicious_changes/registry_detector.py +354 -0
- stackparity/_engine/suspicious_changes/suspicious_models.py +57 -0
- stackparity/_engine/suspicious_changes/typosquatting_detector.py +298 -0
- stackparity/_engine/tools/__init__.py +1 -0
- stackparity/_engine/tools/builtin.py +93 -0
- stackparity/_engine/tools/registry.py +66 -0
- stackparity/_engine/ui/__init__.py +0 -0
- stackparity/_engine/ui/components/__init__.py +0 -0
- stackparity/_engine/ui/components/common.py +238 -0
- stackparity/_engine/ui/components/live_progress.py +157 -0
- stackparity/_engine/ui/components/memory_panel.py +82 -0
- stackparity/_engine/ui/pages/__init__.py +0 -0
- stackparity/_engine/ui/pages/agents_page.py +76 -0
- stackparity/_engine/ui/pages/architecture_page.py +44 -0
- stackparity/_engine/ui/pages/fixes_page.py +98 -0
- stackparity/_engine/ui/pages/graph_page.py +203 -0
- stackparity/_engine/ui/pages/health_page.py +117 -0
- stackparity/_engine/ui/pages/monitor_page.py +67 -0
- stackparity/_engine/ui/pages/pipeline_page.py +219 -0
- stackparity/_engine/ui/pages/remediation_page.py +409 -0
- stackparity/_engine/ui/pages/reports_page.py +54 -0
- stackparity/_engine/ui/pages/sbom_page.py +210 -0
- stackparity/_engine/ui/pages/scan_page.py +131 -0
- stackparity/_engine/ui/pages/suspicious_page.py +551 -0
- stackparity/_engine/ui/pages/vulns_page.py +201 -0
- stackparity/_engine/ui/state.py +116 -0
- stackparity/_engine/ui/theme.py +201 -0
- stackparity/_engine/ui/visualizations/__init__.py +0 -0
- stackparity/_engine/ui/visualizations/graphs.py +373 -0
- stackparity/_engine/vulnerability/__init__.py +0 -0
- stackparity/_engine/vulnerability/cvss.py +58 -0
- stackparity/_engine/vulnerability/kev_client.py +47 -0
- stackparity/_engine/vulnerability/nvd_client.py +74 -0
- stackparity/_engine/vulnerability/osv_client.py +139 -0
- stackparity/_engine/vulnerability/remediation_engine.py +50 -0
- stackparity/_engine/vulnerability/verification.py +94 -0
- stackparity/_engine/vulnerability/version_matcher.py +299 -0
- stackparity/_engine/vulnerability/vulnerability_correlator.py +303 -0
- stackparity/_engine/vulnerability/vulnerability_models.py +64 -0
- stackparity/cli.py +30 -0
- stackparity/dashboard_app.py +95 -0
- stackparity/web_dist/assets/index-DRJYw2Du.css +1 -0
- stackparity/web_dist/assets/index-Q6LLpbEi.js +495 -0
- stackparity/web_dist/index.html +13 -0
- stackparity/web_server.py +533 -0
- stackparity-1.0.0.dist-info/METADATA +204 -0
- stackparity-1.0.0.dist-info/RECORD +212 -0
- stackparity-1.0.0.dist-info/WHEEL +4 -0
- stackparity-1.0.0.dist-info/entry_points.txt +2 -0
- stackparity-1.0.0.dist-info/licenses/LICENSE +201 -0
|
@@ -0,0 +1,358 @@
|
|
|
1
|
+
"""Clone -> apply -> test -> validate, for the legacy dashboard's read-only "Resolve" preview of a local-folder scan.
|
|
2
|
+
|
|
3
|
+
``run_trial`` never touches the real folder. It copies the project into a scratch clone under StackParity's home, applies the
|
|
4
|
+
proposed fix there (manifest patch + lockfile refresh), rescans the clone and optionally runs the project's own build/tests in
|
|
5
|
+
the Docker sandbox. Writing changes into the real folder is not done here: that goes through ``remediation.lifecycle`` (exact
|
|
6
|
+
diff review, approval bound to the revision and patch, isolated validation, a final confirmation), from
|
|
7
|
+
``stackparity fix --apply --to-working-tree`` or the dashboard.
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import hashlib
|
|
12
|
+
import json
|
|
13
|
+
import os
|
|
14
|
+
import shutil
|
|
15
|
+
import stat
|
|
16
|
+
import subprocess
|
|
17
|
+
import tempfile
|
|
18
|
+
import time
|
|
19
|
+
import uuid
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
from typing import Any, Callable, Optional
|
|
22
|
+
|
|
23
|
+
from config.constants import IGNORED_DIRS
|
|
24
|
+
from config.settings import Settings, get_settings
|
|
25
|
+
from remediation.apply_local import _store, apply_in_place
|
|
26
|
+
|
|
27
|
+
BLOCKING = ("CRITICAL", "HIGH")
|
|
28
|
+
SKIP = set(IGNORED_DIRS) | {".guardian"}
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _rm(path: Path, tries: int = 4) -> bool:
|
|
32
|
+
"""Remove a directory tree on Windows too. Copies of OneDrive-synced folders carry the read-only attribute on directories, which
|
|
33
|
+
makes rmdir fail with 'Access denied'; clear it first, retry while sync/antivirus hold files, and finally fall back to ``rmdir /s /q``."""
|
|
34
|
+
path = Path(path)
|
|
35
|
+
for n in range(tries):
|
|
36
|
+
if not path.exists():
|
|
37
|
+
return True
|
|
38
|
+
for cur, dirs, files in os.walk(path):
|
|
39
|
+
for name in dirs + files:
|
|
40
|
+
try:
|
|
41
|
+
os.chmod(os.path.join(cur, name), stat.S_IWRITE | stat.S_IREAD)
|
|
42
|
+
except OSError:
|
|
43
|
+
pass
|
|
44
|
+
try:
|
|
45
|
+
os.chmod(path, stat.S_IWRITE | stat.S_IREAD)
|
|
46
|
+
except OSError:
|
|
47
|
+
pass
|
|
48
|
+
shutil.rmtree(path, ignore_errors=True)
|
|
49
|
+
if not path.exists():
|
|
50
|
+
return True
|
|
51
|
+
if os.name == "nt":
|
|
52
|
+
try:
|
|
53
|
+
subprocess.run(["cmd", "/c", "rmdir", "/s", "/q", str(path)], capture_output=True, timeout=60, shell=False)
|
|
54
|
+
except (OSError, subprocess.TimeoutExpired):
|
|
55
|
+
pass
|
|
56
|
+
if not path.exists():
|
|
57
|
+
return True
|
|
58
|
+
time.sleep(0.4 * (n + 1))
|
|
59
|
+
return not path.exists()
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _sha(p: Path) -> Optional[str]:
|
|
63
|
+
try:
|
|
64
|
+
return hashlib.sha256(p.read_bytes()).hexdigest()
|
|
65
|
+
except OSError:
|
|
66
|
+
return None
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _trial_dir(root: Path, rem: dict) -> Path:
|
|
70
|
+
return _store(root) / "trials" / "".join(c if c.isalnum() or c in "-_." else "_" for c in rem["id"])
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _fingerprint(root: Path, rem: dict, with_tests: bool) -> str:
|
|
74
|
+
diff = (rem.get("patch") or {}).get("diff", "")
|
|
75
|
+
manifest = (rem.get("patch") or {}).get("path", "")
|
|
76
|
+
return hashlib.sha256(f"{diff}|{_sha(root / manifest) if manifest else ''}|{with_tests}".encode()).hexdigest()[:20]
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _copy_project(root: Path, dest: Path, max_bytes: int) -> int:
|
|
80
|
+
total = 0
|
|
81
|
+
|
|
82
|
+
def ignore(d: str, names: list[str]) -> set[str]:
|
|
83
|
+
nonlocal total
|
|
84
|
+
skip = {n for n in names if n in SKIP or (Path(d) / n).is_symlink()}
|
|
85
|
+
for n in names:
|
|
86
|
+
if n in skip:
|
|
87
|
+
continue
|
|
88
|
+
p = Path(d) / n
|
|
89
|
+
if p.is_file():
|
|
90
|
+
total += p.stat().st_size
|
|
91
|
+
if total > max_bytes:
|
|
92
|
+
raise ValueError(f"project is larger than {max_bytes // (1024 * 1024)} MB (excluding node_modules, .git, build output); validate a smaller folder")
|
|
93
|
+
return skip
|
|
94
|
+
|
|
95
|
+
shutil.copytree(root, dest, ignore=ignore, symlinks=False)
|
|
96
|
+
return total
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _finding_keys(vulns: list[dict]) -> dict[tuple, dict]:
|
|
100
|
+
return {(v.get("package_name"), v.get("installed_version"), v.get("primary_id")): v for v in vulns or []}
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _compare(rem: dict, before: list[dict], after: list[dict]) -> dict[str, Any]:
|
|
104
|
+
b, a = _finding_keys(before), _finding_keys(after)
|
|
105
|
+
# the fixed package's version changes, so also match on (package, advisory id)
|
|
106
|
+
a_ids = {(k[0], k[2]) for k in a}
|
|
107
|
+
b_ids = {(k[0], k[2]) for k in b}
|
|
108
|
+
fixed = [v for k, v in b.items() if (k[0], k[2]) not in a_ids]
|
|
109
|
+
new = [v for k, v in a.items() if (k[0], k[2]) not in b_ids]
|
|
110
|
+
remaining = [v for k, v in a.items() if (k[0], k[2]) in b_ids]
|
|
111
|
+
brief = lambda v: {"package": v.get("package_name"), "version": v.get("installed_version"), "id": v.get("primary_id"), "severity": v.get("severity")} # noqa: E731
|
|
112
|
+
return {"before": len(b), "after": len(a), "fixed": [brief(v) for v in fixed], "remaining": [brief(v) for v in remaining], "new": [brief(v) for v in new]}
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _keep_validated(out: dict, res: dict, clone: Path, tdir: Path, root: Path) -> None:
|
|
116
|
+
"""Keep only the tested files, with the hashes of the originals, so Accept applies exactly what was validated."""
|
|
117
|
+
vdir = tdir / "validated"
|
|
118
|
+
files: dict[str, dict] = {}
|
|
119
|
+
for rel in res["backups"]:
|
|
120
|
+
src = clone / rel
|
|
121
|
+
dst = vdir / rel
|
|
122
|
+
dst.parent.mkdir(parents=True, exist_ok=True)
|
|
123
|
+
if src.exists():
|
|
124
|
+
shutil.copy2(src, dst)
|
|
125
|
+
files[rel] = {"base_sha": _sha(root / rel), "new_sha": _sha(src)}
|
|
126
|
+
out["files"] = files
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def run_trial(root: Path | str, rem: dict, original: dict, settings: Settings | None = None, with_tests: bool = False,
|
|
130
|
+
progress: Optional[Callable[[str], None]] = None) -> dict[str, Any]:
|
|
131
|
+
"""Validate ``rem`` on a scratch clone of ``root``. ``original`` is the stored scan result the proposal came from."""
|
|
132
|
+
say = progress or (lambda m: None)
|
|
133
|
+
s = settings or get_settings()
|
|
134
|
+
root = Path(root).resolve()
|
|
135
|
+
tdir = _trial_dir(root, rem)
|
|
136
|
+
tdir.mkdir(parents=True, exist_ok=True)
|
|
137
|
+
for old in tdir.glob("clone*"): # leftovers of earlier runs; never reused
|
|
138
|
+
_rm(old)
|
|
139
|
+
_rm(tdir / "validated")
|
|
140
|
+
clone = tdir / f"clone-{uuid.uuid4().hex[:8]}" # unique per run: a stale or concurrent run cannot collide with it
|
|
141
|
+
out: dict[str, Any] = {"status": "failed", "id": rem["id"], "fingerprint": _fingerprint(root, rem, with_tests), "ran_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
|
|
142
|
+
"steps": [], "reasons": [], "warnings": []}
|
|
143
|
+
scratch_db_dir = Path(tempfile.mkdtemp(prefix="guardian-trial-"))
|
|
144
|
+
try:
|
|
145
|
+
if not (rem.get("patch") or {}).get("diff"):
|
|
146
|
+
out["reasons"].append("this proposal has no automatic file change")
|
|
147
|
+
return out
|
|
148
|
+
say("1/4 Cloning the project into a scratch workspace ...")
|
|
149
|
+
size = _copy_project(root, clone, min(s.max_repo_bytes, 200 * 1024 * 1024))
|
|
150
|
+
out["steps"].append({"step": "clone", "ok": True, "detail": f"copied {size // 1024} KB (node_modules, .git and build output excluded)"})
|
|
151
|
+
|
|
152
|
+
say("2/4 Applying the fix in the clone and refreshing the lockfile ...")
|
|
153
|
+
res = apply_in_place(clone, rem)
|
|
154
|
+
if res["status"] != "success":
|
|
155
|
+
out["steps"].append({"step": "apply", "ok": False, "detail": res["error"]})
|
|
156
|
+
out["reasons"].append(res["error"])
|
|
157
|
+
return out
|
|
158
|
+
lock = res["lock"]
|
|
159
|
+
out["steps"].append({"step": "apply", "ok": True, "detail": "changed " + ", ".join(res["files"]) + f"; lockfile: {lock['note']}"})
|
|
160
|
+
out["lock"] = lock
|
|
161
|
+
if lock["status"] in ("failed", "tool_missing"):
|
|
162
|
+
out["reasons"].append("the lockfile could not be refreshed, so a rescan would still see the old version: " + lock["note"])
|
|
163
|
+
|
|
164
|
+
if rem.get("ecosystem") == "Container":
|
|
165
|
+
return _container_trial(out, res, clone, root, rem, original, s, with_tests, say, tdir)
|
|
166
|
+
|
|
167
|
+
say("3/4 Rescanning the clone ...")
|
|
168
|
+
from core.scan_orchestrator import ScanOptions, scan_local_directory
|
|
169
|
+
from storage.database import Database
|
|
170
|
+
used = (original.get("sbom_tool") or {}).get("used")
|
|
171
|
+
opts = ScanOptions(use_nvd=False, use_kev=False, registry_checks=False, metadata_registry=False, investigate=False, remediate=False, use_llm=False,
|
|
172
|
+
reuse_cached=False, sbom_scanner=used if used in ("syft", "trivy", "builtin") else "auto")
|
|
173
|
+
rescan = scan_local_directory(clone, opts, s, Database(scratch_db_dir / "trial.db"), name="validation-clone")
|
|
174
|
+
if rescan.get("status") == "failed":
|
|
175
|
+
out["steps"].append({"step": "rescan", "ok": False, "detail": rescan.get("error", "rescan failed")})
|
|
176
|
+
out["reasons"].append("the rescan of the patched clone failed")
|
|
177
|
+
return out
|
|
178
|
+
cmp_ = _compare(rem, original.get("vulnerabilities") or [], rescan.get("vulnerabilities") or [])
|
|
179
|
+
out["comparison"] = cmp_
|
|
180
|
+
out["steps"].append({"step": "rescan", "ok": True, "detail": f"{cmp_['before']} -> {cmp_['after']} findings: {len(cmp_['fixed'])} fixed, {len(cmp_['new'])} new"})
|
|
181
|
+
if not cmp_["fixed"]:
|
|
182
|
+
out["reasons"].append("the fix does not remove any finding in the rescan")
|
|
183
|
+
worse = [n for n in cmp_["new"] if str(n.get("severity") or "").upper() in BLOCKING]
|
|
184
|
+
if worse:
|
|
185
|
+
out["reasons"].append(f"the fix introduces {len(worse)} new High/Critical finding(s): " + ", ".join(f"{n['id']} ({n['package']})" for n in worse[:3]))
|
|
186
|
+
|
|
187
|
+
say("Checking declared compatibility (registry metadata) ...")
|
|
188
|
+
from remediation.compat import static_compat
|
|
189
|
+
compat = static_compat(rem, root)
|
|
190
|
+
out["compat"] = compat
|
|
191
|
+
bad = [c for c in compat["checks"] if c["status"] == "fail"]
|
|
192
|
+
out["steps"].append({"step": "compatibility", "ok": not bad, "detail": f"{compat['status']}: " + (", ".join(f"{c['name']}" for c in bad) if bad else f"{len(compat['checks'])} check(s)")})
|
|
193
|
+
for c in bad:
|
|
194
|
+
out["reasons"].append(f"incompatible: {c['name']} - {c['detail']}")
|
|
195
|
+
out["warnings"] += [f"{c['name']}: {c['detail']}" for c in compat["checks"] if c["status"] == "warn"]
|
|
196
|
+
|
|
197
|
+
tests: dict[str, Any] = {"status": "not_run", "reason": "build/tests were not requested"}
|
|
198
|
+
if with_tests:
|
|
199
|
+
say("4/4 Running the project's build and tests in the Docker sandbox ...")
|
|
200
|
+
tests = _run_tests(s, clone, root, rem, say)
|
|
201
|
+
if tests["status"] == "failed" and (tests.get("baseline") or {}).get("status") != "failed":
|
|
202
|
+
out["reasons"].append("the project's tests pass without the fix but fail with it")
|
|
203
|
+
out["tests"] = tests
|
|
204
|
+
if tests["status"] == "failed" and (tests.get("baseline") or {}).get("status") == "failed":
|
|
205
|
+
out["warnings"].append("the project's tests fail both with and without the fix, so they cannot confirm compatibility")
|
|
206
|
+
elif tests["status"] in ("not_run", "skipped", "error"):
|
|
207
|
+
out["warnings"].append("compatibility was not confirmed by the project's tests: " + str(tests.get("reason") or "not run"))
|
|
208
|
+
out["steps"].append({"step": "tests", "ok": tests["status"] in ("passed", "not_run", "skipped") or (tests["status"] == "failed" and (tests.get("baseline") or {}).get("status") == "failed"),
|
|
209
|
+
"detail": f"{tests['status']}: {tests.get('reason') or tests.get('attribution') or ''}".strip(": ")})
|
|
210
|
+
|
|
211
|
+
_keep_validated(out, res, clone, tdir, root)
|
|
212
|
+
out["status"] = "passed" if not out["reasons"] else "failed"
|
|
213
|
+
return out
|
|
214
|
+
except Exception as e: # noqa: BLE001
|
|
215
|
+
out["reasons"].append(f"validation could not complete: {type(e).__name__}: {str(e)[:200]}")
|
|
216
|
+
return out
|
|
217
|
+
finally:
|
|
218
|
+
_rm(clone)
|
|
219
|
+
_rm(_store(clone))
|
|
220
|
+
_rm(scratch_db_dir)
|
|
221
|
+
try:
|
|
222
|
+
(tdir / "result.json").write_text(json.dumps(out, indent=2, default=str), encoding="utf-8")
|
|
223
|
+
except OSError:
|
|
224
|
+
pass
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def _container_trial(out: dict, res: dict, clone: Path, root: Path, rem: dict, original: dict, s: Settings, allowed: bool,
|
|
228
|
+
say: Callable[[str], None], tdir: Path) -> dict[str, Any]:
|
|
229
|
+
"""Container proposal: build the patched Dockerfile in the clone, scan the built image with Trivy, compare OS-package findings."""
|
|
230
|
+
from containers.trivy_image_scanner import parse_trivy_image_json
|
|
231
|
+
from core.safe_env import scrubbed_env
|
|
232
|
+
from sandbox.runner import docker_status
|
|
233
|
+
from sbom.tool_locator import find_tool
|
|
234
|
+
rel = (rem.get("patch") or {}).get("path", "")
|
|
235
|
+
ds, trivy = docker_status(), find_tool("trivy")
|
|
236
|
+
why = ("verification was not requested" if not allowed else ds["reason"] if not ds["available"] else "Trivy is not installed" if not trivy else "")
|
|
237
|
+
if why:
|
|
238
|
+
out["steps"].append({"step": "image build and rescan", "ok": True, "detail": f"skipped: {why}"})
|
|
239
|
+
out["warnings"].append(f"the fix was not verified (building the image and rescanning it needs Docker and Trivy): {why}")
|
|
240
|
+
_keep_validated(out, res, clone, tdir, root)
|
|
241
|
+
out["status"] = "passed" if not out["reasons"] else "failed"
|
|
242
|
+
return out
|
|
243
|
+
dockerfile = clone / rel
|
|
244
|
+
ctx_dir = dockerfile.parent # build context: the Dockerfile's own folder (the project root for a root-level Dockerfile)
|
|
245
|
+
tag = f"guardian-trial-{uuid.uuid4().hex[:10]}"
|
|
246
|
+
env = scrubbed_env()
|
|
247
|
+
try:
|
|
248
|
+
say("Building the patched image from the clone (runs the project's Dockerfile) ...")
|
|
249
|
+
b = subprocess.run([ds["exe"], "build", "-t", tag, "-f", str(dockerfile), str(ctx_dir)], capture_output=True, text=True, encoding="utf-8", errors="replace",
|
|
250
|
+
timeout=1500, shell=False, env=env)
|
|
251
|
+
if b.returncode != 0:
|
|
252
|
+
tail = "\n".join((b.stdout + "\n" + b.stderr).strip().splitlines()[-12:])
|
|
253
|
+
out["steps"].append({"step": "image build", "ok": False, "detail": tail[-400:]})
|
|
254
|
+
out["reasons"].append("the patched image does not build: " + tail.splitlines()[-1][:200] if tail else "the patched image does not build")
|
|
255
|
+
return out
|
|
256
|
+
out["steps"].append({"step": "image build", "ok": True, "detail": f"built {tag}"})
|
|
257
|
+
say("Scanning the built image with Trivy ...")
|
|
258
|
+
t = subprocess.run([trivy, "image", "--quiet", "--format", "json", "--scanners", "vuln", "--timeout", "15m", tag], capture_output=True, text=True,
|
|
259
|
+
encoding="utf-8", errors="replace", timeout=1200, shell=False, env=env)
|
|
260
|
+
after = [f.to_dict() for f in parse_trivy_image_json(t.stdout, tag, rel) if f.package_type == "os_pkg"]
|
|
261
|
+
if t.returncode not in (0, 1) or (not t.stdout.strip()):
|
|
262
|
+
out["steps"].append({"step": "image rescan", "ok": False, "detail": (t.stderr or "trivy produced no output")[-300:]})
|
|
263
|
+
out["reasons"].append("the rebuilt image could not be scanned: " + (t.stderr or "no output")[-160:])
|
|
264
|
+
return out
|
|
265
|
+
before = [v for v in original.get("vulnerabilities") or [] if v.get("asset_type") == "container_image"
|
|
266
|
+
and (v.get("container_details") or {}).get("source_file") == rel and (v.get("container_details") or {}).get("package_type") == "os_pkg"]
|
|
267
|
+
key = lambda v: (v.get("package_name"), v.get("primary_id") or v.get("vuln_id")) # noqa: E731
|
|
268
|
+
b_keys, a_keys = {key(v) for v in before}, {key(v) for v in after}
|
|
269
|
+
brief = lambda v: {"package": v.get("package_name"), "version": v.get("installed_version"), "id": v.get("primary_id") or v.get("vuln_id"), "severity": v.get("severity")} # noqa: E731
|
|
270
|
+
fixed = [brief(v) for v in before if key(v) not in a_keys]
|
|
271
|
+
new = [brief(v) for v in after if key(v) not in b_keys]
|
|
272
|
+
out["comparison"] = {"before": len(before), "after": len(after), "fixed": fixed, "remaining": [brief(v) for v in after if key(v) in b_keys], "new": new}
|
|
273
|
+
out["steps"].append({"step": "image rescan", "ok": True, "detail": f"{len(before)} -> {len(after)} OS-package findings: {len(fixed)} fixed, {len(new)} new"})
|
|
274
|
+
if not fixed:
|
|
275
|
+
out["reasons"].append("the rebuilt image still has every OS-package finding: the distribution repository has not published the fixes yet")
|
|
276
|
+
worse = [n for n in new if str(n.get("severity") or "").upper() in BLOCKING]
|
|
277
|
+
if worse:
|
|
278
|
+
out["reasons"].append(f"the rebuilt image has {len(worse)} new High/Critical OS-package finding(s)")
|
|
279
|
+
out["tests"] = {"status": "not_run", "reason": "image build and rescan replace the language test run for container changes"}
|
|
280
|
+
_keep_validated(out, res, clone, tdir, root)
|
|
281
|
+
out["status"] = "passed" if not out["reasons"] else "failed"
|
|
282
|
+
return out
|
|
283
|
+
finally:
|
|
284
|
+
try:
|
|
285
|
+
subprocess.run([ds["exe"], "rmi", "-f", tag], capture_output=True, timeout=120, shell=False, env=env)
|
|
286
|
+
except (OSError, subprocess.TimeoutExpired):
|
|
287
|
+
pass
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
def tests_possible(root: Path | str, rem: dict) -> tuple[bool, str]:
|
|
291
|
+
"""Can this project's own build/tests run in the Docker sandbox? (False, reason) when not."""
|
|
292
|
+
from sandbox.runner import detect_recipe, docker_status
|
|
293
|
+
ds = docker_status()
|
|
294
|
+
if not ds["available"]:
|
|
295
|
+
return False, ds["reason"]
|
|
296
|
+
if rem.get("ecosystem") == "Container":
|
|
297
|
+
from sbom.tool_locator import find_tool
|
|
298
|
+
return (True, "") if find_tool("trivy") else (False, "Trivy is not installed (needed to rescan the rebuilt image)")
|
|
299
|
+
eco = rem.get("ecosystem") or (rem.get("target") or {}).get("ecosystem")
|
|
300
|
+
if not detect_recipe(Path(root), eco, rem.get("service") or "."):
|
|
301
|
+
return False, f"no recognised build/test recipe for {eco} in this project"
|
|
302
|
+
return True, ""
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
def _run_tests(s: Settings, clone: Path, root: Path, rem: dict, say: Callable[[str], None]) -> dict[str, Any]:
|
|
306
|
+
from sandbox.runner import INSTALL_TIMEOUT, TEST_TIMEOUT, _run, detect_recipe, docker_status
|
|
307
|
+
ds = docker_status()
|
|
308
|
+
if not ds["available"]:
|
|
309
|
+
return {"status": "skipped", "reason": ds["reason"]}
|
|
310
|
+
eco = rem.get("ecosystem") or (rem.get("target") or {}).get("ecosystem")
|
|
311
|
+
recipe = detect_recipe(clone, eco, rem.get("service") or ".")
|
|
312
|
+
if not recipe:
|
|
313
|
+
return {"status": "skipped", "reason": f"no recognised build/test recipe for {eco} in this project (commands are never guessed)"}
|
|
314
|
+
say(f"Installing dependencies in {recipe['image']} ...")
|
|
315
|
+
inst = _run(ds["exe"], clone, recipe, "install", INSTALL_TIMEOUT)
|
|
316
|
+
if inst["exit_code"] != 0:
|
|
317
|
+
return {"status": "error", "reason": "dependency installation failed in the sandbox", "recipe": recipe, "runs": [inst]}
|
|
318
|
+
say("Running the tests with the network disabled ...")
|
|
319
|
+
test = _run(ds["exe"], clone, recipe, "test", TEST_TIMEOUT)
|
|
320
|
+
out: dict[str, Any] = {"status": "passed" if test["exit_code"] == 0 else "failed", "recipe": recipe, "runs": [inst, test]}
|
|
321
|
+
if test["exit_code"] != 0: # was it already failing before the fix?
|
|
322
|
+
say("Tests failed: running the unpatched project to see whether that pre-existed ...")
|
|
323
|
+
base = Path(tempfile.mkdtemp(prefix="guardian-base-"))
|
|
324
|
+
try:
|
|
325
|
+
_copy_project(root, base / "p", 200 * 1024 * 1024)
|
|
326
|
+
binst = _run(ds["exe"], base / "p", recipe, "install", INSTALL_TIMEOUT)
|
|
327
|
+
btest = _run(ds["exe"], base / "p", recipe, "test", TEST_TIMEOUT) if binst["exit_code"] == 0 else None
|
|
328
|
+
out["baseline"] = {"status": "passed" if btest and btest["exit_code"] == 0 else "failed", "runs": [binst] + ([btest] if btest else [])}
|
|
329
|
+
out["attribution"] = "the same failure occurs without the fix (pre-existing)" if out["baseline"]["status"] == "failed" else "the project passes without the fix: the fix likely broke a test"
|
|
330
|
+
finally:
|
|
331
|
+
_rm(base)
|
|
332
|
+
return out
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def _load_any(root: Path, rem: dict) -> Optional[dict]:
|
|
336
|
+
"""The stored result for the current files regardless of whether tests were part of it."""
|
|
337
|
+
try:
|
|
338
|
+
res = json.loads((_trial_dir(root, rem) / "result.json").read_text(encoding="utf-8"))
|
|
339
|
+
except (OSError, ValueError):
|
|
340
|
+
return None
|
|
341
|
+
ok = res.get("fingerprint") in (_fingerprint(root, rem, False), _fingerprint(root, rem, True))
|
|
342
|
+
return res if ok else None
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
def trial_record(root: Path | str, rem: dict) -> Optional[dict]:
|
|
346
|
+
"""The stored validation result of a proposal, even after the files changed (used by the Fix Report)."""
|
|
347
|
+
try:
|
|
348
|
+
return json.loads((_trial_dir(Path(root).resolve(), rem) / "result.json").read_text(encoding="utf-8"))
|
|
349
|
+
except (OSError, ValueError):
|
|
350
|
+
return None
|
|
351
|
+
|
|
352
|
+
|
|
353
|
+
def latest_trial(root: Path | str, rem: dict) -> Optional[dict]:
|
|
354
|
+
return _load_any(Path(root).resolve(), rem)
|
|
355
|
+
|
|
356
|
+
|
|
357
|
+
def discard_trial(root: Path | str, rem: dict) -> None:
|
|
358
|
+
_rm(_trial_dir(Path(root).resolve(), rem))
|
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
"""Per-ecosystem manifest patch generators. Pure functions: (manifest text, change) -> new text, rendered as a unified diff.
|
|
2
|
+
|
|
3
|
+
Two kinds of change:
|
|
4
|
+
bump - raise the version of a *direct* dependency
|
|
5
|
+
pin - force a *transitive* dependency to a fixed version (npm overrides/resolutions, pip constraint line, Maven dependencyManagement, ...)
|
|
6
|
+
|
|
7
|
+
A patcher returns None when it cannot make a safe, minimal textual change; the plan then carries instructions only. Patches are never
|
|
8
|
+
applied by the Guardian: they are proposals that a human approves and applies (``git apply``).
|
|
9
|
+
"""
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import difflib
|
|
13
|
+
import json
|
|
14
|
+
import re
|
|
15
|
+
from typing import Optional
|
|
16
|
+
|
|
17
|
+
from sbom.package_extractors.common import normalize_name
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def unified_diff(path: str, old: str, new: str) -> str:
|
|
21
|
+
return "".join(difflib.unified_diff(old.splitlines(keepends=True), new.splitlines(keepends=True), fromfile=f"a/{path}", tofile=f"b/{path}", n=3))
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _indent_of(text: str) -> str | int:
|
|
25
|
+
m = re.search(r"^(\s+)\"", text, re.M)
|
|
26
|
+
if not m:
|
|
27
|
+
return 2
|
|
28
|
+
return "\t" if "\t" in m.group(1) else len(m.group(1))
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _json_dump(data: dict, original: str) -> str:
|
|
32
|
+
out = json.dumps(data, indent=_indent_of(original), ensure_ascii=False)
|
|
33
|
+
return out + ("\n" if original.endswith("\n") else "")
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
# ------------------------------------------------------------------ npm
|
|
37
|
+
def npm(text: str, name: str, to: str, kind: str, lock_hint: str = "") -> Optional[str]:
|
|
38
|
+
if kind == "bump":
|
|
39
|
+
pat = re.compile(r'("' + re.escape(name) + r'"\s*:\s*")([\^~]|>=)?([^"]+)(")')
|
|
40
|
+
m = pat.search(text)
|
|
41
|
+
if not m:
|
|
42
|
+
return None
|
|
43
|
+
return text[:m.start()] + f"{m.group(1)}{m.group(2) or ''}{to}{m.group(4)}" + text[m.end():]
|
|
44
|
+
try:
|
|
45
|
+
data = json.loads(text)
|
|
46
|
+
except ValueError:
|
|
47
|
+
return None
|
|
48
|
+
if not isinstance(data, dict):
|
|
49
|
+
return None
|
|
50
|
+
for sec in ("dependencies", "devDependencies", "optionalDependencies"):
|
|
51
|
+
cur = (data.get(sec) or {}).get(name)
|
|
52
|
+
if isinstance(cur, str): # a direct dependency: raise its own spec; an override here would make npm fail with EOVERRIDE
|
|
53
|
+
data[sec][name] = ("~" if cur.startswith("~") else "^") + to
|
|
54
|
+
return _json_dump(data, text)
|
|
55
|
+
if "yarn" in lock_hint:
|
|
56
|
+
data.setdefault("resolutions", {})[name] = to
|
|
57
|
+
elif "pnpm" in lock_hint:
|
|
58
|
+
data.setdefault("pnpm", {}).setdefault("overrides", {})[name] = to
|
|
59
|
+
else:
|
|
60
|
+
data.setdefault("overrides", {})[name] = to
|
|
61
|
+
return _json_dump(data, text)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
# ------------------------------------------------------------------ PyPI
|
|
65
|
+
def pypi_requirements(text: str, name: str, to: str, kind: str) -> Optional[str]:
|
|
66
|
+
n = normalize_name("PyPI", name)
|
|
67
|
+
lines = text.splitlines(keepends=True)
|
|
68
|
+
for i, ln in enumerate(lines):
|
|
69
|
+
m = re.match(r"^(\s*)([A-Za-z0-9_.\-]+)(\[[^\]]*\])?\s*(==|>=|~=|<=|>|<|!=)?\s*([^\s;#,]+)?(.*)$", ln)
|
|
70
|
+
if m and normalize_name("PyPI", m.group(2)) == n and not ln.lstrip().startswith(("#", "-")):
|
|
71
|
+
if kind == "bump":
|
|
72
|
+
op = m.group(4) if m.group(4) in ("==", "~=", ">=") else "=="
|
|
73
|
+
lines[i] = f"{m.group(1)}{m.group(2)}{m.group(3) or ''}{op}{to}{m.group(6)}\n" if ln.endswith("\n") else f"{m.group(1)}{m.group(2)}{m.group(3) or ''}{op}{to}{m.group(6)}"
|
|
74
|
+
return "".join(lines)
|
|
75
|
+
if kind == "pin":
|
|
76
|
+
sep = "" if text.endswith("\n") or not text else "\n"
|
|
77
|
+
return text + f"{sep}{name}>={to} # guardian: constraint for a vulnerable transitive dependency\n"
|
|
78
|
+
return None
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def pypi_pyproject(text: str, name: str, to: str, kind: str) -> Optional[str]:
|
|
82
|
+
if kind != "bump":
|
|
83
|
+
return None
|
|
84
|
+
n = re.escape(name)
|
|
85
|
+
pat = re.compile(r'(["\']' + n + r'(?:\[[^\]]*\])?\s*)(==|>=|~=|\^)?\s*[0-9][^"\',\]]*(["\'])', re.I)
|
|
86
|
+
m = pat.search(text)
|
|
87
|
+
if not m:
|
|
88
|
+
pat2 = re.compile(r'^(\s*' + n + r'\s*=\s*["\'])[\^~>=]*[0-9][^"\']*(["\'])', re.M | re.I) # poetry style
|
|
89
|
+
m2 = pat2.search(text)
|
|
90
|
+
return (text[:m2.start()] + f"{m2.group(1)}^{to}{m2.group(2)}" + text[m2.end():]) if m2 else None
|
|
91
|
+
return text[:m.start()] + f"{m.group(1)}{m.group(2) or '>='}{to}{m.group(3)}" + text[m.end():]
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
# ------------------------------------------------------------------ Maven
|
|
95
|
+
def maven(text: str, name: str, to: str, kind: str) -> Optional[str]:
|
|
96
|
+
g, _, a = name.partition(":")
|
|
97
|
+
if not a:
|
|
98
|
+
return None
|
|
99
|
+
if kind == "bump":
|
|
100
|
+
for m in re.finditer(r"<dependency>.*?</dependency>", text, re.S):
|
|
101
|
+
blk = m.group(0)
|
|
102
|
+
if re.search(r"<groupId>\s*" + re.escape(g) + r"\s*</groupId>", blk) and re.search(r"<artifactId>\s*" + re.escape(a) + r"\s*</artifactId>", blk):
|
|
103
|
+
v = re.search(r"<version>\s*([^<]+?)\s*</version>", blk)
|
|
104
|
+
if not v:
|
|
105
|
+
return None
|
|
106
|
+
ver = v.group(1)
|
|
107
|
+
pm = re.match(r"^\$\{([^}]+)\}$", ver)
|
|
108
|
+
if pm: # version comes from a property: change the property definition
|
|
109
|
+
prop = re.search(r"(<" + re.escape(pm.group(1)) + r">\s*)([^<]+?)(\s*</" + re.escape(pm.group(1)) + r">)", text)
|
|
110
|
+
return (text[:prop.start()] + prop.group(1) + to + prop.group(3) + text[prop.end():]) if prop else None
|
|
111
|
+
nb = blk[:v.start(1)] + to + blk[v.end(1):]
|
|
112
|
+
return text[:m.start()] + nb + text[m.end():]
|
|
113
|
+
return None
|
|
114
|
+
entry = (f" <dependency>\n <groupId>{g}</groupId>\n <artifactId>{a}</artifactId>\n <version>{to}</version>\n </dependency>\n")
|
|
115
|
+
dm = re.search(r"<dependencyManagement>.*?</dependencyManagement>", text, re.S)
|
|
116
|
+
if dm:
|
|
117
|
+
close = dm.group(0).rfind("</dependencies>")
|
|
118
|
+
if close < 0:
|
|
119
|
+
return None
|
|
120
|
+
pos = dm.start() + close
|
|
121
|
+
return text[:pos] + entry + " " + text[pos:]
|
|
122
|
+
top = re.search(r"^(\s*)<dependencies>", text, re.M)
|
|
123
|
+
if not top:
|
|
124
|
+
return None
|
|
125
|
+
block = f"{top.group(1)}<dependencyManagement>\n{top.group(1)} <dependencies>\n{entry}{top.group(1)} </dependencies>\n{top.group(1)}</dependencyManagement>\n"
|
|
126
|
+
return text[:top.start()] + block + text[top.start():]
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
# ------------------------------------------------------------------ Go / Cargo / Composer / NuGet
|
|
130
|
+
def go(text: str, name: str, to: str, kind: str) -> Optional[str]:
|
|
131
|
+
to = to if to.startswith("v") else "v" + to
|
|
132
|
+
pat = re.compile(r"^(\s*(?:require\s+)?" + re.escape(name) + r"\s+)v[^\s]+((?:\s*//.*)?)$", re.M)
|
|
133
|
+
m = pat.search(text)
|
|
134
|
+
if m:
|
|
135
|
+
return text[:m.start()] + f"{m.group(1)}{to}{m.group(2)}" + text[m.end():]
|
|
136
|
+
if kind == "pin":
|
|
137
|
+
rb = re.search(r"^require\s*\((.*?)^\)", text, re.M | re.S)
|
|
138
|
+
if rb:
|
|
139
|
+
pos = rb.end() - 1
|
|
140
|
+
return text[:pos] + f"\t{name} {to} // indirect\n" + text[pos:]
|
|
141
|
+
return text + ("" if text.endswith("\n") else "\n") + f"\nrequire {name} {to} // indirect\n"
|
|
142
|
+
return None
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def cargo(text: str, name: str, to: str, kind: str) -> Optional[str]:
|
|
146
|
+
if kind != "bump":
|
|
147
|
+
return None
|
|
148
|
+
p1 = re.compile(r'^(\s*' + re.escape(name) + r'\s*=\s*")[\^~=]?[0-9][^"]*(")', re.M)
|
|
149
|
+
m = p1.search(text)
|
|
150
|
+
if m:
|
|
151
|
+
return text[:m.start()] + f"{m.group(1)}{to}{m.group(2)}" + text[m.end():]
|
|
152
|
+
p2 = re.compile(r'^(\s*' + re.escape(name) + r'\s*=\s*\{[^}]*version\s*=\s*")[\^~=]?[0-9][^"]*(")', re.M)
|
|
153
|
+
m = p2.search(text)
|
|
154
|
+
return (text[:m.start()] + f"{m.group(1)}{to}{m.group(2)}" + text[m.end():]) if m else None
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def composer(text: str, name: str, to: str, kind: str) -> Optional[str]:
|
|
158
|
+
try:
|
|
159
|
+
data = json.loads(text)
|
|
160
|
+
except ValueError:
|
|
161
|
+
return None
|
|
162
|
+
for sec in ("require", "require-dev"):
|
|
163
|
+
if name in (data.get(sec) or {}):
|
|
164
|
+
cur = data[sec][name]
|
|
165
|
+
data[sec][name] = ("^" if cur.startswith("^") else "~" if cur.startswith("~") else "") + to.lstrip("v")
|
|
166
|
+
return _json_dump(data, text)
|
|
167
|
+
if kind == "pin":
|
|
168
|
+
data.setdefault("require", {})[name] = ">=" + to.lstrip("v")
|
|
169
|
+
return _json_dump(data, text)
|
|
170
|
+
return None
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def nuget(text: str, name: str, to: str, kind: str) -> Optional[str]:
|
|
174
|
+
pat = re.compile(r'(<PackageReference\s+[^>]*Include\s*=\s*"' + re.escape(name) + r'"[^>]*Version\s*=\s*")[^"]+(")', re.I)
|
|
175
|
+
m = pat.search(text)
|
|
176
|
+
if m:
|
|
177
|
+
return text[:m.start()] + f"{m.group(1)}{to}{m.group(2)}" + text[m.end():]
|
|
178
|
+
if kind == "pin":
|
|
179
|
+
close = text.rfind("</Project>")
|
|
180
|
+
if close > 0:
|
|
181
|
+
return text[:close] + f' <ItemGroup>\n <PackageReference Include="{name}" Version="{to}" />\n </ItemGroup>\n' + text[close:]
|
|
182
|
+
return None
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
# ecosystems with a built-in manifest patcher (keep in step with the dispatch below)
|
|
186
|
+
PATCHABLE = frozenset({"npm", "PyPI", "Maven", "Go", "crates.io", "Packagist", "NuGet"})
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def patch_for(eco: str, manifest_path: str, text: str, name: str, to: str, kind: str, lock_hint: str = "") -> Optional[dict]:
|
|
190
|
+
"""Return {path, diff, new_text} or None."""
|
|
191
|
+
base = manifest_path.rsplit("/", 1)[-1]
|
|
192
|
+
new: Optional[str] = None
|
|
193
|
+
from ecosystems.registry import get
|
|
194
|
+
plugin = get(eco)
|
|
195
|
+
if plugin is not None and plugin.patcher is not None:
|
|
196
|
+
new = plugin.patcher(manifest_path, text, name, to, kind)
|
|
197
|
+
elif eco == "npm" and base == "package.json":
|
|
198
|
+
new = npm(text, name, to, kind, lock_hint)
|
|
199
|
+
elif eco == "PyPI" and base.startswith("requirements") and base.endswith(".txt"):
|
|
200
|
+
new = pypi_requirements(text, name, to, kind)
|
|
201
|
+
elif eco == "PyPI" and base == "pyproject.toml":
|
|
202
|
+
new = pypi_pyproject(text, name, to, kind)
|
|
203
|
+
elif eco == "Maven" and base == "pom.xml":
|
|
204
|
+
new = maven(text, name, to, kind)
|
|
205
|
+
elif eco == "Go" and base == "go.mod":
|
|
206
|
+
new = go(text, name, to, kind)
|
|
207
|
+
elif eco == "crates.io" and base == "Cargo.toml":
|
|
208
|
+
new = cargo(text, name, to, kind)
|
|
209
|
+
elif eco == "Packagist" and base == "composer.json":
|
|
210
|
+
new = composer(text, name, to, kind)
|
|
211
|
+
elif eco == "NuGet" and base.endswith("proj"):
|
|
212
|
+
new = nuget(text, name, to, kind)
|
|
213
|
+
if new is None or new == text:
|
|
214
|
+
return None
|
|
215
|
+
return {"path": manifest_path, "diff": unified_diff(manifest_path, text, new), "new_text": new}
|