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,253 @@
1
+ """Contextual Vulnerability Risk Scoring Engine v2.0.
2
+
3
+ Implements the four-factor linear contextual risk model:
4
+ R = 0.15*C + 0.20*A + 0.35*P + 0.30*I
5
+
6
+ Where:
7
+ C: CVSS Severity (0-100)
8
+ A: Application Code Reachability (0-100)
9
+ P: Production Code Reachability (0-100)
10
+ I: Function-Level Application Impact (0-100)
11
+
12
+ Follows strict missing-evidence handling: Unknown is not zero.
13
+ Threat intelligence (CISA KEV, EPSS) is maintained as an independent prioritization dimension.
14
+ """
15
+ from __future__ import annotations
16
+
17
+ from dataclasses import asdict, dataclass, field
18
+ from typing import Any, Optional
19
+
20
+
21
+ @dataclass
22
+ class FunctionImpactBreakdown:
23
+ """Breakdown of the 5 sub-factors comprising Dimension I."""
24
+ function_criticality_F: float = 25.0 # F: 0-100 (weight 0.25)
25
+ data_sensitivity_S: float = 30.0 # S: 0-100 (weight 0.25)
26
+ privilege_boundary_B: float = 30.0 # B: 0-100 (weight 0.20)
27
+ downstream_impact_D: float = 35.0 # D: 0-100 (weight 0.20)
28
+ production_exposure_X: float = 40.0 # X: 0-100 (weight 0.10)
29
+ composite_score_I: float = 30.0 # 0-100
30
+ rationale: dict[str, str] = field(default_factory=dict)
31
+
32
+ def to_dict(self) -> dict[str, Any]:
33
+ return asdict(self)
34
+
35
+
36
+ @dataclass
37
+ class DimensionScore:
38
+ """Detailed score and evidence audit for a single scoring dimension."""
39
+ dimension: str # "C", "A", "P", "I"
40
+ name: str
41
+ weight: float
42
+ raw_value: Any
43
+ normalized_score: Optional[float] # None if unknown / missing
44
+ status: str # "confirmed", "potential", "unreachable", "unknown", etc.
45
+ weighted_contribution: float
46
+ evidence: list[str] = field(default_factory=list)
47
+ confidence: str = "medium" # "high", "medium", "low", "none"
48
+
49
+ def to_dict(self) -> dict[str, Any]:
50
+ return asdict(self)
51
+
52
+
53
+ @dataclass
54
+ class ContextualRiskResult:
55
+ """Complete assessment result from ContextualScorer."""
56
+ finding_id: str
57
+ score: float # Final score 0-100 (or provisional score)
58
+ rounded_score: int
59
+ label: str # CRITICAL, HIGH, MEDIUM, LOW, INFORMATIONAL
60
+ priority: str # P0, P1, P2, P3
61
+ is_provisional: bool
62
+ formula: str
63
+ weights: dict[str, float]
64
+ dimensions: dict[str, DimensionScore]
65
+ impact_breakdown: Optional[FunctionImpactBreakdown] = None
66
+ missing_dimensions: list[str] = field(default_factory=list)
67
+ missing_evidence_reasons: list[str] = field(default_factory=list)
68
+ threat_intel_escalations: list[str] = field(default_factory=list)
69
+ factors: list[dict[str, Any]] = field(default_factory=list)
70
+
71
+ def to_dict(self) -> dict[str, Any]:
72
+ data = asdict(self)
73
+ if self.impact_breakdown:
74
+ data["impact_breakdown"] = self.impact_breakdown.to_dict()
75
+ data["dimensions"] = {k: v.to_dict() for k, v in self.dimensions.items()}
76
+ return data
77
+
78
+
79
+ class ContextualScorer:
80
+ """Calculates contextual risk using the v2.0 model with missing-evidence awareness."""
81
+
82
+ DEFAULT_WEIGHTS = {
83
+ "C": 0.15,
84
+ "A": 0.20,
85
+ "P": 0.35,
86
+ "I": 0.30,
87
+ }
88
+
89
+ DEFAULT_THRESHOLDS = {
90
+ "CRITICAL": 70.0,
91
+ "HIGH": 45.0,
92
+ "MEDIUM": 25.0,
93
+ "LOW": 10.0,
94
+ }
95
+
96
+ def __init__(
97
+ self,
98
+ weights: Optional[dict[str, float]] = None,
99
+ thresholds: Optional[dict[str, float]] = None,
100
+ ):
101
+ self.weights = dict(weights or self.DEFAULT_WEIGHTS)
102
+ self.thresholds = dict(thresholds or self.DEFAULT_THRESHOLDS)
103
+ self._validate_weights()
104
+
105
+ def _validate_weights(self) -> None:
106
+ total = sum(self.weights.values())
107
+ if abs(total - 1.0) > 1e-4:
108
+ raise ValueError(f"Contextual scoring weights must sum to 1.0; got {total:.4f} ({self.weights})")
109
+ for k in ("C", "A", "P", "I"):
110
+ if k not in self.weights:
111
+ raise ValueError(f"Missing weight for dimension '{k}'")
112
+ if self.weights[k] < 0:
113
+ raise ValueError(f"Weight for '{k}' cannot be negative: {self.weights[k]}")
114
+
115
+ def label_for(self, score: float) -> str:
116
+ for lab in ("CRITICAL", "HIGH", "MEDIUM", "LOW"):
117
+ if score >= self.thresholds[lab]:
118
+ return lab
119
+ return "INFORMATIONAL"
120
+
121
+ def calculate_priority(
122
+ self,
123
+ risk_score: float,
124
+ label: str,
125
+ dim_a: DimensionScore,
126
+ dim_p: DimensionScore,
127
+ kev: bool = False,
128
+ epss: Optional[float] = None,
129
+ ) -> tuple[str, list[str]]:
130
+ """Calculate operational priority P0-P3 with decoupled threat intelligence."""
131
+ reasons = []
132
+ is_kev_active = bool(kev)
133
+ high_epss = (epss or 0.0) >= 0.20
134
+ app_reachable = dim_a.normalized_score is not None and dim_a.normalized_score >= 60.0
135
+ prod_reachable = dim_p.normalized_score is not None and dim_p.normalized_score >= 70.0
136
+ test_only = dim_p.status == "test_only" or (dim_p.normalized_score is not None and dim_p.normalized_score == 0.0)
137
+ unimported = dim_a.status == "unreachable" or (dim_a.normalized_score is not None and dim_a.normalized_score == 0.0)
138
+
139
+ if is_kev_active:
140
+ reasons.append("Active exploitation in CISA KEV catalog")
141
+ if high_epss:
142
+ reasons.append(f"High exploitation probability (EPSS {epss:.1%})")
143
+
144
+ # Deprioritization if verified test-only or completely unimported without active KEV
145
+ if (test_only or unimported) and not is_kev_active:
146
+ if label in ("CRITICAL", "HIGH", "MEDIUM"):
147
+ return "P2", ["Deprioritized: zero production/application runtime exposure (no active KEV)"]
148
+ return "P3", ["Deprioritized: zero production/application runtime exposure"]
149
+
150
+ # Escalation rules
151
+ if risk_score >= self.thresholds["CRITICAL"] or (is_kev_active and app_reachable) or (risk_score >= self.thresholds["HIGH"] and prod_reachable):
152
+ if is_kev_active and app_reachable:
153
+ reasons.append("Escalated to P0 due to active CISA KEV with verified application reachability")
154
+ elif prod_reachable and risk_score >= self.thresholds["HIGH"]:
155
+ reasons.append("Escalated to P0 due to high contextual risk in confirmed production path")
156
+ return "P0", reasons
157
+
158
+ if risk_score >= self.thresholds["HIGH"] or (risk_score >= self.thresholds["MEDIUM"] and prod_reachable) or (is_kev_active):
159
+ if is_kev_active:
160
+ reasons.append("Escalated to P1 due to active CISA KEV")
161
+ elif prod_reachable:
162
+ reasons.append("Escalated to P1 due to medium contextual risk with strong production path")
163
+ return "P1", reasons
164
+
165
+ if risk_score >= self.thresholds["MEDIUM"]:
166
+ return "P2", reasons
167
+
168
+ return "P3", reasons
169
+
170
+ def score(
171
+ self,
172
+ finding_id: str,
173
+ dim_c: DimensionScore,
174
+ dim_a: DimensionScore,
175
+ dim_p: DimensionScore,
176
+ dim_i: DimensionScore,
177
+ impact_breakdown: Optional[FunctionImpactBreakdown] = None,
178
+ kev: bool = False,
179
+ epss: Optional[float] = None,
180
+ ) -> ContextualRiskResult:
181
+ """Execute the 4-factor scoring calculation."""
182
+ dims = {"C": dim_c, "A": dim_a, "P": dim_p, "I": dim_i}
183
+ missing_dims: list[str] = []
184
+ missing_reasons: list[str] = []
185
+ factors: list[dict[str, Any]] = []
186
+
187
+ available_weights = 0.0
188
+ weighted_sum = 0.0
189
+
190
+ for key, dim in dims.items():
191
+ # Clamp raw normalized score if present
192
+ if dim.normalized_score is not None:
193
+ dim.normalized_score = max(0.0, min(100.0, float(dim.normalized_score)))
194
+ contrib = self.weights[key] * dim.normalized_score
195
+ dim.weighted_contribution = round(contrib, 2)
196
+ weighted_sum += contrib
197
+ available_weights += self.weights[key]
198
+ factors.append({
199
+ "factor": f"Dimension {key} ({dim.name})",
200
+ "points": round(contrib, 1),
201
+ "normalized": round(dim.normalized_score, 1),
202
+ "weight": f"{int(self.weights[key] * 100)}%",
203
+ "detail": f"{dim.status}: {'; '.join(dim.evidence[:2]) if dim.evidence else 'Score ' + str(round(dim.normalized_score, 1))}",
204
+ })
205
+ else:
206
+ dim.weighted_contribution = 0.0
207
+ missing_dims.append(key)
208
+ reason = f"Dimension {key} ({dim.name}) is unknown or missing evidence."
209
+ missing_reasons.append(reason)
210
+ factors.append({
211
+ "factor": f"Dimension {key} ({dim.name})",
212
+ "points": 0.0,
213
+ "normalized": "Unknown",
214
+ "weight": f"{int(self.weights[key] * 100)}%",
215
+ "detail": "Missing or unassessed evidence; treated as provisional (NOT zero).",
216
+ })
217
+
218
+ is_provisional = len(missing_dims) > 0
219
+
220
+ # Calculate final or provisional score
221
+ if available_weights > 0.0:
222
+ if is_provisional:
223
+ # Re-normalize over available weights
224
+ final_score = weighted_sum / available_weights
225
+ else:
226
+ final_score = weighted_sum
227
+ else:
228
+ final_score = 50.0 # Complete uncertainty baseline
229
+
230
+ final_score = max(0.0, min(100.0, final_score))
231
+ label = self.label_for(final_score)
232
+ priority, escalations = self.calculate_priority(
233
+ final_score, label, dim_a, dim_p, kev=kev, epss=epss
234
+ )
235
+
236
+ formula_str = f"R = {self.weights['C']:.2f}*C + {self.weights['A']:.2f}*A + {self.weights['P']:.2f}*P + {self.weights['I']:.2f}*I"
237
+
238
+ return ContextualRiskResult(
239
+ finding_id=finding_id,
240
+ score=round(final_score, 1),
241
+ rounded_score=int(round(final_score)),
242
+ label=label,
243
+ priority=priority,
244
+ is_provisional=is_provisional,
245
+ formula=formula_str,
246
+ weights=dict(self.weights),
247
+ dimensions=dims,
248
+ impact_breakdown=impact_breakdown,
249
+ missing_dimensions=missing_dims,
250
+ missing_evidence_reasons=missing_reasons,
251
+ threat_intel_escalations=escalations,
252
+ factors=factors,
253
+ )
@@ -0,0 +1,62 @@
1
+ """Collect traceable evidence for every finding (SBOM, advisory, graph, repository/Git)."""
2
+ from __future__ import annotations
3
+
4
+ from typing import Any, Optional
5
+
6
+
7
+ def _repo_block(repo: dict) -> dict:
8
+ return {"repository_url": repo.get("url"), "commit_sha": repo.get("commit_sha"), "branch": repo.get("branch"),
9
+ "scan_id": repo.get("scan_id"), "scan_timestamp": repo.get("scan_timestamp")}
10
+
11
+
12
+ def collect_vulnerability_evidence(f: dict, repo: dict, sbom_id: Optional[str], lock_index: dict) -> dict[str, Any]:
13
+ lock = lock_index.get((f["service_dir"], f["ecosystem"], f["package_name"], f["installed_version"]))
14
+ return {
15
+ "kind": "vulnerability", "finding_id": f["finding_id"],
16
+ "advisory": {"ids": f["vulnerability_ids"], "cve_ids": f["cve_ids"], "primary_id": f["primary_id"], "summary": f.get("summary"),
17
+ "sources": f["sources"], "urls": f["advisory_urls"], "retrieved_at": f.get("retrieved_at"),
18
+ "published": f.get("published"), "modified": f.get("modified"),
19
+ "affected_ranges": f["affected_ranges"], "fixed_versions": f["fixed_versions"],
20
+ "recommended_fix": f["recommended_fix"], "severity": f["severity"], "severity_source": f["severity_source"],
21
+ "cvss_score": f["cvss_score"], "cvss_vector": f["cvss_vector"], "cvss_version": f.get("cvss_version"),
22
+ "kev": f["kev"], "kev_info": f.get("kev_info"), "affected_status": f["affected_status"],
23
+ "affected_status_reason": f.get("affected_status_reason")},
24
+ "component": {"name": f["package_name"], "ecosystem": f["ecosystem"], "version": f["installed_version"], "purl": f.get("purl"),
25
+ "bom_ref": f["component_ref"], "sbom_id": sbom_id, "service_dir": f.get("service_dir")},
26
+ "dependency": {"type": f["dependency_type"], "roots": f["roots"], "immediate_parents": f["immediate_parents"],
27
+ "exposures": [{"root": e["root"], "relationship": e["relationship"], "depth": e["depth"],
28
+ "paths": e["paths"][:5], "immediate_parents": e["immediate_parents"]} for e in f["exposures"]],
29
+ "dev_dependency": f.get("dev_dependency")},
30
+ "repository": {**_repo_block(repo), "lockfile": lock.get("lockfile") if lock else None,
31
+ "lockfile_record": lock.get("record") if lock else None,
32
+ "lockfile_integrity": lock.get("integrity") if lock else None},
33
+ "notes": f.get("notes", []),
34
+ }
35
+
36
+
37
+ def collect_typosquat_evidence(f: dict, repo: dict, sbom_id: Optional[str]) -> dict[str, Any]:
38
+ return {
39
+ "kind": "typosquatting", "finding_id": f["finding_id"],
40
+ "detection": {"package": f["package_name"], "ecosystem": f["ecosystem"], "similar_to": f["similar_to"],
41
+ "similarity_score": f["similarity_score"], "edit_distance": f["edit_distance"], "techniques": f["techniques"],
42
+ "reference_source": f["reference_source"], "evidence": f["evidence"], "registry": f.get("registry", {}),
43
+ "evidence_strength": f["evidence_strength"], "caveats": f["caveats"]},
44
+ "component": {"name": f["package_name"], "ecosystem": f["ecosystem"], "versions": f["versions"],
45
+ "bom_refs": f["component_refs"], "sbom_id": sbom_id, "services": f["services"]},
46
+ "dependency": {"type": f["dependency_type"], "roots": f["roots"]},
47
+ "repository": _repo_block(repo), "notes": [],
48
+ }
49
+
50
+
51
+ def collect_lockfile_evidence(c: dict, repo: dict, sbom_id: Optional[str]) -> dict[str, Any]:
52
+ return {
53
+ "kind": "lockfile_change", "finding_id": c["finding_id"],
54
+ "change": {"file": c["file"], "package": c["package_name"], "ecosystem": c["ecosystem"], "change_type": c["change_type"],
55
+ "previous": c["previous"], "new": c["new"], "classification": c["classification"], "signals": c["signals"],
56
+ "reasons": c["reasons"], "evidence_strength": c["evidence_strength"], "diff_excerpt": c["diff_excerpt"],
57
+ "manifest_changed": c["manifest_changed"], "manifest_files_changed": c["manifest_files_changed"]},
58
+ "git": {"commit": c["commit"], "baseline": c["baseline"], "baseline_mode": c["baseline_mode"], "commit_info": c["commit_info"]},
59
+ "component": {"name": c["package_name"], "ecosystem": c["ecosystem"], "sbom_id": sbom_id},
60
+ "dependency": {"type": (c.get("new") or c.get("previous") or {}).get("direct")},
61
+ "repository": _repo_block(repo), "notes": [],
62
+ }
@@ -0,0 +1,37 @@
1
+ """Flatten evidence bundles into a uniform fact list + a text corpus used to ground/validate explanations."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ from typing import Any
6
+
7
+
8
+ def _flatten(prefix: str, value: Any, out: list[tuple[str, str]]) -> None:
9
+ if value is None or value == "" or value == [] or value == {}:
10
+ return
11
+ if isinstance(value, dict):
12
+ for k, v in value.items():
13
+ _flatten(f"{prefix}.{k}" if prefix else str(k), v, out)
14
+ elif isinstance(value, (list, tuple)):
15
+ for i, v in enumerate(value):
16
+ if isinstance(v, (dict, list)):
17
+ _flatten(f"{prefix}[{i}]", v, out)
18
+ else:
19
+ out.append((prefix, str(v)))
20
+ else:
21
+ out.append((prefix, str(value)))
22
+
23
+
24
+ def normalize_bundle(bundle: dict) -> dict:
25
+ """Return the bundle plus ``facts`` [{id, path, value}] and ``corpus`` (lower-cased text of every fact value)."""
26
+ facts: list[tuple[str, str]] = []
27
+ _flatten("", {k: v for k, v in bundle.items() if k not in ("facts", "corpus")}, facts)
28
+ fl = [{"id": f"F{i + 1:03d}", "path": p, "value": v} for i, (p, v) in enumerate(facts)]
29
+ corpus = "\n".join(f["value"] for f in fl).lower()
30
+ return {**bundle, "facts": fl, "corpus": corpus}
31
+
32
+
33
+ def compact_for_llm(bundle: dict, max_facts: int = 120) -> str:
34
+ """Compact JSON of the bundle for prompts (facts only, no corpus duplication)."""
35
+ b = {k: v for k, v in bundle.items() if k not in ("facts", "corpus")}
36
+ s = json.dumps(b, default=str, ensure_ascii=False)
37
+ return s[:12000]
@@ -0,0 +1,90 @@
1
+ """Cross-detector correlation and dedup: links findings that concern the same package and builds risk assessments."""
2
+ from __future__ import annotations
3
+
4
+ from collections import defaultdict
5
+ from typing import Any
6
+
7
+ from risk_analysis.risk_scorer import score_lockfile_change, score_pipeline, score_typosquat, score_vulnerability
8
+ from sbom.package_extractors.common import normalize_name
9
+
10
+
11
+ def _k(eco: str, name: str) -> tuple[str, str]:
12
+ return (eco, normalize_name(eco, name))
13
+
14
+
15
+ def correlate_findings(
16
+ vulns: list[dict],
17
+ typos: list[dict],
18
+ locks: list[dict],
19
+ rules: dict | None = None,
20
+ pipes: list[dict] | None = None,
21
+ source_index: Any = None,
22
+ repo_dir: Any = None,
23
+ ) -> dict[str, Any]:
24
+ """Return {assessments: [...], correlations: [...]} (assessments are deterministic and rule-based)."""
25
+ v_by = defaultdict(list)
26
+ t_by = defaultdict(list)
27
+ l_by = defaultdict(list)
28
+ for v in vulns:
29
+ v_by[_k(v["ecosystem"], v["package_name"])].append(v)
30
+ for t in typos:
31
+ t_by[_k(t["ecosystem"], t["package_name"])].append(t)
32
+ for c in locks:
33
+ if c["classification"] in ("potentially_suspicious", "unexplained_change"):
34
+ l_by[_k(c["ecosystem"], c["package_name"])].append(c)
35
+ correlations: list[dict] = []
36
+ assessments: list[dict] = []
37
+ for key in set(v_by) | set(t_by) | set(l_by):
38
+ involved = [x["finding_id"] for grp in (v_by.get(key, []), t_by.get(key, []), l_by.get(key, [])) for x in grp]
39
+ kinds = [k for k, g in (("vulnerability", v_by), ("typosquatting", t_by), ("lockfile_change", l_by)) if g.get(key)]
40
+ if len(kinds) > 1:
41
+ correlations.append({"package": key[1], "ecosystem": key[0], "kinds": kinds, "finding_ids": involved,
42
+ "note": f"{key[1]} appears in multiple independent detections: {', '.join(kinds)}."})
43
+ for v in vulns:
44
+ key = _k(v["ecosystem"], v["package_name"])
45
+ rel = {}
46
+ if source_index:
47
+ rel["source_index"] = source_index
48
+ if repo_dir:
49
+ rel["repo_dir"] = repo_dir
50
+ if l_by.get(key):
51
+ c_sha = (l_by[key][0].get("commit") or "HEAD")[:10]
52
+ rel["lockfile_change"] = f"{l_by[key][0]['finding_id']} ({l_by[key][0]['classification']}) changed this package in commit {c_sha}"
53
+ assessments.append(score_vulnerability(v, rules, rel))
54
+ for t in typos:
55
+ key = _k(t["ecosystem"], t["package_name"])
56
+ rel = {}
57
+ added = [c for c in l_by.get(key, []) if c["change_type"] == "added"]
58
+ if added:
59
+ c_sha = (added[0].get("commit") or "HEAD")[:10]
60
+ rel["lockfile_addition"] = f"{added[0]['finding_id']}: added in commit {c_sha}"
61
+ if v_by.get(key):
62
+ pid = v_by[key][0].get("primary_id") or v_by[key][0].get("finding_id")
63
+ rel["vulnerability"] = f"{v_by[key][0]['finding_id']} ({pid})"
64
+ assessments.append(score_typosquat(t, rules, rel))
65
+ for c in locks:
66
+ key = _k(c["ecosystem"], c["package_name"])
67
+ rel = {}
68
+ if v_by.get(key) and c.get("classification") != "insufficient_baseline":
69
+ pid = v_by[key][0].get("primary_id") or v_by[key][0].get("finding_id")
70
+ rel["vulnerability"] = f"{v_by[key][0]['finding_id']} ({pid})"
71
+ if t_by.get(key):
72
+ rel["typosquat"] = f"{t_by[key][0]['finding_id']} resembles {t_by[key][0]['similar_to']}"
73
+ assessments.append(score_lockfile_change(c, rules, rel))
74
+ for p in pipes or []:
75
+ assessments.append(score_pipeline(p, rules))
76
+ return {"assessments": assessments, "correlations": correlations}
77
+
78
+
79
+ def summarize_by_root(vulns: list[dict], assessments: list[dict]) -> list[dict]:
80
+ """Per-root exposure summary: counts of findings by risk label, direct vs transitive."""
81
+ risk = {a["finding_id"]: a["label"] for a in assessments}
82
+ roots: dict[str, dict] = {}
83
+ for v in vulns:
84
+ for e in v.get("exposures", []):
85
+ r = roots.setdefault(e["root"], {"root": e["root"], "findings": 0, "direct": 0, "transitive": 0,
86
+ "by_risk": {l: 0 for l in ("CRITICAL", "HIGH", "MEDIUM", "LOW", "INFORMATIONAL")}})
87
+ r["findings"] += 1
88
+ r["direct" if e["relationship"].startswith("direct") else "transitive"] += 1
89
+ r["by_risk"][risk.get(v["finding_id"], "INFORMATIONAL")] += 1
90
+ return sorted(roots.values(), key=lambda r: -r["findings"])
@@ -0,0 +1,184 @@
1
+ """Function-Level Application Impact Evaluation for Contextual Risk Scoring v2.0.
2
+
3
+ Implements Dimension I:
4
+ I = 0.25*F + 0.25*S + 0.20*B + 0.20*D + 0.10*X
5
+
6
+ Where:
7
+ F: Function responsibility & criticality (0-100)
8
+ S: Sensitivity of data handled (0-100)
9
+ B: Privilege-boundary significance (0-100)
10
+ D: Downstream application impact (0-100)
11
+ X: Production execution exposure (0-100)
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import re
16
+ from typing import Any, Optional
17
+
18
+ from risk_analysis.contextual_scorer import DimensionScore, FunctionImpactBreakdown
19
+
20
+ # Keywords identifying security-critical functions and modules
21
+ SECURITY_CRITICAL_KEYWORDS = {
22
+ "auth", "authentication", "authorize", "authorization", "crypto", "cryptography",
23
+ "jwt", "token", "password", "session", "login", "oauth", "saml", "secret",
24
+ "signature", "sign", "verify", "permission", "rbac", "acl", "tls", "ssl", "cipher"
25
+ }
26
+
27
+ TRANSACTIONAL_KEYWORDS = {
28
+ "pay", "payment", "billing", "checkout", "order", "invoice", "transfer",
29
+ "account", "bank", "credit", "charge", "subscription", "cart", "transaction"
30
+ }
31
+
32
+ DATA_SENSITIVITY_KEYWORDS = {
33
+ "password", "secret", "token", "key", "credential", "private", "card",
34
+ "ssn", "pii", "identity", "email", "phone", "dob", "address", "salt"
35
+ }
36
+
37
+ NETWORK_INGRESS_KEYWORDS = {
38
+ "route", "endpoint", "api", "handler", "request", "webhook", "controller",
39
+ "ingress", "listener", "server", "http", "graphql", "rest"
40
+ }
41
+
42
+ # Downstream impact classification based on vulnerability summaries, CWEs, or descriptions
43
+ RCE_CWE = {"CWE-78", "CWE-89", "CWE-94", "CWE-502", "CWE-434", "CWE-120", "CWE-79"}
44
+ AUTH_BYPASS_CWE = {"CWE-287", "CWE-269", "CWE-918", "CWE-862", "CWE-863", "CWE-306"}
45
+ INFO_LEAK_CWE = {"CWE-200", "CWE-209", "CWE-352", "CWE-532", "CWE-601"}
46
+ DOS_CWE = {"CWE-400", "CWE-770", "CWE-1333", "CWE-835", "CWE-674"}
47
+
48
+
49
+ class FunctionImpactAnalyzer:
50
+ """Evaluates the 5 sub-factors of function-level application impact."""
51
+
52
+ def evaluate_function_impact(
53
+ self,
54
+ package_name: str,
55
+ vulnerable_symbols: Optional[list[str]] = None,
56
+ advisory_summary: Optional[str] = None,
57
+ advisory_details: Optional[str] = None,
58
+ app_file_locations: Optional[list[str]] = None,
59
+ dim_p_score: Optional[float] = None,
60
+ is_dev: bool = False,
61
+ ) -> tuple[DimensionScore, FunctionImpactBreakdown]:
62
+ """Compute Dimension I and return both the DimensionScore and the sub-factor breakdown."""
63
+ dim_name = "Function-Level Application Impact"
64
+ weight = 0.30
65
+
66
+ text_corpus = f"{package_name} {' '.join(vulnerable_symbols or [])} {' '.join(app_file_locations or [])}".lower()
67
+ adv_corpus = f"{advisory_summary or ''} {advisory_details or ''}".lower()
68
+
69
+ rationale: dict[str, str] = {}
70
+
71
+ # 1. Sub-factor F: Function Responsibility & Criticality (0-100)
72
+ if any(k in text_corpus for k in SECURITY_CRITICAL_KEYWORDS):
73
+ score_F = 100.0
74
+ rationale["F"] = "Security-critical functionality: package or call-site handles authentication, crypto, or access control."
75
+ elif any(k in text_corpus for k in TRANSACTIONAL_KEYWORDS):
76
+ score_F = 75.0
77
+ rationale["F"] = "Core transactional logic: package operates within financial, payment, or order processing flows."
78
+ elif any(k in text_corpus for k in ("db", "database", "sql", "orm", "redis", "mongo", "queue", "kafka")):
79
+ score_F = 50.0
80
+ rationale["F"] = "Supporting business infrastructure: package manages data persistence or messaging queues."
81
+ elif any(k in text_corpus for k in ("log", "logger", "format", "string", "util", "helper", "math")):
82
+ score_F = 25.0
83
+ rationale["F"] = "Auxiliary/utility logic: package provides non-critical utility, formatting, or helper functions."
84
+ else:
85
+ score_F = 35.0
86
+ rationale["F"] = "General application component: standard application functionality."
87
+
88
+ # 2. Sub-factor S: Sensitivity of Data Handled (0-100)
89
+ if any(k in text_corpus for k in DATA_SENSITIVITY_KEYWORDS):
90
+ score_S = 100.0
91
+ rationale["S"] = "Highly sensitive data: call sites handle credentials, cryptographic keys, PII, or tokens."
92
+ elif any(k in text_corpus for k in ("user", "profile", "account", "customer", "tenant")):
93
+ score_S = 60.0
94
+ rationale["S"] = "Internal business state: package processes user profiles or tenant data."
95
+ elif any(k in text_corpus for k in ("req", "request", "param", "query", "body", "input")):
96
+ score_S = 30.0
97
+ rationale["S"] = "Public/untrusted input: package processes external request parameters or query data."
98
+ else:
99
+ score_S = 20.0
100
+ rationale["S"] = "No direct sensitive data handling identified."
101
+
102
+ # 3. Sub-factor B: Privilege-Boundary Significance (0-100)
103
+ if any(k in text_corpus for k in NETWORK_INGRESS_KEYWORDS):
104
+ score_B = 100.0
105
+ rationale["B"] = "External network trust boundary: package executes in public HTTP/API request ingress paths."
106
+ elif any(k in text_corpus for k in ("rpc", "grpc", "service", "client", "worker", "agent")):
107
+ score_B = 70.0
108
+ rationale["B"] = "Service/process boundary: package executes in inter-service RPC or worker boundaries."
109
+ else:
110
+ score_B = 30.0
111
+ rationale["B"] = "Internal execution context: package executes within isolated process boundaries."
112
+
113
+ # 4. Sub-factor D: Downstream Application Impact (0-100)
114
+ if any(term in adv_corpus for term in ("remote code execution", "rce", "command injection", "sql injection", "arbitrary code", "deserialization")):
115
+ score_D = 100.0
116
+ rationale["D"] = "Critical downstream impact: vulnerability allows Remote Code Execution, command injection, or SQLi."
117
+ elif any(term in adv_corpus for term in ("bypass", "privilege escalation", "ssrf", "authentication bypass", "unauthorized")):
118
+ score_D = 85.0
119
+ rationale["D"] = "High downstream impact: vulnerability enables authentication bypass or privilege escalation."
120
+ elif any(term in adv_corpus for term in ("information disclosure", "leak", "sensitive data", "csrf", "spoof")):
121
+ score_D = 60.0
122
+ rationale["D"] = "Moderate downstream impact: vulnerability causes sensitive information disclosure or cross-site request forgery."
123
+ elif any(term in adv_corpus for term in ("denial of service", "dos", "crash", "infinite loop", "resource exhaustion")):
124
+ score_D = 35.0
125
+ rationale["D"] = "Bounded downstream impact: vulnerability results in service degradation or Denial of Service."
126
+ else:
127
+ score_D = 40.0
128
+ rationale["D"] = "Moderate downstream impact based on standard advisory classification."
129
+
130
+ # 5. Sub-factor X: Production Execution Exposure (0-100)
131
+ if is_dev:
132
+ score_X = 0.0
133
+ rationale["X"] = "Zero production exposure: development-only dependency."
134
+ elif dim_p_score is not None:
135
+ # Correlate exposure with production reachability score
136
+ score_X = dim_p_score
137
+ rationale["X"] = f"Production exposure directly aligned with production reachability ({dim_p_score:.0f}/100)."
138
+ elif any(k in text_corpus for k in ("server", "app", "main", "service")):
139
+ score_X = 80.0
140
+ rationale["X"] = "High production exposure: active in core server runtime loop."
141
+ else:
142
+ score_X = 40.0
143
+ rationale["X"] = "Intermittent/standard execution exposure."
144
+
145
+ # Compute Dimension I = 0.25*F + 0.25*S + 0.20*B + 0.20*D + 0.10*X
146
+ composite_I = round(
147
+ 0.25 * score_F +
148
+ 0.25 * score_S +
149
+ 0.20 * score_B +
150
+ 0.20 * score_D +
151
+ 0.10 * score_X,
152
+ 1
153
+ )
154
+ composite_I = max(0.0, min(100.0, composite_I))
155
+
156
+ breakdown = FunctionImpactBreakdown(
157
+ function_criticality_F=score_F,
158
+ data_sensitivity_S=score_S,
159
+ privilege_boundary_B=score_B,
160
+ downstream_impact_D=score_D,
161
+ production_exposure_X=score_X,
162
+ composite_score_I=composite_I,
163
+ rationale=rationale,
164
+ )
165
+
166
+ evidence = [
167
+ f"Composite Impact: {composite_I:.1f}/100 (F:{score_F:.0f}, S:{score_S:.0f}, B:{score_B:.0f}, D:{score_D:.0f}, X:{score_X:.0f})",
168
+ rationale["F"],
169
+ rationale["D"],
170
+ ]
171
+
172
+ dim_score = DimensionScore(
173
+ dimension="I",
174
+ name=dim_name,
175
+ weight=weight,
176
+ raw_value=breakdown.to_dict(),
177
+ normalized_score=composite_I,
178
+ status="assessed",
179
+ weighted_contribution=round(weight * composite_I, 2),
180
+ evidence=evidence,
181
+ confidence="high",
182
+ )
183
+
184
+ return dim_score, breakdown