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,309 @@
|
|
|
1
|
+
"""Apply an accepted remediation directly to a local project folder (coding-agent style), with backup and undo.
|
|
2
|
+
|
|
3
|
+
Used when the scanned project came from a folder path instead of a GitHub URL: there is no PR to open, so accepting a
|
|
4
|
+
proposal edits the real files. Steps: apply the manifest patch, back up every touched file first, then refresh the lockfile
|
|
5
|
+
with the ecosystem's package manager (scripts disabled) so that a rescan no longer reports the fixed advisories.
|
|
6
|
+
Nothing is committed, no branch is created and the working branch is never switched.
|
|
7
|
+
Backups and undo records are kept outside the project, in ~/.sc-guardian/local-changes/.
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import hashlib
|
|
12
|
+
import json
|
|
13
|
+
import os
|
|
14
|
+
import re
|
|
15
|
+
import shutil
|
|
16
|
+
import subprocess
|
|
17
|
+
import time
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
from typing import Any, Optional
|
|
20
|
+
|
|
21
|
+
from sbom.tool_locator import find_tool
|
|
22
|
+
|
|
23
|
+
_HUNK = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@")
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _store(root: Path) -> Path:
|
|
27
|
+
"""Backups and undo records live outside the project (so scanners never see the backup copies)."""
|
|
28
|
+
h = hashlib.sha1(str(Path(root).resolve()).lower().encode("utf-8")).hexdigest()[:16]
|
|
29
|
+
return Path(os.environ.get("STACKPARITY_HOME") or os.environ.get("SC_GUARDIAN_HOME") or (Path.home() / ".stackparity")) / "local-changes" / h
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class ApplyError(Exception):
|
|
33
|
+
pass
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
# --------------------------------------------------------------------------------------------- unified diff
|
|
37
|
+
def _parse(diff: str) -> list[tuple[str, list[tuple[int, list[str]]]]]:
|
|
38
|
+
"""Return [(relative path, [(old_start, hunk_lines)])] for a unified diff (a/<path> b/<path> headers)."""
|
|
39
|
+
files: list[tuple[str, list]] = []
|
|
40
|
+
cur: Optional[list] = None
|
|
41
|
+
hunk: Optional[list[str]] = None
|
|
42
|
+
for ln in diff.splitlines():
|
|
43
|
+
if ln.startswith("+++ "):
|
|
44
|
+
p = ln[4:].split("\t")[0].strip()
|
|
45
|
+
p = p[2:] if p.startswith("b/") else p
|
|
46
|
+
cur = []
|
|
47
|
+
files.append((p, cur))
|
|
48
|
+
hunk = None
|
|
49
|
+
elif ln.startswith("--- "):
|
|
50
|
+
hunk = None
|
|
51
|
+
elif ln.startswith("@@") and cur is not None:
|
|
52
|
+
m = _HUNK.match(ln)
|
|
53
|
+
if not m:
|
|
54
|
+
raise ApplyError(f"unreadable hunk header: {ln[:60]}")
|
|
55
|
+
hunk = []
|
|
56
|
+
cur.append((int(m.group(1)), hunk))
|
|
57
|
+
elif hunk is not None and ln[:1] in (" ", "+", "-"):
|
|
58
|
+
hunk.append(ln)
|
|
59
|
+
elif hunk is not None and ln.startswith("\\"):
|
|
60
|
+
continue # ""
|
|
61
|
+
return files
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def apply_unified(old: str, hunks: list[tuple[int, list[str]]]) -> str:
|
|
65
|
+
"""Apply hunks to ``old``; every context/removed line must match exactly, otherwise ApplyError (nothing is guessed)."""
|
|
66
|
+
src = old.split("\n")
|
|
67
|
+
out: list[str] = []
|
|
68
|
+
pos = 0 # index into src
|
|
69
|
+
for start, lines in hunks:
|
|
70
|
+
begin = max(start - 1, 0) if any(l[:1] != "+" for l in lines) else start
|
|
71
|
+
if begin < pos:
|
|
72
|
+
raise ApplyError("overlapping hunks")
|
|
73
|
+
out.extend(src[pos:begin])
|
|
74
|
+
pos = begin
|
|
75
|
+
for l in lines:
|
|
76
|
+
tag, text = l[:1], l[1:]
|
|
77
|
+
if tag == "+":
|
|
78
|
+
out.append(text)
|
|
79
|
+
else:
|
|
80
|
+
if pos >= len(src) or src[pos] != text:
|
|
81
|
+
raise ApplyError("the file no longer matches the scanned version (it changed since the scan)")
|
|
82
|
+
if tag == " ":
|
|
83
|
+
out.append(text)
|
|
84
|
+
pos += 1
|
|
85
|
+
out.extend(src[pos:])
|
|
86
|
+
return "\n".join(out)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _safe(root: Path, rel: str) -> Path:
|
|
90
|
+
p = (root / rel).resolve()
|
|
91
|
+
if root.resolve() not in p.parents:
|
|
92
|
+
raise ApplyError(f"refusing to touch a path outside the project: {rel}")
|
|
93
|
+
return p
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
# --------------------------------------------------------------------------------------------- npm override repair
|
|
97
|
+
_DEP_SECTIONS = ("dependencies", "devDependencies", "optionalDependencies")
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _ver_tuple(spec: str) -> tuple[int, ...]:
|
|
101
|
+
return tuple(int(x) for x in re.findall(r"\d+", spec)[:3]) or (0,)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def normalize_npm_overrides(pkg_json: Path) -> list[dict]:
|
|
105
|
+
"""npm refuses an ``overrides`` entry that differs from the same package's direct dependency spec (EOVERRIDE). Repair each such entry
|
|
106
|
+
the way npm documents it: keep the pinned security floor on the direct dependency and make the override a ``$name`` reference.
|
|
107
|
+
Returns the changes made (empty = nothing to repair)."""
|
|
108
|
+
from remediation.patchers import _json_dump
|
|
109
|
+
text = pkg_json.read_text(encoding="utf-8")
|
|
110
|
+
try:
|
|
111
|
+
data = json.loads(text)
|
|
112
|
+
except ValueError:
|
|
113
|
+
return []
|
|
114
|
+
ov = data.get("overrides")
|
|
115
|
+
if not isinstance(data, dict) or not isinstance(ov, dict):
|
|
116
|
+
return []
|
|
117
|
+
changes: list[dict] = []
|
|
118
|
+
for name, val in list(ov.items()):
|
|
119
|
+
if not isinstance(val, str) or val.startswith("$"):
|
|
120
|
+
continue
|
|
121
|
+
for sec in _DEP_SECTIONS:
|
|
122
|
+
deps = data.get(sec) or {}
|
|
123
|
+
cur = deps.get(name)
|
|
124
|
+
if not isinstance(cur, str) or cur == val:
|
|
125
|
+
continue
|
|
126
|
+
after = cur
|
|
127
|
+
m = re.match(r"^[v=]?(\d+\.\d+\.\d+(?:[-+][\w.]+)?)$", val.strip())
|
|
128
|
+
if m and _ver_tuple(m.group(1)) > _ver_tuple(cur): # keep the security floor the override expressed
|
|
129
|
+
after = ("~" if cur.startswith("~") else "^") + m.group(1)
|
|
130
|
+
deps[name] = after
|
|
131
|
+
ov[name] = f"${name}"
|
|
132
|
+
changes.append({"package": name, "direct_before": cur, "direct_after": after, "override_before": val, "override_after": f"${name}"})
|
|
133
|
+
break
|
|
134
|
+
if changes:
|
|
135
|
+
pkg_json.write_text(_json_dump(data, text), encoding="utf-8")
|
|
136
|
+
return changes
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
# --------------------------------------------------------------------------------------------- lockfile refresh
|
|
140
|
+
def _lock_command(eco: str, rem: dict, mdir: Path) -> Optional[tuple[list[str], str]]:
|
|
141
|
+
"""(argv, display) to refresh the lockfile next to the changed manifest, or None when the ecosystem needs none/has no safe command."""
|
|
142
|
+
has = lambda n: (mdir / n).exists() # noqa: E731
|
|
143
|
+
pkg = ((rem.get("target") or {}).get("package") or rem.get("package") or rem.get("source_package") or "").strip()
|
|
144
|
+
if eco == "npm":
|
|
145
|
+
if has("package-lock.json") or has("npm-shrinkwrap.json"):
|
|
146
|
+
return ["npm", "install", "--package-lock-only", "--ignore-scripts", "--no-audit", "--no-fund"], "npm install --package-lock-only --ignore-scripts"
|
|
147
|
+
if has("pnpm-lock.yaml"):
|
|
148
|
+
return ["pnpm", "install", "--lockfile-only", "--ignore-scripts"], "pnpm install --lockfile-only --ignore-scripts"
|
|
149
|
+
if has("yarn.lock"):
|
|
150
|
+
return ["yarn", "install", "--mode", "update-lockfile", "--mode", "skip-build"], "yarn install --mode update-lockfile"
|
|
151
|
+
elif eco == "Go" and has("go.sum"):
|
|
152
|
+
return ["go", "mod", "tidy"], "go mod tidy"
|
|
153
|
+
elif eco == "crates.io" and has("Cargo.lock") and pkg:
|
|
154
|
+
return ["cargo", "update", "-p", pkg], f"cargo update -p {pkg}"
|
|
155
|
+
elif eco == "Packagist" and has("composer.lock") and pkg:
|
|
156
|
+
return ["composer", "update", pkg, "--no-scripts", "--no-plugins", "--no-interaction"], f"composer update {pkg} --no-scripts"
|
|
157
|
+
elif eco == "PyPI":
|
|
158
|
+
if has("poetry.lock"):
|
|
159
|
+
return ["poetry", "lock"], "poetry lock"
|
|
160
|
+
if has("uv.lock"):
|
|
161
|
+
return ["uv", "lock"], "uv lock"
|
|
162
|
+
return None
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _refresh_lock(eco: str, rem: dict, mdir: Path, backups: dict[str, Path], root: Path, bdir: Path) -> dict[str, Any]:
|
|
166
|
+
cmd = _lock_command(eco, rem, mdir)
|
|
167
|
+
if not cmd:
|
|
168
|
+
return {"status": "not_needed", "note": "no lockfile for this manifest (or none that can be refreshed safely); the pinned manifest is what a rescan reads"}
|
|
169
|
+
argv, shown = cmd
|
|
170
|
+
exe = find_tool(argv[0])
|
|
171
|
+
if not exe:
|
|
172
|
+
return {"status": "tool_missing", "command": shown, "note": f"`{argv[0]}` is not installed; run `{shown}` in `{mdir}` to finish"}
|
|
173
|
+
for lock in ("package-lock.json", "npm-shrinkwrap.json", "pnpm-lock.yaml", "yarn.lock", "go.sum", "go.mod", "Cargo.lock", "composer.lock", "poetry.lock", "uv.lock"):
|
|
174
|
+
f = mdir / lock
|
|
175
|
+
if f.exists():
|
|
176
|
+
rel = f.relative_to(root).as_posix()
|
|
177
|
+
if rel not in backups:
|
|
178
|
+
dest = bdir / rel
|
|
179
|
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
|
180
|
+
shutil.copy2(f, dest)
|
|
181
|
+
backups[rel] = dest
|
|
182
|
+
def _run() -> subprocess.CompletedProcess:
|
|
183
|
+
return subprocess.run([exe, *argv[1:]], cwd=str(mdir), capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=300, shell=False,
|
|
184
|
+
env={**os.environ, "npm_config_ignore_scripts": "true", "CI": "1"})
|
|
185
|
+
normalized: list[dict] = []
|
|
186
|
+
try:
|
|
187
|
+
p = _run()
|
|
188
|
+
if p.returncode != 0 and eco == "npm" and "EOVERRIDE" in (p.stderr or p.stdout) and (mdir / "package.json").exists():
|
|
189
|
+
normalized = normalize_npm_overrides(mdir / "package.json")
|
|
190
|
+
if normalized:
|
|
191
|
+
p = _run()
|
|
192
|
+
except subprocess.TimeoutExpired:
|
|
193
|
+
return {"status": "failed", "command": shown, "note": f"`{shown}` timed out; run it manually in `{mdir}`"}
|
|
194
|
+
except OSError as e:
|
|
195
|
+
return {"status": "failed", "command": shown, "note": str(e)}
|
|
196
|
+
if p.returncode == 0 and normalized:
|
|
197
|
+
return {"status": "refreshed", "command": shown, "normalized": normalized,
|
|
198
|
+
"note": "lockfile refreshed after repairing conflicting overrides: "
|
|
199
|
+
+ "; ".join(f"{c['package']} (override {c['override_before']} -> {c['override_after']}, direct {c['direct_before']} -> {c['direct_after']})" for c in normalized)}
|
|
200
|
+
if p.returncode != 0:
|
|
201
|
+
err = (p.stderr or p.stdout).strip()
|
|
202
|
+
m = re.search(r"Override for (\S+?)@(\S+) conflicts with direct dependency", err)
|
|
203
|
+
if "EOVERRIDE" in err and m:
|
|
204
|
+
return {"status": "failed", "command": shown, "kind": "override_conflict",
|
|
205
|
+
"note": f"npm refuses this project's package.json: `{m.group(1)}` is in `overrides` and is also a direct dependency declared as `{m.group(2)}`. "
|
|
206
|
+
f"Make them agree first (set the override to \"${m.group(1)}\" or change the direct dependency), then re-validate"}
|
|
207
|
+
return {"status": "failed", "command": shown, "note": f"`{shown}` exited {p.returncode}: {err[-300:]}"}
|
|
208
|
+
return {"status": "refreshed", "command": shown, "note": f"lockfile refreshed with `{shown}`"}
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
# --------------------------------------------------------------------------------------------- public API
|
|
212
|
+
def _rem_key(rem: dict) -> str:
|
|
213
|
+
"""Stable identity of a fix: proposal ids (REM-001...) are renumbered on every scan, the fingerprint is not."""
|
|
214
|
+
fp = rem.get("fingerprint") or rem.get("title") or rem["id"]
|
|
215
|
+
return hashlib.sha1(str(fp).encode("utf-8")).hexdigest()[:20]
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def _state_file(root: Path, rem: dict) -> Path:
|
|
219
|
+
return _store(root) / "applied" / f"{_rem_key(rem)}.json"
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def _legacy_file(root: Path, rem: dict) -> Path:
|
|
223
|
+
return _store(root) / "applied" / f"{re.sub(r'[^A-Za-z0-9_.-]', '_', rem['id'])}.json"
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def applied_record(root: Path | str, rem: dict) -> Optional[dict]:
|
|
227
|
+
root = Path(root)
|
|
228
|
+
try:
|
|
229
|
+
f = _state_file(root, rem)
|
|
230
|
+
if f.exists():
|
|
231
|
+
return json.loads(f.read_text(encoding="utf-8"))
|
|
232
|
+
old = _legacy_file(root, rem) # records written before fingerprint keys: only if it is the same fix
|
|
233
|
+
if old.exists():
|
|
234
|
+
rec = json.loads(old.read_text(encoding="utf-8"))
|
|
235
|
+
if rec.get("title") == rem.get("title"):
|
|
236
|
+
return rec
|
|
237
|
+
except (OSError, ValueError):
|
|
238
|
+
pass
|
|
239
|
+
return None
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def _trial_area() -> Path:
|
|
243
|
+
return (Path(os.environ.get("STACKPARITY_HOME") or os.environ.get("SC_GUARDIAN_HOME") or (Path.home() / ".stackparity")) / "local-changes").resolve()
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def apply_in_place(root: Path | str, rem: dict, repo: dict | None = None) -> dict[str, Any]:
|
|
247
|
+
"""Edit the files of a StackParity trial clone for ``rem``. Returns {status: success|error, files, lock, backup_dir, ...}.
|
|
248
|
+
|
|
249
|
+
Only clones inside StackParity's own trial area are accepted. A user's repository is changed exclusively through
|
|
250
|
+
``remediation.lifecycle`` (approval bound to the scan, revision and patch), never through this function.
|
|
251
|
+
"""
|
|
252
|
+
root = Path(root).resolve()
|
|
253
|
+
area = _trial_area()
|
|
254
|
+
if root != area and area not in root.parents:
|
|
255
|
+
return {"status": "error", "error": f"Refusing to edit {root}: direct edits are limited to StackParity trial clones in {area}. "
|
|
256
|
+
"Apply approved changes with 'stackparity fix --apply --to-working-tree'."}
|
|
257
|
+
diff = (rem.get("patch") or {}).get("diff")
|
|
258
|
+
if not diff:
|
|
259
|
+
return {"status": "error", "error": f"Proposal '{rem.get('id')}' ({rem.get('action', 'remediation')}) has no automated patch; follow the rationale for a manual change."}
|
|
260
|
+
if not root.is_dir():
|
|
261
|
+
return {"status": "error", "error": f"Project folder not found: {root}"}
|
|
262
|
+
if applied_record(root, rem):
|
|
263
|
+
return {"status": "error", "error": "This proposal was already applied. Use Undo to revert it first."}
|
|
264
|
+
stamp = time.strftime("%Y%m%dT%H%M%S")
|
|
265
|
+
bdir = _store(root) / "backups" / f"{rem['id']}-{stamp}"
|
|
266
|
+
backups: dict[str, Path] = {}
|
|
267
|
+
changed: list[str] = []
|
|
268
|
+
try:
|
|
269
|
+
plan: list[tuple[Path, str, str, str]] = [] # (file, rel, original bytes-as-text, new text)
|
|
270
|
+
for rel, hunks in _parse(diff):
|
|
271
|
+
f = _safe(root, rel)
|
|
272
|
+
if not f.is_file():
|
|
273
|
+
raise ApplyError(f"file not found: {rel}")
|
|
274
|
+
raw = f.read_bytes().decode("utf-8")
|
|
275
|
+
crlf = "\r\n" in raw
|
|
276
|
+
new = apply_unified(raw.replace("\r\n", "\n"), hunks)
|
|
277
|
+
plan.append((f, rel, raw, new.replace("\n", "\r\n") if crlf else new))
|
|
278
|
+
if not plan:
|
|
279
|
+
raise ApplyError("the patch contains no file changes")
|
|
280
|
+
for f, rel, raw, new in plan: # back up first, then write
|
|
281
|
+
dest = bdir / rel
|
|
282
|
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
|
283
|
+
shutil.copy2(f, dest)
|
|
284
|
+
backups[rel] = dest
|
|
285
|
+
for f, rel, raw, new in plan:
|
|
286
|
+
f.write_bytes(new.encode("utf-8"))
|
|
287
|
+
changed.append(rel)
|
|
288
|
+
except (ApplyError, UnicodeDecodeError, OSError) as e:
|
|
289
|
+
for rel in changed: # roll back any file already written
|
|
290
|
+
try:
|
|
291
|
+
shutil.copy2(backups[rel], root / rel)
|
|
292
|
+
except OSError:
|
|
293
|
+
pass
|
|
294
|
+
return {"status": "error", "error": f"Could not apply the change: {e}"}
|
|
295
|
+
|
|
296
|
+
eco = rem.get("ecosystem") or (rem.get("target") or {}).get("ecosystem") or _guess_eco(changed[0])
|
|
297
|
+
lock = _refresh_lock(eco, rem, (root / changed[0]).parent, backups, root, bdir)
|
|
298
|
+
result = {"status": "success", "files": changed, "lock": lock, "backup_dir": str(bdir), "applied_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
|
|
299
|
+
"backups": {k: str(v) for k, v in backups.items()}, "id": rem["id"], "title": rem.get("title", "")}
|
|
300
|
+
sf = _state_file(root, rem)
|
|
301
|
+
sf.parent.mkdir(parents=True, exist_ok=True)
|
|
302
|
+
sf.write_text(json.dumps(result, indent=2), encoding="utf-8")
|
|
303
|
+
return result
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def _guess_eco(path: str) -> str:
|
|
307
|
+
base = path.rsplit("/", 1)[-1]
|
|
308
|
+
return {"package.json": "npm", "pyproject.toml": "PyPI", "pom.xml": "Maven", "go.mod": "Go", "Cargo.toml": "crates.io", "composer.json": "Packagist"}.get(
|
|
309
|
+
base, "PyPI" if base.startswith("requirements") else "")
|