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,98 @@
|
|
|
1
|
+
"""SBOM scanner selection engine.
|
|
2
|
+
|
|
3
|
+
Strategy ``auto`` tries the scanners in priority order and falls through on failure:
|
|
4
|
+
|
|
5
|
+
1. Syft (best coverage of container/OS/binary catalogers)
|
|
6
|
+
2. Trivy (lockfile-oriented, no vulnerability DB needed)
|
|
7
|
+
3. built-in rule engine (always available; lockfile/manifest parsing, see ``builtin_generator``)
|
|
8
|
+
|
|
9
|
+
Choosing a specific scanner tries it first and still falls back to the rule engine, so a CycloneDX file exists for
|
|
10
|
+
every scan that has any dependency evidence. Every attempt is recorded so the UI can show what was tried and why.
|
|
11
|
+
The raw scanner output is stored untouched; Trivy documents are normalised in memory (never rewritten on disk).
|
|
12
|
+
"""
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import json
|
|
16
|
+
from dataclasses import dataclass, field
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
from typing import Optional
|
|
19
|
+
|
|
20
|
+
from config.settings import Settings
|
|
21
|
+
from core.models import LockDependency
|
|
22
|
+
from sbom.adapters import get_adapter
|
|
23
|
+
from sbom.builtin_generator import TOOL_NAME, generate_cyclonedx
|
|
24
|
+
from sbom.cyclonedx_validator import load_sbom
|
|
25
|
+
from sbom.syft_runner import ScannerResult, resolve_syft, run_syft
|
|
26
|
+
from sbom.trivy_runner import resolve_trivy, run_trivy
|
|
27
|
+
|
|
28
|
+
SCANNER_CHOICES = ("auto", "syft", "trivy", "builtin")
|
|
29
|
+
SCANNER_LABELS = {"auto": "Auto (Syft → Trivy → built-in rules)", "syft": "Syft", "trivy": "Trivy", "builtin": "Built-in rule engine"}
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass
|
|
33
|
+
class SbomOutcome:
|
|
34
|
+
scanner: Optional[str] = None # syft | trivy | builtin | None
|
|
35
|
+
raw_path: Optional[str] = None # file exactly as the scanner wrote it
|
|
36
|
+
doc: dict = field(default_factory=dict) # normalised document used for analysis
|
|
37
|
+
run: Optional[ScannerResult] = None # command/version/duration of the winning external scanner
|
|
38
|
+
attempts: list[dict] = field(default_factory=list)
|
|
39
|
+
engine_stats: dict = field(default_factory=dict) # built-in rule engine counters
|
|
40
|
+
requested: str = "auto"
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def available_scanners(settings: Settings) -> dict:
|
|
44
|
+
return {"syft": resolve_syft(settings), "trivy": resolve_trivy(settings), "builtin": "built-in"}
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def plan(choice: str, settings: Settings) -> list[str]:
|
|
48
|
+
"""Ordered list of scanners that will be tried (unavailable ones are listed too so the UI can explain skips)."""
|
|
49
|
+
choice = choice if choice in SCANNER_CHOICES else "auto"
|
|
50
|
+
order = ["syft", "trivy", "builtin"] if choice == "auto" else [choice] + [s for s in ("builtin",) if s != choice]
|
|
51
|
+
return order
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def generate_sbom(repo_dir: Path, lock_deps: list[LockDependency], out_dir: Path, prefix: str, choice: str,
|
|
55
|
+
settings: Settings, repo_name: str, commit_sha: str = "") -> SbomOutcome:
|
|
56
|
+
out = SbomOutcome(requested=choice)
|
|
57
|
+
out_dir.mkdir(parents=True, exist_ok=True)
|
|
58
|
+
for name in plan(choice, settings):
|
|
59
|
+
if name in ("syft", "trivy"):
|
|
60
|
+
path = out_dir / f"{prefix}.{name}.cdx.json"
|
|
61
|
+
res = (run_syft if name == "syft" else run_trivy)(repo_dir, path, settings)
|
|
62
|
+
att = {"scanner": name, "ok": res.ok, "version": res.version, "duration_s": res.duration_s, "error": res.error,
|
|
63
|
+
"command": " ".join(res.command) if res.command else None}
|
|
64
|
+
out.attempts.append(att)
|
|
65
|
+
if not res.ok:
|
|
66
|
+
continue
|
|
67
|
+
try:
|
|
68
|
+
raw = load_sbom(res.sbom_path)
|
|
69
|
+
except Exception as e: # unreadable output counts as a failed attempt
|
|
70
|
+
att.update(ok=False, error=f"unreadable output: {e}")
|
|
71
|
+
continue
|
|
72
|
+
out.scanner, out.raw_path, out.run = name, res.sbom_path, res
|
|
73
|
+
canon = get_adapter(name).canonicalize(raw)
|
|
74
|
+
if lock_deps:
|
|
75
|
+
try:
|
|
76
|
+
from sbom.cyclonedx_validator import normalize_components
|
|
77
|
+
from sbom.merge import merge_inventories
|
|
78
|
+
|
|
79
|
+
base_doc, base_stats = generate_cyclonedx(lock_deps, repo_name, commit_sha)
|
|
80
|
+
ext_comps = normalize_components(canon, repo_dir, ["."], tool=name)
|
|
81
|
+
base_comps = normalize_components(base_doc, repo_dir, ["."], tool="builtin")
|
|
82
|
+
merged_doc, _, _ = merge_inventories(canon, ext_comps, base_doc, base_comps)
|
|
83
|
+
out.doc = merged_doc
|
|
84
|
+
out.engine_stats = base_stats
|
|
85
|
+
except Exception:
|
|
86
|
+
out.doc = canon
|
|
87
|
+
else:
|
|
88
|
+
out.doc = canon
|
|
89
|
+
return out
|
|
90
|
+
# built-in rule engine
|
|
91
|
+
doc, stats = generate_cyclonedx(lock_deps, repo_name, commit_sha)
|
|
92
|
+
path = out_dir / f"{prefix}.builtin.cdx.json"
|
|
93
|
+
path.write_text(json.dumps(doc, indent=2), encoding="utf-8")
|
|
94
|
+
out.attempts.append({"scanner": "builtin", "ok": True, "version": None, "duration_s": 0.0, "error": None,
|
|
95
|
+
"command": f"{TOOL_NAME} (in-process, {len(lock_deps)} lockfile/manifest records)"})
|
|
96
|
+
out.scanner, out.raw_path, out.doc, out.engine_stats = "builtin", str(path), doc, stats
|
|
97
|
+
return out
|
|
98
|
+
return out
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
"""Controlled Syft subprocess wrapper. No shell, argument list only, captured output, timeout."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
import shutil
|
|
7
|
+
import subprocess
|
|
8
|
+
import time
|
|
9
|
+
from dataclasses import asdict, dataclass, field
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Optional
|
|
12
|
+
|
|
13
|
+
from config.settings import Settings, get_settings
|
|
14
|
+
from core.safe_env import scrubbed_env
|
|
15
|
+
from sbom.tool_locator import find_tool
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass
|
|
19
|
+
class ScannerResult:
|
|
20
|
+
ok: bool
|
|
21
|
+
command: list[str] = field(default_factory=list)
|
|
22
|
+
exit_code: Optional[int] = None
|
|
23
|
+
stdout: str = ""
|
|
24
|
+
stderr: str = ""
|
|
25
|
+
duration_s: float = 0.0
|
|
26
|
+
version: Optional[str] = None
|
|
27
|
+
sbom_path: Optional[str] = None
|
|
28
|
+
error: Optional[str] = None
|
|
29
|
+
options: dict = field(default_factory=lambda: {"javascript.include-dev-dependencies": True})
|
|
30
|
+
|
|
31
|
+
def to_dict(self) -> dict:
|
|
32
|
+
d = asdict(self)
|
|
33
|
+
d["stdout"] = self.stdout[-2000:]
|
|
34
|
+
d["stderr"] = self.stderr[-2000:]
|
|
35
|
+
return d
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def resolve_syft(settings: Settings | None = None) -> Optional[str]:
|
|
39
|
+
s = settings or get_settings()
|
|
40
|
+
cand = s.syft_bin
|
|
41
|
+
if os.path.sep in cand or "/" in cand:
|
|
42
|
+
return cand if Path(cand).exists() else None
|
|
43
|
+
return shutil.which(cand) or find_tool(cand)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def syft_version(syft_bin: str) -> Optional[str]:
|
|
47
|
+
try:
|
|
48
|
+
p = subprocess.run([syft_bin, "version"], capture_output=True, text=True, timeout=60, shell=False,
|
|
49
|
+
env=scrubbed_env({"SYFT_CHECK_FOR_APP_UPDATE": "false"}))
|
|
50
|
+
except (OSError, subprocess.TimeoutExpired):
|
|
51
|
+
return None
|
|
52
|
+
for line in p.stdout.splitlines():
|
|
53
|
+
if line.lower().startswith("version:"):
|
|
54
|
+
return line.split(":", 1)[1].strip()
|
|
55
|
+
return p.stdout.strip() or None
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def build_command(syft_bin: str, repo_dir: Path, out_path: Path) -> list[str]:
|
|
59
|
+
return [syft_bin, "scan", f"dir:{Path(repo_dir).resolve()}", "-o", f"cyclonedx-json={Path(out_path).resolve()}", "-q"]
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def run_syft(repo_dir: Path, out_path: Path, settings: Settings | None = None) -> ScannerResult:
|
|
63
|
+
s = settings or get_settings()
|
|
64
|
+
syft = resolve_syft(s)
|
|
65
|
+
if not syft:
|
|
66
|
+
return ScannerResult(ok=False, error="Syft executable not found. Install Syft (see README) or set SYFT_BIN.")
|
|
67
|
+
out_path = Path(out_path)
|
|
68
|
+
out_path.parent.mkdir(parents=True, exist_ok=True)
|
|
69
|
+
if out_path.exists():
|
|
70
|
+
out_path.unlink()
|
|
71
|
+
cmd = build_command(syft, repo_dir, out_path)
|
|
72
|
+
res = ScannerResult(ok=False, command=cmd, version=syft_version(syft))
|
|
73
|
+
env = scrubbed_env({"SYFT_CHECK_FOR_APP_UPDATE": "false", "SYFT_JAVASCRIPT_INCLUDE_DEV_DEPENDENCIES": "true",
|
|
74
|
+
"SYFT_JAVA_USE_NETWORK": "false", "SYFT_PYTHON_SEARCH_REMOTE_LICENSES": "false", "SYFT_JAVASCRIPT_SEARCH_REMOTE_LICENSES": "false"})
|
|
75
|
+
t0 = time.time()
|
|
76
|
+
try:
|
|
77
|
+
p = subprocess.run(cmd, capture_output=True, text=True, encoding="utf-8", errors="replace",
|
|
78
|
+
timeout=s.syft_timeout_s, shell=False, env=env)
|
|
79
|
+
except subprocess.TimeoutExpired:
|
|
80
|
+
res.duration_s = time.time() - t0
|
|
81
|
+
res.error = f"Syft timed out after {s.syft_timeout_s}s"
|
|
82
|
+
return res
|
|
83
|
+
except OSError as e:
|
|
84
|
+
res.error = f"Could not execute Syft: {e}"
|
|
85
|
+
return res
|
|
86
|
+
res.duration_s = round(time.time() - t0, 2)
|
|
87
|
+
res.exit_code, res.stdout, res.stderr = p.returncode, p.stdout, p.stderr
|
|
88
|
+
if p.returncode != 0:
|
|
89
|
+
res.error = f"Syft exited with code {p.returncode}: {p.stderr.strip()[:300]}"
|
|
90
|
+
return res
|
|
91
|
+
if not out_path.exists():
|
|
92
|
+
res.error = "Syft reported success but produced no output file"
|
|
93
|
+
return res
|
|
94
|
+
try:
|
|
95
|
+
json.loads(out_path.read_text(encoding="utf-8"))
|
|
96
|
+
except Exception as e:
|
|
97
|
+
res.error = f"Syft output is not valid JSON: {e}"
|
|
98
|
+
return res
|
|
99
|
+
res.ok, res.sbom_path = True, str(out_path)
|
|
100
|
+
return res
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"""Locate external scanner binaries (Syft, Trivy) even when the running process has a stale PATH.
|
|
2
|
+
|
|
3
|
+
Installers such as winget/choco/scoop add their folder to the *registry* PATH, which processes started earlier (an open
|
|
4
|
+
terminal, VS Code, a running Streamlit server) never see. ``find_tool`` therefore checks, in order: the process PATH, the
|
|
5
|
+
current Windows registry PATH (user + machine), and the usual install locations.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import os
|
|
10
|
+
import shutil
|
|
11
|
+
import sys
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import Optional
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _registry_path_dirs() -> list[str]:
|
|
17
|
+
if sys.platform != "win32":
|
|
18
|
+
return []
|
|
19
|
+
dirs: list[str] = []
|
|
20
|
+
try:
|
|
21
|
+
import winreg
|
|
22
|
+
for hive, sub in ((winreg.HKEY_CURRENT_USER, r"Environment"),
|
|
23
|
+
(winreg.HKEY_LOCAL_MACHINE, r"SYSTEM\CurrentControlSet\Control\Session Manager\Environment")):
|
|
24
|
+
try:
|
|
25
|
+
with winreg.OpenKey(hive, sub) as k:
|
|
26
|
+
val, _ = winreg.QueryValueEx(k, "Path")
|
|
27
|
+
dirs += [os.path.expandvars(p) for p in str(val).split(os.pathsep) if p]
|
|
28
|
+
except OSError:
|
|
29
|
+
continue
|
|
30
|
+
except ImportError:
|
|
31
|
+
pass
|
|
32
|
+
return dirs
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def managed_tools_dir() -> Path:
|
|
36
|
+
return Path(os.environ.get("STACKPARITY_TOOLS_DIR") or (Path.home() / ".stackparity" / "bin")).expanduser()
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _known_dirs(name: str) -> list[Path]:
|
|
40
|
+
home = Path.home()
|
|
41
|
+
out: list[Path] = [managed_tools_dir(), home / "bin", home / ".local" / "bin", home / "go" / "bin", Path("/usr/local/bin"), Path("/opt/homebrew/bin")]
|
|
42
|
+
if sys.platform == "win32":
|
|
43
|
+
local = Path(os.environ.get("LOCALAPPDATA", home / "AppData" / "Local"))
|
|
44
|
+
pf = [Path(os.environ.get(v, d)) for v, d in (("ProgramFiles", r"C:\Program Files"), ("ProgramFiles(x86)", r"C:\Program Files (x86)"))]
|
|
45
|
+
out += [local / "Microsoft" / "WinGet" / "Links", home / "scoop" / "shims", Path(os.environ.get("ChocolateyInstall", r"C:\ProgramData\chocolatey")) / "bin"]
|
|
46
|
+
out += [p / name for p in pf]
|
|
47
|
+
pkgs = local / "Microsoft" / "WinGet" / "Packages" # winget "portable" packages live in one folder per package
|
|
48
|
+
if pkgs.is_dir():
|
|
49
|
+
out += [d for d in pkgs.iterdir() if d.is_dir() and name.lower() in d.name.lower()]
|
|
50
|
+
return out
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def find_tool(name: str) -> Optional[str]:
|
|
54
|
+
"""Return the full path of ``name`` (e.g. 'syft', 'trivy') or None."""
|
|
55
|
+
hit = shutil.which(name)
|
|
56
|
+
if hit:
|
|
57
|
+
return hit
|
|
58
|
+
for d in _registry_path_dirs():
|
|
59
|
+
hit = shutil.which(name, path=d)
|
|
60
|
+
if hit:
|
|
61
|
+
return hit
|
|
62
|
+
for d in _known_dirs(name):
|
|
63
|
+
try:
|
|
64
|
+
hit = shutil.which(name, path=str(d))
|
|
65
|
+
except OSError:
|
|
66
|
+
hit = None
|
|
67
|
+
if hit:
|
|
68
|
+
return hit
|
|
69
|
+
return None
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
"""Controlled Trivy subprocess wrapper (SBOM generation only). No shell, argument list, captured output, timeout.
|
|
2
|
+
|
|
3
|
+
``--scanners license`` is used on purpose: it makes Trivy walk the lockfiles and emit the package inventory without
|
|
4
|
+
needing its vulnerability database (vulnerabilities are looked up separately against OSV).
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
import os
|
|
10
|
+
import shutil
|
|
11
|
+
import subprocess
|
|
12
|
+
import time
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import Optional
|
|
15
|
+
|
|
16
|
+
from config.settings import Settings, get_settings
|
|
17
|
+
from core.safe_env import scrubbed_env
|
|
18
|
+
from sbom.tool_locator import find_tool
|
|
19
|
+
from sbom.syft_runner import ScannerResult # same result shape for every scanner
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def resolve_trivy(settings: Settings | None = None) -> Optional[str]:
|
|
23
|
+
cand = (settings or get_settings()).trivy_bin
|
|
24
|
+
if os.path.sep in cand or "/" in cand:
|
|
25
|
+
return cand if Path(cand).exists() else None
|
|
26
|
+
return shutil.which(cand) or find_tool(cand)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def trivy_version(trivy_bin: str) -> Optional[str]:
|
|
30
|
+
try:
|
|
31
|
+
p = subprocess.run([trivy_bin, "--version"], capture_output=True, text=True, timeout=60, shell=False, env=scrubbed_env())
|
|
32
|
+
except (OSError, subprocess.TimeoutExpired):
|
|
33
|
+
return None
|
|
34
|
+
for line in p.stdout.splitlines():
|
|
35
|
+
if line.lower().startswith("version:"):
|
|
36
|
+
return line.split(":", 1)[1].strip()
|
|
37
|
+
return None
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def build_command(trivy_bin: str, repo_dir: Path, out_path: Path) -> list[str]:
|
|
41
|
+
return [trivy_bin, "fs", "--format", "cyclonedx", "--scanners", "license", "--include-dev-deps",
|
|
42
|
+
"--skip-db-update", "--skip-java-db-update", "--offline-scan", "--quiet", "--output", str(Path(out_path).resolve()),
|
|
43
|
+
str(Path(repo_dir).resolve())]
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def run_trivy(repo_dir: Path, out_path: Path, settings: Settings | None = None) -> ScannerResult:
|
|
47
|
+
s = settings or get_settings()
|
|
48
|
+
trivy = resolve_trivy(s)
|
|
49
|
+
if not trivy:
|
|
50
|
+
return ScannerResult(ok=False, error="Trivy executable not found. Install Trivy (see README) or set TRIVY_BIN.", options={})
|
|
51
|
+
out_path = Path(out_path)
|
|
52
|
+
out_path.parent.mkdir(parents=True, exist_ok=True)
|
|
53
|
+
if out_path.exists():
|
|
54
|
+
out_path.unlink()
|
|
55
|
+
cmd = build_command(trivy, repo_dir, out_path)
|
|
56
|
+
res = ScannerResult(ok=False, command=cmd, version=trivy_version(trivy), options={"include-dev-deps": True, "scanners": "license"})
|
|
57
|
+
t0 = time.time()
|
|
58
|
+
try:
|
|
59
|
+
p = subprocess.run(cmd, capture_output=True, text=True, encoding="utf-8", errors="replace",
|
|
60
|
+
timeout=s.syft_timeout_s, shell=False, env=scrubbed_env({"TRIVY_DISABLE_TELEMETRY": "true", "TRIVY_SKIP_VERSION_CHECK": "true"}))
|
|
61
|
+
except subprocess.TimeoutExpired:
|
|
62
|
+
res.duration_s = round(time.time() - t0, 2)
|
|
63
|
+
res.error = f"Trivy timed out after {s.syft_timeout_s}s"
|
|
64
|
+
return res
|
|
65
|
+
except OSError as e:
|
|
66
|
+
res.error = f"Could not execute Trivy: {e}"
|
|
67
|
+
return res
|
|
68
|
+
res.duration_s = round(time.time() - t0, 2)
|
|
69
|
+
res.exit_code, res.stdout, res.stderr = p.returncode, p.stdout, p.stderr
|
|
70
|
+
if p.returncode != 0:
|
|
71
|
+
res.error = f"Trivy exited with code {p.returncode}: {(p.stderr or p.stdout).strip()[-300:]}"
|
|
72
|
+
return res
|
|
73
|
+
if not out_path.exists():
|
|
74
|
+
res.error = "Trivy reported success but produced no output file"
|
|
75
|
+
return res
|
|
76
|
+
try:
|
|
77
|
+
json.loads(out_path.read_text(encoding="utf-8"))
|
|
78
|
+
except Exception as e:
|
|
79
|
+
res.error = f"Trivy output is not valid JSON: {e}"
|
|
80
|
+
return res
|
|
81
|
+
res.ok, res.sbom_path = True, str(out_path)
|
|
82
|
+
return res
|
|
File without changes
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
"""TTL cache backed by the SQLite ``cache`` table (advisories, registry metadata, KEV, NVD)."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
import time
|
|
6
|
+
from typing import Any, Optional
|
|
7
|
+
|
|
8
|
+
from storage.database import Database
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class Cache:
|
|
12
|
+
def __init__(self, db: Database):
|
|
13
|
+
self.db = db
|
|
14
|
+
|
|
15
|
+
def get(self, namespace: str, key: str, ttl: float | None = None, allow_stale: bool = False) -> Optional[Any]:
|
|
16
|
+
with self.db.connect() as c:
|
|
17
|
+
r = c.execute("SELECT payload, fetched_at FROM cache WHERE namespace=? AND key=?", (namespace, key)).fetchone()
|
|
18
|
+
if not r:
|
|
19
|
+
return None
|
|
20
|
+
if ttl is not None and not allow_stale and (time.time() - r["fetched_at"]) > ttl:
|
|
21
|
+
return None
|
|
22
|
+
return json.loads(r["payload"])
|
|
23
|
+
|
|
24
|
+
def get_with_time(self, namespace: str, key: str) -> Optional[tuple[Any, float]]:
|
|
25
|
+
with self.db.connect() as c:
|
|
26
|
+
r = c.execute("SELECT payload, fetched_at FROM cache WHERE namespace=? AND key=?", (namespace, key)).fetchone()
|
|
27
|
+
return (json.loads(r["payload"]), r["fetched_at"]) if r else None
|
|
28
|
+
|
|
29
|
+
def set(self, namespace: str, key: str, value: Any) -> None:
|
|
30
|
+
with self.db.connect() as c:
|
|
31
|
+
c.execute("INSERT OR REPLACE INTO cache(namespace, key, payload, fetched_at) VALUES (?,?,?,?)",
|
|
32
|
+
(namespace, key, json.dumps(value, default=str), time.time()))
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
# ------------------------------------------------------------------ maintenance
|
|
36
|
+
def stats(self) -> dict:
|
|
37
|
+
"""Rows, bytes and age per namespace (for the Settings & Health page)."""
|
|
38
|
+
with self.db.connect() as c:
|
|
39
|
+
rows = c.execute("SELECT namespace, COUNT(*) n, COALESCE(SUM(LENGTH(payload)),0) b, MIN(fetched_at) oldest, MAX(fetched_at) newest FROM cache GROUP BY namespace ORDER BY n DESC").fetchall()
|
|
40
|
+
return {"namespaces": [{"namespace": r["namespace"], "rows": r["n"], "bytes": r["b"], "oldest": r["oldest"], "newest": r["newest"]} for r in rows],
|
|
41
|
+
"total_rows": sum(r["n"] for r in rows), "total_bytes": sum(r["b"] for r in rows)}
|
|
42
|
+
|
|
43
|
+
def maintain(self, max_age_days: int = 120, max_rows: int = 2_000_000) -> dict:
|
|
44
|
+
"""Purge rows older than ``max_age_days`` and, if still above ``max_rows``, the oldest rows. Cheap enough to call at the start of every scan."""
|
|
45
|
+
cutoff = time.time() - max_age_days * 86400
|
|
46
|
+
with self.db.connect() as c:
|
|
47
|
+
old = c.execute("DELETE FROM cache WHERE fetched_at < ?", (cutoff,)).rowcount
|
|
48
|
+
total = c.execute("SELECT COUNT(*) FROM cache").fetchone()[0]
|
|
49
|
+
over = 0
|
|
50
|
+
if total > max_rows:
|
|
51
|
+
over = c.execute("DELETE FROM cache WHERE rowid IN (SELECT rowid FROM cache ORDER BY fetched_at ASC LIMIT ?)", (total - max_rows,)).rowcount
|
|
52
|
+
return {"purged_old": old, "purged_over_limit": over}
|
|
53
|
+
|
|
54
|
+
def clear(self, namespace: str | None = None) -> int:
|
|
55
|
+
with self.db.connect() as c:
|
|
56
|
+
return c.execute("DELETE FROM cache WHERE namespace=?", (namespace,)).rowcount if namespace else c.execute("DELETE FROM cache").rowcount
|