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.
Files changed (212) hide show
  1. stackparity/__init__.py +17 -0
  2. stackparity/_engine/agents/investigator.py +294 -0
  3. stackparity/_engine/agents/memory_agent.py +37 -0
  4. stackparity/_engine/agents/pipeline_agent.py +152 -0
  5. stackparity/_engine/agents/remediation_agent.py +248 -0
  6. stackparity/_engine/agents/runtime.py +177 -0
  7. stackparity/_engine/agents/specialists.py +709 -0
  8. stackparity/_engine/agents/suspicious_change_agent.py +1275 -0
  9. stackparity/_engine/cli/__init__.py +2 -0
  10. stackparity/_engine/cli/main.py +1252 -0
  11. stackparity/_engine/cli/remediate.py +461 -0
  12. stackparity/_engine/cli/term.py +44 -0
  13. stackparity/_engine/config/__init__.py +0 -0
  14. stackparity/_engine/config/constants.py +88 -0
  15. stackparity/_engine/config/loader.py +155 -0
  16. stackparity/_engine/config/settings.py +108 -0
  17. stackparity/_engine/containers/__init__.py +12 -0
  18. stackparity/_engine/containers/discovery.py +143 -0
  19. stackparity/_engine/containers/models.py +72 -0
  20. stackparity/_engine/containers/trivy_image_scanner.py +165 -0
  21. stackparity/_engine/core/__init__.py +0 -0
  22. stackparity/_engine/core/capabilities.py +107 -0
  23. stackparity/_engine/core/finding_schema.py +305 -0
  24. stackparity/_engine/core/git_manager.py +206 -0
  25. stackparity/_engine/core/http.py +64 -0
  26. stackparity/_engine/core/models.py +109 -0
  27. stackparity/_engine/core/netpolicy.py +242 -0
  28. stackparity/_engine/core/plugins.py +43 -0
  29. stackparity/_engine/core/repository_inspector.py +243 -0
  30. stackparity/_engine/core/safe_env.py +48 -0
  31. stackparity/_engine/core/scan_orchestrator.py +289 -0
  32. stackparity/_engine/core/scan_state.py +58 -0
  33. stackparity/_engine/core/url_validator.py +135 -0
  34. stackparity/_engine/ecosystems/__init__.py +1 -0
  35. stackparity/_engine/ecosystems/registry.py +138 -0
  36. stackparity/_engine/evidence/__init__.py +1 -0
  37. stackparity/_engine/evidence/store.py +65 -0
  38. stackparity/_engine/explainability/__init__.py +0 -0
  39. stackparity/_engine/explainability/evidence_formatter.py +30 -0
  40. stackparity/_engine/explainability/explanation_engine.py +132 -0
  41. stackparity/_engine/explainability/explanation_validator.py +54 -0
  42. stackparity/_engine/explainability/prompt_templates.py +18 -0
  43. stackparity/_engine/graph/__init__.py +0 -0
  44. stackparity/_engine/graph/dependency_tracer.py +86 -0
  45. stackparity/_engine/graph/graph_builder.py +165 -0
  46. stackparity/_engine/graph/graph_diff.py +57 -0
  47. stackparity/_engine/graph/graph_exporter.py +194 -0
  48. stackparity/_engine/graph/graph_validator.py +46 -0
  49. stackparity/_engine/graph/impact_analyzer.py +23 -0
  50. stackparity/_engine/graph/tree_view.py +185 -0
  51. stackparity/_engine/intel/__init__.py +0 -0
  52. stackparity/_engine/intel/epss.py +53 -0
  53. stackparity/_engine/llm/__init__.py +1 -0
  54. stackparity/_engine/llm/client.py +138 -0
  55. stackparity/_engine/monitor/__init__.py +0 -0
  56. stackparity/_engine/monitor/watch.py +171 -0
  57. stackparity/_engine/non_cve/__init__.py +7 -0
  58. stackparity/_engine/non_cve/base.py +62 -0
  59. stackparity/_engine/non_cve/iac.py +144 -0
  60. stackparity/_engine/non_cve/sast.py +272 -0
  61. stackparity/_engine/non_cve/supply_chain.py +147 -0
  62. stackparity/_engine/orchestration/__init__.py +1 -0
  63. stackparity/_engine/orchestration/pipeline.py +279 -0
  64. stackparity/_engine/orchestration/supervisor.py +167 -0
  65. stackparity/_engine/pipeline_analysis/__init__.py +0 -0
  66. stackparity/_engine/pipeline_analysis/analyzer.py +90 -0
  67. stackparity/_engine/pipeline_analysis/ci.py +189 -0
  68. stackparity/_engine/pipeline_analysis/ci_adapters/__init__.py +24 -0
  69. stackparity/_engine/pipeline_analysis/ci_adapters/azure_pipelines.py +221 -0
  70. stackparity/_engine/pipeline_analysis/ci_adapters/base.py +239 -0
  71. stackparity/_engine/pipeline_analysis/ci_adapters/circleci.py +176 -0
  72. stackparity/_engine/pipeline_analysis/ci_adapters/github_actions.py +356 -0
  73. stackparity/_engine/pipeline_analysis/ci_adapters/gitlab_ci.py +268 -0
  74. stackparity/_engine/pipeline_analysis/ci_adapters/jenkins.py +180 -0
  75. stackparity/_engine/pipeline_analysis/ci_adapters/registry.py +80 -0
  76. stackparity/_engine/pipeline_analysis/ci_models.py +72 -0
  77. stackparity/_engine/pipeline_analysis/dockerfile.py +235 -0
  78. stackparity/_engine/pipeline_analysis/eol.py +62 -0
  79. stackparity/_engine/pipeline_analysis/models.py +37 -0
  80. stackparity/_engine/policy/__init__.py +0 -0
  81. stackparity/_engine/policy/engine.py +216 -0
  82. stackparity/_engine/policy/resources/default.yaml +56 -0
  83. stackparity/_engine/policy/resources/strict.yaml +35 -0
  84. stackparity/_engine/reachability/__init__.py +0 -0
  85. stackparity/_engine/reachability/app_reachability.py +186 -0
  86. stackparity/_engine/reachability/scanners.py +215 -0
  87. stackparity/_engine/remediation/__init__.py +0 -0
  88. stackparity/_engine/remediation/adapters.py +198 -0
  89. stackparity/_engine/remediation/apply_local.py +309 -0
  90. stackparity/_engine/remediation/code_fixes.py +383 -0
  91. stackparity/_engine/remediation/compat.py +156 -0
  92. stackparity/_engine/remediation/container_plan.py +127 -0
  93. stackparity/_engine/remediation/delivery.py +31 -0
  94. stackparity/_engine/remediation/export.py +44 -0
  95. stackparity/_engine/remediation/lifecycle.py +623 -0
  96. stackparity/_engine/remediation/local_trial.py +358 -0
  97. stackparity/_engine/remediation/patchers.py +215 -0
  98. stackparity/_engine/remediation/planner.py +285 -0
  99. stackparity/_engine/remediation/pr_template_engine.py +234 -0
  100. stackparity/_engine/remediation/reachability_impact.py +147 -0
  101. stackparity/_engine/remediation/versions.py +92 -0
  102. stackparity/_engine/remediation/whatif.py +64 -0
  103. stackparity/_engine/remediation/worktree_pr.py +434 -0
  104. stackparity/_engine/reporting/__init__.py +0 -0
  105. stackparity/_engine/reporting/counts.py +63 -0
  106. stackparity/_engine/reporting/fix_pdf.py +343 -0
  107. stackparity/_engine/reporting/fix_report.py +135 -0
  108. stackparity/_engine/reporting/json_exporter.py +61 -0
  109. stackparity/_engine/reporting/report_generator.py +200 -0
  110. stackparity/_engine/reporting/sarif.py +71 -0
  111. stackparity/_engine/reporting/vex.py +57 -0
  112. stackparity/_engine/reporting/view.py +166 -0
  113. stackparity/_engine/risk_analysis/__init__.py +0 -0
  114. stackparity/_engine/risk_analysis/contextual_scorer.py +253 -0
  115. stackparity/_engine/risk_analysis/evidence_collector.py +62 -0
  116. stackparity/_engine/risk_analysis/evidence_normalizer.py +37 -0
  117. stackparity/_engine/risk_analysis/finding_correlator.py +90 -0
  118. stackparity/_engine/risk_analysis/function_impact.py +184 -0
  119. stackparity/_engine/risk_analysis/production_context.py +252 -0
  120. stackparity/_engine/risk_analysis/risk_rules.py +81 -0
  121. stackparity/_engine/risk_analysis/risk_scorer.py +390 -0
  122. stackparity/_engine/sandbox/__init__.py +0 -0
  123. stackparity/_engine/sandbox/runner.py +142 -0
  124. stackparity/_engine/sbom/__init__.py +0 -0
  125. stackparity/_engine/sbom/adapters/__init__.py +19 -0
  126. stackparity/_engine/sbom/adapters/builtin.py +29 -0
  127. stackparity/_engine/sbom/adapters/syft.py +26 -0
  128. stackparity/_engine/sbom/adapters/trivy.py +76 -0
  129. stackparity/_engine/sbom/builtin_generator.py +227 -0
  130. stackparity/_engine/sbom/cyclonedx_validator.py +166 -0
  131. stackparity/_engine/sbom/exporters.py +153 -0
  132. stackparity/_engine/sbom/fusion/__init__.py +5 -0
  133. stackparity/_engine/sbom/fusion/engine.py +315 -0
  134. stackparity/_engine/sbom/fusion/hashes.py +47 -0
  135. stackparity/_engine/sbom/fusion/ledger.py +96 -0
  136. stackparity/_engine/sbom/fusion/registries.py +271 -0
  137. stackparity/_engine/sbom/fusion/resolver.py +143 -0
  138. stackparity/_engine/sbom/fusion/writer.py +114 -0
  139. stackparity/_engine/sbom/lockfile_analyzer.py +114 -0
  140. stackparity/_engine/sbom/merge.py +71 -0
  141. stackparity/_engine/sbom/package_extractors/common.py +104 -0
  142. stackparity/_engine/sbom/package_extractors/manifests.py +101 -0
  143. stackparity/_engine/sbom/package_extractors/npm.py +206 -0
  144. stackparity/_engine/sbom/package_extractors/others.py +267 -0
  145. stackparity/_engine/sbom/package_extractors/python.py +143 -0
  146. stackparity/_engine/sbom/quality_analyzer.py +191 -0
  147. stackparity/_engine/sbom/scanner_engine.py +98 -0
  148. stackparity/_engine/sbom/syft_runner.py +100 -0
  149. stackparity/_engine/sbom/tool_locator.py +69 -0
  150. stackparity/_engine/sbom/trivy_runner.py +82 -0
  151. stackparity/_engine/storage/__init__.py +0 -0
  152. stackparity/_engine/storage/cache.py +56 -0
  153. stackparity/_engine/storage/database.py +295 -0
  154. stackparity/_engine/storage/memory.py +146 -0
  155. stackparity/_engine/suspicious_changes/__init__.py +12 -0
  156. stackparity/_engine/suspicious_changes/analyzer.py +1022 -0
  157. stackparity/_engine/suspicious_changes/change_correlation.py +861 -0
  158. stackparity/_engine/suspicious_changes/lifecycle_script_detector.py +263 -0
  159. stackparity/_engine/suspicious_changes/lockfile_change_detector.py +316 -0
  160. stackparity/_engine/suspicious_changes/manifest_diff_detector.py +251 -0
  161. stackparity/_engine/suspicious_changes/package_risk.py +78 -0
  162. stackparity/_engine/suspicious_changes/popular_packages.py +94 -0
  163. stackparity/_engine/suspicious_changes/registry_detector.py +354 -0
  164. stackparity/_engine/suspicious_changes/suspicious_models.py +57 -0
  165. stackparity/_engine/suspicious_changes/typosquatting_detector.py +298 -0
  166. stackparity/_engine/tools/__init__.py +1 -0
  167. stackparity/_engine/tools/builtin.py +93 -0
  168. stackparity/_engine/tools/registry.py +66 -0
  169. stackparity/_engine/ui/__init__.py +0 -0
  170. stackparity/_engine/ui/components/__init__.py +0 -0
  171. stackparity/_engine/ui/components/common.py +238 -0
  172. stackparity/_engine/ui/components/live_progress.py +157 -0
  173. stackparity/_engine/ui/components/memory_panel.py +82 -0
  174. stackparity/_engine/ui/pages/__init__.py +0 -0
  175. stackparity/_engine/ui/pages/agents_page.py +76 -0
  176. stackparity/_engine/ui/pages/architecture_page.py +44 -0
  177. stackparity/_engine/ui/pages/fixes_page.py +98 -0
  178. stackparity/_engine/ui/pages/graph_page.py +203 -0
  179. stackparity/_engine/ui/pages/health_page.py +117 -0
  180. stackparity/_engine/ui/pages/monitor_page.py +67 -0
  181. stackparity/_engine/ui/pages/pipeline_page.py +219 -0
  182. stackparity/_engine/ui/pages/remediation_page.py +409 -0
  183. stackparity/_engine/ui/pages/reports_page.py +54 -0
  184. stackparity/_engine/ui/pages/sbom_page.py +210 -0
  185. stackparity/_engine/ui/pages/scan_page.py +131 -0
  186. stackparity/_engine/ui/pages/suspicious_page.py +551 -0
  187. stackparity/_engine/ui/pages/vulns_page.py +201 -0
  188. stackparity/_engine/ui/state.py +116 -0
  189. stackparity/_engine/ui/theme.py +201 -0
  190. stackparity/_engine/ui/visualizations/__init__.py +0 -0
  191. stackparity/_engine/ui/visualizations/graphs.py +373 -0
  192. stackparity/_engine/vulnerability/__init__.py +0 -0
  193. stackparity/_engine/vulnerability/cvss.py +58 -0
  194. stackparity/_engine/vulnerability/kev_client.py +47 -0
  195. stackparity/_engine/vulnerability/nvd_client.py +74 -0
  196. stackparity/_engine/vulnerability/osv_client.py +139 -0
  197. stackparity/_engine/vulnerability/remediation_engine.py +50 -0
  198. stackparity/_engine/vulnerability/verification.py +94 -0
  199. stackparity/_engine/vulnerability/version_matcher.py +299 -0
  200. stackparity/_engine/vulnerability/vulnerability_correlator.py +303 -0
  201. stackparity/_engine/vulnerability/vulnerability_models.py +64 -0
  202. stackparity/cli.py +30 -0
  203. stackparity/dashboard_app.py +95 -0
  204. stackparity/web_dist/assets/index-DRJYw2Du.css +1 -0
  205. stackparity/web_dist/assets/index-Q6LLpbEi.js +495 -0
  206. stackparity/web_dist/index.html +13 -0
  207. stackparity/web_server.py +533 -0
  208. stackparity-1.0.0.dist-info/METADATA +204 -0
  209. stackparity-1.0.0.dist-info/RECORD +212 -0
  210. stackparity-1.0.0.dist-info/WHEEL +4 -0
  211. stackparity-1.0.0.dist-info/entry_points.txt +2 -0
  212. stackparity-1.0.0.dist-info/licenses/LICENSE +201 -0
