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,461 @@
|
|
|
1
|
+
"""Terminal remediation review, isolated application and pull-request publication.
|
|
2
|
+
|
|
3
|
+
Every function here is a thin interface over ``remediation.lifecycle`` and ``remediation.worktree_pr``; the dashboard calls the
|
|
4
|
+
same services, so a decision made in one interface is the decision the other one shows.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import getpass
|
|
9
|
+
import os
|
|
10
|
+
import re
|
|
11
|
+
import subprocess
|
|
12
|
+
import sys
|
|
13
|
+
from datetime import datetime, timezone
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import Callable, Optional
|
|
16
|
+
|
|
17
|
+
from rich.console import Console
|
|
18
|
+
from rich.markup import escape
|
|
19
|
+
from rich.panel import Panel
|
|
20
|
+
from rich.prompt import Prompt
|
|
21
|
+
from rich.syntax import Syntax
|
|
22
|
+
from rich.table import Table
|
|
23
|
+
|
|
24
|
+
from cli.term import visible
|
|
25
|
+
from remediation import lifecycle
|
|
26
|
+
from remediation.lifecycle import Candidate, LifecycleError
|
|
27
|
+
|
|
28
|
+
SEV_STYLE = {"CRITICAL": "bold red", "HIGH": "red", "MEDIUM": "yellow", "LOW": "cyan"}
|
|
29
|
+
STATE_STYLE = {"approved": "green", "rejected": "red", "skipped": "dim", "pending_review": "yellow", "proposed": "white",
|
|
30
|
+
"validation_passed": "green", "validation_failed": "red", "applied_in_isolation": "cyan", "ready_for_pr": "green",
|
|
31
|
+
"pr_created": "bold green", "applied": "bold green"}
|
|
32
|
+
PAGE_LINES = 60
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def safe(value) -> str:
|
|
36
|
+
"""Repository content is untrusted: never let it inject Rich markup or terminal control sequences (ESC, CSI, OSC...).
|
|
37
|
+
|
|
38
|
+
Control and bidi-override characters are shown as visible markers (see ``cli.term``), not silently removed."""
|
|
39
|
+
return escape(visible(value))
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def actor() -> str:
|
|
43
|
+
try:
|
|
44
|
+
return getpass.getuser()
|
|
45
|
+
except (OSError, KeyError, ImportError):
|
|
46
|
+
return "local-user"
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def is_interactive(non_interactive: bool = False) -> bool:
|
|
50
|
+
if non_interactive or os.environ.get("CI") or os.environ.get("STACKPARITY_NON_INTERACTIVE"):
|
|
51
|
+
return False
|
|
52
|
+
try:
|
|
53
|
+
return sys.stdin.isatty() and sys.stdout.isatty()
|
|
54
|
+
except (AttributeError, ValueError):
|
|
55
|
+
return False
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def confirm(console: Console, question: str, interactive: bool, yes: bool) -> bool:
|
|
59
|
+
"""Explicit authorization: --yes, or an interactive answer. Non-interactive runs never assume consent."""
|
|
60
|
+
if yes:
|
|
61
|
+
console.print(f"[dim]{question} authorized by --yes[/dim]")
|
|
62
|
+
return True
|
|
63
|
+
if not interactive:
|
|
64
|
+
console.print(f"[yellow]{question} not authorized: this is a non-interactive session (pass --yes to authorize).[/yellow]")
|
|
65
|
+
return False
|
|
66
|
+
return ask_yes(console, question)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def ask_yes(console: Console, question: str) -> bool:
|
|
70
|
+
"""y/N prompt. End of input (Ctrl+D / Ctrl+Z, closed stdin) is a 'no', never a 'yes'."""
|
|
71
|
+
try:
|
|
72
|
+
return Prompt.ask(f"{safe(question)} \\[y/N]", choices=["y", "n"], default="n", show_choices=False, console=console) == "y"
|
|
73
|
+
except EOFError:
|
|
74
|
+
console.print("\n[yellow]No answer (end of input): declined.[/yellow]")
|
|
75
|
+
return False
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
# ---------------------------------------------------------------------------------------------------------------- rendering
|
|
79
|
+
def _sev(sev: str) -> str:
|
|
80
|
+
return f"[{SEV_STYLE.get(sev, 'white')}]{sev}[/]"
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _state(st: dict) -> str:
|
|
84
|
+
label = st["state"].replace("_", " ")
|
|
85
|
+
if st.get("stale"):
|
|
86
|
+
label += " (approval invalidated)"
|
|
87
|
+
return f"[{STATE_STYLE.get(st['state'], 'white')}]{label}[/]"
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def candidates_table(rows: list[tuple[Candidate, dict]], title: str = "Remediation candidates") -> Table:
|
|
91
|
+
t = Table(title=title, show_lines=False)
|
|
92
|
+
t.add_column("ID", style="cyan", no_wrap=True)
|
|
93
|
+
t.add_column("Severity")
|
|
94
|
+
t.add_column("Type")
|
|
95
|
+
t.add_column("Change")
|
|
96
|
+
t.add_column("Location")
|
|
97
|
+
t.add_column("State")
|
|
98
|
+
for cand, st in rows:
|
|
99
|
+
where = ", ".join(f"{x['path']}" + (f":{x['line']}" if x.get("line") else "") for x in cand.targets) or "-"
|
|
100
|
+
kind = "manual" if cand.manual else ("dependency" if cand.kind == "dependency" else "code")
|
|
101
|
+
t.add_row(safe(cand.id), _sev(cand.severity), kind, safe(cand.title), safe(where), _state(st))
|
|
102
|
+
return t
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def show_diff(console: Console, diff: str, full: bool = False) -> None:
|
|
106
|
+
if not diff:
|
|
107
|
+
console.print("[dim]No automatic change: this is a manual recommendation.[/dim]")
|
|
108
|
+
return
|
|
109
|
+
lines = diff.splitlines()
|
|
110
|
+
diff = visible(diff) # a reviewer must see escape or bidi characters a change carries, and they must not act on the terminal
|
|
111
|
+
if full and len(lines) > PAGE_LINES and console.is_terminal:
|
|
112
|
+
with console.pager(styles=False):
|
|
113
|
+
console.print(diff, markup=False, highlight=False)
|
|
114
|
+
return
|
|
115
|
+
shown = diff if full or len(lines) <= PAGE_LINES else "\n".join(diff.splitlines()[:PAGE_LINES]) + f"\n... {len(lines) - PAGE_LINES} more line(s): press d for the full diff"
|
|
116
|
+
console.print(Syntax(shown, "diff", theme="ansi_dark", word_wrap=True, background_color="default"))
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def show_evidence(console: Console, cand: Candidate) -> None:
|
|
120
|
+
t = Table(title=f"Evidence for {cand.id}")
|
|
121
|
+
if cand.kind == "dependency":
|
|
122
|
+
for col in ("Advisory", "Package", "Installed", "Fixed in", "Severity", "Reachability", "Summary"):
|
|
123
|
+
t.add_column(col)
|
|
124
|
+
for e in cand.evidence:
|
|
125
|
+
t.add_row(safe(e.get("id")) + (" (KEV)" if e.get("kev") else ""), safe(e.get("package")), safe(e.get("installed")), safe(e.get("fixed") or "-"),
|
|
126
|
+
_sev(str(e.get("severity") or "UNKNOWN").upper()), safe(e.get("reachability") or "-"), safe(e.get("summary") or ""))
|
|
127
|
+
else:
|
|
128
|
+
for col in ("Rule", "Engine", "Location", "Snippet", "Classification"):
|
|
129
|
+
t.add_column(col)
|
|
130
|
+
for e in cand.evidence:
|
|
131
|
+
t.add_row(safe(e.get("id")), safe(e.get("engine")), safe(f"{e.get('file')}:{e.get('line')}"), safe((e.get("snippet") or "").strip()[:160]), safe(e.get("classification") or ""))
|
|
132
|
+
console.print(t)
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def show_candidate(console: Console, cand: Candidate, st: dict, index: int, total: int) -> None:
|
|
136
|
+
head = [f"[bold]{safe(cand.title)}[/bold]",
|
|
137
|
+
f"ID [cyan]{safe(cand.id)}[/cyan] Severity {_sev(cand.severity)} Confidence {safe(cand.confidence)} State {_state(st)}",
|
|
138
|
+
f"Findings: {safe(', '.join(cand.finding_ids[:12]))}" + (" ..." if len(cand.finding_ids) > 12 else "")]
|
|
139
|
+
for x in cand.targets:
|
|
140
|
+
head.append(f"Affected: {safe(x['path'])}" + (f" line {x['line']}" if x.get("line") else ""))
|
|
141
|
+
if cand.kind == "dependency" and cand.changes:
|
|
142
|
+
for ch in cand.changes[:6]:
|
|
143
|
+
head.append(safe(f"Current {ch['package']} {ch.get('from') or '?'} -> proposed {ch['to']} ({ch.get('kind', 'bump')})"))
|
|
144
|
+
elif cand.line_text:
|
|
145
|
+
head.append(f"Current line: {safe(cand.line_text.strip()[:200])}")
|
|
146
|
+
if cand.evidence:
|
|
147
|
+
e = cand.evidence[0]
|
|
148
|
+
head.append("Evidence: " + safe(f"{e.get('id')} in {e.get('package')} {e.get('installed')}" if cand.kind == "dependency"
|
|
149
|
+
else f"{e.get('id')} ({e.get('engine')}): {(e.get('snippet') or '').strip()[:120]}")
|
|
150
|
+
+ (f" (+{len(cand.evidence) - 1} more, press e)" if len(cand.evidence) > 1 else ""))
|
|
151
|
+
head.append(f"Why: {safe(cand.rationale)}")
|
|
152
|
+
if cand.compatibility:
|
|
153
|
+
head.append(f"Behavioural change / compatibility risk: {safe(cand.compatibility)}")
|
|
154
|
+
if cand.applicability and not cand.manual:
|
|
155
|
+
head.append(f"Applies because: {safe(cand.applicability)}")
|
|
156
|
+
if cand.validation_requirements and not cand.manual:
|
|
157
|
+
head.append(f"Check after applying: {safe(cand.validation_requirements)}")
|
|
158
|
+
validation = (st.get("detail") or {}).get("validation")
|
|
159
|
+
head.append(f"Validation: {safe(validation.get('status'))} (tests {safe(validation.get('tests'))})" if validation
|
|
160
|
+
else "Validation: not run yet (runs in an isolated worktree after approval)")
|
|
161
|
+
if cand.lock_note:
|
|
162
|
+
head.append(f"Lockfile: {safe(cand.lock_note)}")
|
|
163
|
+
if cand.alternatives:
|
|
164
|
+
head.append("Alternatives: " + "; ".join(safe(f"[{i + 1}] {a['title']}") + (" (selected)" if a["key"] == cand.choice else "")
|
|
165
|
+
for i, a in enumerate(cand.alternatives)))
|
|
166
|
+
if cand.manual:
|
|
167
|
+
head.append(f"[yellow]Manual recommendation:[/yellow] {safe(cand.recommendation)}")
|
|
168
|
+
if cand.stale_reason:
|
|
169
|
+
head.append(f"[yellow]{safe(cand.stale_reason)}[/yellow]")
|
|
170
|
+
if st.get("stale"):
|
|
171
|
+
head.append(f"[yellow]{safe(st['reason'])}[/yellow]")
|
|
172
|
+
console.print(Panel("\n".join(head), title=f"Remediation {index}/{total}", border_style="blue", expand=True))
|
|
173
|
+
show_diff(console, cand.diff)
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
# ---------------------------------------------------------------------------------------------------------------- review
|
|
177
|
+
def review(console: Console, db, scan: dict, only: Optional[list[str]] = None) -> dict:
|
|
178
|
+
"""Interactive review session. Every decision is recorded individually as it is made."""
|
|
179
|
+
def load() -> list[Candidate]:
|
|
180
|
+
cs = lifecycle.candidates(scan, lifecycle.choices_of(db, scan["repo"]["scan_id"]))
|
|
181
|
+
return [c for c in cs if not only or c.id in only]
|
|
182
|
+
|
|
183
|
+
cands = load()
|
|
184
|
+
if not cands:
|
|
185
|
+
console.print("[green]No remediation candidates for this scan.[/green]")
|
|
186
|
+
return {"approved": 0, "rejected": 0, "skipped": 0}
|
|
187
|
+
tally = {"approved": 0, "rejected": 0, "skipped": 0}
|
|
188
|
+
console.print(f"[bold]{len(cands)}[/bold] candidate(s). Nothing is changed in your repository during review.")
|
|
189
|
+
if not only: # resume an interrupted session: decisions already recorded are kept and not asked again
|
|
190
|
+
states = {c.id: lifecycle.status(db, scan, c)["state"] for c in cands}
|
|
191
|
+
decided = [c for c in cands if states[c.id] not in ("proposed", "pending_review")]
|
|
192
|
+
if decided:
|
|
193
|
+
cands = [c for c in cands if states[c.id] in ("proposed", "pending_review")]
|
|
194
|
+
console.print(f"{len(decided)} already decided and kept ({', '.join(sorted({states[c.id].replace('_', ' ') for c in decided}))}); "
|
|
195
|
+
f"reviewing the {len(cands)} undecided. Revisit one with: stackparity fix -i --id ID")
|
|
196
|
+
if not cands:
|
|
197
|
+
return tally
|
|
198
|
+
i = 0
|
|
199
|
+
shown = None
|
|
200
|
+
while i < len(cands):
|
|
201
|
+
cand = cands[i]
|
|
202
|
+
st = lifecycle.status(db, scan, cand)
|
|
203
|
+
if st["state"] in lifecycle.TERMINAL:
|
|
204
|
+
i += 1
|
|
205
|
+
continue
|
|
206
|
+
if shown != (cand.id, cand.choice): # redraw only when the candidate (or its selected fix) changes
|
|
207
|
+
show_candidate(console, cand, st, i + 1, len(cands))
|
|
208
|
+
shown = (cand.id, cand.choice)
|
|
209
|
+
options = (["s", "r", "e", "l", "x", "q"] if cand.manual else ["a", "r", "s", "d", "e", "o", "l", "g", "x", "q"])
|
|
210
|
+
legend = ("[s]kip [r]eject [e]vidence [l]ist e[x]port [q]uit" if cand.manual else
|
|
211
|
+
"[a]pprove [r]eject [s]kip [d]iff [e]vidence [o]ther fix [l]ist [g]roup approve e[x]port [q]uit")
|
|
212
|
+
try:
|
|
213
|
+
choice = Prompt.ask(escape(legend), choices=options, show_choices=False, console=console) # "[a]" is not a markup tag
|
|
214
|
+
except EOFError:
|
|
215
|
+
console.print("\n[yellow]End of input: review ended. Decisions already recorded are kept; nothing else changed.[/yellow]")
|
|
216
|
+
break
|
|
217
|
+
except KeyboardInterrupt:
|
|
218
|
+
console.print("\n[yellow]Interrupted: review ended. Decisions already recorded are kept; nothing else changed. "
|
|
219
|
+
"Run the same command to continue with the undecided candidates.[/yellow]")
|
|
220
|
+
console.print(f"Session: {tally['approved']} approved, {tally['rejected']} rejected, {tally['skipped']} skipped.")
|
|
221
|
+
raise SystemExit(130)
|
|
222
|
+
try:
|
|
223
|
+
if choice == "a":
|
|
224
|
+
reason = Prompt.ask("Reason (optional)", default="Reviewed the diff and evidence", console=console)
|
|
225
|
+
lifecycle.decide(db, scan, cand, "approved", actor(), reason)
|
|
226
|
+
tally["approved"] += 1
|
|
227
|
+
console.print(f"[green]{cand.id} approved.[/green] Only this change is approved.")
|
|
228
|
+
i += 1
|
|
229
|
+
elif choice == "r":
|
|
230
|
+
reason = Prompt.ask("Reason", default="Rejected after review", console=console)
|
|
231
|
+
lifecycle.decide(db, scan, cand, "rejected", actor(), reason)
|
|
232
|
+
tally["rejected"] += 1
|
|
233
|
+
i += 1
|
|
234
|
+
elif choice == "s":
|
|
235
|
+
lifecycle.decide(db, scan, cand, "skipped", actor(), "Skipped; review later")
|
|
236
|
+
tally["skipped"] += 1
|
|
237
|
+
i += 1
|
|
238
|
+
elif choice == "d":
|
|
239
|
+
show_diff(console, cand.diff, full=True)
|
|
240
|
+
elif choice == "e":
|
|
241
|
+
show_evidence(console, cand)
|
|
242
|
+
elif choice == "o":
|
|
243
|
+
if len(cand.alternatives) < 2 or not any(a.get("patch") for a in cand.alternatives):
|
|
244
|
+
console.print("[yellow]No alternative automatic fix exists for this candidate.[/yellow]")
|
|
245
|
+
for a in cand.alternatives:
|
|
246
|
+
console.print(f" - {a['title']}", markup=False)
|
|
247
|
+
continue
|
|
248
|
+
n = Prompt.ask("Alternative number", choices=[str(k + 1) for k in range(len(cand.alternatives))], console=console)
|
|
249
|
+
alt = cand.alternatives[int(n) - 1]
|
|
250
|
+
cands[i] = lifecycle._rechoose(scan, cand, alt["key"])
|
|
251
|
+
lifecycle.transition(db, scan, cands[i], "pending_review", actor(), f"Selected alternative {alt['key']}")
|
|
252
|
+
elif choice == "l":
|
|
253
|
+
console.print(candidates_table([(c, lifecycle.status(db, scan, c)) for c in cands]))
|
|
254
|
+
elif choice == "g":
|
|
255
|
+
ids = [x.strip().upper() for x in Prompt.ask("IDs to approve (comma separated)", console=console).split(",") if x.strip()]
|
|
256
|
+
group = [c for c in cands if c.id in ids and not c.manual]
|
|
257
|
+
missing = set(ids) - {c.id for c in group}
|
|
258
|
+
if missing:
|
|
259
|
+
console.print(f"[yellow]Not approvable or unknown: {', '.join(sorted(missing))}[/yellow]")
|
|
260
|
+
if group:
|
|
261
|
+
for c in group:
|
|
262
|
+
console.print(f"[bold]{c.id}[/bold] {c.title}")
|
|
263
|
+
show_diff(console, c.diff)
|
|
264
|
+
if ask_yes(console, f"Approve exactly these {len(group)} change(s)?"):
|
|
265
|
+
for c in group:
|
|
266
|
+
lifecycle.decide(db, scan, c, "approved", actor(), "Approved as part of a reviewed group")
|
|
267
|
+
tally["approved"] += 1
|
|
268
|
+
elif choice == "x":
|
|
269
|
+
path = Prompt.ask("Export the approved changes as a patch file to", default=str(default_patch_path(scan)), console=console)
|
|
270
|
+
export_patch(console, db, scan, Path(path))
|
|
271
|
+
elif choice == "q":
|
|
272
|
+
console.print("[yellow]Review cancelled. Decisions already recorded are kept; nothing else changed.[/yellow]")
|
|
273
|
+
break
|
|
274
|
+
except LifecycleError as exc:
|
|
275
|
+
console.print(f"[red]{safe(exc)}[/red]")
|
|
276
|
+
fresh = {c.id: c for c in load()}
|
|
277
|
+
cands = [fresh[c.id] for c in cands if c.id in fresh]
|
|
278
|
+
except EOFError:
|
|
279
|
+
console.print("\n[yellow]End of input: this candidate was not decided. Decisions already recorded are kept.[/yellow]")
|
|
280
|
+
break
|
|
281
|
+
except KeyboardInterrupt:
|
|
282
|
+
console.print("\n[yellow]Interrupted: this candidate was not decided. Decisions already recorded are kept.[/yellow]")
|
|
283
|
+
console.print(f"Session: {tally['approved']} approved, {tally['rejected']} rejected, {tally['skipped']} skipped.")
|
|
284
|
+
raise SystemExit(130)
|
|
285
|
+
console.print(f"Session: {tally['approved']} approved, {tally['rejected']} rejected, {tally['skipped']} skipped.")
|
|
286
|
+
return tally
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
# ---------------------------------------------------------------------------------------------------------------- apply / export
|
|
290
|
+
def default_patch_path(scan: dict) -> Path:
|
|
291
|
+
from config.settings import get_settings
|
|
292
|
+
stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
|
|
293
|
+
d = get_settings().artifacts_dir / "patches"
|
|
294
|
+
d.mkdir(parents=True, exist_ok=True)
|
|
295
|
+
return d / f"{scan['repo']['scan_id']}-{stamp}.patch"
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
def export_patch(console: Console, db, scan: dict, out: Path, run=None) -> Optional[Path]:
|
|
299
|
+
root = lifecycle.repo_root_of(scan)
|
|
300
|
+
approved = lifecycle.approved(db, scan)
|
|
301
|
+
if not approved or not root:
|
|
302
|
+
console.print("[yellow]No approved, applicable change to export.[/yellow]")
|
|
303
|
+
return None
|
|
304
|
+
diff = run.diff if run is not None and run.diff else lifecycle.combined_diff(*lifecycle.materialize(root, approved))
|
|
305
|
+
out.parent.mkdir(parents=True, exist_ok=True)
|
|
306
|
+
out.write_text(diff, encoding="utf-8", newline="")
|
|
307
|
+
console.print(f"[green]Wrote {len(approved)} approved change(s) to {out}[/green] Apply later with: git apply \"{out}\"")
|
|
308
|
+
return out
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
def network_policy(console: Console, scan: dict, operations: list[str], purpose: str, *, online: bool, interactive: bool):
|
|
312
|
+
"""The execution policy for a remediation step: the scan's own, plus network access the user explicitly authorizes.
|
|
313
|
+
|
|
314
|
+
An offline scan stays offline unless --online was passed or the user agrees at the prompt (``--yes`` does not count:
|
|
315
|
+
switching from offline to online is its own decision)."""
|
|
316
|
+
from core import netpolicy
|
|
317
|
+
pol = netpolicy.for_scan(scan)
|
|
318
|
+
if not pol.offline:
|
|
319
|
+
return pol
|
|
320
|
+
if online:
|
|
321
|
+
console.print(f"[yellow]This scan ran offline. Network access authorized by --online for: {', '.join(operations)}.[/yellow]")
|
|
322
|
+
return pol.authorize(operations, actor())
|
|
323
|
+
if interactive and ask_yes(console, f"This scan ran offline. {purpose} needs network access ({', '.join(operations)}). Allow it for this command"):
|
|
324
|
+
return pol.authorize(operations, actor())
|
|
325
|
+
console.print(f"[dim]Staying offline ({safe(pol.origin)}). Steps that need the network are reported as unavailable, not as passed. "
|
|
326
|
+
"Pass --online to allow them.[/dim]")
|
|
327
|
+
return pol
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
def lockfile_review(console: Console, run, interactive: bool, yes: bool, allow_stale: bool) -> tuple[bool, bool]:
|
|
331
|
+
"""Show lockfile changes that were not part of the reviewed diff and ask for them separately.
|
|
332
|
+
|
|
333
|
+
Returns (include_generated, allow_inconsistent). Nothing is assumed: each needs its own yes."""
|
|
334
|
+
include = allow = False
|
|
335
|
+
if run.generated:
|
|
336
|
+
console.print(f"[bold]Validation regenerated {len(run.generated)} lockfile(s) that were not in the diff you reviewed:[/bold]")
|
|
337
|
+
from remediation.patchers import unified_diff
|
|
338
|
+
for rel in sorted(run.generated):
|
|
339
|
+
d = unified_diff(rel, run.generated_originals.get(rel, ""), run.generated[rel])
|
|
340
|
+
console.print(f" {safe(rel)}: {sum(1 for line in d.splitlines() if line[:1] in '+-' and line[:3] not in ('+++', '---'))} changed line(s)")
|
|
341
|
+
if interactive and ask_yes(console, "Show the lockfile diff"):
|
|
342
|
+
show_diff(console, "".join(unified_diff(r, run.generated_originals.get(r, ""), run.generated[r]) for r in sorted(run.generated)))
|
|
343
|
+
include = confirm(console, "Include the regenerated lockfile(s)", interactive, yes)
|
|
344
|
+
if not run.lock_consistent:
|
|
345
|
+
stale = [e for e in run.lockfiles if not (e["status"] == "regenerated" and e["consistent"])]
|
|
346
|
+
for e in stale:
|
|
347
|
+
console.print(f"[yellow]{safe(e['lockfile'])} will not match the changed manifest ({safe(e['status'])}): {safe(e['detail'])}[/yellow]")
|
|
348
|
+
console.print(f" To fix it afterwards: {safe(e['command'])}", markup=False)
|
|
349
|
+
allow = allow_stale or (interactive and ask_yes(console, "Continue with a lockfile that does not match its manifest"))
|
|
350
|
+
if not allow and not interactive:
|
|
351
|
+
console.print("Declined: pass --allow-stale-lockfile to accept this, or --lockfiles to regenerate it.", markup=False)
|
|
352
|
+
return include, allow
|
|
353
|
+
|
|
354
|
+
|
|
355
|
+
def apply_to_working_tree(console: Console, db, scan: dict, run, files: dict[str, str], originals: dict[str, str], *,
|
|
356
|
+
interactive: bool, yes: bool, allow_stale: bool = False) -> bool:
|
|
357
|
+
"""Write the validated contents into the user's checkout through the lifecycle service (which re-checks everything)."""
|
|
358
|
+
include, allow = lockfile_review(console, run, interactive, yes, allow_stale)
|
|
359
|
+
if (run.generated and not include) or (not run.lock_consistent and not allow):
|
|
360
|
+
console.print("[yellow]Nothing was written.[/yellow]")
|
|
361
|
+
return False
|
|
362
|
+
if not confirm(console, f"Write {len(files) + (len(run.generated) if include else 0)} validated file change(s) into your checkout", interactive, yes):
|
|
363
|
+
return False
|
|
364
|
+
try:
|
|
365
|
+
written = lifecycle.apply_to_working_tree(db, scan, run, files, originals, actor(), include_generated=include, allow_inconsistent_lockfile=allow)
|
|
366
|
+
except LifecycleError as exc:
|
|
367
|
+
console.print(f"[red]{safe(exc)}[/red]")
|
|
368
|
+
return False
|
|
369
|
+
console.print(f"[green]Applied {len(written)} file(s) in {safe(lifecycle.repo_root_of(scan))}: {safe(', '.join(written))}.[/green] "
|
|
370
|
+
"They are uncommitted; review with git diff, undo with git restore.")
|
|
371
|
+
return True
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
def execute(console: Console, db, scan: dict, *, run_tests: bool, lockfiles: bool, publish: Optional[Callable] = None, base: Optional[str] = None,
|
|
375
|
+
policy=None, allow_build_code: bool = False):
|
|
376
|
+
"""Validate the approved changes in an isolated worktree (shared service) and print the actual results."""
|
|
377
|
+
approved = lifecycle.approved(db, scan)
|
|
378
|
+
if approved:
|
|
379
|
+
console.print(f"Validating {len(approved)} approved change(s) in an isolated Git worktree: {', '.join(c.id for c in approved)}")
|
|
380
|
+
with console.status("Applying in a temporary worktree, checking compatibility and rescanning...") if console.is_terminal and publish is None else _null():
|
|
381
|
+
run, files, error = lifecycle.validate_approved(db, scan, actor(), run_tests=run_tests, lockfiles=lockfiles, publish=publish, base=base,
|
|
382
|
+
policy=policy, allow_build_code=allow_build_code)
|
|
383
|
+
if error:
|
|
384
|
+
console.print(f"[yellow]{safe(error)}[/yellow]")
|
|
385
|
+
if "approve" in error:
|
|
386
|
+
console.print("Review with 'stackparity fix --interactive', or approve one with 'stackparity fix --approve ID'.")
|
|
387
|
+
return None, None
|
|
388
|
+
show_run(console, run)
|
|
389
|
+
return run, files
|
|
390
|
+
|
|
391
|
+
|
|
392
|
+
class _null:
|
|
393
|
+
def __enter__(self):
|
|
394
|
+
return self
|
|
395
|
+
|
|
396
|
+
def __exit__(self, *a):
|
|
397
|
+
return False
|
|
398
|
+
|
|
399
|
+
|
|
400
|
+
def show_run(console: Console, run) -> None:
|
|
401
|
+
r = run.rescan or {}
|
|
402
|
+
fixed = "not measured" if r.get("fixed_cve") is None else f"{r.get('fixed_cve')}/{r.get('targeted_cve')}"
|
|
403
|
+
color = {"validated": "green", "failed": "red"}.get(run.validation_status, "yellow")
|
|
404
|
+
lines = [f"Changes: {safe(', '.join(run.item_ids))}", f"Files: {safe(', '.join(run.files_changed) or 'none')}",
|
|
405
|
+
f"Tests: {safe(run.tests_status)} ({safe(run.tests_detail)})",
|
|
406
|
+
f"Rescan: advisories fixed {fixed}; new high/critical {r.get('new_high_critical', 'not measured')}; "
|
|
407
|
+
f"non-CVE fixed {r.get('fixed_non_cve', 'n/a')}/{r.get('targeted_non_cve', 0)}; new non-CVE {r.get('new_non_cve', 'n/a')}"]
|
|
408
|
+
if r.get("error"):
|
|
409
|
+
lines.append(f"Rescan error: {safe(r['error'])}")
|
|
410
|
+
for e in run.lockfiles:
|
|
411
|
+
lines.append(f"Lockfile {safe(e['lockfile'])} ({safe(e['adapter'])}): {safe(e['status'])}"
|
|
412
|
+
+ ("; verified consistent" if e.get("consistent") else "; NOT consistent with the manifest") + f" - {safe(e['detail'][:200])}")
|
|
413
|
+
pol = run.policy or {}
|
|
414
|
+
if pol.get("mode") == "offline":
|
|
415
|
+
lines.append(f"Network: offline ({safe(pol.get('origin'))})" + (f"; authorized: {safe(', '.join(pol['authorized']))}" if pol.get("authorized") else ""))
|
|
416
|
+
for w in run.compat_warnings[:8]:
|
|
417
|
+
lines.append(f"Compatibility: {safe(w)}")
|
|
418
|
+
lines.append(f"Validation status: [{color}]{run.validation_status}[/{color}]"
|
|
419
|
+
+ (" (tests did not run, so this is not a full validation)" if run.validation_status == "partially_validated_no_tests" else ""))
|
|
420
|
+
if run.error:
|
|
421
|
+
lines.append(f"[red]{safe(run.error)}[/red]")
|
|
422
|
+
console.print(Panel("\n".join(lines), title="Isolated validation (temporary worktree, your checkout untouched)", border_style=color))
|
|
423
|
+
if run.diff:
|
|
424
|
+
console.print("[bold]Final diff[/bold]")
|
|
425
|
+
show_diff(console, run.diff)
|
|
426
|
+
|
|
427
|
+
|
|
428
|
+
# ---------------------------------------------------------------------------------------------------------------- git / PR
|
|
429
|
+
def git_context(root: Path, check_auth: bool = True) -> dict:
|
|
430
|
+
"""Branch, origin, provider and GitHub CLI state. ``check_auth=False`` (offline policy) skips the network call to GitHub."""
|
|
431
|
+
from core.git_manager import run_git
|
|
432
|
+
from remediation.worktree_pr import gh_executable
|
|
433
|
+
gh = gh_executable()
|
|
434
|
+
ctx = {"branch": None, "remote": None, "provider": None, "gh": bool(gh), "gh_auth": False, "problems": []}
|
|
435
|
+
ctx["branch"] = run_git(["rev-parse", "--abbrev-ref", "HEAD"], cwd=root, check=False).stdout.strip() or None
|
|
436
|
+
remote = run_git(["config", "--get", "remote.origin.url"], cwd=root, check=False) # as configured (before insteadOf rewriting)
|
|
437
|
+
ctx["remote"] = remote.stdout.strip() if remote.returncode == 0 else None
|
|
438
|
+
if ctx["remote"]:
|
|
439
|
+
ctx["provider"] = "github" if "github.com" in ctx["remote"] else "other"
|
|
440
|
+
else:
|
|
441
|
+
ctx["problems"].append("No 'origin' remote is configured.")
|
|
442
|
+
if ctx["provider"] == "other":
|
|
443
|
+
ctx["problems"].append("Pull requests can only be opened automatically on GitHub; other providers get a patch export.")
|
|
444
|
+
if not ctx["gh"]:
|
|
445
|
+
ctx["problems"].append("GitHub CLI (gh) is not installed: https://cli.github.com")
|
|
446
|
+
elif ctx["provider"] == "github" and not check_auth:
|
|
447
|
+
ctx["problems"].append("GitHub authentication was not checked: the execution policy is offline (pass --online to publish).")
|
|
448
|
+
elif ctx["provider"] == "github":
|
|
449
|
+
p = subprocess.run([gh, "auth", "status", "--hostname", "github.com"], capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=30, shell=False)
|
|
450
|
+
ctx["gh_auth"] = p.returncode == 0
|
|
451
|
+
if not ctx["gh_auth"]:
|
|
452
|
+
ctx["problems"].append("GitHub CLI is not authenticated: run 'gh auth login'.")
|
|
453
|
+
return ctx
|
|
454
|
+
|
|
455
|
+
|
|
456
|
+
def preview_publish(console: Console, run, ctx: dict, base: Optional[str]) -> None:
|
|
457
|
+
body = run.pr_body if len(run.pr_body) < 4000 else run.pr_body[:4000] + "\n..."
|
|
458
|
+
console.print(Panel(safe(f"Branch: {run.branch}\nCommit: {(run.commit_sha or '')[:12]} {run.commit_message.splitlines()[0]}\n"
|
|
459
|
+
f"Remote: {ctx.get('remote')}\nBase: {base or 'repository default'}\nTitle: {run.pr_title}"),
|
|
460
|
+
title="Pull request preview", border_style="magenta"))
|
|
461
|
+
console.print(visible(body), markup=False, highlight=False)
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"""Terminal output that untrusted text cannot take over.
|
|
2
|
+
|
|
3
|
+
Repository files, package metadata, scanner output, advisory text and git/gh error messages all reach the terminal. A
|
|
4
|
+
control character in any of them could move the cursor, clear the screen, retitle the window, write to the clipboard
|
|
5
|
+
(OSC 52) or hide a line; a bidirectional-override character can make code read differently from what it does ("Trojan
|
|
6
|
+
Source"). ``SafeConsole`` rewrites the text of every rendered segment so such characters are shown as visible symbols
|
|
7
|
+
(``␛`` for ESC, ``<U+202E>`` for a right-to-left override) while Rich's own styling and cursor control still work. The
|
|
8
|
+
reviewer therefore sees that something unusual is in the content instead of having it silently removed.
|
|
9
|
+
"""
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import re
|
|
13
|
+
|
|
14
|
+
from rich.console import Console
|
|
15
|
+
from rich.segment import Segment
|
|
16
|
+
|
|
17
|
+
_C0 = {i: chr(0x2400 + i) for i in range(0x20) if i not in (0x09, 0x0A)} # ␀ ... ␟ (tab and newline stay)
|
|
18
|
+
_C0[0x7F] = "␡" # ␡
|
|
19
|
+
_BIDI = ""
|
|
20
|
+
_UNSAFE = re.compile("[\x00-\x08\x0b-\x1f\x7f\x80-\x9f" + _BIDI + "]")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _visible(m: re.Match) -> str:
|
|
24
|
+
c = m.group(0)
|
|
25
|
+
o = ord(c)
|
|
26
|
+
if o in _C0:
|
|
27
|
+
return _C0[o]
|
|
28
|
+
if 0x80 <= o <= 0x9F:
|
|
29
|
+
return f"\\x{o:02x}"
|
|
30
|
+
return f"<U+{o:04X}>"
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def visible(text) -> str:
|
|
34
|
+
"""``text`` with terminal control, C1 and bidi-override characters replaced by visible markers."""
|
|
35
|
+
return _UNSAFE.sub(_visible, "" if text is None else str(text))
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class SafeConsole(Console):
|
|
39
|
+
"""A Rich console whose rendered text can never carry raw control sequences from the content being printed."""
|
|
40
|
+
|
|
41
|
+
def _render_buffer(self, buffer): # noqa: D401 - Rich internal hook, stable across Rich 13-15
|
|
42
|
+
return super()._render_buffer(
|
|
43
|
+
seg if seg.control or not _UNSAFE.search(seg.text) else Segment(visible(seg.text), seg.style, seg.control)
|
|
44
|
+
for seg in buffer)
|
|
File without changes
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
"""Static tables shared across modules."""
|
|
2
|
+
|
|
3
|
+
IGNORED_DIRS = {
|
|
4
|
+
".git", "node_modules", ".venv", "venv", "__pycache__", "dist", "build", "target",
|
|
5
|
+
".tox", ".mypy_cache", ".pytest_cache", "bower_components", ".idea", ".vscode", ".guardian", ".stackparity", ".workspaces",
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
EXTENSION_LANGUAGES = {
|
|
9
|
+
".py": "Python", ".js": "JavaScript", ".jsx": "JavaScript", ".mjs": "JavaScript", ".cjs": "JavaScript",
|
|
10
|
+
".ts": "TypeScript", ".tsx": "TypeScript", ".java": "Java", ".kt": "Kotlin", ".go": "Go",
|
|
11
|
+
".rs": "Rust", ".cs": "C#", ".php": "PHP", ".rb": "Ruby", ".c": "C", ".h": "C",
|
|
12
|
+
".cpp": "C++", ".cc": "C++", ".hpp": "C++", ".swift": "Swift", ".scala": "Scala",
|
|
13
|
+
".dart": "Dart", ".ex": "Elixir", ".exs": "Elixir", ".hs": "Haskell", ".m": "Objective-C",
|
|
14
|
+
".sh": "Shell", ".ps1": "PowerShell", ".html": "HTML", ".css": "CSS", ".vue": "Vue",
|
|
15
|
+
}
|
|
16
|
+
MARKUP_LANGUAGES = {"HTML", "CSS"}
|
|
17
|
+
|
|
18
|
+
# file name -> (kind, ecosystem). kind: manifest | lockfile
|
|
19
|
+
MANIFEST_FILES = {
|
|
20
|
+
"package.json": ("manifest", "npm"),
|
|
21
|
+
"package-lock.json": ("lockfile", "npm"),
|
|
22
|
+
"npm-shrinkwrap.json": ("lockfile", "npm"),
|
|
23
|
+
"yarn.lock": ("lockfile", "npm"),
|
|
24
|
+
"pnpm-lock.yaml": ("lockfile", "npm"),
|
|
25
|
+
"requirements.txt": ("lockfile", "PyPI"), # pinned requirements act as resolution
|
|
26
|
+
"pyproject.toml": ("manifest", "PyPI"),
|
|
27
|
+
"setup.py": ("manifest", "PyPI"),
|
|
28
|
+
"Pipfile": ("manifest", "PyPI"),
|
|
29
|
+
"Pipfile.lock": ("lockfile", "PyPI"),
|
|
30
|
+
"poetry.lock": ("lockfile", "PyPI"),
|
|
31
|
+
"uv.lock": ("lockfile", "PyPI"),
|
|
32
|
+
"pom.xml": ("manifest", "Maven"),
|
|
33
|
+
"build.gradle": ("manifest", "Maven"),
|
|
34
|
+
"build.gradle.kts": ("manifest", "Maven"),
|
|
35
|
+
"gradle.lockfile": ("lockfile", "Maven"),
|
|
36
|
+
"go.mod": ("manifest", "Go"),
|
|
37
|
+
"go.sum": ("lockfile", "Go"),
|
|
38
|
+
"Cargo.toml": ("manifest", "crates.io"),
|
|
39
|
+
"Cargo.lock": ("lockfile", "crates.io"),
|
|
40
|
+
"composer.json": ("manifest", "Packagist"),
|
|
41
|
+
"composer.lock": ("lockfile", "Packagist"),
|
|
42
|
+
"packages.lock.json": ("lockfile", "NuGet"),
|
|
43
|
+
"Gemfile": ("manifest", "RubyGems"),
|
|
44
|
+
"Gemfile.lock": ("lockfile", "RubyGems"),
|
|
45
|
+
}
|
|
46
|
+
MANIFEST_SUFFIXES = {".csproj": ("manifest", "NuGet"), ".fsproj": ("manifest", "NuGet"), ".vbproj": ("manifest", "NuGet")}
|
|
47
|
+
|
|
48
|
+
CI_FILE_PATTERNS = (".github/workflows/", ".gitlab-ci.yml", "Jenkinsfile", ".circleci/", "azure-pipelines.yml",
|
|
49
|
+
".travis.yml", "bitbucket-pipelines.yml", "Procfile")
|
|
50
|
+
|
|
51
|
+
# PURL type -> OSV ecosystem
|
|
52
|
+
PURL_TO_OSV = {
|
|
53
|
+
"npm": "npm", "pypi": "PyPI", "golang": "Go", "cargo": "crates.io", "maven": "Maven",
|
|
54
|
+
"composer": "Packagist", "nuget": "NuGet", "gem": "RubyGems",
|
|
55
|
+
}
|
|
56
|
+
OSV_TO_PURL = {v: k for k, v in PURL_TO_OSV.items()}
|
|
57
|
+
|
|
58
|
+
SEVERITY_ORDER = ["CRITICAL", "HIGH", "MEDIUM", "LOW"]
|
|
59
|
+
RISK_ORDER = ["CRITICAL", "HIGH", "MEDIUM", "LOW", "INFORMATIONAL"]
|
|
60
|
+
|
|
61
|
+
FRAMEWORK_HINTS = {
|
|
62
|
+
"npm": {
|
|
63
|
+
"react": "React", "next": "Next.js", "vue": "Vue.js", "@angular/core": "Angular", "svelte": "Svelte",
|
|
64
|
+
"express": "Express", "@nestjs/core": "NestJS", "koa": "Koa", "fastify": "Fastify", "hapi": "Hapi",
|
|
65
|
+
"@hapi/hapi": "Hapi", "nuxt": "Nuxt", "gatsby": "Gatsby", "electron": "Electron", "vite": "Vite",
|
|
66
|
+
"jest": "Jest", "mocha": "Mocha", "grunt": "Grunt", "webpack": "Webpack",
|
|
67
|
+
},
|
|
68
|
+
"PyPI": {
|
|
69
|
+
"django": "Django", "flask": "Flask", "fastapi": "FastAPI", "streamlit": "Streamlit", "tornado": "Tornado",
|
|
70
|
+
"pyramid": "Pyramid", "starlette": "Starlette", "aiohttp": "aiohttp", "celery": "Celery",
|
|
71
|
+
"pytest": "pytest", "pandas": "pandas", "numpy": "NumPy", "torch": "PyTorch", "tensorflow": "TensorFlow",
|
|
72
|
+
},
|
|
73
|
+
"Maven": {
|
|
74
|
+
"spring-boot": "Spring Boot", "springframework": "Spring", "quarkus": "Quarkus", "micronaut": "Micronaut",
|
|
75
|
+
"jakarta": "Jakarta EE", "struts": "Apache Struts", "junit": "JUnit",
|
|
76
|
+
},
|
|
77
|
+
"Go": {"gin-gonic/gin": "Gin", "labstack/echo": "Echo", "gofiber/fiber": "Fiber", "gorilla/mux": "Gorilla Mux"},
|
|
78
|
+
"crates.io": {"actix-web": "Actix Web", "rocket": "Rocket", "axum": "Axum", "tokio": "Tokio", "warp": "Warp"},
|
|
79
|
+
"Packagist": {"laravel/framework": "Laravel", "symfony/": "Symfony", "slim/slim": "Slim", "cakephp/cakephp": "CakePHP"},
|
|
80
|
+
"NuGet": {"Microsoft.AspNetCore": "ASP.NET Core", "Microsoft.EntityFrameworkCore": "Entity Framework Core",
|
|
81
|
+
"xunit": "xUnit", "NUnit": "NUnit"},
|
|
82
|
+
"RubyGems": {"rails": "Ruby on Rails", "sinatra": "Sinatra"},
|
|
83
|
+
}
|
|
84
|
+
FRAMEWORK_CONFIG_FILES = {
|
|
85
|
+
"manage.py": "Django", "next.config.js": "Next.js", "next.config.mjs": "Next.js", "angular.json": "Angular",
|
|
86
|
+
"vite.config.js": "Vite", "vite.config.ts": "Vite", "nuxt.config.js": "Nuxt", "svelte.config.js": "Svelte",
|
|
87
|
+
"artisan": "Laravel", "gatsby-config.js": "Gatsby", "Gruntfile.js": "Grunt", "webpack.config.js": "Webpack",
|
|
88
|
+
}
|