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,295 @@
1
+ """SQLite persistence: scan records, findings and a generic advisory/registry cache."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import sqlite3
6
+ import threading
7
+ from contextlib import contextmanager
8
+ from pathlib import Path
9
+ from typing import Any, Iterator, Optional
10
+
11
+ SCHEMA_VERSION = 3 # 1: scans/findings/cache 2: + memory tables, graph tables, scans.scanner_version
12
+
13
+ SCHEMA = """
14
+ CREATE TABLE IF NOT EXISTS scans (
15
+ scan_id TEXT PRIMARY KEY,
16
+ repo_url TEXT NOT NULL,
17
+ repo_name TEXT,
18
+ ref TEXT,
19
+ commit_sha TEXT NOT NULL,
20
+ scan_timestamp TEXT NOT NULL,
21
+ status TEXT NOT NULL,
22
+ tool_versions TEXT,
23
+ sbom_path TEXT,
24
+ summary TEXT,
25
+ result_json TEXT
26
+ );
27
+ CREATE INDEX IF NOT EXISTS idx_scans_repo_commit ON scans(repo_url, commit_sha);
28
+ CREATE TABLE IF NOT EXISTS findings (
29
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
30
+ scan_id TEXT NOT NULL REFERENCES scans(scan_id) ON DELETE CASCADE,
31
+ kind TEXT NOT NULL, -- vulnerability | typosquatting | lockfile_change
32
+ finding_id TEXT NOT NULL,
33
+ component_ref TEXT,
34
+ severity TEXT,
35
+ risk_label TEXT,
36
+ payload TEXT NOT NULL
37
+ );
38
+ CREATE INDEX IF NOT EXISTS idx_findings_scan ON findings(scan_id, kind);
39
+ CREATE TABLE IF NOT EXISTS finding_state (
40
+ repo_url TEXT NOT NULL,
41
+ fingerprint TEXT NOT NULL,
42
+ kind TEXT NOT NULL,
43
+ title TEXT,
44
+ severity TEXT,
45
+ risk_label TEXT,
46
+ status TEXT NOT NULL, -- open | fixed
47
+ first_seen_scan TEXT NOT NULL,
48
+ first_seen_at TEXT NOT NULL,
49
+ last_seen_scan TEXT NOT NULL,
50
+ last_seen_at TEXT NOT NULL,
51
+ fixed_scan TEXT,
52
+ times_seen INTEGER NOT NULL DEFAULT 1,
53
+ PRIMARY KEY (repo_url, fingerprint)
54
+ );
55
+ CREATE TABLE IF NOT EXISTS decisions (
56
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
57
+ repo_url TEXT NOT NULL,
58
+ fingerprint TEXT NOT NULL,
59
+ decision TEXT NOT NULL, -- accepted_risk | false_positive | suppress
60
+ reason TEXT NOT NULL,
61
+ title TEXT,
62
+ created_at TEXT NOT NULL,
63
+ expires_at TEXT,
64
+ author TEXT
65
+ );
66
+ CREATE INDEX IF NOT EXISTS idx_decisions_repo ON decisions(repo_url, fingerprint);
67
+ CREATE TABLE IF NOT EXISTS package_seen (
68
+ ecosystem TEXT NOT NULL,
69
+ name TEXT NOT NULL,
70
+ first_seen_at TEXT NOT NULL,
71
+ last_seen_at TEXT NOT NULL,
72
+ repos_seen INTEGER NOT NULL DEFAULT 1,
73
+ scans_seen INTEGER NOT NULL DEFAULT 1,
74
+ last_repo TEXT,
75
+ PRIMARY KEY (ecosystem, name)
76
+ );
77
+ CREATE TABLE IF NOT EXISTS graph_meta (
78
+ scan_id TEXT PRIMARY KEY REFERENCES scans(scan_id) ON DELETE CASCADE,
79
+ graph_hash TEXT NOT NULL,
80
+ nodes INTEGER NOT NULL,
81
+ edges INTEGER NOT NULL
82
+ );
83
+ CREATE TABLE IF NOT EXISTS graph_nodes (
84
+ scan_id TEXT NOT NULL REFERENCES scans(scan_id) ON DELETE CASCADE,
85
+ node_id TEXT NOT NULL,
86
+ node_key TEXT NOT NULL,
87
+ kind TEXT, label TEXT, name TEXT, version TEXT, ecosystem TEXT, service_dir TEXT, purl TEXT,
88
+ PRIMARY KEY (scan_id, node_id)
89
+ );
90
+ CREATE TABLE IF NOT EXISTS graph_edges (
91
+ scan_id TEXT NOT NULL REFERENCES scans(scan_id) ON DELETE CASCADE,
92
+ src TEXT NOT NULL,
93
+ dst TEXT NOT NULL,
94
+ provenance TEXT,
95
+ PRIMARY KEY (scan_id, src, dst)
96
+ );
97
+ CREATE INDEX IF NOT EXISTS idx_graph_nodes_key ON graph_nodes(node_key);
98
+ CREATE TABLE IF NOT EXISTS remediation_runs (
99
+ scan_id TEXT NOT NULL REFERENCES scans(scan_id) ON DELETE CASCADE,
100
+ item_id TEXT NOT NULL,
101
+ payload TEXT NOT NULL,
102
+ PRIMARY KEY (scan_id, item_id)
103
+ );
104
+ CREATE TABLE IF NOT EXISTS approvals (
105
+ repo_url TEXT NOT NULL,
106
+ fingerprint TEXT NOT NULL,
107
+ state TEXT NOT NULL, -- approved | rejected | needs_review
108
+ reason TEXT NOT NULL,
109
+ title TEXT,
110
+ actor TEXT NOT NULL,
111
+ decided_at TEXT NOT NULL,
112
+ PRIMARY KEY (repo_url, fingerprint)
113
+ );
114
+ CREATE TABLE IF NOT EXISTS audit_log (
115
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
116
+ repo_url TEXT NOT NULL,
117
+ at TEXT NOT NULL,
118
+ actor TEXT NOT NULL,
119
+ action TEXT NOT NULL,
120
+ subject TEXT,
121
+ detail TEXT
122
+ );
123
+ CREATE INDEX IF NOT EXISTS idx_audit_repo ON audit_log(repo_url, id);
124
+ CREATE TABLE IF NOT EXISTS cache (
125
+ namespace TEXT NOT NULL,
126
+ key TEXT NOT NULL,
127
+ payload TEXT NOT NULL,
128
+ fetched_at REAL NOT NULL,
129
+ PRIMARY KEY (namespace, key)
130
+ );
131
+ """
132
+
133
+
134
+ class Database:
135
+ def __init__(self, path: Path | str):
136
+ self.path = str(path)
137
+ self._lock = threading.RLock()
138
+ with self.connect() as c:
139
+ c.executescript(SCHEMA)
140
+ self._migrate(c)
141
+
142
+ @staticmethod
143
+ def _migrate(c: sqlite3.Connection) -> None:
144
+ """Forward-only migrations keyed by PRAGMA user_version (CREATE IF NOT EXISTS above covers new tables)."""
145
+ ver = c.execute("PRAGMA user_version").fetchone()[0]
146
+ if ver > SCHEMA_VERSION:
147
+ raise RuntimeError(f"database schema v{ver} is newer than this code (v{SCHEMA_VERSION}); refusing to open it")
148
+ cols = {r[1] for r in c.execute("PRAGMA table_info(scans)").fetchall()}
149
+ if "scanner_version" not in cols:
150
+ c.execute("ALTER TABLE scans ADD COLUMN scanner_version TEXT")
151
+ if ver < SCHEMA_VERSION:
152
+ c.execute(f"PRAGMA user_version={SCHEMA_VERSION}")
153
+
154
+ @contextmanager
155
+ def connect(self) -> Iterator[sqlite3.Connection]:
156
+ with self._lock:
157
+ conn = sqlite3.connect(self.path, timeout=30)
158
+ conn.row_factory = sqlite3.Row
159
+ conn.execute("PRAGMA foreign_keys=ON")
160
+ conn.execute("PRAGMA journal_mode=WAL")
161
+ conn.execute("PRAGMA synchronous=NORMAL")
162
+ conn.execute("PRAGMA busy_timeout=30000")
163
+ try:
164
+ yield conn
165
+ conn.commit()
166
+ finally:
167
+ conn.close()
168
+
169
+ # ------------------------------------------------------------ scans
170
+ def save_scan(self, result: dict[str, Any]) -> None:
171
+ repo = result["repo"]
172
+ findings: list[tuple[str, dict]] = []
173
+ for f in result.get("vulnerabilities", []):
174
+ findings.append(("vulnerability", f))
175
+ for f in result.get("typosquatting", []):
176
+ findings.append(("typosquatting", f))
177
+ for f in result.get("lockfile_changes", []):
178
+ findings.append(("lockfile_change", f))
179
+ for f in (result.get("pipeline") or {}).get("findings", []):
180
+ findings.append(("pipeline", f))
181
+ for f in (result.get("package_risk") or {}).get("findings", []):
182
+ findings.append(("package_risk", f))
183
+ risks = {r["finding_id"]: r for r in result.get("risk_assessments", [])}
184
+ with self.connect() as c:
185
+ c.execute("DELETE FROM scans WHERE scan_id=?", (repo["scan_id"],))
186
+ c.execute(
187
+ "INSERT INTO scans(scan_id, repo_url, repo_name, ref, commit_sha, scan_timestamp, status, tool_versions,"
188
+ " sbom_path, summary, result_json, scanner_version) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)",
189
+ (repo["scan_id"], repo["url"], repo["name"], repo.get("ref"), repo["commit_sha"], repo["scan_timestamp"],
190
+ result.get("status", "unknown"), json.dumps(result.get("tool_versions", {})), result.get("sbom_path"),
191
+ json.dumps(result.get("summary", {})), json.dumps(result, default=str), (result.get("tool_versions") or {}).get("scanner")),
192
+ )
193
+ self._save_graph(c, repo["scan_id"], result.get("graph") or {})
194
+ for kind, f in findings:
195
+ fid = f.get("finding_id", "")
196
+ c.execute(
197
+ "INSERT INTO findings(scan_id, kind, finding_id, component_ref, severity, risk_label, payload)"
198
+ " VALUES (?,?,?,?,?,?,?)",
199
+ (repo["scan_id"], kind, fid, f.get("component_ref"), f.get("severity"),
200
+ (risks.get(fid) or {}).get("label"), json.dumps(f, default=str)),
201
+ )
202
+
203
+ def health(self) -> dict:
204
+ """Schema version, integrity and sizes for the Settings & Health page."""
205
+ out: dict = {"path": self.path, "schema_version": None, "integrity": None, "tables": {}, "size_bytes": None, "journal_mode": None}
206
+ try:
207
+ with self.connect() as c:
208
+ out["schema_version"] = c.execute("PRAGMA user_version").fetchone()[0]
209
+ out["integrity"] = c.execute("PRAGMA integrity_check").fetchone()[0]
210
+ out["journal_mode"] = c.execute("PRAGMA journal_mode").fetchone()[0]
211
+ for t in ("scans", "findings", "finding_state", "decisions", "package_seen", "graph_nodes", "graph_edges", "cache"):
212
+ out["tables"][t] = c.execute(f"SELECT COUNT(*) FROM {t}").fetchone()[0]
213
+ out["size_bytes"] = Path(self.path).stat().st_size
214
+ except Exception as e:
215
+ out["integrity"] = f"error: {type(e).__name__}: {e}"
216
+ return out
217
+
218
+ @staticmethod
219
+ def _save_graph(c: sqlite3.Connection, scan_id: str, graph: dict) -> None:
220
+ from graph.graph_diff import graph_hash, node_key
221
+ nodes, edges = graph.get("nodes") or [], graph.get("edges") or []
222
+ if not nodes:
223
+ return
224
+ c.execute("INSERT OR REPLACE INTO graph_meta(scan_id, graph_hash, nodes, edges) VALUES (?,?,?,?)", (scan_id, graph_hash(graph), len(nodes), len(edges)))
225
+ c.executemany("INSERT OR REPLACE INTO graph_nodes(scan_id,node_id,node_key,kind,label,name,version,ecosystem,service_dir,purl) VALUES (?,?,?,?,?,?,?,?,?,?)",
226
+ [(scan_id, n["id"], node_key(n), n.get("kind"), n.get("label"), n.get("name"), n.get("version"), n.get("ecosystem"), n.get("service_dir"), n.get("purl")) for n in nodes])
227
+ c.executemany("INSERT OR REPLACE INTO graph_edges(scan_id,src,dst,provenance) VALUES (?,?,?,?)", [(scan_id, e["source"], e["target"], e.get("provenance")) for e in edges])
228
+
229
+ def load_graph(self, scan_id: str) -> Optional[dict]:
230
+ """Rebuild a ``graph_to_json``-shaped dict from the persisted tables (queryable/diffable without loading the full result)."""
231
+ with self.connect() as c:
232
+ nodes = [dict(r) for r in c.execute("SELECT * FROM graph_nodes WHERE scan_id=?", (scan_id,)).fetchall()]
233
+ edges = [dict(r) for r in c.execute("SELECT * FROM graph_edges WHERE scan_id=?", (scan_id,)).fetchall()]
234
+ if not nodes:
235
+ return None
236
+ return {"nodes": [{"id": n["node_id"], **{k: n[k] for k in ("kind", "label", "name", "version", "ecosystem", "service_dir", "purl")}} for n in nodes],
237
+ "edges": [{"source": e["src"], "target": e["dst"], "provenance": e["provenance"]} for e in edges]}
238
+
239
+ def previous_scan(self, repo_url: str, scan_id: str) -> Optional[str]:
240
+ """Id of the scan of the same repository that precedes ``scan_id`` (by timestamp)."""
241
+ with self.connect() as c:
242
+ cur = c.execute("SELECT scan_timestamp, rowid FROM scans WHERE scan_id=?", (scan_id,)).fetchone()
243
+ if not cur:
244
+ return None
245
+ r = c.execute("SELECT scan_id FROM scans WHERE repo_url=? AND status!='failed' AND (scan_timestamp < ? OR (scan_timestamp = ? AND rowid < ?))"
246
+ " ORDER BY scan_timestamp DESC, rowid DESC LIMIT 1", (repo_url, cur["scan_timestamp"], cur["scan_timestamp"], cur["rowid"])).fetchone()
247
+ return r["scan_id"] if r else None
248
+
249
+ def save_remediation_run(self, scan_id: str, item_id: str, result: dict) -> None:
250
+ with self.connect() as c:
251
+ c.execute("INSERT OR REPLACE INTO remediation_runs VALUES (?, ?, ?)",
252
+ (scan_id, item_id, json.dumps(result)))
253
+
254
+ def remediation_runs(self, scan_id: str) -> dict:
255
+ with self.connect() as c:
256
+ rows = c.execute("SELECT item_id, payload FROM remediation_runs WHERE scan_id=?", (scan_id,))
257
+ return {r["item_id"]: json.loads(r["payload"]) for r in rows}
258
+
259
+ def list_scans(self, limit: int = 50, offset: int = 0) -> list[dict]:
260
+ with self.connect() as c:
261
+ rows = c.execute(
262
+ "SELECT scan_id, repo_url, repo_name, ref, commit_sha, scan_timestamp, status, summary FROM scans"
263
+ " ORDER BY scan_timestamp DESC, rowid DESC LIMIT ? OFFSET ?", (limit, offset)).fetchall()
264
+ return [{**dict(r), "summary": json.loads(r["summary"] or "{}")} for r in rows]
265
+
266
+ def load_scan(self, scan_id: str) -> Optional[dict]:
267
+ with self.connect() as c:
268
+ r = c.execute("SELECT result_json FROM scans WHERE scan_id=?", (scan_id,)).fetchone()
269
+ if not r:
270
+ return None
271
+ from reporting.counts import reconcile_summary
272
+ return reconcile_summary(json.loads(r["result_json"]))
273
+
274
+ def find_scan(self, repo_url: str, commit_sha: str) -> Optional[str]:
275
+ with self.connect() as c:
276
+ r = c.execute("SELECT scan_id FROM scans WHERE repo_url=? AND commit_sha=? AND status!='failed'"
277
+ " ORDER BY scan_timestamp DESC LIMIT 1", (repo_url, commit_sha)).fetchone()
278
+ return r["scan_id"] if r else None
279
+
280
+ def prune_repo(self, repo_url: str, keep: int) -> list[str]:
281
+ """Keep the newest ``keep`` scans of a repository; return the ids that were deleted."""
282
+ with self.connect() as c:
283
+ ids = [r["scan_id"] for r in c.execute("SELECT scan_id FROM scans WHERE repo_url=? ORDER BY scan_timestamp DESC, rowid DESC", (repo_url,)).fetchall()]
284
+ old = ids[keep:]
285
+ for sid in old:
286
+ c.execute("DELETE FROM scans WHERE scan_id=?", (sid,))
287
+ return old
288
+
289
+ def findings(self, scan_id: str, kind: str | None = None) -> list[dict]:
290
+ q, args = "SELECT payload FROM findings WHERE scan_id=?", [scan_id]
291
+ if kind:
292
+ q += " AND kind=?"
293
+ args.append(kind)
294
+ with self.connect() as c:
295
+ return [json.loads(r["payload"]) for r in c.execute(q, args).fetchall()]
@@ -0,0 +1,146 @@
1
+ """Persistent scan memory (SQLite, deterministic, no embeddings).
2
+
3
+ * ``finding_state`` per repository + stable finding fingerprint: first/last seen, status, times seen -> new / persisting / fixed
4
+ * ``decisions`` analyst decisions (accepted risk, false positive, suppress) with reason and optional expiry
5
+ * ``package_seen`` which packages were seen in how many scans/repositories (context, e.g. for typosquat triage)
6
+
7
+ Decisions never delete findings: they are shown, flagged, and expire.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import time
12
+ from typing import Any, Iterable, Optional
13
+
14
+ from storage.database import Database
15
+
16
+ DECISIONS = ("accepted_risk", "false_positive", "suppress")
17
+
18
+
19
+ def _now() -> str:
20
+ return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
21
+
22
+
23
+ def fingerprint(kind: str, f: dict) -> str:
24
+ """Stable identity of a finding across scans (finding_ids like VULN-001 are per-scan sequence numbers)."""
25
+ if kind == "vulnerability":
26
+ return "|".join(["vuln", f.get("ecosystem") or "", f.get("package_name") or "", f.get("installed_version") or "", f.get("primary_id") or "", f.get("service_dir") or "."])
27
+ if kind == "typosquatting":
28
+ return "|".join(["typo", f.get("ecosystem") or "", f.get("package_name") or "", f.get("similar_to") or ""])
29
+ if kind == "package_risk":
30
+ return "|".join(["pkgrisk", f.get("rule_id") or "", f.get("ecosystem") or "", f.get("subject") or ""])
31
+ if kind == "pipeline":
32
+ return "|".join(["pipe", f.get("rule_id") or "", f.get("file") or "", (f.get("subject") or "")[:80]])
33
+ prev, new = f.get("previous") or {}, f.get("new") or {}
34
+ return "|".join(["lock", f.get("file") or "", f.get("package_name") or "", f.get("change_type") or "", str(prev.get("version") or ""), str(new.get("version") or "")])
35
+
36
+
37
+ def title(kind: str, f: dict) -> str:
38
+ if kind == "vulnerability":
39
+ return f"{f.get('primary_id')} in {f.get('package_name')}@{f.get('installed_version')}"
40
+ if kind == "typosquatting":
41
+ return f"{f.get('package_name')} resembles {f.get('similar_to')}"
42
+ if kind in ("pipeline", "package_risk"):
43
+ return f"{f.get('rule_id')} {f.get('title')}" + (f" ({f.get('file')})" if kind == "pipeline" else "")
44
+ return f"{f.get('change_type')} {f.get('package_name')} in {f.get('file')}"
45
+
46
+
47
+ class Memory:
48
+ def __init__(self, db: Database):
49
+ self.db = db
50
+
51
+ # ------------------------------------------------------------------ findings over time
52
+ def record_scan(self, repo_url: str, scan_id: str, scan_ts: str, findings: Iterable[tuple[str, dict, Optional[str]]]) -> dict[str, Any]:
53
+ """Update finding_state with this scan and return the diff against the previous state of the repository."""
54
+ cur = {fingerprint(k, f): (k, f, lab) for k, f, lab in findings}
55
+ with self.db.connect() as c:
56
+ rows = {r["fingerprint"]: dict(r) for r in c.execute("SELECT * FROM finding_state WHERE repo_url=?", (repo_url,)).fetchall()}
57
+ had_history = bool(rows)
58
+ new, persisting, regressed = [], [], []
59
+ for fp, (kind, f, lab) in cur.items():
60
+ old = rows.get(fp)
61
+ t = title(kind, f)
62
+ if old is None:
63
+ new.append(fp)
64
+ c.execute("INSERT INTO finding_state(repo_url,fingerprint,kind,title,severity,risk_label,status,first_seen_scan,first_seen_at,last_seen_scan,last_seen_at,times_seen)"
65
+ " VALUES (?,?,?,?,?,?,'open',?,?,?,?,1)", (repo_url, fp, kind, t, f.get("severity"), lab, scan_id, scan_ts, scan_id, scan_ts))
66
+ else:
67
+ (regressed if old["status"] == "fixed" else persisting).append(fp)
68
+ c.execute("UPDATE finding_state SET status='open', fixed_scan=NULL, last_seen_scan=?, last_seen_at=?, times_seen=times_seen+1, severity=?, risk_label=?, title=? "
69
+ "WHERE repo_url=? AND fingerprint=?", (scan_id, scan_ts, f.get("severity"), lab, t, repo_url, fp))
70
+ fixed = [fp for fp, r in rows.items() if r["status"] == "open" and fp not in cur]
71
+ for fp in fixed:
72
+ c.execute("UPDATE finding_state SET status='fixed', fixed_scan=? WHERE repo_url=? AND fingerprint=?", (scan_id, repo_url, fp))
73
+ fixed_rows = [{"fingerprint": fp, "title": rows[fp]["title"], "kind": rows[fp]["kind"], "severity": rows[fp]["severity"], "first_seen_at": rows[fp]["first_seen_at"]} for fp in fixed]
74
+ return {"baseline": not had_history, "new": new, "persisting": persisting, "regressed": regressed, "fixed": fixed_rows,
75
+ "counts": {"new": len(new), "persisting": len(persisting), "regressed": len(regressed), "fixed": len(fixed_rows)}}
76
+
77
+ def state(self, repo_url: str) -> dict[str, dict]:
78
+ with self.db.connect() as c:
79
+ return {r["fingerprint"]: dict(r) for r in c.execute("SELECT * FROM finding_state WHERE repo_url=?", (repo_url,)).fetchall()}
80
+
81
+ # ------------------------------------------------------------------ decisions
82
+ def add_decision(self, repo_url: str, fp: str, decision: str, reason: str, title_: str = "", expires_days: Optional[int] = None, author: str = "analyst") -> int:
83
+ if decision not in DECISIONS:
84
+ raise ValueError(f"decision must be one of {DECISIONS}")
85
+ if not reason.strip():
86
+ raise ValueError("a reason is required")
87
+ exp = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(time.time() + expires_days * 86400)) if expires_days else None
88
+ with self.db.connect() as c:
89
+ cur = c.execute("INSERT INTO decisions(repo_url,fingerprint,decision,reason,title,created_at,expires_at,author) VALUES (?,?,?,?,?,?,?,?)",
90
+ (repo_url, fp, decision, reason.strip(), title_, _now(), exp, author))
91
+ return int(cur.lastrowid)
92
+
93
+ def decisions(self, repo_url: str, include_expired: bool = False) -> dict[str, dict]:
94
+ """fingerprint -> newest decision (expired ones are excluded unless requested)."""
95
+ with self.db.connect() as c:
96
+ rows = [dict(r) for r in c.execute("SELECT * FROM decisions WHERE repo_url=? ORDER BY id", (repo_url,)).fetchall()]
97
+ now = _now()
98
+ newest: dict[str, dict] = {}
99
+ for r in rows: # rows are ordered by id: the latest decision per finding wins, even if it has expired
100
+ r["expired"] = bool(r["expires_at"] and r["expires_at"] < now)
101
+ newest[r["fingerprint"]] = r
102
+ return {fp: r for fp, r in newest.items() if include_expired or not r["expired"]}
103
+
104
+ def remove_decision(self, decision_id: int) -> None:
105
+ with self.db.connect() as c:
106
+ c.execute("DELETE FROM decisions WHERE id=?", (decision_id,))
107
+
108
+ # ------------------------------------------------------------------ packages seen
109
+ def record_packages(self, repo_url: str, packages: Iterable[tuple[str, str]]) -> dict[tuple[str, str], int]:
110
+ """Count scans/repos per package; returns {(eco, name): repos_seen_before} for packages already seen in other repositories."""
111
+ prior: dict[tuple[str, str], int] = {}
112
+ now = _now()
113
+ with self.db.connect() as c:
114
+ for eco, name in set(packages):
115
+ r = c.execute("SELECT repos_seen, last_repo FROM package_seen WHERE ecosystem=? AND name=?", (eco, name)).fetchone()
116
+ if r is None:
117
+ c.execute("INSERT INTO package_seen(ecosystem,name,first_seen_at,last_seen_at,last_repo) VALUES (?,?,?,?,?)", (eco, name, now, now, repo_url))
118
+ else:
119
+ other = r["last_repo"] != repo_url
120
+ if other:
121
+ prior[(eco, name)] = r["repos_seen"]
122
+ c.execute("UPDATE package_seen SET last_seen_at=?, scans_seen=scans_seen+1, repos_seen=repos_seen+?, last_repo=? WHERE ecosystem=? AND name=?",
123
+ (now, 1 if other else 0, repo_url, eco, name))
124
+ return prior
125
+
126
+ # ------------------------------------------------------------------ approvals (human-in-the-loop) and audit trail
127
+ def set_approval(self, repo_url: str, fingerprint: str, state: str, reason: str, title_: str = "", actor: str = "analyst") -> None:
128
+ if state not in ("approved", "rejected", "needs_review"):
129
+ raise ValueError("state must be approved, rejected or needs_review")
130
+ if not reason.strip():
131
+ raise ValueError("a reason is required")
132
+ with self.db.connect() as c:
133
+ c.execute("INSERT OR REPLACE INTO approvals(repo_url,fingerprint,state,reason,title,actor,decided_at) VALUES (?,?,?,?,?,?,?)", (repo_url, fingerprint, state, reason.strip(), title_, actor, _now()))
134
+ self.audit(repo_url, actor, f"remediation_{state}", title_ or fingerprint, reason.strip())
135
+
136
+ def approvals(self, repo_url: str) -> dict[str, dict]:
137
+ with self.db.connect() as c:
138
+ return {r["fingerprint"]: dict(r) for r in c.execute("SELECT * FROM approvals WHERE repo_url=?", (repo_url,)).fetchall()}
139
+
140
+ def audit(self, repo_url: str, actor: str, action: str, subject: str = "", detail: str = "") -> None:
141
+ with self.db.connect() as c:
142
+ c.execute("INSERT INTO audit_log(repo_url,at,actor,action,subject,detail) VALUES (?,?,?,?,?,?)", (repo_url, _now(), actor, action, subject[:200], detail[:1000]))
143
+
144
+ def audit_log(self, repo_url: str, limit: int = 200) -> list[dict]:
145
+ with self.db.connect() as c:
146
+ return [dict(r) for r in c.execute("SELECT at, actor, action, subject, detail FROM audit_log WHERE repo_url=? ORDER BY id DESC LIMIT ?", (repo_url, limit)).fetchall()]
@@ -0,0 +1,12 @@
1
+ """Suspicious changes detection and evidence correlation package."""
2
+ from suspicious_changes.change_correlation import (
3
+ ChangeCorrelator,
4
+ CompositeFinding,
5
+ correlate_suspicious_changes,
6
+ )
7
+
8
+ __all__ = [
9
+ "ChangeCorrelator",
10
+ "CompositeFinding",
11
+ "correlate_suspicious_changes",
12
+ ]