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,107 @@
|
|
|
1
|
+
"""One registry of the external tools StackParity can use.
|
|
2
|
+
|
|
3
|
+
``doctor``, ``setup`` and the dashboard diagnostics all read it, so a tool (built-in or added by a plugin) is described
|
|
4
|
+
exactly once. Detection only looks for the executable; it never runs repository code and never installs anything.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import importlib.util
|
|
9
|
+
import platform
|
|
10
|
+
import shutil
|
|
11
|
+
import sys
|
|
12
|
+
from dataclasses import dataclass, field
|
|
13
|
+
from typing import Any, Callable, Optional
|
|
14
|
+
|
|
15
|
+
from config.settings import Settings
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass(frozen=True)
|
|
19
|
+
class Tool:
|
|
20
|
+
key: str
|
|
21
|
+
label: str
|
|
22
|
+
purpose: str
|
|
23
|
+
required: bool = False
|
|
24
|
+
fallback: str = "" # what happens when it is absent
|
|
25
|
+
executable: Optional[Callable[[Settings], str]] = None # defaults to ``key``
|
|
26
|
+
install: dict[str, list[str]] = field(default_factory=dict) # platform.system().lower() -> argv
|
|
27
|
+
source: str = ""
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
TOOLS: dict[str, Tool] = {}
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def register_tool(tool: Tool) -> Tool:
|
|
34
|
+
TOOLS[tool.key] = tool
|
|
35
|
+
return tool
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _brew_winget(brew: str, winget_id: str) -> dict[str, list[str]]:
|
|
39
|
+
return {"windows": ["winget", "install", "--exact", "--id", winget_id], "darwin": ["brew", "install", brew], "linux": ["brew", "install", brew]}
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
register_tool(Tool("git", "Git", "repository history, remote cloning, isolated worktree remediation",
|
|
43
|
+
fallback="local folders are scanned without history; remote scans and fix --apply are unavailable", source="https://git-scm.com"))
|
|
44
|
+
register_tool(Tool("syft", "Syft", "external SBOM generation", fallback="built-in SBOM engine", executable=lambda s: s.syft_bin,
|
|
45
|
+
install=_brew_winget("syft", "Anchore.Syft"), source="Anchore.Syft (winget) / Homebrew"))
|
|
46
|
+
register_tool(Tool("trivy", "Trivy", "external SBOM generation and container image analysis", fallback="built-in SBOM engine; images are not scanned",
|
|
47
|
+
executable=lambda s: s.trivy_bin, install=_brew_winget("trivy", "AquaSecurity.Trivy"), source="AquaSecurity.Trivy (winget) / Homebrew"))
|
|
48
|
+
register_tool(Tool("semgrep", "Semgrep", "additional static analysis rules (online scans only)", fallback="built-in AST and pattern rules",
|
|
49
|
+
install={"windows": [sys.executable, "-m", "pip", "install", "semgrep"], "darwin": ["brew", "install", "semgrep"],
|
|
50
|
+
"linux": [sys.executable, "-m", "pip", "install", "semgrep"]}, source="PyPI (semgrep) / Homebrew"))
|
|
51
|
+
register_tool(Tool("gh", "GitHub CLI", "opening pull requests", fallback="stackparity pr is unavailable; patches can still be exported",
|
|
52
|
+
install=_brew_winget("gh", "GitHub.cli"), source="GitHub.cli (winget) / Homebrew"))
|
|
53
|
+
register_tool(Tool("docker", "Docker", "running a repository's tests in a sandbox during fix validation", fallback="tests are reported as unavailable",
|
|
54
|
+
source="https://docs.docker.com/get-docker/"))
|
|
55
|
+
register_tool(Tool("node", "Node.js", "semantic-version compatibility checks for npm fixes", fallback="those checks are reported as unverified",
|
|
56
|
+
source="https://nodejs.org"))
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def find_executable(tool: Tool, settings: Settings) -> Optional[str]:
|
|
60
|
+
from sbom.tool_locator import find_tool
|
|
61
|
+
name = tool.executable(settings) if tool.executable else tool.key
|
|
62
|
+
return shutil.which(name) or find_tool(name)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def detect(settings: Settings) -> list[dict[str, Any]]:
|
|
66
|
+
rows = []
|
|
67
|
+
for t in TOOLS.values():
|
|
68
|
+
path = find_executable(t, settings)
|
|
69
|
+
rows.append({"key": t.key, "label": t.label, "available": bool(path), "path": path, "required": t.required, "purpose": t.purpose, "fallback": t.fallback})
|
|
70
|
+
return rows
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def install_command(key: str) -> Optional[list[str]]:
|
|
74
|
+
cmds = TOOLS[key].install
|
|
75
|
+
return cmds.get(platform.system().lower()) or cmds.get("linux")
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
OPTIONAL_EXTRAS = {"dashboard": ("starlette", "uvicorn"), "legacy-dashboard": ("streamlit", "pandas"), "reports": ("reportlab",)}
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def extras() -> list[dict[str, Any]]:
|
|
82
|
+
out = []
|
|
83
|
+
for extra, modules in OPTIONAL_EXTRAS.items():
|
|
84
|
+
missing = [m for m in modules if importlib.util.find_spec(m) is None]
|
|
85
|
+
out.append({"extra": extra, "installed": not missing, "missing": missing})
|
|
86
|
+
return out
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def diagnostics(settings: Settings) -> dict[str, Any]:
|
|
90
|
+
"""Environment report shared by ``stackparity doctor --json`` and ``GET /api/diagnostics``. Contains no secrets."""
|
|
91
|
+
from core.plugins import load_plugins
|
|
92
|
+
from ecosystems.registry import capability_matrix
|
|
93
|
+
from non_cve import registered_scanners
|
|
94
|
+
from stackparity import __version__
|
|
95
|
+
return {
|
|
96
|
+
"version": __version__,
|
|
97
|
+
"python": platform.python_version(),
|
|
98
|
+
"platform": platform.system(),
|
|
99
|
+
"builtin": {"sbom_engine": True, "scanners": [{"name": s.name, "category": s.category} for s in registered_scanners()]},
|
|
100
|
+
"tools": detect(settings),
|
|
101
|
+
"extras": extras(),
|
|
102
|
+
"plugins": load_plugins(),
|
|
103
|
+
"ecosystems": capability_matrix(),
|
|
104
|
+
"credentials": {"nvd_api_key": bool(settings.nvd_api_key), "llm_api_key": bool(settings.llm_api_key)},
|
|
105
|
+
"storage": {"database": str(settings.db_path), "artifacts": str(settings.artifacts_dir)},
|
|
106
|
+
"configuration_problems": list(settings.problems),
|
|
107
|
+
}
|
|
@@ -0,0 +1,305 @@
|
|
|
1
|
+
"""Standardized finding schema shared across all StackParity detection engines.
|
|
2
|
+
|
|
3
|
+
Every detection engine (OSV/CVE, Suspicious Changes, Supply-Chain Anomaly,
|
|
4
|
+
SAST/Taint, IaC/Pipeline, Typosquatting, Package Risk, Lockfile History) can
|
|
5
|
+
emit or normalize into ``StandardFinding``. This guarantees consistent:
|
|
6
|
+
- distinction between confirmed vulnerabilities and heuristic flags
|
|
7
|
+
- severity, confidence, provenance, evidence, and remediation fields
|
|
8
|
+
- backward compatibility with existing engine-specific schemas
|
|
9
|
+
"""
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
from typing import Any, Literal, Optional
|
|
13
|
+
from pydantic import BaseModel, Field
|
|
14
|
+
|
|
15
|
+
Classification = Literal[
|
|
16
|
+
"CONFIRMED_VULNERABILITY",
|
|
17
|
+
"OBSERVED_CHANGE",
|
|
18
|
+
"HEURISTIC_FLAG",
|
|
19
|
+
"CONFIGURATION_RISK",
|
|
20
|
+
]
|
|
21
|
+
|
|
22
|
+
Severity = Literal["CRITICAL", "HIGH", "MEDIUM", "LOW", "INFO", "UNKNOWN"]
|
|
23
|
+
Confidence = Literal["HIGH", "MEDIUM", "LOW"]
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class FindingEvidence(BaseModel):
|
|
27
|
+
kind: str = "static" # static | advisory | git_diff | registry | ast | taint | pipeline
|
|
28
|
+
source: str = ""
|
|
29
|
+
file_path: Optional[str] = None
|
|
30
|
+
line: Optional[int] = None
|
|
31
|
+
snippet: Optional[str] = None
|
|
32
|
+
detail: dict[str, Any] = Field(default_factory=dict)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class StandardFinding(BaseModel):
|
|
36
|
+
finding_id: str
|
|
37
|
+
source_engine: str
|
|
38
|
+
category: str
|
|
39
|
+
rule_id: str = ""
|
|
40
|
+
title: str
|
|
41
|
+
description: str = ""
|
|
42
|
+
classification: Classification = "HEURISTIC_FLAG"
|
|
43
|
+
severity: Severity = "UNKNOWN"
|
|
44
|
+
confidence: Confidence = "MEDIUM"
|
|
45
|
+
confidence_score: float = 0.5
|
|
46
|
+
non_cve: bool = True
|
|
47
|
+
cve_ids: list[str] = Field(default_factory=list)
|
|
48
|
+
advisory_urls: list[str] = Field(default_factory=list)
|
|
49
|
+
provenance: dict[str, Any] = Field(default_factory=dict)
|
|
50
|
+
evidence: list[FindingEvidence] = Field(default_factory=list)
|
|
51
|
+
affected_target: dict[str, Any] = Field(default_factory=dict)
|
|
52
|
+
remediation: dict[str, Any] = Field(default_factory=dict)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
_SEV_SET = {"CRITICAL", "HIGH", "MEDIUM", "LOW", "INFO", "UNKNOWN"}
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _norm_sev(val: Any, default: str = "UNKNOWN") -> Severity:
|
|
59
|
+
s = str(val or default).upper().strip()
|
|
60
|
+
s = {"MODERATE": "MEDIUM", "INFORMATIONAL": "INFO"}.get(s, s)
|
|
61
|
+
return s if s in _SEV_SET else "UNKNOWN" # type: ignore[return-value]
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _norm_conf(val: Any, default: str = "MEDIUM") -> tuple[Confidence, float]:
|
|
65
|
+
s = str(val or default).upper().strip()
|
|
66
|
+
if s in ("HIGH", "CONFIRMED"):
|
|
67
|
+
return "HIGH", 0.9
|
|
68
|
+
if s in ("LOW", "WEAK"):
|
|
69
|
+
return "LOW", 0.3
|
|
70
|
+
return "MEDIUM", 0.6
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def from_cve_finding(f: dict[str, Any]) -> StandardFinding:
|
|
74
|
+
"""Normalize a vulnerability finding from OSV/Trivy correlation."""
|
|
75
|
+
status = f.get("affected_status") or "unknown"
|
|
76
|
+
classification: Classification = (
|
|
77
|
+
"CONFIRMED_VULNERABILITY" if status == "confirmed_affected" else "HEURISTIC_FLAG"
|
|
78
|
+
)
|
|
79
|
+
conf_label: Confidence = "HIGH" if f.get("cross_verified") else "MEDIUM"
|
|
80
|
+
conf_score = 0.95 if f.get("cross_verified") else 0.7
|
|
81
|
+
ev = [
|
|
82
|
+
FindingEvidence(
|
|
83
|
+
kind="advisory",
|
|
84
|
+
source=",".join(f.get("sources") or []),
|
|
85
|
+
detail={
|
|
86
|
+
"primary_id": f.get("primary_id"),
|
|
87
|
+
"affected_status": status,
|
|
88
|
+
"dependency_type": f.get("dependency_type"),
|
|
89
|
+
"source_packages": f.get("source_packages", []),
|
|
90
|
+
},
|
|
91
|
+
)
|
|
92
|
+
]
|
|
93
|
+
return StandardFinding(
|
|
94
|
+
finding_id=str(f.get("finding_id") or f.get("primary_id") or "VULN-UNKNOWN"),
|
|
95
|
+
source_engine="vulnerability_correlator",
|
|
96
|
+
category="cve",
|
|
97
|
+
rule_id=str(f.get("primary_id") or ""),
|
|
98
|
+
title=f"{f.get('package_name', 'unknown')}@{f.get('installed_version', '?')} ({f.get('primary_id', '')})",
|
|
99
|
+
description=str(f.get("summary") or f.get("affected_status_reason") or ""),
|
|
100
|
+
classification=classification,
|
|
101
|
+
severity=_norm_sev(f.get("severity"), "UNKNOWN"),
|
|
102
|
+
confidence=conf_label,
|
|
103
|
+
confidence_score=conf_score,
|
|
104
|
+
non_cve=False,
|
|
105
|
+
cve_ids=list(f.get("cve_ids") or []),
|
|
106
|
+
advisory_urls=list(f.get("advisory_urls") or []),
|
|
107
|
+
provenance={
|
|
108
|
+
"sources": f.get("sources") or [],
|
|
109
|
+
"cross_verified": bool(f.get("cross_verified")),
|
|
110
|
+
"ecosystem": f.get("ecosystem"),
|
|
111
|
+
},
|
|
112
|
+
evidence=ev,
|
|
113
|
+
affected_target={
|
|
114
|
+
"package_name": f.get("package_name"),
|
|
115
|
+
"installed_version": f.get("installed_version"),
|
|
116
|
+
"ecosystem": f.get("ecosystem"),
|
|
117
|
+
"purl": f.get("purl"),
|
|
118
|
+
"service_dir": f.get("service_dir"),
|
|
119
|
+
},
|
|
120
|
+
remediation={
|
|
121
|
+
"fixed_versions": f.get("fixed_versions") or [],
|
|
122
|
+
"recommended_fix": f.get("recommended_fix"),
|
|
123
|
+
"summary": f"Upgrade to {f['recommended_fix']}" if f.get("recommended_fix") else "Review advisory for mitigation.",
|
|
124
|
+
},
|
|
125
|
+
)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def from_suspicious_finding(f: dict[str, Any]) -> StandardFinding:
|
|
129
|
+
"""Normalize a finding from ChangeAnalyzer / SuspiciousChangeAgent."""
|
|
130
|
+
ev_type = str(f.get("evidence_type") or "HEURISTIC_FLAG").upper()
|
|
131
|
+
classification: Classification = (
|
|
132
|
+
"OBSERVED_CHANGE" if ev_type == "OBSERVED_CHANGE" else "HEURISTIC_FLAG"
|
|
133
|
+
)
|
|
134
|
+
conf_label, conf_score = _norm_conf(f.get("confidence"), "MEDIUM")
|
|
135
|
+
ev = [
|
|
136
|
+
FindingEvidence(
|
|
137
|
+
kind="git_diff" if ev_type == "OBSERVED_CHANGE" else "static",
|
|
138
|
+
source=str(f.get("category") or "suspicious_changes"),
|
|
139
|
+
file_path=f.get("affected_file"),
|
|
140
|
+
line=f.get("line_number"),
|
|
141
|
+
snippet=f.get("evidence_excerpt") or f.get("snippet"),
|
|
142
|
+
detail={"introduced_status": f.get("introduced_status"), "commit": f.get("commit")},
|
|
143
|
+
)
|
|
144
|
+
]
|
|
145
|
+
return StandardFinding(
|
|
146
|
+
finding_id=str(f.get("finding_id") or f.get("id") or "SUSP-UNKNOWN"),
|
|
147
|
+
source_engine="suspicious_changes",
|
|
148
|
+
category=str(f.get("category") or "supply_chain").lower().replace(" ", "_"),
|
|
149
|
+
rule_id=str(f.get("rule_id") or f.get("signal_type") or ""),
|
|
150
|
+
title=str(f.get("title") or f.get("summary") or "Suspicious supply-chain signal"),
|
|
151
|
+
description=str(f.get("description") or f.get("rationale") or ""),
|
|
152
|
+
classification=classification,
|
|
153
|
+
severity=_norm_sev(f.get("severity"), "MEDIUM"),
|
|
154
|
+
confidence=conf_label,
|
|
155
|
+
confidence_score=conf_score,
|
|
156
|
+
non_cve=True,
|
|
157
|
+
provenance={
|
|
158
|
+
"evidence_type": ev_type,
|
|
159
|
+
"introduced_status": f.get("introduced_status"),
|
|
160
|
+
"commit": f.get("commit"),
|
|
161
|
+
},
|
|
162
|
+
evidence=ev,
|
|
163
|
+
affected_target={
|
|
164
|
+
"file_path": f.get("affected_file"),
|
|
165
|
+
"line": f.get("line_number"),
|
|
166
|
+
"package_name": f.get("package_name"),
|
|
167
|
+
"ecosystem": f.get("ecosystem"),
|
|
168
|
+
},
|
|
169
|
+
remediation={
|
|
170
|
+
"summary": str(f.get("remediation") or f.get("recommended_action") or "Inspect the flagged file/change before merging."),
|
|
171
|
+
},
|
|
172
|
+
)
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def from_pipeline_finding(f: dict[str, Any]) -> StandardFinding:
|
|
176
|
+
"""Normalize a Dockerfile / Compose / CI / IaC finding."""
|
|
177
|
+
conf_label, conf_score = _norm_conf(f.get("confidence"), "HIGH")
|
|
178
|
+
return StandardFinding(
|
|
179
|
+
finding_id=str(f.get("finding_id") or "PIPE-UNKNOWN"),
|
|
180
|
+
source_engine=str(f.get("source_engine") or "pipeline_analysis"),
|
|
181
|
+
category=str(f.get("category") or "pipeline"),
|
|
182
|
+
rule_id=str(f.get("rule_id") or ""),
|
|
183
|
+
title=str(f.get("title") or "Pipeline / IaC configuration risk"),
|
|
184
|
+
description=str(f.get("description") or f.get("rationale") or ""),
|
|
185
|
+
classification="CONFIGURATION_RISK",
|
|
186
|
+
severity=_norm_sev(f.get("severity"), "MEDIUM"),
|
|
187
|
+
confidence=conf_label,
|
|
188
|
+
confidence_score=conf_score,
|
|
189
|
+
non_cve=True,
|
|
190
|
+
provenance={"scanner": f.get("source_engine") or "pipeline_analysis", "rule_id": f.get("rule_id")},
|
|
191
|
+
evidence=[
|
|
192
|
+
FindingEvidence(
|
|
193
|
+
kind="pipeline",
|
|
194
|
+
source=str(f.get("rule_id") or "pipeline"),
|
|
195
|
+
file_path=f.get("file"),
|
|
196
|
+
line=f.get("line"),
|
|
197
|
+
snippet=f.get("snippet"),
|
|
198
|
+
)
|
|
199
|
+
],
|
|
200
|
+
affected_target={"file_path": f.get("file"), "line": f.get("line")},
|
|
201
|
+
remediation={"summary": str(f.get("remediation") or "Pin versions/digests and enforce least-privilege configuration.")},
|
|
202
|
+
)
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def from_generic_non_cve(f: dict[str, Any], source_engine: str, category: str) -> StandardFinding:
|
|
206
|
+
"""Normalize a finding from modular Non-CVE scanners (supply-chain anomaly, SAST/taint, IaC)."""
|
|
207
|
+
conf_label, conf_score = _norm_conf(f.get("confidence"), "MEDIUM")
|
|
208
|
+
cls_raw = str(f.get("classification") or "HEURISTIC_FLAG").upper()
|
|
209
|
+
classification: Classification = (
|
|
210
|
+
cls_raw if cls_raw in ("CONFIRMED_VULNERABILITY", "OBSERVED_CHANGE", "HEURISTIC_FLAG", "CONFIGURATION_RISK") else "HEURISTIC_FLAG" # type: ignore[assignment]
|
|
211
|
+
)
|
|
212
|
+
ev_list = []
|
|
213
|
+
if f.get("evidence"):
|
|
214
|
+
for item in f["evidence"]:
|
|
215
|
+
if isinstance(item, FindingEvidence):
|
|
216
|
+
ev_list.append(item)
|
|
217
|
+
elif isinstance(item, dict):
|
|
218
|
+
ev_list.append(FindingEvidence(**item))
|
|
219
|
+
else:
|
|
220
|
+
ev_list.append(FindingEvidence(kind="static", source=source_engine, snippet=str(item)))
|
|
221
|
+
else:
|
|
222
|
+
ev_list.append(
|
|
223
|
+
FindingEvidence(
|
|
224
|
+
kind=str(f.get("evidence_kind") or "static"),
|
|
225
|
+
source=source_engine,
|
|
226
|
+
file_path=f.get("file_path") or f.get("file"),
|
|
227
|
+
line=f.get("line"),
|
|
228
|
+
snippet=f.get("snippet"),
|
|
229
|
+
)
|
|
230
|
+
)
|
|
231
|
+
return StandardFinding(
|
|
232
|
+
finding_id=str(f.get("finding_id") or "NONCVE-UNKNOWN"),
|
|
233
|
+
source_engine=source_engine,
|
|
234
|
+
category=category,
|
|
235
|
+
rule_id=str(f.get("rule_id") or ""),
|
|
236
|
+
title=str(f.get("title") or "Non-CVE security finding"),
|
|
237
|
+
description=str(f.get("description") or ""),
|
|
238
|
+
classification=classification,
|
|
239
|
+
severity=_norm_sev(f.get("severity"), "MEDIUM"),
|
|
240
|
+
confidence=conf_label,
|
|
241
|
+
confidence_score=conf_score,
|
|
242
|
+
non_cve=True,
|
|
243
|
+
provenance=dict(f.get("provenance") or {"scanner": source_engine}),
|
|
244
|
+
evidence=ev_list,
|
|
245
|
+
affected_target=dict(f.get("affected_target") or {"file_path": f.get("file_path") or f.get("file"), "line": f.get("line"), "package_name": f.get("package_name")}),
|
|
246
|
+
remediation=dict(f.get("remediation") or {"summary": str(f.get("remediation_text") or "Review and remediate the flagged pattern.")}),
|
|
247
|
+
)
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def normalize_all_findings(result: dict[str, Any]) -> list[dict[str, Any]]:
|
|
251
|
+
"""Produce a deduplicated, standardized list of all findings in a scan result."""
|
|
252
|
+
out: list[dict[str, Any]] = []
|
|
253
|
+
seen_ids: set[str] = set()
|
|
254
|
+
|
|
255
|
+
def _add(sf: StandardFinding) -> None:
|
|
256
|
+
key = f"{sf.source_engine}:{sf.finding_id}"
|
|
257
|
+
if key not in seen_ids:
|
|
258
|
+
seen_ids.add(key)
|
|
259
|
+
out.append(sf.model_dump())
|
|
260
|
+
|
|
261
|
+
for v in result.get("vulnerabilities") or []:
|
|
262
|
+
_add(from_cve_finding(v))
|
|
263
|
+
for p in (result.get("pipeline") or {}).get("findings") or []:
|
|
264
|
+
_add(from_pipeline_finding(p))
|
|
265
|
+
for s in (result.get("suspicious_changes") or {}).get("findings") or []:
|
|
266
|
+
_add(from_suspicious_finding(s))
|
|
267
|
+
for pr in (result.get("package_risk") or {}).get("findings") or []:
|
|
268
|
+
_add(from_generic_non_cve({
|
|
269
|
+
"finding_id": pr.get("finding_id"),
|
|
270
|
+
"rule_id": pr.get("rule_id"),
|
|
271
|
+
"title": pr.get("title"),
|
|
272
|
+
"description": pr.get("rationale") or pr.get("description") or "",
|
|
273
|
+
"severity": pr.get("severity") or "MEDIUM",
|
|
274
|
+
"confidence": "HIGH" if pr.get("rule_id") == "PKG-INT" else "MEDIUM",
|
|
275
|
+
"classification": "OBSERVED_CHANGE" if pr.get("rule_id") == "PKG-INT" else "HEURISTIC_FLAG",
|
|
276
|
+
"package_name": pr.get("subject"),
|
|
277
|
+
"remediation_text": pr.get("remediation") or "Inspect package metadata and pinned integrity.",
|
|
278
|
+
}, "package_risk", "supply_chain"))
|
|
279
|
+
for sa in (result.get("sast_findings") or []):
|
|
280
|
+
_add(from_generic_non_cve(sa, "sast_taint", "sast"))
|
|
281
|
+
for sc in (result.get("supply_chain_anomalies") or []):
|
|
282
|
+
_add(from_generic_non_cve(sc, "supply_chain_anomaly", "supply_chain"))
|
|
283
|
+
for iac in (result.get("iac_findings") or []):
|
|
284
|
+
_add(from_generic_non_cve(iac, "iac_scanner", "iac"))
|
|
285
|
+
for plug in (result.get("plugin_findings") or []):
|
|
286
|
+
_add(from_generic_non_cve(plug, str(plug.get("source_engine") or "plugin"), str(plug.get("category") or "plugin")))
|
|
287
|
+
risks = {a.get("finding_id"): a for a in result.get("risk_assessments") or []}
|
|
288
|
+
for t in (result.get("typosquatting") or []):
|
|
289
|
+
_add(from_generic_non_cve({
|
|
290
|
+
"finding_id": t.get("finding_id"), "title": f"{t.get('package_name')} resembles {t.get('similar_to')}",
|
|
291
|
+
"description": t.get("why_flagged") or "Name similarity is a signal, not proof of malice.",
|
|
292
|
+
"severity": (risks.get(t.get("finding_id")) or {}).get("label") or "UNKNOWN", "confidence": t.get("evidence_strength"),
|
|
293
|
+
"classification": "HEURISTIC_FLAG", "package_name": t.get("package_name"),
|
|
294
|
+
"remediation_text": "Confirm the package name is the intended one.",
|
|
295
|
+
}, "typosquatting", "typosquatting"))
|
|
296
|
+
for c in (result.get("lockfile_changes") or []):
|
|
297
|
+
if c.get("classification") in ("normal_update", "insufficient_baseline"):
|
|
298
|
+
continue
|
|
299
|
+
_add(from_generic_non_cve({
|
|
300
|
+
"finding_id": c.get("finding_id"), "title": f"{str(c.get('change_type')).replace('_', ' ')}: {c.get('package_name')}",
|
|
301
|
+
"description": " ".join(c.get("reasons") or []), "severity": (risks.get(c.get("finding_id")) or {}).get("label") or "UNKNOWN",
|
|
302
|
+
"confidence": c.get("evidence_strength"), "classification": "OBSERVED_CHANGE", "file_path": c.get("file"),
|
|
303
|
+
"package_name": c.get("package_name"), "remediation_text": "Verify the lockfile change was intentional.",
|
|
304
|
+
}, "lockfile_history", "lockfile_history"))
|
|
305
|
+
return out
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
"""Safe Git helpers: all calls use argument lists (never a shell) and a hardened environment."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import os
|
|
5
|
+
import shutil
|
|
6
|
+
import stat
|
|
7
|
+
import subprocess
|
|
8
|
+
import uuid
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import Optional
|
|
11
|
+
|
|
12
|
+
from config.settings import Settings, get_settings
|
|
13
|
+
from core.safe_env import scrubbed_env
|
|
14
|
+
from core.url_validator import GitHubRepo, validate_ref
|
|
15
|
+
|
|
16
|
+
SAFE_CONFIG = [
|
|
17
|
+
"-c", "core.symlinks=false",
|
|
18
|
+
"-c", "protocol.file.allow=never",
|
|
19
|
+
"-c", "core.fsmonitor=false",
|
|
20
|
+
"-c", "core.hooksPath=NUL" if os.name == "nt" else "core.hooksPath=/dev/null",
|
|
21
|
+
"-c", "credential.helper=",
|
|
22
|
+
"-c", "submodule.recurse=false",
|
|
23
|
+
]
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class GitError(RuntimeError):
|
|
27
|
+
pass
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _env() -> dict[str, str]:
|
|
31
|
+
env = scrubbed_env()
|
|
32
|
+
env["GIT_TERMINAL_PROMPT"] = "0"
|
|
33
|
+
env["GIT_ASKPASS"] = "echo"
|
|
34
|
+
env["GCM_INTERACTIVE"] = "never"
|
|
35
|
+
env.pop("GIT_SSH_COMMAND", None)
|
|
36
|
+
return env
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def run_git(args: list[str], cwd: Path | None = None, timeout: int = 60, check: bool = True) -> subprocess.CompletedProcess:
|
|
40
|
+
cmd = ["git", *SAFE_CONFIG, *args]
|
|
41
|
+
try:
|
|
42
|
+
proc = subprocess.run(
|
|
43
|
+
cmd, cwd=str(cwd) if cwd else None, capture_output=True, text=True, encoding="utf-8", errors="replace",
|
|
44
|
+
timeout=timeout, env=_env(), shell=False,
|
|
45
|
+
)
|
|
46
|
+
except subprocess.TimeoutExpired as e:
|
|
47
|
+
raise GitError(f"git {args[0]} timed out after {timeout}s") from e
|
|
48
|
+
except FileNotFoundError as e:
|
|
49
|
+
raise GitError("git executable not found") from e
|
|
50
|
+
if check and proc.returncode != 0:
|
|
51
|
+
raise GitError(f"git {args[0]} failed: {proc.stderr.strip()[:500]}")
|
|
52
|
+
return proc
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _rmtree_force(path: Path) -> None:
|
|
56
|
+
def onerror(func, p, _exc): # read-only files inside .git on Windows
|
|
57
|
+
try:
|
|
58
|
+
os.chmod(p, stat.S_IWRITE)
|
|
59
|
+
func(p)
|
|
60
|
+
except Exception:
|
|
61
|
+
pass
|
|
62
|
+
|
|
63
|
+
shutil.rmtree(path, onerror=onerror)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def dir_size(path: Path, limit: int | None = None) -> int:
|
|
67
|
+
total = 0
|
|
68
|
+
for root, dirs, files in os.walk(path, followlinks=False):
|
|
69
|
+
for f in files:
|
|
70
|
+
try:
|
|
71
|
+
total += os.lstat(os.path.join(root, f)).st_size
|
|
72
|
+
except OSError:
|
|
73
|
+
continue
|
|
74
|
+
if limit and total > limit:
|
|
75
|
+
return total
|
|
76
|
+
return total
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def new_workspace(settings: Settings | None = None) -> tuple[str, Path]:
|
|
80
|
+
s = settings or get_settings()
|
|
81
|
+
scan_id = uuid.uuid4().hex[:12]
|
|
82
|
+
ws = s.workspace_dir / scan_id
|
|
83
|
+
ws.mkdir(parents=True, exist_ok=False)
|
|
84
|
+
return scan_id, ws
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def reap_stale_workspaces(settings: Settings | None = None) -> int:
|
|
88
|
+
"""Delete clone workspaces left behind by crashed/killed scans (older than ``workspace_max_age_s``)."""
|
|
89
|
+
import time
|
|
90
|
+
s = settings or get_settings()
|
|
91
|
+
removed = 0
|
|
92
|
+
try:
|
|
93
|
+
for d in s.workspace_dir.iterdir():
|
|
94
|
+
try:
|
|
95
|
+
if d.is_dir() and time.time() - d.stat().st_mtime > s.workspace_max_age_s:
|
|
96
|
+
_rmtree_force(d)
|
|
97
|
+
removed += 1
|
|
98
|
+
except OSError:
|
|
99
|
+
continue
|
|
100
|
+
except OSError:
|
|
101
|
+
pass
|
|
102
|
+
return removed
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def remove_artifacts(settings: Settings, scan_id: str) -> None:
|
|
106
|
+
"""Delete every generated artifact of a pruned scan (files are named ``<scan_id>-*``)."""
|
|
107
|
+
for sub in ("sbom", "scans", "reports", "graphs"):
|
|
108
|
+
for f in (settings.artifacts_dir / sub).glob(f"{scan_id}-*"):
|
|
109
|
+
try:
|
|
110
|
+
f.unlink()
|
|
111
|
+
except OSError:
|
|
112
|
+
pass
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def clone_repository(repo: GitHubRepo, workspace: Path, ref: str | None = None, settings: Settings | None = None) -> Path:
|
|
116
|
+
"""Shallow, hook-less, submodule-less clone into ``workspace/repo``. Never runs repository code."""
|
|
117
|
+
s = settings or get_settings()
|
|
118
|
+
ref = validate_ref(ref)
|
|
119
|
+
dest = workspace / "repo"
|
|
120
|
+
args = ["clone", "--depth", str(s.clone_depth), "--no-tags", "--single-branch", "--no-recurse-submodules"]
|
|
121
|
+
if ref:
|
|
122
|
+
args += ["--branch", ref]
|
|
123
|
+
args += ["--", repo.clone_url, str(dest)]
|
|
124
|
+
run_git(args, timeout=s.clone_timeout_s)
|
|
125
|
+
size = dir_size(dest, s.max_repo_bytes)
|
|
126
|
+
if size > s.max_repo_bytes:
|
|
127
|
+
cleanup(workspace)
|
|
128
|
+
raise GitError(f"Repository exceeds the {s.max_repo_bytes // (1024 * 1024)} MB size limit")
|
|
129
|
+
return dest
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def head_sha(repo_dir: Path) -> str:
|
|
133
|
+
return run_git(["rev-parse", "HEAD"], cwd=repo_dir).stdout.strip()
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def current_branch(repo_dir: Path) -> Optional[str]:
|
|
137
|
+
out = run_git(["rev-parse", "--abbrev-ref", "HEAD"], cwd=repo_dir, check=False).stdout.strip()
|
|
138
|
+
return None if out in ("", "HEAD") else out
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def is_shallow(repo_dir: Path) -> bool:
|
|
142
|
+
return run_git(["rev-parse", "--is-shallow-repository"], cwd=repo_dir, check=False).stdout.strip() == "true"
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def parent_sha(repo_dir: Path, sha: str = "HEAD") -> Optional[str]:
|
|
146
|
+
p = run_git(["rev-parse", "--verify", "--quiet", f"{sha}^"], cwd=repo_dir, check=False)
|
|
147
|
+
return p.stdout.strip() or None if p.returncode == 0 else None
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def commit_exists(repo_dir: Path, sha: str) -> bool:
|
|
151
|
+
return run_git(["cat-file", "-e", f"{sha}^{{commit}}"], cwd=repo_dir, check=False).returncode == 0
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def commit_info(repo_dir: Path, sha: str) -> dict[str, str]:
|
|
155
|
+
out = run_git(["show", "-s", "--format=%H%x1f%an%x1f%aI%x1f%s", sha], cwd=repo_dir, check=False).stdout.strip()
|
|
156
|
+
parts = out.split("\x1f")
|
|
157
|
+
if len(parts) < 4:
|
|
158
|
+
return {"sha": sha, "author": "", "date": "", "subject": ""}
|
|
159
|
+
return {"sha": parts[0], "author": parts[1], "date": parts[2], "subject": parts[3]}
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def recent_commits(repo_dir: Path, n: int, ref: str = "HEAD") -> list[str]:
|
|
163
|
+
out = run_git(["rev-list", f"--max-count={int(n)}", ref], cwd=repo_dir, check=False).stdout.split()
|
|
164
|
+
return out
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def changed_files(repo_dir: Path, base: str, head: str) -> list[tuple[str, str]]:
|
|
168
|
+
"""Return [(status, path)] between two commits (renames reported as D+A for simplicity)."""
|
|
169
|
+
out = run_git(["diff", "--name-status", "--no-renames", base, head], cwd=repo_dir, check=False).stdout
|
|
170
|
+
res = []
|
|
171
|
+
for line in out.splitlines():
|
|
172
|
+
if "\t" in line:
|
|
173
|
+
st, path = line.split("\t", 1)
|
|
174
|
+
res.append((st[0], path.strip()))
|
|
175
|
+
return res
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def show_file(repo_dir: Path, sha: str, path: str, max_bytes: int = 20 * 1024 * 1024) -> Optional[str]:
|
|
179
|
+
"""Return file text at a commit, or None if absent/too large. Never touches the working tree."""
|
|
180
|
+
p = subprocess.run(
|
|
181
|
+
["git", *SAFE_CONFIG, "show", f"{sha}:{path}"], cwd=str(repo_dir), capture_output=True, env=_env(),
|
|
182
|
+
timeout=60, shell=False,
|
|
183
|
+
)
|
|
184
|
+
if p.returncode != 0 or len(p.stdout) > max_bytes:
|
|
185
|
+
return None
|
|
186
|
+
return p.stdout.decode("utf-8", errors="replace")
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def diff_text(repo_dir: Path, base: str, head: str, path: str, max_chars: int = 200000, context: int = 1) -> str:
|
|
190
|
+
out = run_git(["diff", f"-U{int(context)}", "--no-color", base, head, "--", path], cwd=repo_dir, check=False).stdout
|
|
191
|
+
return out[:max_chars]
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def cleanup(workspace: Path, attempts: int = 4) -> bool:
|
|
195
|
+
"""Delete a workspace, retrying (Windows indexers/antivirus can briefly lock fresh files). Returns True if it is gone."""
|
|
196
|
+
import time
|
|
197
|
+
for i in range(attempts):
|
|
198
|
+
try:
|
|
199
|
+
if workspace.exists():
|
|
200
|
+
_rmtree_force(workspace)
|
|
201
|
+
except Exception:
|
|
202
|
+
pass
|
|
203
|
+
if not workspace.exists():
|
|
204
|
+
return True
|
|
205
|
+
time.sleep(0.5 * (i + 1))
|
|
206
|
+
return not workspace.exists()
|