@@ -0,0 +1,13 @@
1
+ <!doctype html>
2
+ <html lang="en" class="dark">
3
+ <head>
4
+ <meta charset="UTF-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
+ <title>StackParity | Security Review Dashboard</title>
7
+ <script type="module" crossorigin src="/assets/index-Q6LLpbEi.js"></script>
8
+ <link rel="stylesheet" crossorigin href="/assets/index-DRJYw2Du.css">
9
+ </head>
10
+ <body class="bg-[#0B0F17] text-slate-100 antialiased selection:bg-blue-500/30">
11
+ <div id="root"></div>
12
+ </body>
13
+ </html>
@@ -0,0 +1,533 @@
1
+ """High-speed local Starlette + Uvicorn backend for the StackParity React dashboard.
2
+
3
+ Serves the compiled Vite/React SPA from src/stackparity/web_dist/ and provides
4
+ REST + WebSocket endpoints backed directly by the local SQLite database.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import asyncio
9
+ import getpass
10
+ import hmac
11
+ import json
12
+ import os
13
+ import re
14
+ import secrets
15
+ import threading
16
+ from concurrent.futures import CancelledError
17
+ import sys
18
+ from pathlib import Path
19
+ from typing import Any
20
+
21
+ _PKG_PARENT = str(Path(__file__).resolve().parent.parent)
22
+ if _PKG_PARENT not in sys.path:
23
+ sys.path.insert(0, _PKG_PARENT)
24
+ import stackparity # noqa: E402,F401 (an installed wheel puts the engine modules on sys.path here)
25
+
26
+ from starlette.applications import Starlette # noqa: E402
27
+ from starlette.middleware.trustedhost import TrustedHostMiddleware # noqa: E402
28
+ from starlette.responses import Response # noqa: E402
29
+ from starlette.routing import Mount, Route, WebSocketRoute # noqa: E402
30
+ from starlette.staticfiles import StaticFiles # noqa: E402
31
+ from starlette.websockets import WebSocket, WebSocketDisconnect # noqa: E402
32
+
33
+ from config.settings import get_settings # noqa: E402
34
+ from reporting import json_exporter, report_generator # noqa: E402
35
+ from reporting.sarif import to_sarif # noqa: E402
36
+ from reporting.view import dashboard_view # noqa: E402
37
+ from reporting.vex import to_vex # noqa: E402
38
+ from storage.database import Database # noqa: E402
39
+ from stackparity import __version__ # noqa: E402
40
+ from storage.memory import Memory # noqa: E402
41
+
42
+ WEB_DIST_DIR = Path(__file__).resolve().parent / "web_dist"
43
+ # Writes need this per-launch token. The page receives it in a meta tag; other sites cannot read it (same-origin policy) and
44
+ # DNS rebinding is refused by the Host check, so only this dashboard's own page can change state.
45
+ SESSION_TOKEN = os.environ.get("STACKPARITY_DASHBOARD_TOKEN") or secrets.token_urlsafe(24)
46
+
47
+
48
+ def _json_resp(payload: Any, status_code: int = 200) -> Response:
49
+ return Response(
50
+ content=json.dumps(payload, default=str),
51
+ status_code=status_code,
52
+ media_type="application/json",
53
+ )
54
+
55
+
56
+ def _local_user() -> str:
57
+ try:
58
+ return getpass.getuser()
59
+ except (OSError, KeyError, ImportError):
60
+ return "local-user"
61
+
62
+
63
+ def _db() -> Database:
64
+ return Database(get_settings().db_path)
65
+
66
+
67
+ def _list_scans(limit: int = 25) -> list[dict[str, Any]]:
68
+ return _db().list_scans(limit)
69
+
70
+
71
+ def _db_mtime_ns(p: Path) -> int:
72
+ wal = Path(f"{p}-wal")
73
+ times = [0]
74
+ for file in (p, wal):
75
+ try:
76
+ times.append(file.stat().st_mtime_ns)
77
+ except FileNotFoundError:
78
+ continue
79
+ return max(times)
80
+
81
+
82
+ async def api_job(request):
83
+ state = request.app.state
84
+ if request.method == "GET":
85
+ return _json_resp(state.job)
86
+ body = await _write_body(request)
87
+ if isinstance(body, Response):
88
+ return body
89
+ busy = state.job.get("status") in ("running", "cancelling")
90
+ if request.method == "DELETE":
91
+ if not busy:
92
+ return _json_resp({"error": "No active scan"}, 409)
93
+ state.cancel.set()
94
+ state.job = {**state.job, "status": "cancelling"}
95
+ return _json_resp(state.job, 202)
96
+ if busy:
97
+ return _json_resp({"error": "A scan is already running"}, 409)
98
+ target = body.get("target")
99
+ offline = body.get("offline", False)
100
+ deep = body.get("deep", False)
101
+ if not isinstance(target, str) or not target.strip() or not isinstance(offline, bool) or not isinstance(deep, bool):
102
+ return _json_resp({"error": "A local directory and boolean offline and deep modes are required"}, 400)
103
+ path = Path(target).expanduser()
104
+ if path.as_posix().startswith("//") or not path.is_dir():
105
+ return _json_resp({"error": "Local directory unavailable"}, 400)
106
+ from core.scan_orchestrator import ScanOptions, run_scan
107
+ loop = asyncio.get_running_loop()
108
+ state.cancel = threading.Event()
109
+ state.job = {"status": "running", "target": str(path), "progress": 0.0}
110
+ def progress(event):
111
+ if state.job.get("status") in ("running", "cancelling"):
112
+ state.job = {**state.job, "step": event["step"], "agent": event.get("agent"), "message": event["message"], "progress": event["progress"]}
113
+ async def execute():
114
+ try:
115
+ options = ScanOptions.for_profile(str(path.resolve()), deep=deep, offline=offline, cancelled=state.cancel.is_set)
116
+ result = await asyncio.to_thread(run_scan, options, on_event=lambda e: loop.call_soon_threadsafe(progress, e))
117
+ state.job = {"status": result["status"], "scan_id": result["repo"]["scan_id"]}
118
+ except (CancelledError, asyncio.CancelledError):
119
+ state.job = {"status": "cancelled"}
120
+ except Exception as exc:
121
+ state.job = {"status": "failed", "error": str(exc)[:300]}
122
+ state.task = asyncio.create_task(execute())
123
+ return _json_resp(state.job, 202)
124
+
125
+
126
+ async def api_health(request) -> Response: # type: ignore[no-untyped-def]
127
+ return _json_resp({"status": "ok", "version": __version__})
128
+
129
+
130
+ async def api_diagnostics(request) -> Response: # type: ignore[no-untyped-def]
131
+ from core.capabilities import diagnostics
132
+ return _json_resp(await asyncio.to_thread(diagnostics, get_settings()))
133
+
134
+
135
+ def api_list_scans(request) -> Response: # type: ignore[no-untyped-def]
136
+ try:
137
+ limit = int(request.query_params.get("limit", "25"))
138
+ offset = int(request.query_params.get("offset", "0"))
139
+ if not 1 <= limit <= 1000 or not 0 <= offset <= 2**31-1:
140
+ raise ValueError
141
+ except ValueError:
142
+ return _json_resp({"error": "limit must be between 1 and 1000"}, 400)
143
+ return _json_resp({"scans": _db().list_scans(limit, offset)})
144
+
145
+
146
+
147
+ def api_get_scan(request) -> Response: # type: ignore[no-untyped-def]
148
+ scan_id = request.path_params["scan_id"]
149
+ db = _db()
150
+ if scan_id == "latest":
151
+ recent = db.list_scans(limit=1)
152
+ if not recent:
153
+ return _json_resp({"error": "No scans found"}, status_code=404)
154
+ scan_id = recent[0]["scan_id"]
155
+ data = db.load_scan(scan_id)
156
+ if not data:
157
+ return _json_resp({"error": f"Scan {scan_id} not found"}, status_code=404)
158
+
159
+ data["remediation_runs"] = db.remediation_runs(scan_id)
160
+ try:
161
+ from remediation import lifecycle
162
+ data["remediation_lifecycle"] = lifecycle.overview(db, data)
163
+ except Exception as exc: # the scan is still readable; say why the review list is missing
164
+ data["remediation_lifecycle"] = []
165
+ data.setdefault("limitations", []).append(f"Remediation review state unavailable: {type(exc).__name__}")
166
+ # Enrich with persisted approval decisions
167
+ try:
168
+ mem = Memory(db)
169
+ repo_url = (data.get("repo") or {}).get("url") or ""
170
+ if repo_url:
171
+ data["approvals"] = mem.approvals(repo_url)
172
+ except Exception:
173
+ data.setdefault("limitations", []).append("Approval history is unavailable.")
174
+ try:
175
+ data["view"] = dashboard_view(data)
176
+ except (KeyError, TypeError, AttributeError) as exc:
177
+ return _json_resp({"error": f"Stored scan {scan_id} cannot be read ({type(exc).__name__}). Scan the project again."}, 422)
178
+ return _json_resp(data)
179
+
180
+
181
+ async def _write_body(request):
182
+ if request.headers.get("origin") not in (None, str(request.base_url).rstrip("/")):
183
+ return _json_resp({"error": "Cross-origin write denied"}, 403)
184
+ if not hmac.compare_digest(request.headers.get("x-stackparity-token", ""), SESSION_TOKEN):
185
+ return _json_resp({"error": "Missing or invalid dashboard session token; reload the page opened by 'stackparity dashboard'"}, 403)
186
+ if request.headers.get("content-type", "").split(";")[0] != "application/json":
187
+ return _json_resp({"error": "JSON required"}, 415)
188
+ try:
189
+ payload = bytearray()
190
+ async for chunk in request.stream():
191
+ if len(payload) + len(chunk) > 16384:
192
+ return _json_resp({"error": "Request too large"}, 413)
193
+ payload.extend(chunk)
194
+ body = json.loads(payload)
195
+ except ValueError:
196
+ return _json_resp({"error": "Invalid JSON"}, 400)
197
+ if not isinstance(body, dict) or any(isinstance(v, str) and len(v) > 4096 for v in body.values()):
198
+ return _json_resp({"error": "Invalid decision fields"}, 400)
199
+ return body
200
+
201
+
202
+ async def api_pr_preview(request):
203
+ scan = _db().load_scan(request.path_params["scan_id"])
204
+ items = ((scan or {}).get("remediation") or {}).get("items") or []
205
+ item = next((r for r in items if r.get("id") == request.path_params["item_id"]), None)
206
+ if not item:
207
+ return _json_resp({"error": "Proposal unavailable"}, 404)
208
+ from remediation.pr_template_engine import render_pull_request
209
+ title, body, _ = render_pull_request(item, scan["repo"], impact=item.get("reachability_impact"))
210
+ return Response(f"# {title}\n\n{body}", media_type="text/markdown",
211
+ headers={"Content-Disposition": 'attachment; filename="pull-request.md"'})
212
+
213
+
214
+ async def api_remediation_decision(request) -> Response: # type: ignore[no-untyped-def]
215
+ """Record a review decision through the same lifecycle service the CLI uses."""
216
+ from remediation import lifecycle
217
+ body = await _write_body(request)
218
+ if isinstance(body, Response):
219
+ return body
220
+ if any(not isinstance(v, (str, type(None))) for v in body.values()):
221
+ return _json_resp({"error": "Expected text fields"}, 400)
222
+ decision = {"needs_review": "pending_review"}.get((body.get("decision") or "").strip().lower(), (body.get("decision") or "").strip().lower())
223
+ if decision not in lifecycle.DECISIONS:
224
+ return _json_resp({"error": f"Decision must be one of: {', '.join(lifecycle.DECISIONS)}"}, 400)
225
+ db = _db()
226
+ data = db.load_scan(request.path_params["scan_id"])
227
+ if not data:
228
+ return _json_resp({"error": "Scan not found"}, 404)
229
+ item_id = request.path_params["item_id"]
230
+ cand = next((c for c in lifecycle.candidates(data, lifecycle.choices_of(db, data["repo"]["scan_id"])) if c.id == item_id), None)
231
+ if not cand:
232
+ return _json_resp({"error": f"Candidate {item_id} not found"}, 404)
233
+ try:
234
+ status = await asyncio.to_thread(lifecycle.decide, db, data, cand, decision, _local_user(),
235
+ (body.get("reason") or f"{decision} via dashboard").strip()[:1000], body.get("choice"))
236
+ except lifecycle.LifecycleError as exc:
237
+ return _json_resp({"error": str(exc)}, 409)
238
+ return _json_resp({"status": "ok", "item_id": item_id, "state": status})
239
+
240
+
241
+ def _run_payload(run, applied: list[str] | None = None) -> dict:
242
+ import hashlib
243
+ return {"validation_status": run.validation_status, "tests": run.tests_status, "tests_detail": run.tests_detail,
244
+ "rescan": run.rescan, "lockfiles": run.lockfiles, "lock_consistent": run.lock_consistent, "generated": sorted(run.generated),
245
+ "policy": run.policy, "diff": run.diff, "diff_sha256": hashlib.sha256(run.diff.encode()).hexdigest() if run.diff else None,
246
+ "files": run.files_changed, "branch": run.branch if run.published else None, "pr_url": run.pr_url,
247
+ "reused_pr": run.reused_pr, "applied": applied, "error": run.error}
248
+
249
+
250
+ async def api_remediation_execute(request) -> Response: # type: ignore[no-untyped-def]
251
+ """Approved changes through the shared lifecycle: ``validate`` in an isolated worktree, ``publish`` a pull request, or
252
+ ``apply`` them to the working tree. Same rules as the CLI: the scan's execution policy applies (network only with
253
+ ``allow_network``), publication and application each need their own confirmation, and ``apply`` writes only the
254
+ validated diff the page displayed (``expected_diff_sha256``)."""
255
+ from core import netpolicy
256
+ from remediation import lifecycle
257
+ body = await _write_body(request)
258
+ if isinstance(body, Response):
259
+ return body
260
+ action = request.path_params["action"]
261
+ if action not in ("validate", "publish", "apply"):
262
+ return _json_resp({"error": "Unknown action"}, 404)
263
+ flags = {k: body.get(k) is True for k in ("run_tests", "lockfiles", "allow_network", "include_lockfiles", "allow_stale_lockfile")}
264
+ db = _db()
265
+ data = db.load_scan(request.path_params["scan_id"])
266
+ if not data:
267
+ return _json_resp({"error": "Scan not found"}, 404)
268
+ policy = netpolicy.for_scan(data)
269
+ if policy.offline and flags["allow_network"]:
270
+ policy = policy.authorize(["compatibility", "package_manager", "git_remote", "pr_publish"], f"{_local_user()} (dashboard)")
271
+ publish = None
272
+ if action == "publish":
273
+ if body.get("confirm") != "publish":
274
+ return _json_resp({"error": "Publishing needs explicit confirmation"}, 400)
275
+ if not policy.allows("git_remote") or not policy.allows("pr_publish"):
276
+ return _json_resp({"error": f"This scan ran offline ({policy.origin}). Publishing needs network access: confirm it with allow_network."}, 409)
277
+ from cli.remediate import git_context
278
+ root = lifecycle.repo_root_of(data)
279
+ ctx = await asyncio.to_thread(git_context, root) if root else {"problems": ["Repository not available locally"]}
280
+ if not (ctx.get("provider") == "github" and ctx.get("gh_auth")):
281
+ return _json_resp({"error": "A pull request cannot be opened from here: " + " ".join(ctx.get("problems") or []) +
282
+ " Use 'stackparity pr' for a patch export."}, 409)
283
+
284
+ def publish(run) -> bool: # the user confirmed this exact action in the dashboard; stale lockfiles need their own consent
285
+ return run.lock_consistent or flags["allow_stale_lockfile"]
286
+ if action == "apply":
287
+ if body.get("confirm") != "apply":
288
+ return _json_resp({"error": "Applying to the working tree needs explicit confirmation"}, 400)
289
+ if not isinstance(body.get("expected_diff_sha256"), str):
290
+ return _json_resp({"error": "Validate first and send the expected_diff_sha256 of the diff you reviewed"}, 400)
291
+ run, files, error = await asyncio.to_thread(lifecycle.validate_approved, db, data, _local_user(), run_tests=flags["run_tests"],
292
+ lockfiles=flags["lockfiles"], publish=publish, policy=policy)
293
+ if error:
294
+ return _json_resp({"error": error}, 409)
295
+ if action == "publish" and not run.published and not run.error:
296
+ run.error = "Not published: a lockfile does not match its manifest (send allow_stale_lockfile to accept that)."
297
+ if action != "apply":
298
+ return _json_resp(_run_payload(run))
299
+ payload = _run_payload(run)
300
+ if payload["diff_sha256"] != body["expected_diff_sha256"]:
301
+ return _json_resp({**payload, "error": "The validated diff differs from the one you reviewed; review the new diff and apply again."}, 409)
302
+ try:
303
+ written = await asyncio.to_thread(lifecycle.apply_to_working_tree, db, data, run, *files, _local_user(),
304
+ include_generated=flags["include_lockfiles"], allow_inconsistent_lockfile=flags["allow_stale_lockfile"])
305
+ except lifecycle.LifecycleError as exc:
306
+ return _json_resp({**payload, "error": str(exc)}, 409)
307
+ return _json_resp(_run_payload(run, written))
308
+
309
+
310
+ def api_export_scan(request) -> Response: # type: ignore[no-untyped-def]
311
+ scan_id = request.path_params["scan_id"]
312
+ kind = request.path_params["kind"].lower()
313
+ db = _db()
314
+ data = db.load_scan(scan_id)
315
+ if not data:
316
+ return _json_resp({"error": "Scan not found"}, status_code=404)
317
+ name = (data.get("repo") or {}).get("name") or "stackparity"
318
+
319
+ name = re.sub(r"[^a-zA-Z0-9_.-]", "_", name)[:100]
320
+ if kind == "sbom":
321
+ from sbom.exporters import stored_sbom_path
322
+ try:
323
+ sbom_path = stored_sbom_path(data, get_settings().artifacts_dir)
324
+ return Response(
325
+ content=Path(sbom_path).read_bytes(),
326
+ media_type="application/json",
327
+ headers={"Content-Disposition": f'attachment; filename="{name}-sbom.cdx.json"'},
328
+ )
329
+ except OSError:
330
+ return _json_resp({"error": "SBOM file not available"}, status_code=404)
331
+
332
+ extras = {}
333
+ if kind in ("vex", "markdown", "html"):
334
+ try:
335
+ mem = Memory(db)
336
+ url = (data.get("repo") or {}).get("url") or ""
337
+ extras = {"decisions": mem.decisions(url)}
338
+ if kind != "vex":
339
+ extras.update(approvals=mem.approvals(url), audit=mem.audit_log(url, 30))
340
+ except Exception:
341
+ extras = {}
342
+
343
+ if kind == "sarif":
344
+ return Response(
345
+ content=json_exporter.dumps(to_sarif(data)),
346
+ media_type="application/sarif+json",
347
+ headers={"Content-Disposition": f'attachment; filename="{name}.sarif"'},
348
+ )
349
+ if kind == "vex":
350
+ return Response(
351
+ content=json_exporter.dumps(to_vex(data, extras.get("decisions"))),
352
+ media_type="application/json",
353
+ headers={"Content-Disposition": f'attachment; filename="{name}.vex.json"'},
354
+ )
355
+ if kind == "vulnerabilities":
356
+ return Response(
357
+ content=json_exporter.dumps(json_exporter.vulnerability_export(data)),
358
+ media_type="application/json",
359
+ headers={"Content-Disposition": f'attachment; filename="{name}-vulnerabilities.json"'},
360
+ )
361
+ if kind == "consolidated":
362
+ return Response(
363
+ content=json_exporter.dumps(json_exporter.consolidated_export(data)),
364
+ media_type="application/json",
365
+ headers={"Content-Disposition": f'attachment; filename="{name}-consolidated.json"'},
366
+ )
367
+ if kind == "markdown":
368
+ return Response(
369
+ content=report_generator.generate_markdown(data, extras),
370
+ media_type="text/markdown",
371
+ headers={"Content-Disposition": f'attachment; filename="{name}-report.md"'},
372
+ )
373
+ if kind == "html":
374
+ return Response(
375
+ content=report_generator.generate_html(data, extras),
376
+ media_type="text/html",
377
+ headers={"Content-Disposition": f'attachment; filename="{name}-report.html"'},
378
+ )
379
+ return _json_resp({"error": f"Unknown export kind: {kind}"}, status_code=400)
380
+
381
+
382
+ async def ws_sync(websocket: WebSocket) -> None:
383
+ """Push live SQLite DB updates to connected React clients."""
384
+ if websocket.headers.get("origin") != f"http://{websocket.headers.get('host')}":
385
+ await websocket.close(code=1008)
386
+ return
387
+ await websocket.accept()
388
+ db_path = get_settings().db_path
389
+ last_mtime = _db_mtime_ns(db_path)
390
+ try:
391
+ recent = await asyncio.to_thread(_list_scans, 25)
392
+ await websocket.send_text(json.dumps({
393
+ "type": "connected",
394
+ "latest_scan_id": recent[0]["scan_id"] if recent else None,
395
+ "scans": recent,
396
+ }))
397
+ while True:
398
+ try:
399
+ message = await asyncio.wait_for(websocket.receive(), timeout=1.0)
400
+ if message["type"] == "websocket.disconnect":
401
+ break
402
+ except asyncio.TimeoutError:
403
+ pass
404
+ cur_mtime = _db_mtime_ns(db_path)
405
+ if cur_mtime != last_mtime:
406
+ last_mtime = cur_mtime
407
+ scans = await asyncio.to_thread(_list_scans, 25)
408
+ await websocket.send_text(json.dumps({
409
+ "type": "db_updated",
410
+ "latest_scan_id": scans[0]["scan_id"] if scans else None,
411
+ "scans": scans,
412
+ }))
413
+ except WebSocketDisconnect:
414
+ return
415
+
416
+
417
+ async def spa_fallback(request) -> Any: # type: ignore[no-untyped-def]
418
+ index_file = WEB_DIST_DIR / "index.html"
419
+ if index_file.exists():
420
+ html = index_file.read_text(encoding="utf-8").replace(
421
+ "<head>", f'<head><meta name="stackparity-token" content="{SESSION_TOKEN}">', 1)
422
+ return Response(html, media_type="text/html", headers={"Cache-Control": "no-store"})
423
+ return _json_resp(
424
+ {"message": "StackParity API is running. Build frontend/ into src/stackparity/web_dist/ to serve the UI."}
425
+ )
426
+
427
+
428
+ async def api_unknown(request) -> Response: # type: ignore[no-untyped-def]
429
+ return _json_resp({"error": "Unknown API endpoint"}, 404)
430
+
431
+
432
+ _SECURITY_HEADERS = [
433
+ (b"referrer-policy", b"no-referrer"),
434
+ (b"x-content-type-options", b"nosniff"),
435
+ (b"x-frame-options", b"DENY"),
436
+ (b"cross-origin-opener-policy", b"same-origin"),
437
+ (b"cross-origin-resource-policy", b"same-origin"),
438
+ (b"content-security-policy", b"default-src 'self'; img-src 'self' data: blob:; style-src 'self' 'unsafe-inline'; font-src 'self' data:; "
439
+ b"connect-src 'self' ws://127.0.0.1:* ws://localhost:*; worker-src 'self' blob:; "
440
+ b"frame-ancestors 'none'; base-uri 'none'; form-action 'self'; object-src 'none'"),
441
+ ]
442
+
443
+
444
+ class SecurityHeaders:
445
+ """Pure ASGI middleware: no referrer (the session token never appears in URLs, and links leak nothing), no framing,
446
+ no MIME sniffing, a same-origin content policy, and no caching of API responses."""
447
+
448
+ def __init__(self, app) -> None:
449
+ self.app = app
450
+
451
+ async def __call__(self, scope, receive, send) -> None:
452
+ if scope["type"] != "http":
453
+ await self.app(scope, receive, send)
454
+ return
455
+ is_api = scope.get("path", "").startswith("/api/")
456
+
457
+ async def wrapped(message):
458
+ if message["type"] == "http.response.start":
459
+ headers = [(k, v) for k, v in message.get("headers", []) if k.lower() not in {h for h, _ in _SECURITY_HEADERS}]
460
+ headers += _SECURITY_HEADERS
461
+ if is_api and not any(k.lower() == b"cache-control" for k, _ in headers):
462
+ headers.append((b"cache-control", b"no-store"))
463
+ message = {**message, "headers": headers}
464
+ await send(message)
465
+
466
+ await self.app(scope, receive, wrapped)
467
+
468
+
469
+ def _watch_parent() -> None:
470
+ """Exit when the ``stackparity dashboard`` process that started this server is gone, however it ended (Ctrl+C, a closed
471
+ terminal, a kill), so the server never outlives its launcher and keeps the port. Active only when the launcher set
472
+ STACKPARITY_PARENT_PID."""
473
+ raw = os.environ.get("STACKPARITY_PARENT_PID", "")
474
+ if not raw.isdigit():
475
+ return
476
+ pid = int(raw)
477
+ if os.name == "nt":
478
+ import ctypes
479
+ kernel32 = ctypes.windll.kernel32
480
+ handle = kernel32.OpenProcess(0x00100000, False, pid) # SYNCHRONIZE: holding the handle also pins the PID
481
+ if not handle:
482
+ os._exit(0)
483
+
484
+ def wait() -> None:
485
+ kernel32.WaitForSingleObject(handle, 0xFFFFFFFF)
486
+ os._exit(0)
487
+ else:
488
+ import time
489
+ original = os.getppid()
490
+
491
+ def wait() -> None:
492
+ while True:
493
+ if os.getppid() != original:
494
+ os._exit(0)
495
+ try:
496
+ os.kill(pid, 0)
497
+ except ProcessLookupError:
498
+ os._exit(0)
499
+ except PermissionError:
500
+ pass
501
+ time.sleep(1)
502
+ threading.Thread(target=wait, name="stackparity-parent-watchdog", daemon=True).start()
503
+
504
+
505
+ def create_app() -> Starlette:
506
+ routes: list[Any] = [
507
+ Route("/api/job", api_job, methods=["GET", "POST", "DELETE"]),
508
+ Route("/api/health", api_health),
509
+ Route("/api/diagnostics", api_diagnostics),
510
+ Route("/api/scans", api_list_scans),
511
+ Route("/api/scans/{scan_id}", api_get_scan),
512
+ Route("/api/scans/{scan_id}/remediation/{item_id}/preview", api_pr_preview),
513
+ Route("/api/scans/{scan_id}/remediation/{item_id}", api_remediation_decision, methods=["POST"]),
514
+ Route("/api/scans/{scan_id}/remediation-actions/{action}", api_remediation_execute, methods=["POST"]),
515
+ Route("/api/scans/{scan_id}/export/{kind}", api_export_scan),
516
+ WebSocketRoute("/ws/sync", ws_sync),
517
+ Route("/api/{path:path}", api_unknown),
518
+ ]
519
+ assets_dir = WEB_DIST_DIR / "assets"
520
+ if assets_dir.exists():
521
+ routes.append(Mount("/assets", app=StaticFiles(directory=str(assets_dir)), name="assets"))
522
+ routes.append(Route("/{path:path}", spa_fallback))
523
+ routes.append(Route("/", spa_fallback))
524
+
525
+ app = Starlette(debug=False, routes=routes)
526
+ app.state.job = {"status": "idle"}
527
+ app.add_middleware(TrustedHostMiddleware, allowed_hosts=["localhost", "127.0.0.1"])
528
+ app.add_middleware(SecurityHeaders)
529
+ return app
530
+
531
+
532
+ app = create_app()
533
+ _watch_parent()