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,315 @@
1
+ """Metadata fusion engine.
2
+
3
+ Pipeline (all deterministic, no code of the scanned repository is run):
4
+
5
+ 1. LOCKFILE - apply what the native lockfile parsers recorded (exact pin: digest, resolved URL, scope, install-script flag, license, ...)
6
+ 2. SCANNER - remember what the SBOM scanner already put in its entry (provenance only; lower trust than the lockfile)
7
+ 3. REGISTRY - for fields still empty (and for integrity verification) ask the package registries, in parallel, cached, within a time budget,
8
+ with a circuit breaker per host so an outage costs seconds, not minutes
9
+ 4. INTEGRITY - compare the lockfile digest with the digest the registry publishes today:
10
+ verified same artifact digest
11
+ mismatch different digest for the same name@version -> alert (possible tampered lockfile / republished artifact)
12
+ unverifiable lockfile has a digest, the registry offers nothing comparable
13
+ absent the lockfile records no digest (the registry digest, if any, is used as a *lower-confidence* hash)
14
+ 5. REPORT - per-field coverage before/after, conflicts, missing-reason per field, completeness score per component
15
+
16
+ Fields are never invented and a less trusted source never overwrites a more trusted one (see ledger.py).
17
+ """
18
+ from __future__ import annotations
19
+
20
+ import threading
21
+ import time
22
+ from concurrent.futures import ThreadPoolExecutor, as_completed
23
+ from typing import Any, Callable, Optional
24
+
25
+ from core.http import HttpClient, NotFound, SourceUnavailable
26
+ from core.models import Component, LockDependency
27
+ from sbom.fusion import ledger
28
+ from sbom.fusion.hashes import parse_digest, to_cyclonedx
29
+ from sbom.fusion.registries import FETCHERS, supported
30
+ from sbom.package_extractors.common import normalize_name
31
+ from storage.cache import Cache
32
+
33
+ TTL = 30 * 24 * 3600 # a published name@version is immutable; descriptive data changes rarely
34
+ NEG_TTL = 24 * 3600
35
+ FIELDS_REPORTED = ("licenses", "hashes", "supplier", "description", "external_refs", "scope", "published_at")
36
+
37
+
38
+ def _key(eco: Optional[str], name: str, version: Optional[str], svc: Optional[str] = None) -> tuple:
39
+ return (eco or "", normalize_name(eco or "", name), version or "", svc if svc is not None else "")
40
+
41
+
42
+ def apply_lockfile(components: list[Component], lock_deps: list[LockDependency]) -> dict[str, int]:
43
+ """Phase 1: native lockfile facts onto matching components (service-scoped first, then any service)."""
44
+ by_svc: dict[tuple, list[LockDependency]] = {}
45
+ by_any: dict[tuple, list[LockDependency]] = {}
46
+ for d in lock_deps:
47
+ if d.derived or not d.version:
48
+ continue
49
+ by_svc.setdefault(_key(d.ecosystem, d.name, d.version, d.service_dir), []).append(d)
50
+ by_any.setdefault(_key(d.ecosystem, d.name, d.version), []).append(d)
51
+ hit = 0
52
+ for c in components:
53
+ if c.is_self or c.type == "file" or not c.ecosystem:
54
+ continue
55
+ cands = by_svc.get(_key(c.ecosystem, c.name, c.version, c.service_dir)) or by_any.get(_key(c.ecosystem, c.name, c.version)) or []
56
+ if not cands:
57
+ continue
58
+ hit += 1
59
+ c.sources = sorted(set(c.sources) | {"lockfile"})
60
+ for d in cands:
61
+ ev = f"{d.lockfile} {d.record or ''}".strip()
62
+ if d.license:
63
+ ledger.set_field(c, "licenses", [d.license], "lockfile", ev)
64
+ dig = parse_digest(d.integrity, (d.meta or {}).get("hash_alg"))
65
+ hashes = []
66
+ for raw in [d.integrity] + list((d.meta or {}).get("hashes") or []):
67
+ p = parse_digest(raw, (d.meta or {}).get("hash_alg"))
68
+ ch = to_cyclonedx(p) if p else None
69
+ if ch and ch not in hashes:
70
+ hashes.append(ch)
71
+ if hashes:
72
+ ledger.set_field(c, "hashes", hashes, "lockfile", ev)
73
+ if dig:
74
+ c.integrity.setdefault("lockfile", {"alg": dig["alg"], "hex": dig["hex"], "kind": dig["kind"], "file": d.lockfile})
75
+ if d.resolved:
76
+ ledger.set_field(c, "resolved_url", d.resolved, "lockfile", ev)
77
+ if d.source_type:
78
+ ledger.set_field(c, "source_type", d.source_type, "lockfile", ev)
79
+ if d.direct is not None:
80
+ ledger.set_field(c, "direct_declared", d.direct, "lockfile", ev)
81
+ scope = "dev" if d.dev else "optional" if (d.meta or {}).get("optional") or (d.meta or {}).get("peer") else ("required" if d.dev is None and d.direct is not None else None)
82
+ if d.dev is True:
83
+ scope = "dev"
84
+ if scope:
85
+ ledger.set_field(c, "scope", scope, "lockfile", ev)
86
+ m = d.meta or {}
87
+ if m.get("install_script"):
88
+ ledger.set_field(c, "install_script", True, "lockfile", ev)
89
+ if m.get("deprecated"):
90
+ ledger.set_field(c, "deprecated", True, "lockfile", ev)
91
+ if m.get("description"):
92
+ ledger.set_field(c, "description", str(m["description"])[:300], "lockfile", ev)
93
+ if m.get("published"):
94
+ ledger.set_field(c, "published_at", m["published"], "lockfile", ev)
95
+ if m.get("authors"):
96
+ ledger.set_field(c, "supplier", ", ".join(m["authors"][:2]), "lockfile", ev)
97
+ refs = [{"type": t, "url": m[k], "source": "lockfile"} for t, k in (("website", "homepage"), ("vcs", "vcs")) if m.get(k)]
98
+ if refs:
99
+ ledger.set_field(c, "external_refs", refs, "lockfile", ev)
100
+ return {"components_matched_to_lockfile": hit}
101
+
102
+
103
+ class _Breaker:
104
+ """Per-host circuit breaker: after N consecutive outages a host is skipped for the rest of the run."""
105
+
106
+ def __init__(self, limit: int = 4):
107
+ self.limit, self.fails, self.open = limit, {}, set()
108
+ self.lock = threading.Lock()
109
+
110
+ def ok(self, host: str) -> bool:
111
+ return host not in self.open
112
+
113
+ def failure(self, host: str) -> None:
114
+ with self.lock:
115
+ self.fails[host] = self.fails.get(host, 0) + 1
116
+ if self.fails[host] >= self.limit:
117
+ self.open.add(host)
118
+
119
+ def success(self, host: str) -> None:
120
+ with self.lock:
121
+ self.fails[host] = 0
122
+
123
+
124
+ def _needs_registry(c: Component) -> bool:
125
+ return any(ledger._empty(getattr(c, f)) for f in ("licenses", "supplier", "description", "external_refs", "published_at", "hashes")) or "lockfile" in c.integrity
126
+
127
+
128
+ def fetch_registry(components: list[Component], http: HttpClient, cache: Optional[Cache], budget_s: float = 120.0, workers: int = 8,
129
+ on_progress: Optional[Callable[[str], None]] = None) -> dict[str, Any]:
130
+ """Phase 3: query registries for components that still miss data or whose lockfile digest should be verified."""
131
+ todo = [c for c in components if not c.is_self and c.type != "file" and c.version and supported(c.ecosystem) and _needs_registry(c)]
132
+ stats: dict[str, Any] = {"eligible": len(todo), "from_cache": 0, "fetched": 0, "not_found": 0, "unavailable": 0, "skipped_budget": 0, "hosts_tripped": [],
133
+ "unsupported_ecosystems": sorted({c.ecosystem for c in components if c.ecosystem and not supported(c.ecosystem) and not c.is_self})}
134
+ if not todo:
135
+ return stats
136
+ br, t0 = _Breaker(), time.time()
137
+ uniq: dict[tuple, list[Component]] = {}
138
+ for c in todo:
139
+ uniq.setdefault((c.ecosystem, c.name, c.version), []).append(c)
140
+
141
+ def work(k: tuple) -> tuple[tuple, dict, str]:
142
+ eco, name, ver = k
143
+ ck = f"{eco}:{name}@{ver}|{'+'.join(l for l, _ in FETCHERS[eco])}" # key includes the client set: adding a client never serves stale, thinner records
144
+ cached = cache.get("meta_fusion", ck, ttl=TTL) if cache else None
145
+ if cached is not None:
146
+ return k, cached, "cache"
147
+ if time.time() - t0 > budget_s:
148
+ return k, {}, "budget"
149
+ merged: dict[str, Any] = {"sources": {}}
150
+ saw_any = False
151
+ for label, fn in FETCHERS[eco]:
152
+ if not br.ok(label):
153
+ continue
154
+ try:
155
+ rec = fn(http, eco, name, ver)
156
+ br.success(label)
157
+ except NotFound:
158
+ continue
159
+ except SourceUnavailable:
160
+ br.failure(label)
161
+ continue
162
+ except Exception:
163
+ continue
164
+ if not rec:
165
+ continue
166
+ saw_any = True
167
+ merged["sources"][label] = rec.get("url")
168
+ for f, v in rec.items():
169
+ if f in ("url",):
170
+ continue
171
+ if f in ("licenses", "links", "digests") and f in merged:
172
+ seen = {str(x) for x in merged[f]}
173
+ merged[f] = merged[f] + [x for x in v if str(x) not in seen]
174
+ elif f not in merged:
175
+ merged[f] = v
176
+ if not saw_any:
177
+ all_down = all(not br.ok(l) for l, _ in FETCHERS[eco])
178
+ if cache and not all_down:
179
+ cache.set("meta_fusion", ck, {"_negative": True, "ts": time.time()})
180
+ return k, {}, "unavailable" if all_down else "not_found"
181
+ if cache:
182
+ cache.set("meta_fusion", ck, merged)
183
+ return k, merged, "fetched"
184
+
185
+ done = 0
186
+ with ThreadPoolExecutor(max_workers=workers) as ex:
187
+ futs = [ex.submit(work, k) for k in uniq]
188
+ for f in as_completed(futs):
189
+ k, rec, status = f.result()
190
+ if rec.get("_negative"):
191
+ status, rec = "not_found", {}
192
+ stats["from_cache" if status == "cache" else "fetched" if status == "fetched" else "not_found" if status == "not_found"
193
+ else "skipped_budget" if status == "budget" else "unavailable"] += 1
194
+ for c in uniq[k]:
195
+ if rec:
196
+ _apply_record(c, rec)
197
+ c.integrity["lookup"] = "found"
198
+ elif status == "not_found":
199
+ c.integrity["lookup"] = "not_found"
200
+ done += 1
201
+ if on_progress and done % 50 == 0:
202
+ on_progress(f"{done}/{len(uniq)} package versions resolved against registries")
203
+ stats["hosts_tripped"] = sorted(br.open)
204
+ stats["seconds"] = round(time.time() - t0, 1)
205
+ return stats
206
+
207
+
208
+ def _apply_record(c: Component, rec: dict) -> None:
209
+ srcs = rec.get("sources") or {}
210
+ src_label = "registry:" + "+".join(srcs) if srcs else "registry"
211
+ ev = "; ".join(f"{k}: {v}" for k, v in srcs.items() if v)[:300]
212
+ if rec.get("licenses"):
213
+ ledger.set_field(c, "licenses", rec["licenses"][:3], src_label, ev)
214
+ if rec.get("supplier"):
215
+ ledger.set_field(c, "supplier", rec["supplier"], src_label, ev)
216
+ if rec.get("description"):
217
+ ledger.set_field(c, "description", rec["description"], src_label, ev)
218
+ if rec.get("published_at"):
219
+ ledger.set_field(c, "published_at", rec["published_at"], src_label, ev)
220
+ if "deprecated" in rec:
221
+ ledger.set_field(c, "deprecated", bool(rec["deprecated"]), src_label, ev) if rec["deprecated"] else None
222
+ if "install_script" in rec and rec["install_script"]:
223
+ ledger.set_field(c, "install_script", True, src_label, ev)
224
+ if rec.get("links"):
225
+ ledger.set_field(c, "external_refs", [{**l, "source": src_label} for l in rec["links"]], src_label, ev)
226
+ if rec.get("provenance_attestations"):
227
+ c.integrity["attestations"] = rec["provenance_attestations"]
228
+ c.integrity["attested"] = True
229
+ if rec.get("yanked"):
230
+ c.integrity["yanked"] = True
231
+ # integrity triangulation
232
+ digs = [d for d in rec.get("digests", []) if d.get("kind") == "file"]
233
+ lock = c.integrity.get("lockfile")
234
+ if lock:
235
+ if lock.get("kind") == "tree":
236
+ trees = [d for d in rec.get("digests", []) if d.get("kind") == "tree"]
237
+ if not trees:
238
+ c.integrity.update(status="unverifiable", reason="Go module tree hash (h1:) could not be compared: checksum database returned nothing")
239
+ elif any(d["hex"] == lock["hex"] for d in trees):
240
+ c.integrity.update(status="verified", algorithm="go-h1", registry=trees[0]["hex"], reason="go.sum h1 equals the Go checksum database (sum.golang.org)")
241
+ else:
242
+ c.integrity.update(status="mismatch", algorithm="go-h1", registry=trees[0]["hex"], reason="go.sum h1 differs from the Go checksum database")
243
+ else:
244
+ comparable = [d for d in digs if d["alg"] == lock["alg"]]
245
+ if not digs or not comparable:
246
+ c.integrity.update(status="unverifiable", reason="the registry publishes no digest of the same algorithm")
247
+ elif any(d["hex"] == lock["hex"] for d in comparable):
248
+ c.integrity.update(status="verified", algorithm=lock["alg"], registry=comparable[0]["hex"], reason="lockfile digest equals the registry digest")
249
+ else:
250
+ c.integrity.update(status="mismatch", algorithm=lock["alg"], registry=comparable[0]["hex"],
251
+ reason="the lockfile pins a digest that differs from the registry's current digest for this exact version")
252
+ elif digs:
253
+ ch = [to_cyclonedx(d) for d in digs[:2]]
254
+ ch = [h for h in ch if h]
255
+ if ch:
256
+ ledger.set_field(c, "hashes", ch, src_label, ev, "medium")
257
+ c.integrity.update(status="absent", reason="the lockfile records no digest; registry digest added with medium confidence")
258
+
259
+
260
+ def finalize(components: list[Component], lock_only_snapshot: dict[str, int]) -> dict[str, Any]:
261
+ """Phase 5: completeness, coverage before/after, integrity summary, missing reasons."""
262
+ pk = [c for c in components if not c.is_self and c.type != "file"]
263
+ n = len(pk) or 1
264
+ cov = {f: sum(1 for c in pk if not ledger._empty(getattr(c, f))) for f in FIELDS_REPORTED}
265
+ by_source: dict[str, int] = {}
266
+ for c in pk:
267
+ for f in FIELDS_REPORTED:
268
+ p = c.provenance.get(f)
269
+ if p and not ledger._empty(getattr(c, f)):
270
+ by_source[ledger.source_class(p["source"])] = by_source.get(ledger.source_class(p["source"]), 0) + 1
271
+ integ: dict[str, int] = {}
272
+ for c in pk:
273
+ st = c.integrity.get("status") or ("absent" if "lockfile" not in c.integrity else "unverifiable")
274
+ c.integrity.setdefault("status", st)
275
+ integ[st] = integ.get(st, 0) + 1
276
+ for c in pk:
277
+ reasons = {}
278
+ for f in FIELDS_REPORTED:
279
+ if ledger._empty(getattr(c, f)):
280
+ if not supported(c.ecosystem):
281
+ reasons[f] = "no registry client for this ecosystem and the lockfile does not record it"
282
+ else:
283
+ reasons[f] = "not recorded by the lockfile/scanner and not published by the registry (or registry unreachable)"
284
+ c.provenance.setdefault("_missing", {})["reasons"] = reasons
285
+ comp_scores = [ledger.completeness(c) for c in pk]
286
+ for c, sc in zip(pk, comp_scores):
287
+ c.completeness = sc
288
+ conflicts = [{"component": f"{c.name}@{c.version}", "field": f, "chosen": c.provenance[f]["source"], "conflicts": c.provenance[f]["conflicts"]}
289
+ for c in pk for f in FIELDS_REPORTED if c.provenance.get(f, {}).get("conflicts")]
290
+ mism = [{"component": f"{c.name}@{c.version}", "ecosystem": c.ecosystem, "service": c.service_dir, "lockfile": c.integrity.get("lockfile", {}).get("file"),
291
+ "algorithm": c.integrity.get("algorithm"), "lockfile_digest": c.integrity["lockfile"]["hex"], "registry_digest": c.integrity.get("registry")}
292
+ for c in pk if c.integrity.get("status") == "mismatch"]
293
+ return {"components": len(pk), "coverage": {f: {"before": lock_only_snapshot.get(f, 0), "after": cov[f], "percent": round(100 * cov[f] / n, 1)} for f in FIELDS_REPORTED},
294
+ "fields_by_source": by_source, "integrity": integ, "integrity_mismatches": mism, "conflicts": conflicts[:100], "conflict_count": len(conflicts),
295
+ "average_completeness": round(sum(comp_scores) / n, 3) if comp_scores else 0.0,
296
+ "install_script_packages": sorted(f"{c.name}@{c.version}" for c in pk if c.install_script)[:50],
297
+ "deprecated_packages": sorted(f"{c.name}@{c.version}" for c in pk if c.deprecated)[:50]}
298
+
299
+
300
+ def fuse(components: list[Component], lock_deps: list[LockDependency], http: Optional[HttpClient], cache: Optional[Cache], registry: bool = True,
301
+ budget_s: float = 120.0, on_progress: Optional[Callable[[str], None]] = None) -> dict[str, Any]:
302
+ """Run all phases in place on ``components`` and return the fusion report."""
303
+ pk = [c for c in components if not c.is_self and c.type != "file"]
304
+ for c in pk:
305
+ ledger.init_scanner_provenance(c)
306
+ snap_scanner = {f: sum(1 for c in pk if not ledger._empty(getattr(c, f))) for f in FIELDS_REPORTED}
307
+ lk = apply_lockfile(components, lock_deps)
308
+ snap_lock = {f: sum(1 for c in pk if not ledger._empty(getattr(c, f))) for f in FIELDS_REPORTED}
309
+ reg: dict[str, Any] = {"skipped": True}
310
+ if registry and http is not None:
311
+ reg = fetch_registry(components, http, cache, budget_s=budget_s, on_progress=on_progress)
312
+ rep = finalize(components, snap_scanner)
313
+ rep["lockfile_phase"] = {**lk, "coverage_after_lockfile": snap_lock}
314
+ rep["registry_phase"] = reg
315
+ return rep
@@ -0,0 +1,47 @@
1
+ """Digest normalisation: SRI / hex / go h1 / NuGet base64 -> [{alg, hex|b64, kind}] and CycloneDX hash entries."""
2
+ from __future__ import annotations
3
+
4
+ import base64
5
+ import re
6
+ from typing import Optional
7
+
8
+ _ALG = {"sha1": "SHA-1", "sha256": "SHA-256", "sha384": "SHA-384", "sha512": "SHA-512", "md5": "MD5"}
9
+ _HEXLEN = {32: "md5", 40: "sha1", 64: "sha256", 96: "sha384", 128: "sha512"}
10
+ _HEX = re.compile(r"^[0-9a-fA-F]+$")
11
+
12
+
13
+ def parse_digest(s: Optional[str], hint: Optional[str] = None) -> Optional[dict]:
14
+ """Return {alg, hex, kind} where kind is 'file' (digest of the distributed artifact) or 'tree' (Go module hash: not comparable to registry digests)."""
15
+ if not s or not isinstance(s, str):
16
+ return None
17
+ s = s.strip()
18
+ m = re.match(r"^(sha1|sha256|sha384|sha512|md5)[-:=](.+)$", s, re.I)
19
+ if m:
20
+ alg, val = m.group(1).lower(), m.group(2).strip()
21
+ if _HEX.match(val) and _HEXLEN.get(len(val)) == alg:
22
+ return {"alg": alg, "hex": val.lower(), "kind": "file"}
23
+ try:
24
+ raw = base64.b64decode(val + "=" * (-len(val) % 4), validate=False)
25
+ return {"alg": alg, "hex": raw.hex(), "kind": "file"}
26
+ except Exception:
27
+ return None
28
+ if s.startswith("h1:"):
29
+ try:
30
+ return {"alg": "sha256", "hex": base64.b64decode(s[3:] + "=" * (-len(s[3:]) % 4)).hex(), "kind": "tree"}
31
+ except Exception:
32
+ return None
33
+ if _HEX.match(s) and len(s) in _HEXLEN:
34
+ return {"alg": _HEXLEN[len(s)], "hex": s.lower(), "kind": "file"}
35
+ if hint and hint.lower() in _ALG: # bare base64 (NuGet contentHash is sha512)
36
+ try:
37
+ return {"alg": hint.lower(), "hex": base64.b64decode(s + "=" * (-len(s) % 4)).hex(), "kind": "file"}
38
+ except Exception:
39
+ return None
40
+ return None
41
+
42
+
43
+ def to_cyclonedx(d: dict) -> Optional[dict]:
44
+ if not d or d.get("kind") == "tree":
45
+ return None
46
+ alg = _ALG.get(d["alg"])
47
+ return {"alg": alg, "content": d["hex"]} if alg else None
@@ -0,0 +1,96 @@
1
+ """Field-level provenance ledger.
2
+
3
+ Every metadata field of a component records where its value came from. Rules:
4
+
5
+ * a value from a more trusted source replaces a less trusted one (the displaced value is kept as a *conflict* if it differs)
6
+ * a value from a less or equally trusted source never overwrites; if it differs it is recorded as a conflict
7
+ * nothing is ever invented: an unknown field stays empty and the engine records *why* it is unknown (``missing_reasons``)
8
+
9
+ Trust order reflects how directly the source describes *the artifact the repository actually pins*:
10
+ lockfile (exact pin) > manifest > registry (authoritative for descriptive data, current not pinned) > scanner > inferred.
11
+ """
12
+ from __future__ import annotations
13
+
14
+ from typing import Any
15
+
16
+ from core.models import Component
17
+
18
+ TRUST = {"lockfile": 100, "manifest": 90, "registry": 80, "scanner": 60, "inferred": 20}
19
+
20
+ # field -> (Component attribute, how to compare/store)
21
+ LIST_FIELDS = {"licenses", "hashes", "external_refs"}
22
+ FIELDS = ("licenses", "supplier", "description", "scope", "install_script", "deprecated", "published_at", "hashes", "external_refs", "resolved_url", "source_type", "direct_declared")
23
+
24
+
25
+ def _empty(v: Any) -> bool:
26
+ return v is None or v == [] or v == "" or v == {}
27
+
28
+
29
+ def source_class(source: str) -> str:
30
+ return source.split(":", 1)[0]
31
+
32
+
33
+ def trust_of(source: str) -> int:
34
+ return TRUST.get(source_class(source), 0)
35
+
36
+
37
+ def record(c: Component, field: str, source: str, evidence: str = "", confidence: str = "high") -> None:
38
+ c.provenance[field] = {"source": source, "confidence": confidence, "evidence": evidence, "conflicts": c.provenance.get(field, {}).get("conflicts", [])}
39
+
40
+
41
+ def _same(a: Any, b: Any) -> bool:
42
+ if isinstance(a, list) and isinstance(b, list):
43
+ key = lambda x: str(sorted(x.items())) if isinstance(x, dict) else str(x).lower() # noqa: E731
44
+ return sorted(map(key, a)) == sorted(map(key, b))
45
+ return str(a).strip().lower() == str(b).strip().lower()
46
+
47
+
48
+ def set_field(c: Component, field: str, value: Any, source: str, evidence: str = "", confidence: str = "high") -> bool:
49
+ """Apply ``value`` under the trust rules. Returns True if the component's value changed."""
50
+ if _empty(value):
51
+ return False
52
+ cur = getattr(c, field)
53
+ prov = c.provenance.get(field)
54
+ if _empty(cur):
55
+ setattr(c, field, value)
56
+ record(c, field, source, evidence, confidence)
57
+ return True
58
+ cur_src = (prov or {}).get("source", "scanner")
59
+ if _same(cur, value):
60
+ if prov and trust_of(source) > trust_of(cur_src): # same value, better witness
61
+ record(c, field, source, evidence, confidence)
62
+ elif prov:
63
+ prov.setdefault("corroborated_by", [])
64
+ if source not in prov["corroborated_by"]:
65
+ prov["corroborated_by"].append(source)
66
+ return False
67
+ conflict = {"source": source, "value": value if not isinstance(value, list) else value[:5]}
68
+ if trust_of(source) > trust_of(cur_src):
69
+ old = {"source": cur_src, "value": cur if not isinstance(cur, list) else cur[:5]}
70
+ setattr(c, field, value)
71
+ record(c, field, source, evidence, confidence)
72
+ c.provenance[field]["conflicts"].append(old)
73
+ return True
74
+ if prov is None:
75
+ record(c, field, cur_src, "", "medium")
76
+ prov = c.provenance[field]
77
+ prov["conflicts"].append(conflict)
78
+ return False
79
+
80
+
81
+ def init_scanner_provenance(c: Component) -> None:
82
+ """Mark values that arrived with the scanner's own SBOM entry so later sources can be ranked against them."""
83
+ tool = (c.sources or ["scanner"])[0]
84
+ for f in FIELDS:
85
+ if not _empty(getattr(c, f, None)) and f not in c.provenance:
86
+ record(c, f, f"scanner:{tool}", "present in the scanner's SBOM entry", "medium")
87
+
88
+
89
+ # ------------------------------------------------------------------ completeness
90
+ WEIGHTS = {"licenses": 3, "hashes": 3, "supplier": 1, "description": 1, "external_refs": 1, "scope": 1, "published_at": 1}
91
+
92
+
93
+ def completeness(c: Component) -> float:
94
+ tot = sum(WEIGHTS.values())
95
+ got = sum(w for f, w in WEIGHTS.items() if not _empty(getattr(c, f, None)))
96
+ return round(got / tot, 3)