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,390 @@
1
+ """Contextual Risk Scoring Engine.
2
+
3
+ Implements the four-factor linear contextual vulnerability risk model (v2.0):
4
+ R = 0.15*C + 0.20*A + 0.35*P + 0.30*I
5
+ With function-level application impact:
6
+ I = 0.25*F + 0.25*S + 0.20*B + 0.20*D + 0.10*X
7
+
8
+ Maintains deterministic, evidence-grounded rule scoring for pipeline, typosquatting, and lockfile findings.
9
+ """
10
+ from __future__ import annotations
11
+
12
+ from typing import Any, Optional
13
+
14
+ from config.constants import RISK_ORDER
15
+ from reachability.app_reachability import evaluate_app_reachability, extract_vulnerable_symbols
16
+ from risk_analysis.contextual_scorer import ContextualScorer, DimensionScore
17
+ from risk_analysis.function_impact import FunctionImpactAnalyzer
18
+ from risk_analysis.production_context import ProductionContextAnalyzer
19
+ from risk_analysis.risk_rules import DEFAULT_RULES, RULES_VERSION
20
+
21
+
22
+ def label_for(score: int | float, thresholds: dict) -> str:
23
+ for lab in ("CRITICAL", "HIGH", "MEDIUM", "LOW"):
24
+ if score >= thresholds[lab]:
25
+ return lab
26
+ return "INFORMATIONAL"
27
+
28
+
29
+ def _cap(label: str, cap: str) -> tuple[str, bool]:
30
+ if RISK_ORDER.index(label) < RISK_ORDER.index(cap):
31
+ return cap, True
32
+ return label, False
33
+
34
+
35
+ def _assessment(
36
+ fid: str,
37
+ kind: str,
38
+ score: int,
39
+ factors: list[dict],
40
+ rules: dict,
41
+ cap: Optional[str],
42
+ unknowns: list[str],
43
+ cvss_severity: Optional[str] = None,
44
+ ) -> dict[str, Any]:
45
+ score = max(score, 0)
46
+ label = label_for(score, rules["thresholds"])
47
+ capped = False
48
+ if cap:
49
+ label, capped = _cap(label, cap)
50
+ if capped:
51
+ factors.append({
52
+ "factor": "label cap",
53
+ "points": 0,
54
+ "detail": f"label limited to {cap} for this finding type/state",
55
+ })
56
+ return {
57
+ "finding_id": fid,
58
+ "kind": kind,
59
+ "score": score,
60
+ "label": label,
61
+ "factors": factors,
62
+ "unknowns": unknowns,
63
+ "cvss_severity": cvss_severity,
64
+ "rules_version": RULES_VERSION,
65
+ "thresholds": rules["thresholds"],
66
+ }
67
+
68
+
69
+ def priority_for(
70
+ label: str,
71
+ f: dict,
72
+ reach_status: str = "unknown",
73
+ reach_density: str = "unknown",
74
+ ) -> str:
75
+ """Operational priority rating (P0 act now / P1 this sprint / P2 plan / P3 monitor)."""
76
+ reach = f.get("reachability") or {}
77
+ density = (
78
+ reach_density
79
+ if reach_density != "unknown"
80
+ else (reach.get("import_density") or reach.get("influence_tier") or "unknown")
81
+ )
82
+ is_dev = bool(f.get("dev_dependency"))
83
+ is_heavy = density == "heavy" and not is_dev
84
+ has_kev = bool(f.get("kev"))
85
+
86
+ # Deprioritize unimported or test-only findings with no active KEV exploitation to P2/P3
87
+ if reach_status in ("not_imported", "used_in_tests_only") and not has_kev:
88
+ if label in ("CRITICAL", "HIGH", "MEDIUM"):
89
+ return "P2"
90
+ return "P3"
91
+
92
+ if label == "CRITICAL" or (has_kev and reach_status in ("used_by_app", "reachable_via_dependency")) or (label == "HIGH" and is_heavy):
93
+ return "P0"
94
+ if label == "HIGH" or (label == "MEDIUM" and is_heavy):
95
+ return "P1"
96
+ if label == "MEDIUM":
97
+ return "P2"
98
+ return "P3"
99
+
100
+
101
+ def score_vulnerability(
102
+ f: dict,
103
+ rules: dict | None = None,
104
+ related: dict | None = None,
105
+ ) -> dict[str, Any]:
106
+ """Score a vulnerability finding using the Contextual Vulnerability Risk Scoring v2.0 model."""
107
+ rules = rules or DEFAULT_RULES
108
+ related = related or {}
109
+ source_index = related.get("source_index") or f.get("source_index")
110
+ repo_dir = related.get("repo_dir") or f.get("repo_dir")
111
+
112
+ # Initialize sub-analyzers
113
+ c_weights = (rules.get("contextual_v2") or {}).get("weights", ContextualScorer.DEFAULT_WEIGHTS)
114
+ c_thresholds = (rules.get("contextual_v2") or {}).get("thresholds", rules.get("thresholds", ContextualScorer.DEFAULT_THRESHOLDS))
115
+ scorer = ContextualScorer(weights=c_weights, thresholds=c_thresholds)
116
+ prod_analyzer = ProductionContextAnalyzer(repo_dir=repo_dir)
117
+ impact_analyzer = FunctionImpactAnalyzer()
118
+
119
+ # -------------------------------------------------------------
120
+ # 1. Dimension C: CVSS Severity (Weight: 15%)
121
+ # -------------------------------------------------------------
122
+ raw_cvss = f.get("cvss_score")
123
+ sev = f.get("severity")
124
+ if raw_cvss is not None:
125
+ score_C = max(0.0, min(100.0, float(raw_cvss) * 10.0))
126
+ status_C = "numeric_cvss"
127
+ ev_C = [f"Raw CVSS {raw_cvss:.1f} ({sev or 'unspecified'}) from {f.get('severity_source') or 'advisory'}"]
128
+ conf_C = "high"
129
+ else:
130
+ # Qualitative fallback if numeric CVSS is unavailable
131
+ sev_map = {"CRITICAL": 90.0, "HIGH": 75.0, "MEDIUM": 50.0, "LOW": 25.0}
132
+ score_C = sev_map.get(sev, 40.0)
133
+ status_C = "estimated_from_severity" if sev else "severity_unavailable"
134
+ ev_C = [f"Numeric CVSS unavailable; estimated from severity '{sev or 'UNAVAILABLE'}'"]
135
+ conf_C = "medium" if sev else "low"
136
+
137
+ dim_c = DimensionScore(
138
+ dimension="C",
139
+ name="CVSS Severity",
140
+ weight=scorer.weights["C"],
141
+ raw_value=raw_cvss if raw_cvss is not None else sev,
142
+ normalized_score=score_C,
143
+ status=status_C,
144
+ weighted_contribution=round(scorer.weights["C"] * score_C, 2),
145
+ evidence=ev_C,
146
+ confidence=conf_C,
147
+ )
148
+
149
+ # -------------------------------------------------------------
150
+ # 2. Dimension A: Application Code Reachability (Weight: 20%)
151
+ # -------------------------------------------------------------
152
+ reach = f.get("reachability") or {}
153
+ vuln_symbols = extract_vulnerable_symbols(summary=f.get("summary"), details=f.get("summary"))
154
+
155
+ if source_index:
156
+ dim_a = evaluate_app_reachability(
157
+ package_name=f["package_name"],
158
+ ecosystem=f["ecosystem"],
159
+ source_index=source_index,
160
+ vulnerable_symbols=vuln_symbols,
161
+ dependency_type=f.get("dependency_type", "direct"),
162
+ roots=f.get("roots", []),
163
+ is_dev=bool(f.get("dev_dependency")),
164
+ )
165
+ else:
166
+ # Derive Dimension A from pre-calculated reachability dictionary
167
+ rst = reach.get("status", "unknown")
168
+ app_files = reach.get("app_files", 0)
169
+ density = reach.get("import_density") or reach.get("influence_tier") or "unknown"
170
+ locs = reach.get("locations") or []
171
+ loc_str = f" ({locs[0]['path']}:{locs[0]['line']})" if locs and locs[0].get("path") else ""
172
+
173
+ if rst == "confirmed_reachable":
174
+ norm_a = 100.0
175
+ stat_a = "confirmed_reachable"
176
+ ev_a = ["Vulnerable symbol confirmed reachable in application source code"]
177
+ elif rst == "used_by_app":
178
+ norm_a = 80.0 if (app_files >= 5 or density == "heavy") else 60.0
179
+ stat_a = "potentially_reachable"
180
+ ev_a = [f"Imported in {app_files} application file(s){loc_str}"]
181
+ elif rst == "reachable_via_dependency":
182
+ norm_a = 40.0
183
+ stat_a = "transitive_reachable"
184
+ ev_a = [f"Transitive dependency pulled in by application import(s): {', '.join(reach.get('via') or [])}"]
185
+ elif rst == "used_in_tests_only":
186
+ norm_a = 0.0
187
+ stat_a = "test_only"
188
+ ev_a = [f"Imported only in test files ({reach.get('test_files', 0)} files); excluded from app code"]
189
+ elif rst == "not_imported":
190
+ norm_a = 0.0
191
+ stat_a = "unreachable"
192
+ ev_a = ["No static imports found in analysed application source code"]
193
+ else:
194
+ norm_a = None
195
+ stat_a = "unknown"
196
+ ev_a = ["Reachability has not been assessed; unknown evidence state"]
197
+
198
+ dim_a = DimensionScore(
199
+ dimension="A",
200
+ name="Application Code Reachability",
201
+ weight=scorer.weights["A"],
202
+ raw_value=reach,
203
+ normalized_score=norm_a,
204
+ status=stat_a,
205
+ weighted_contribution=round(scorer.weights["A"] * norm_a, 2) if norm_a is not None else 0.0,
206
+ evidence=ev_a,
207
+ confidence=reach.get("confidence", "medium"),
208
+ )
209
+
210
+ # -------------------------------------------------------------
211
+ # 3. Dimension P: Production Code Reachability (Weight: 35%)
212
+ # -------------------------------------------------------------
213
+ dim_p = prod_analyzer.evaluate_production_reachability(
214
+ package_name=f["package_name"],
215
+ ecosystem=f["ecosystem"],
216
+ source_index=source_index,
217
+ is_dev=bool(f.get("dev_dependency")),
218
+ asset_type=f.get("asset_type", "source_dependency"),
219
+ dependency_type=f.get("dependency_type", "direct"),
220
+ container_details=f.get("container_details"),
221
+ )
222
+
223
+ # -------------------------------------------------------------
224
+ # 4. Dimension I: Function-Level Application Impact (Weight: 30%)
225
+ # -------------------------------------------------------------
226
+ loc_paths = [loc["path"] for loc in (reach.get("locations") or []) if loc.get("path")]
227
+ dim_i, impact_breakdown = impact_analyzer.evaluate_function_impact(
228
+ package_name=f["package_name"],
229
+ vulnerable_symbols=vuln_symbols,
230
+ advisory_summary=f.get("summary"),
231
+ advisory_details=f.get("summary"),
232
+ app_file_locations=loc_paths,
233
+ dim_p_score=dim_p.normalized_score,
234
+ is_dev=bool(f.get("dev_dependency")),
235
+ )
236
+
237
+ # -------------------------------------------------------------
238
+ # 5. Execute 4-Factor Contextual Risk Calculation
239
+ # -------------------------------------------------------------
240
+ result = scorer.score(
241
+ finding_id=f.get("finding_id", "VULN-000"),
242
+ dim_c=dim_c,
243
+ dim_a=dim_a,
244
+ dim_p=dim_p,
245
+ dim_i=dim_i,
246
+ impact_breakdown=impact_breakdown,
247
+ kev=bool(f.get("kev")),
248
+ epss=f.get("epss"),
249
+ )
250
+
251
+ unknowns = list(result.missing_evidence_reasons)
252
+ if not f.get("fixed_versions"):
253
+ unknowns.append("No fixed version is recorded in the advisory data.")
254
+ if f.get("affected_status") != "confirmed_affected":
255
+ unknowns.append("Applicability of the advisory to the installed version could not be confirmed locally.")
256
+
257
+ density = reach.get("import_density") or reach.get("influence_tier") or "unknown"
258
+ app_files = reach.get("app_files", 0)
259
+
260
+ # Confidence calculation
261
+ vc = f.get("verdict_confidence")
262
+ confidence = vc or {
263
+ "score": 30 + (20 if f.get("cross_verified") else 0) + (10 if sev else 0) + (15 if not result.is_provisional else 0),
264
+ "label": "High" if (f.get("cross_verified") and not result.is_provisional) else "Medium" if f.get("cross_verified") else "Low",
265
+ "basis": ["4-factor contextual assessment complete" if not result.is_provisional else "provisional assessment (missing evidence)"],
266
+ }
267
+
268
+ return {
269
+ "finding_id": result.finding_id,
270
+ "kind": "vulnerability",
271
+ "score": result.rounded_score,
272
+ "exact_score": result.score,
273
+ "label": result.label,
274
+ "priority": result.priority,
275
+ "is_provisional": result.is_provisional,
276
+ "formula": result.formula,
277
+ "weights": result.weights,
278
+ "dimensions": {k: v.to_dict() for k, v in result.dimensions.items()},
279
+ "impact_breakdown": result.impact_breakdown.to_dict() if result.impact_breakdown else None,
280
+ "factors": result.factors,
281
+ "missing_dimensions": result.missing_dimensions,
282
+ "missing_evidence_reasons": result.missing_evidence_reasons,
283
+ "threat_intel_escalations": result.threat_intel_escalations,
284
+ "unknowns": unknowns,
285
+ "cvss_severity": sev,
286
+ "cvss_score": raw_cvss,
287
+ "rules_version": RULES_VERSION,
288
+ "thresholds": rules["thresholds"],
289
+ "confidence": confidence,
290
+ "verdict": f.get("verdict"),
291
+ "influence_tier": density,
292
+ "app_files": app_files,
293
+ "asset_type": f.get("asset_type", "source_dependency"),
294
+ "container_details": f.get("container_details"),
295
+ }
296
+
297
+
298
+ def score_pipeline(f: dict, rules: dict | None = None) -> dict[str, Any]:
299
+ rules = rules or DEFAULT_RULES
300
+ r = rules["pipeline"]
301
+ pts = r["severity_points"].get(f["severity"], 4)
302
+ factors = [{"factor": "Rule severity", "points": pts, "detail": f"{f['rule_id']} {f['severity']}: {f['title']}"}]
303
+ total = pts
304
+ if f.get("evidence_strength") == "medium":
305
+ total += r["heuristic_penalty"]
306
+ factors.append({"factor": "Heuristic evidence", "points": r["heuristic_penalty"], "detail": "pattern-based, not directly provable from the file alone"})
307
+ if (f.get("extra") or {}).get("third_party"):
308
+ total += r["third_party_unpinned_action"]
309
+ factors.append({"factor": "Third-party action", "points": r["third_party_unpinned_action"], "detail": "the action is maintained outside GitHub/known first-party orgs"})
310
+ unknowns = ["Static analysis of the file only; whether the workflow/container is used in production is not known."]
311
+ a = _assessment(f["finding_id"], f.get("kind", "pipeline"), total, factors, rules, None, unknowns)
312
+ a["confidence"] = {
313
+ "score": 85 if f.get("evidence_strength") == "high" else 55,
314
+ "label": "High" if f.get("evidence_strength") == "high" else "Medium",
315
+ "basis": ["rule matched directly in the file" if f.get("evidence_strength") == "high" else "pattern-based rule"],
316
+ }
317
+ a["priority"] = {"CRITICAL": "P0", "HIGH": "P1", "MEDIUM": "P2"}.get(a["label"], "P3")
318
+ return a
319
+
320
+
321
+ def score_typosquat(f: dict, rules: dict | None = None, related: dict | None = None) -> dict[str, Any]:
322
+ rules = rules or DEFAULT_RULES
323
+ r = rules["typosquatting"]
324
+ related = related or {}
325
+ factors: list[dict] = []
326
+ s = f.get("evidence_strength", "low")
327
+ total = r["strength_points"][s]
328
+ factors.append({
329
+ "factor": "Name-similarity evidence strength",
330
+ "points": total,
331
+ "detail": f"{s}: '{f['package_name']}' vs '{f['similar_to']}' (similarity {f['similarity_score']}%, techniques: {', '.join(f['techniques'])})",
332
+ })
333
+ ep = r["exposure"].get(f.get("dependency_type", "unknown"), 0)
334
+ total += ep
335
+ factors.append({"factor": "Dependency exposure", "points": ep, "detail": f.get("dependency_type", "unknown")})
336
+ if related.get("lockfile_addition"):
337
+ total += r["correlated_lockfile_addition"]
338
+ factors.append({"factor": "Recently added in lockfile history", "points": r["correlated_lockfile_addition"], "detail": related["lockfile_addition"]})
339
+ if related.get("vulnerability"):
340
+ total += r["correlated_vulnerability"]
341
+ factors.append({"factor": "Also has a vulnerability finding", "points": r["correlated_vulnerability"], "detail": related["vulnerability"]})
342
+ reg = f.get("registry") or {}
343
+ unknowns = ["Similarity is a signal, not proof of malicious intent."]
344
+ if not reg.get("checked"):
345
+ unknowns.append("Registry metadata was not available to corroborate this finding.")
346
+ if reg.get("exists") is False:
347
+ unknowns.append("The package was not found in the public registry; it may be private/internal.")
348
+ a = _assessment(f["finding_id"], "typosquatting", total, factors, rules, r["cap"], unknowns)
349
+ a["confidence"] = {
350
+ "score": 60 if reg.get("checked") else 35,
351
+ "label": "Medium" if reg.get("checked") else "Low",
352
+ "basis": ["name similarity", "registry corroboration" if reg.get("checked") else "no registry corroboration"],
353
+ }
354
+ a["priority"] = {"CRITICAL": "P0", "HIGH": "P1", "MEDIUM": "P2"}.get(a["label"], "P3")
355
+ return a
356
+
357
+
358
+ def score_lockfile_change(c: dict, rules: dict | None = None, related: dict | None = None) -> dict[str, Any]:
359
+ rules = rules or DEFAULT_RULES
360
+ r = rules["lockfile_change"]
361
+ related = related or {}
362
+ factors: list[dict] = []
363
+ total = r["classification_points"].get(c["classification"], 0)
364
+ factors.append({
365
+ "factor": "Classification",
366
+ "points": total,
367
+ "detail": f"{c['classification']}: {c['change_type']} in {c['file']}",
368
+ })
369
+ bonus = r["strength_bonus"].get(c["evidence_strength"], 0)
370
+ total += bonus
371
+ factors.append({
372
+ "factor": "Evidence strength",
373
+ "points": bonus,
374
+ "detail": f"{c['evidence_strength']} ({len(c['signals'])} signal(s): {', '.join(c['signals'])})",
375
+ })
376
+ if related.get("vulnerability"):
377
+ total += r["correlated_vulnerability"]
378
+ factors.append({"factor": "Correlated vulnerability", "points": r["correlated_vulnerability"], "detail": related["vulnerability"]})
379
+ if related.get("typosquat"):
380
+ total += r["correlated_typosquat"]
381
+ factors.append({"factor": "Correlated typosquat candidate", "points": r["correlated_typosquat"], "detail": related["typosquat"]})
382
+ unknowns = ["Lockfile diffs are static changes; they do not prove malicious intent or that the change was unauthorized."]
383
+ a = _assessment(c["finding_id"], "lockfile_change", total, factors, rules, r["cap"], unknowns)
384
+ a["confidence"] = {
385
+ "score": 80 if c["evidence_strength"] == "high" else 50,
386
+ "label": "High" if c["evidence_strength"] == "high" else "Medium",
387
+ "basis": [f"{c['evidence_strength']} evidence ({len(c['signals'])} signals)"],
388
+ }
389
+ a["priority"] = {"CRITICAL": "P0", "HIGH": "P1", "MEDIUM": "P2"}.get(a["label"], "P3")
390
+ return a
File without changes
@@ -0,0 +1,142 @@
1
+ """Optional sandbox validation of an *approved* remediation: apply the patch to a throw-away re-clone and run the repository's own build/tests in Docker.
2
+
3
+ This is the only place where repository-controlled commands (``npm test``, ``pytest``, ``mvn test`` ...) can run, so it is:
4
+
5
+ * opt-in and explicit (UI checkbox + approved remediation); never part of a normal scan
6
+ * isolated: a fresh clone in a temp workspace, bind-mounted as the only host path; no host environment variables or secrets are passed;
7
+ ``--cap-drop ALL``, ``no-new-privileges``, memory/CPU/PID limits and timeouts
8
+ * two phases: *install* (network allowed, to fetch dependencies) and *test* (``--network none``)
9
+ * compared with a baseline run when the patched run fails, so pre-existing failures are not blamed on the patch
10
+
11
+ Docker must be installed and its daemon running; otherwise the result is ``skipped`` with the reason.
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ import shutil
17
+ import subprocess
18
+ import time
19
+ from pathlib import Path
20
+ from typing import Any, Callable, Optional
21
+
22
+ from config.settings import Settings
23
+ from core import git_manager as gm
24
+ from core.safe_env import scrubbed_env
25
+ from core.url_validator import validate_github_url
26
+ from llm.client import redact
27
+
28
+ LIMITS = ["--cap-drop", "ALL", "--security-opt", "no-new-privileges", "--pids-limit", "512", "--memory", "2g", "--cpus", "2", "--tmpfs", "/tmp:rw,exec,size=1g", "-e", "HOME=/tmp"]
29
+ INSTALL_TIMEOUT, TEST_TIMEOUT = 900, 900
30
+
31
+
32
+ def docker_status() -> dict:
33
+ exe = shutil.which("docker")
34
+ if not exe:
35
+ return {"available": False, "reason": "Docker is not installed (no `docker` executable on PATH)."}
36
+ try:
37
+ p = subprocess.run([exe, "version", "--format", "{{.Server.Version}}"], capture_output=True, text=True, timeout=15, shell=False, env=scrubbed_env())
38
+ except (OSError, subprocess.TimeoutExpired):
39
+ return {"available": False, "reason": "Docker did not respond."}
40
+ if p.returncode != 0 or not p.stdout.strip():
41
+ return {"available": False, "reason": "The Docker daemon is not running (start Docker Desktop and retry)."}
42
+ return {"available": True, "version": p.stdout.strip(), "exe": exe}
43
+
44
+
45
+ def detect_recipe(repo_dir: Path, ecosystem: str, service_dir: str = ".") -> Optional[dict]:
46
+ """Install/test commands for the service, or None when there is no recognised build/test recipe (never guessed)."""
47
+ d = repo_dir / (service_dir if service_dir not in (".", "") else "")
48
+ if not d.resolve().is_relative_to(repo_dir.resolve()):
49
+ return None
50
+ wd = (service_dir if service_dir not in (".", "") else ".")
51
+ if ecosystem == "npm" and (d / "package.json").exists():
52
+ try:
53
+ scripts = (json.loads((d / "package.json").read_text(encoding="utf-8")).get("scripts") or {})
54
+ except ValueError:
55
+ return None
56
+ t = scripts.get("test")
57
+ if not t or "no test specified" in t:
58
+ return None
59
+ return {"image": "node:22-bookworm-slim", "workdir": wd, "install": "npm ci || npm install", "test": "npm test --silent"}
60
+ if ecosystem == "PyPI":
61
+ has_tests = any((d / x).exists() for x in ("tests", "test", "pytest.ini", "tox.ini")) or (d / "pyproject.toml").exists()
62
+ if not has_tests:
63
+ return None
64
+ inst = "pip install -r requirements.txt" if (d / "requirements.txt").exists() else "pip install ."
65
+ return {"image": "python:3.12-slim", "workdir": wd, "install": f"{inst} && pip install pytest", "test": "python -m pytest -q -x"}
66
+ if ecosystem == "Maven" and (d / "pom.xml").exists():
67
+ return {"image": "maven:3.9-eclipse-temurin-21", "workdir": wd, "install": "mvn -B -q dependency:go-offline", "test": "mvn -B -q -o test"}
68
+ if ecosystem == "Go" and (d / "go.mod").exists():
69
+ return {"image": "golang:1.23", "workdir": wd, "install": "go mod download", "test": "go test ./..."}
70
+ if ecosystem == "crates.io" and (d / "Cargo.toml").exists():
71
+ return {"image": "rust:1", "workdir": wd, "install": "cargo fetch", "test": "cargo test --offline"}
72
+ return None
73
+
74
+
75
+ def _run(exe: str, repo_dir: Path, recipe: dict, phase: str, timeout: int) -> dict:
76
+ cmd = [exe, "run", "--rm", *LIMITS]
77
+ if phase == "test":
78
+ cmd += ["--network", "none"]
79
+ cmd += ["-v", f"{repo_dir.resolve()}:/work", "-w", "/work/" + recipe["workdir"].strip("./"), recipe["image"], "sh", "-c", recipe[phase]]
80
+ t0 = time.time()
81
+ try:
82
+ p = subprocess.run(cmd, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=timeout, shell=False, env=scrubbed_env())
83
+ tail = redact("\n".join((p.stdout + "\n" + p.stderr).strip().splitlines()[-60:]))
84
+ return {"phase": phase, "exit_code": p.returncode, "seconds": round(time.time() - t0, 1), "log_tail": tail}
85
+ except subprocess.TimeoutExpired:
86
+ return {"phase": phase, "exit_code": None, "seconds": round(time.time() - t0, 1), "log_tail": f"timed out after {timeout}s"}
87
+
88
+
89
+ def _prepare(settings: Settings, repo: dict, patch_diff: Optional[str]) -> tuple[Path, Path]:
90
+ rr = validate_github_url(repo["url"])
91
+ scan_id, ws = gm.new_workspace(settings)
92
+ clone = gm.clone_repository(rr, ws, repo.get("branch") or repo.get("ref"), settings)
93
+ sha = repo.get("commit_sha")
94
+ if sha:
95
+ try:
96
+ gm.run_git(["fetch", "--depth", "1", "origin", sha], cwd=clone, timeout=120)
97
+ gm.run_git(["checkout", "--detach", "FETCH_HEAD"], cwd=clone, timeout=60)
98
+ except gm.GitError:
99
+ pass # stay on the cloned head; reported by the caller through the commit comparison
100
+ if patch_diff:
101
+ (ws / "fix.patch").write_text(patch_diff, encoding="utf-8", newline="")
102
+ gm.run_git(["apply", "--whitespace=nowarn", str(ws / "fix.patch")], cwd=clone, timeout=30)
103
+ return ws, clone
104
+
105
+
106
+ def validate_in_sandbox(settings: Settings, repo: dict, rem: dict, progress: Optional[Callable[[str], None]] = None) -> dict[str, Any]:
107
+ say = progress or (lambda m: None)
108
+ ds = docker_status()
109
+ if not ds["available"]:
110
+ return {"status": "skipped", "reason": ds["reason"]}
111
+ patch = (rem.get("patch") or {}).get("diff")
112
+ if not patch:
113
+ return {"status": "skipped", "reason": "This proposal has no patch to validate."}
114
+ eco = rem.get("ecosystem") or (rem.get("target") or {}).get("ecosystem")
115
+ ws_patched = ws_base = None
116
+ try:
117
+ say("Cloning the repository at the scanned commit and applying the patch ...")
118
+ ws_patched, clone = _prepare(settings, repo, patch)
119
+ recipe = detect_recipe(clone, eco, rem.get("service") or ".")
120
+ if not recipe:
121
+ return {"status": "skipped", "reason": f"No recognised build/test recipe for {eco} in this repository (the Guardian never guesses commands)."}
122
+ say(f"Installing dependencies in {recipe['image']} (network allowed for this phase) ...")
123
+ inst = _run(ds["exe"], clone, recipe, "install", INSTALL_TIMEOUT)
124
+ if inst["exit_code"] != 0:
125
+ return {"status": "error", "reason": "dependency installation failed in the sandbox", "recipe": recipe, "runs": [inst], "docker": ds["version"]}
126
+ say("Running the tests with the network disabled ...")
127
+ test = _run(ds["exe"], clone, recipe, "test", TEST_TIMEOUT)
128
+ out: dict[str, Any] = {"status": "passed" if test["exit_code"] == 0 else "failed", "recipe": recipe, "runs": [inst, test], "docker": ds["version"], "isolation": "cap-drop ALL, no-new-privileges, 2 CPU / 2 GB / 512 pids, tests without network, no host env or secrets"}
129
+ if test["exit_code"] != 0:
130
+ say("Tests failed: running the unpatched baseline to see whether the failure pre-existed ...")
131
+ ws_base, base_clone = _prepare(settings, repo, None)
132
+ binst = _run(ds["exe"], base_clone, recipe, "install", INSTALL_TIMEOUT)
133
+ btest = _run(ds["exe"], base_clone, recipe, "test", TEST_TIMEOUT) if binst["exit_code"] == 0 else None
134
+ out["baseline"] = {"status": "passed" if btest and btest["exit_code"] == 0 else "failed", "runs": [binst] + ([btest] if btest else [])}
135
+ out["attribution"] = "the same failure occurs without the patch (pre-existing)" if out["baseline"]["status"] == "failed" else "the baseline passes: the patch likely broke a test"
136
+ return out
137
+ except Exception as e: # noqa: BLE001
138
+ return {"status": "error", "reason": f"{type(e).__name__}: {str(e)[:200]}"}
139
+ finally:
140
+ for w in (ws_patched, ws_base):
141
+ if w:
142
+ gm.cleanup(w)
File without changes
@@ -0,0 +1,19 @@
1
+ """One adapter per SBOM producer. This is the single normalisation boundary of the project.
2
+
3
+ Each adapter exposes:
4
+ NAME scanner id (``syft`` | ``trivy`` | ``builtin``)
5
+ canonicalize(raw) -> dict CycloneDX document in the canonical shape every later stage consumes (raw input is never mutated)
6
+ locations(component) -> list[str] file paths that evidence the component (as written by the tool)
7
+ found_by(component) -> str|None tool-specific cataloger / package type
8
+
9
+ Downstream code (graph, OSV, detectors, reports) only ever sees the canonical document / ``Component`` models.
10
+ """
11
+ from __future__ import annotations
12
+
13
+ from sbom.adapters import builtin, syft, trivy
14
+
15
+ ADAPTERS = {a.NAME: a for a in (syft, trivy, builtin)}
16
+
17
+
18
+ def get_adapter(name: str):
19
+ return ADAPTERS.get(name, syft)
@@ -0,0 +1,29 @@
1
+ """Read locations from both generations of built-in CycloneDX properties."""
2
+ from __future__ import annotations
3
+
4
+ import re
5
+
6
+ from sbom.builtin_generator import PROP
7
+
8
+ NAME = "builtin"
9
+ _LOCATION = re.compile(rf"(?:{re.escape(PROP)}|sc-guardian):location:(\d+):path")
10
+
11
+
12
+ def canonicalize(raw: dict) -> dict:
13
+ return raw
14
+
15
+
16
+ def locations(c: dict) -> list[str]:
17
+ indexed = []
18
+ for prop in c.get("properties") or []:
19
+ if not isinstance(prop, dict):
20
+ continue
21
+ match = _LOCATION.fullmatch(str(prop.get("name", "")))
22
+ if match and isinstance(prop.get("value"), str):
23
+ indexed.append((int(match[1]), prop["value"]))
24
+ return list(dict.fromkeys(value for _, value in sorted(indexed)))
25
+
26
+
27
+ def found_by(c: dict):
28
+ keys = {f"{prefix}:package:foundBy" for prefix in (PROP, "sc-guardian")}
29
+ return next((p.get("value") for p in c.get("properties") or [] if isinstance(p, dict) and p.get("name") in keys), None)
@@ -0,0 +1,26 @@
1
+ """Syft CycloneDX adapter: Syft already emits one component per package occurrence with ``syft:location:N:path`` properties."""
2
+ from __future__ import annotations
3
+
4
+ NAME = "syft"
5
+
6
+
7
+ def _prop(c: dict, name: str) -> list[str]:
8
+ return [p.get("value", "") for p in c.get("properties", []) or [] if isinstance(p, dict) and p.get("name") == name]
9
+
10
+
11
+ def canonicalize(raw: dict) -> dict:
12
+ return raw
13
+
14
+
15
+ def locations(c: dict) -> list[str]:
16
+ out = []
17
+ for i in range(20):
18
+ v = _prop(c, f"syft:location:{i}:path")
19
+ if not v:
20
+ break
21
+ out.append(v[0])
22
+ return out
23
+
24
+
25
+ def found_by(c: dict):
26
+ return (_prop(c, "syft:package:foundBy") or [None])[0]