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,86 @@
1
+ """Targeted dependency tracing: per-root classification and bounded path extraction.
2
+
3
+ Direct/transitive is ALWAYS relative to a root. Paths are produced lazily (shortest first, Yen's algorithm) on the
4
+ sub-graph of the target's ancestors only and capped, so large graphs never trigger all-simple-paths enumeration.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ from itertools import islice
9
+ from typing import Any
10
+
11
+ import networkx as nx
12
+
13
+ from graph.graph_builder import roots_of
14
+
15
+
16
+ def _label(g: nx.DiGraph, n: str) -> str:
17
+ return g.nodes[n].get("label", n)
18
+
19
+
20
+ def trace_component(g: nx.DiGraph, target: str, max_paths: int = 25, max_depth: int = 40) -> dict[str, Any]:
21
+ """Return per-root exposure for ``target``.
22
+
23
+ {
24
+ component, label, immediate_parents[], dependents_count,
25
+ roots: [{root, root_label, relationship: direct|transitive|direct_inferred, depth, paths:[[labels...]],
26
+ path_refs:[[ids...]], immediate_parents:[..], truncated}],
27
+ }
28
+ """
29
+ if target not in g:
30
+ return {"component": target, "label": target, "found": False, "roots": [], "immediate_parents": [],
31
+ "dependents_count": 0}
32
+ anc = nx.ancestors(g, target)
33
+ sub = g.subgraph(anc | {target})
34
+ parents = sorted(p for p in g.predecessors(target))
35
+ out_roots = []
36
+ for r in roots_of(g):
37
+ if r not in anc:
38
+ continue
39
+ try:
40
+ shortest = nx.shortest_path_length(sub, r, target)
41
+ except nx.NetworkXNoPath:
42
+ continue
43
+ paths: list[list[str]] = []
44
+ truncated = False
45
+ try:
46
+ gen = nx.shortest_simple_paths(sub, r, target)
47
+ for p in islice(gen, max_paths + 1):
48
+ if len(p) - 1 > max_depth:
49
+ break
50
+ paths.append(p)
51
+ if len(paths) > max_paths:
52
+ truncated = True
53
+ paths = paths[:max_paths]
54
+ except nx.NetworkXNoPath:
55
+ pass
56
+ edge_prov = g.edges[paths[0][0], paths[0][1]].get("provenance", "") if paths and len(paths[0]) > 1 else ""
57
+ if shortest == 1:
58
+ rel = "direct_inferred" if edge_prov == "inferred-no-parent" else "direct"
59
+ else:
60
+ rel = "transitive"
61
+ # immediate parents of the target that lie on a path from this root
62
+ ip = sorted({p[-2] for p in paths if len(p) >= 2})
63
+ out_roots.append({
64
+ "root": r, "root_label": _label(g, r), "relationship": rel, "depth": shortest,
65
+ "paths": [[_label(g, n) for n in p] for p in paths], "path_refs": paths,
66
+ "immediate_parents": [_label(g, n) for n in ip], "truncated": truncated,
67
+ })
68
+ return {"component": target, "label": _label(g, target), "found": True,
69
+ "immediate_parents": [_label(g, p) for p in parents if g.nodes[p].get("kind") != "root"],
70
+ "dependents_count": len([a for a in anc if g.nodes[a].get("kind") == "component"]),
71
+ "roots": out_roots}
72
+
73
+
74
+ def classify_all(g: nx.DiGraph) -> dict[str, dict[str, str]]:
75
+ """component -> {root: relationship} via one BFS per root (cheap for the whole graph)."""
76
+ res: dict[str, dict[str, str]] = {}
77
+ for r in roots_of(g):
78
+ for n, d in nx.single_source_shortest_path_length(g, r).items():
79
+ if n == r or g.nodes[n].get("kind") != "component":
80
+ continue
81
+ if d == 1:
82
+ inferred = g.edges[r, n].get("provenance") == "inferred-no-parent"
83
+ res.setdefault(n, {})[r] = "direct_inferred" if inferred else "direct"
84
+ else:
85
+ res.setdefault(n, {})[r] = "transitive"
86
+ return res
@@ -0,0 +1,165 @@
1
+ """Build a directed NetworkX dependency graph (edge = parent -> child, "parent depends on child").
2
+
3
+ Nodes are keyed by CycloneDX ``bom-ref``. Service roots are synthetic nodes (``root:<service dir>``) because Syft
4
+ directory scans rarely emit a root dependency record. Every edge carries a ``provenance``:
5
+
6
+ * ``sbom`` relationship reported by the CycloneDX ``dependencies`` section
7
+ * ``lockfile:<path>`` relationship recorded in a lockfile (only added where the SBOM has none for the parent)
8
+ * ``lockfile-direct`` service root -> package that the lockfile/manifest marks as a direct dependency
9
+ * ``inferred-no-parent`` service root -> package with no recorded parent (relationship NOT proven; flagged)
10
+ """
11
+ from __future__ import annotations
12
+
13
+ from collections import defaultdict
14
+ from typing import Optional
15
+
16
+ import networkx as nx
17
+
18
+ from core.models import Component, LockDependency
19
+ from sbom.package_extractors.common import normalize_name
20
+
21
+ ROOT_PREFIX = "root:"
22
+
23
+
24
+ def root_id(service_dir: str) -> str:
25
+ return f"{ROOT_PREFIX}{service_dir}"
26
+
27
+
28
+ def _key(eco: str, name: str, version: Optional[str]) -> tuple:
29
+ return (eco, normalize_name(eco, name), version or "")
30
+
31
+
32
+ def build_graph(sbom_doc: dict, components: list[Component], lock_deps: list[LockDependency],
33
+ services: list[str], repo_name: str = "repository") -> tuple[nx.DiGraph, dict]:
34
+ """Return (graph, build_info). build_info collects malformed/unresolvable relationship data."""
35
+ g = nx.DiGraph()
36
+ info: dict = {"dangling_refs": [], "duplicate_refs": [], "self_loops": [], "malformed": [],
37
+ "ambiguous_lockfile_edges": [], "inferred_edges": 0, "lockfile_edges": 0, "sbom_edges": 0,
38
+ "meta_root": None}
39
+
40
+ # ---- component nodes
41
+ seen: dict[str, Component] = {}
42
+ self_refs: dict[str, str] = {}
43
+ for c in components:
44
+ if c.type in ("file", "container") or c.purl_type in ("docker", "github"):
45
+ continue # images and CI actions are pipeline dependencies (Pipeline tab), not part of the package dependency graph
46
+ if c.is_self and c.service_dir is not None:
47
+ self_refs[c.bom_ref] = c.service_dir # the application itself == its service root
48
+ continue
49
+ if c.bom_ref in seen:
50
+ info["duplicate_refs"].append(c.bom_ref)
51
+ continue
52
+ seen[c.bom_ref] = c
53
+ g.add_node(c.bom_ref, kind="component", label=f"{c.name}@{c.version}" if c.version else c.name, name=c.name,
54
+ version=c.version, ecosystem=c.ecosystem, purl=c.purl, service_dir=c.service_dir)
55
+
56
+ meta_root = ((sbom_doc.get("metadata") or {}).get("component") or {}).get("bom-ref")
57
+ info["meta_root"] = meta_root
58
+
59
+ # ---- SBOM relationships
60
+ for d in sbom_doc.get("dependencies") or []:
61
+ if not isinstance(d, dict) or not isinstance(d.get("ref"), str):
62
+ info["malformed"].append(str(d)[:100])
63
+ continue
64
+ parent = d["ref"]
65
+ if parent in self_refs:
66
+ parent = root_id(self_refs[parent])
67
+ targets = d.get("dependsOn") or []
68
+ if not isinstance(targets, list):
69
+ info["malformed"].append(f"dependsOn of {parent} is not a list")
70
+ continue
71
+ if parent not in seen and parent != meta_root and not parent.startswith(ROOT_PREFIX):
72
+ if targets:
73
+ info["dangling_refs"].append(parent)
74
+ continue
75
+ for t in targets:
76
+ if not isinstance(t, str):
77
+ info["malformed"].append(f"non-string dependsOn entry under {parent}")
78
+ continue
79
+ if t in self_refs:
80
+ continue
81
+ if t not in seen:
82
+ info["dangling_refs"].append(t)
83
+ continue
84
+ if t == parent:
85
+ info["self_loops"].append(t)
86
+ continue
87
+ if parent == meta_root and parent not in g:
88
+ g.add_node(parent, kind="root", label="SBOM root", service_dir=None)
89
+ g.add_edge(parent, t, provenance="sbom")
90
+ info["sbom_edges"] += 1
91
+
92
+ # ---- service roots
93
+ svc_set = sorted({c.service_dir for c in seen.values() if c.service_dir is not None})
94
+ for s in svc_set:
95
+ g.add_node(root_id(s), kind="root", service_dir=s, name=s if s != "." else repo_name,
96
+ label=(repo_name if s == "." else s) + " (service)", ecosystems=sorted({c.ecosystem for c in seen.values() if c.service_dir == s and c.ecosystem}))
97
+
98
+ # index components by scope for lockfile mapping
99
+ by_scope_key: dict[tuple, list[str]] = defaultdict(list)
100
+ by_scope_name: dict[tuple, list[str]] = defaultdict(list)
101
+ for ref, c in seen.items():
102
+ if c.ecosystem and c.service_dir is not None:
103
+ by_scope_key[(c.service_dir,) + _key(c.ecosystem, c.name, c.version)].append(ref)
104
+ by_scope_name[(c.service_dir, c.ecosystem, normalize_name(c.ecosystem, c.name))].append(ref)
105
+
106
+ def map_lock(d: LockDependency) -> list[str]:
107
+ return by_scope_key.get((d.service_dir,) + _key(d.ecosystem, d.name, d.version), [])
108
+
109
+ # ---- lockfile-derived edges, only for parents without SBOM-recorded children
110
+ for d in lock_deps:
111
+ if not d.requires or not d.version:
112
+ continue
113
+ for pref in map_lock(d):
114
+ if g.out_degree(pref) > 0 and any(g.edges[pref, t].get("provenance") == "sbom" for t in g.successors(pref)):
115
+ continue
116
+ for req in d.requires:
117
+ cands = by_scope_name.get((d.service_dir, d.ecosystem, normalize_name(d.ecosystem, req)), [])
118
+ cands = [c for c in cands if c != pref]
119
+ if len(cands) == 1:
120
+ if not g.has_edge(pref, cands[0]):
121
+ g.add_edge(pref, cands[0], provenance=f"lockfile:{d.lockfile}")
122
+ info["lockfile_edges"] += 1
123
+ elif len(cands) > 1:
124
+ info["ambiguous_lockfile_edges"].append({"parent": g.nodes[pref]["label"], "requires": req, "candidates": len(cands)})
125
+
126
+ # ---- root edges
127
+ direct_refs: dict[str, set[str]] = defaultdict(set)
128
+ scope_has_direct_info: set[tuple] = set()
129
+ for d in lock_deps:
130
+ if d.direct is not None:
131
+ scope_has_direct_info.add((d.service_dir, d.ecosystem))
132
+ if d.direct:
133
+ for r in map_lock(d):
134
+ direct_refs[d.service_dir].add(r)
135
+ for s in svc_set:
136
+ for r in direct_refs.get(s, ()):
137
+ g.add_edge(root_id(s), r, provenance="lockfile-direct")
138
+ # orphans: components with no parent and not known as non-direct by their lockfile
139
+ non_direct_known = {r for d in lock_deps if d.direct is False for r in map_lock(d)}
140
+ for ref, c in seen.items():
141
+ if g.in_degree(ref) == 0 and c.service_dir is not None and ref not in non_direct_known:
142
+ g.add_edge(root_id(c.service_dir), ref, provenance="inferred-no-parent")
143
+ info["inferred_edges"] += 1
144
+ # components still unreachable from every root (dependency cycles or parents that are themselves unrooted):
145
+ # attach the *entry* components of each unreachable strongly-connected group, flagged as inferred.
146
+ roots = roots_of(g)
147
+ reachable = set()
148
+ for r in roots:
149
+ reachable |= nx.descendants(g, r)
150
+ unreachable = [n for n in seen if n not in reachable]
151
+ if unreachable:
152
+ sub = g.subgraph(unreachable)
153
+ cond = nx.condensation(sub)
154
+ for cn in cond.nodes:
155
+ if cond.in_degree(cn) == 0:
156
+ for member in cond.nodes[cn]["members"]:
157
+ svc = g.nodes[member].get("service_dir")
158
+ if svc is not None and root_id(svc) in g:
159
+ g.add_edge(root_id(svc), member, provenance="inferred-no-parent")
160
+ info["inferred_edges"] += 1
161
+ return g, info
162
+
163
+
164
+ def roots_of(g: nx.DiGraph) -> list[str]:
165
+ return [n for n, a in g.nodes(data=True) if a.get("kind") == "root"]
@@ -0,0 +1,57 @@
1
+ """Scanner-independent graph identity, content hash and diff.
2
+
3
+ Node ids (bom-refs) differ between scanners and runs, so graphs are compared by *identity*: components by
4
+ ``service | name@version`` and roots by ``root:service``; edges by the identities of their endpoints.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import hashlib
9
+ from typing import Any
10
+
11
+
12
+ def node_key(n: dict) -> str:
13
+ if n.get("kind") == "root":
14
+ return f"root:{n.get('service_dir') if n.get('service_dir') is not None else n.get('id')}"
15
+ return f"{n.get('service_dir') or '.'}|{n.get('name')}@{n.get('version') or ''}"
16
+
17
+
18
+ def canonical(graph: dict) -> dict[str, Any]:
19
+ """{'nodes': {key: node}, 'edges': {(src_key, dst_key): provenance}} for a ``graph_to_json`` document."""
20
+ by_id = {n["id"]: n for n in graph.get("nodes", [])}
21
+ keys = {i: node_key(n) for i, n in by_id.items()}
22
+ nodes = {keys[i]: {"label": n.get("label"), "kind": n.get("kind"), "ecosystem": n.get("ecosystem"), "service_dir": n.get("service_dir")} for i, n in by_id.items()}
23
+ edges = {(keys[e["source"]], keys[e["target"]]): e.get("provenance", "") for e in graph.get("edges", []) if e["source"] in keys and e["target"] in keys}
24
+ return {"nodes": nodes, "edges": edges}
25
+
26
+
27
+ def graph_hash(graph: dict) -> str:
28
+ c = canonical(graph)
29
+ h = hashlib.sha256()
30
+ for k in sorted(c["nodes"]):
31
+ h.update(k.encode() + b"\n")
32
+ for (a, b) in sorted(c["edges"]):
33
+ h.update(f"{a}->{b}\n".encode())
34
+ return h.hexdigest()[:16]
35
+
36
+
37
+ def diff_graphs(old: dict, new: dict) -> dict[str, Any]:
38
+ a, b = canonical(old), canonical(new)
39
+ an, bn = set(a["nodes"]), set(b["nodes"])
40
+ ae, be = set(a["edges"]), set(b["edges"])
41
+ comp = lambda k: not k.startswith("root:") # noqa: E731
42
+ added = sorted(k for k in bn - an if comp(k))
43
+ removed = sorted(k for k in an - bn if comp(k))
44
+ # version changes: same service+name present on both sides with different versions
45
+ def by_name(keys):
46
+ out: dict[tuple, set] = {}
47
+ for k in keys:
48
+ svc, rest = k.split("|", 1)
49
+ name, _, ver = rest.rpartition("@")
50
+ out.setdefault((svc, name), set()).add(ver)
51
+ return out
52
+ oa, ob = by_name(k for k in an if comp(k)), by_name(k for k in bn if comp(k))
53
+ changed = sorted(f"{s}|{n}: {', '.join(sorted(oa[(s, n)]))} -> {', '.join(sorted(ob[(s, n)]))}" for (s, n) in oa.keys() & ob.keys() if oa[(s, n)] != ob[(s, n)])
54
+ return {"identical": not (added or removed or ae ^ be), "added_components": added, "removed_components": removed, "version_changes": changed,
55
+ "added_edges": len(be - ae), "removed_edges": len(ae - be),
56
+ "new_direct": sorted(f"{x[1]}" for x in be - ae if x[0].startswith("root:") and comp(x[1])),
57
+ "totals": {"before": {"components": len([k for k in an if comp(k)]), "edges": len(ae)}, "after": {"components": len([k for k in bn if comp(k)]), "edges": len(be)}}}
@@ -0,0 +1,194 @@
1
+ """Graph export: JSON (node-link) and the complete, uncapped payload for the interactive WebGL dependency explorer."""
2
+ from __future__ import annotations
3
+
4
+ import math
5
+ from collections import defaultdict
6
+ from typing import Optional
7
+
8
+ import networkx as nx
9
+
10
+ from graph.graph_builder import roots_of
11
+
12
+
13
+ def graph_to_json(g: nx.DiGraph, validation: dict | None = None) -> dict:
14
+ return {
15
+ "directed": True, "semantics": "edge parent->child means parent depends on child",
16
+ "nodes": [{"id": n, **{k: v for k, v in a.items()}} for n, a in g.nodes(data=True)],
17
+ "edges": [{"source": u, "target": v, **a} for u, v, a in g.edges(data=True)],
18
+ "roots": roots_of(g), "validation": validation or {},
19
+ }
20
+
21
+
22
+ def _name(label: str, version: str | None) -> str:
23
+ return label[: -len(version) - 1] if version and label.endswith("@" + version) else label
24
+
25
+
26
+ def _fast_descendant_counts(g: nx.DiGraph) -> dict[str, int]:
27
+ """Approximate/exact descendant counts in O(V + E) via SCC condensation (handles cycles safely)."""
28
+ if g.number_of_nodes() == 0:
29
+ return {}
30
+ if nx.is_directed_acyclic_graph(g):
31
+ counts: dict[str, int] = {}
32
+ for n in reversed(list(nx.topological_sort(g))):
33
+ # For large graphs, bitsets/sets on small DAGs are fast; cap set size if huge to stay O(V+E) memory
34
+ if g.out_degree(n) == 0:
35
+ counts[n] = 0
36
+ else:
37
+ # Sum direct + unique children estimate when > 2000 nodes for O(V+E) speed
38
+ if g.number_of_nodes() <= 2000:
39
+ seen: set[str] = set()
40
+ for succ in g.successors(n):
41
+ seen.add(succ)
42
+ if succ in _DESC_CACHE_LOCAL:
43
+ seen |= _DESC_CACHE_LOCAL[succ]
44
+ _DESC_CACHE_LOCAL[n] = seen
45
+ counts[n] = len(seen)
46
+ else:
47
+ counts[n] = sum(1 + counts.get(s, 0) for s in g.successors(n))
48
+ return counts
49
+
50
+ cond = nx.condensation(g)
51
+ scc_members = {c: cond.nodes[c]["members"] for c in cond.nodes}
52
+ scc_counts: dict[int, int] = {}
53
+ for c in reversed(list(nx.topological_sort(cond))):
54
+ own = len(scc_members[c]) - 1
55
+ scc_counts[c] = own + sum(len(scc_members[s]) + scc_counts.get(s, 0) for s in cond.successors(c))
56
+ out: dict[str, int] = {}
57
+ for c, members in scc_members.items():
58
+ for m in members:
59
+ out[m] = scc_counts[c]
60
+ return out
61
+
62
+
63
+ _DESC_CACHE_LOCAL: dict[str, set[str]] = {}
64
+
65
+
66
+ def _compute_initial_coords(nodes: list[dict], roots: list[str]) -> dict[str, tuple[float, float]]:
67
+ """Deterministic, O(V) layered-radial coordinates so WebGL renders instantly without layout lag."""
68
+ by_depth: dict[int, list[dict]] = defaultdict(list)
69
+ for n in nodes:
70
+ by_depth[int(n.get("depth") or 0)].append(n)
71
+ coords: dict[str, tuple[float, float]] = {}
72
+ for d, group in by_depth.items():
73
+ if d == 0:
74
+ for idx, n in enumerate(group):
75
+ angle = (2 * math.pi * idx) / max(len(group), 1)
76
+ r = 0.0 if len(group) == 1 else 140.0
77
+ coords[n["id"]] = (round(math.cos(angle) * r, 2), round(math.sin(angle) * r, 2))
78
+ continue
79
+ radius = 180.0 * d + (len(group) * 2.5 if len(group) > 40 else 0.0)
80
+ for idx, n in enumerate(group):
81
+ angle = (2 * math.pi * idx) / max(len(group), 1)
82
+ coords[n["id"]] = (round(math.cos(angle) * radius, 2), round(math.sin(angle) * radius, 2))
83
+ return coords
84
+
85
+
86
+ def dependency_payload(
87
+ g: nx.DiGraph,
88
+ rel: dict,
89
+ vulnerable: dict[str, str],
90
+ advisories: dict[str, list[str]],
91
+ info: dict,
92
+ fixes: dict[str, str],
93
+ cap: Optional[int] = None,
94
+ initial_budget: int = 400,
95
+ ) -> dict:
96
+ """Complete, uncapped node/edge payload for the interactive WebGL dependency explorer.
97
+
98
+ - By default (``cap=None``), **all** nodes, edges, vulnerabilities, and dependency paths are preserved.
99
+ - ``initial_budget`` advises the browser on how many priority nodes (roots + direct + vulnerable + root paths)
100
+ to show on first paint while keeping the entire graph in Graphology for global search and lazy expansion.
101
+ """
102
+ _DESC_CACHE_LOCAL.clear()
103
+ roots = roots_of(g)
104
+ root_reach: dict[str, dict[str, int]] = {}
105
+ depth: dict[str, int] = {}
106
+ for r in roots:
107
+ lengths = nx.single_source_shortest_path_length(g, r)
108
+ root_reach[r] = lengths
109
+ for n, d in lengths.items():
110
+ depth[n] = min(depth.get(n, d), d)
111
+
112
+ # Also include any disconnected components so no node is ever silently dropped
113
+ all_comps = [n for n, a in g.nodes(data=True) if a.get("kind") == "component"]
114
+ for n in all_comps:
115
+ if n not in depth:
116
+ depth[n] = 99
117
+
118
+ sev_rank = {"CRITICAL": 4, "HIGH": 3, "MEDIUM": 2, "LOW": 1, "UNKNOWN": 0}
119
+ direct = {n for n in all_comps if any(v.startswith("direct") for v in rel.get(n, {}).values())}
120
+ all_comps.sort(key=lambda n: (-(sev_rank[vulnerable[n]] + 1 if n in vulnerable else 0), n not in direct, -g.in_degree(n), depth[n]))
121
+
122
+ if cap is not None:
123
+ keep: set[str] = set(roots)
124
+ for n in all_comps:
125
+ if len(keep) >= cap:
126
+ break
127
+ keep.add(n)
128
+ if depth[n] > 1:
129
+ parent_root = next((r for r in roots if n in root_reach[r]), None)
130
+ if parent_root:
131
+ keep |= set(nx.shortest_path(g, parent_root, n))
132
+ else:
133
+ keep = set(roots) | set(all_comps)
134
+
135
+ # Compute initial visible priority set (roots + direct + vulnerable + paths) for fast adaptive first paint
136
+ initial_visible: set[str] = set(roots)
137
+ for n in all_comps:
138
+ if n not in keep:
139
+ continue
140
+ if len(initial_visible) >= initial_budget and n not in vulnerable and n not in direct:
141
+ continue
142
+ initial_visible.add(n)
143
+ if depth[n] > 1:
144
+ parent_root = next((r for r in roots if n in root_reach[r]), None)
145
+ if parent_root:
146
+ initial_visible |= set(nx.shortest_path(g, parent_root, n))
147
+
148
+ desc_counts = _fast_descendant_counts(g)
149
+ nodes = []
150
+ for n in keep:
151
+ a = g.nodes[n]
152
+ scope = info.get(n, {}).get("scope")
153
+ nodes.append({
154
+ "id": n,
155
+ "label": _name(a.get("label", n), a.get("version")),
156
+ "version": a.get("version") or "",
157
+ "eco": a.get("ecosystem") or "",
158
+ "kind": "root" if n in roots else ("dev" if scope == "dev" else "prod"),
159
+ "direct": n in direct,
160
+ "depth": depth.get(n, 0),
161
+ "parents": g.in_degree(n),
162
+ "desc": desc_counts.get(n, 0),
163
+ "vuln": vulnerable.get(n, ""),
164
+ "ids": advisories.get(n, [])[:4],
165
+ "fix": fixes.get(n, ""),
166
+ })
167
+
168
+ coords = _compute_initial_coords(nodes, roots)
169
+ for node in nodes:
170
+ x, y = coords.get(node["id"], (0.0, 0.0))
171
+ node["x"] = x
172
+ node["y"] = y
173
+
174
+ edges = [[u, v] for u, v in g.edges if u in keep and v in keep]
175
+ return {
176
+ "nodes": nodes,
177
+ "edges": edges,
178
+ "initial_visible": sorted(initial_visible & keep),
179
+ "total": len(all_comps),
180
+ "directs": len(direct),
181
+ "truncated": len(all_comps) > len(keep) - len(roots),
182
+ }
183
+
184
+
185
+ def graph_from_json(data: dict) -> nx.DiGraph:
186
+ """Rebuild a DiGraph from ``graph_to_json`` output (used by the UI so scans can be reloaded from SQLite)."""
187
+ g = nx.DiGraph()
188
+ for n in data.get("nodes", []):
189
+ n = dict(n)
190
+ g.add_node(n.pop("id"), **n)
191
+ for e in data.get("edges", []):
192
+ e = dict(e)
193
+ g.add_edge(e.pop("source"), e.pop("target"), **e)
194
+ return g
@@ -0,0 +1,46 @@
1
+ """Graph validation: dangling references, duplicates, cycles, orphans, unresolved relationships."""
2
+ from __future__ import annotations
3
+
4
+ import networkx as nx
5
+
6
+ from graph.graph_builder import roots_of
7
+
8
+
9
+ def validate_graph(g: nx.DiGraph, build_info: dict) -> dict:
10
+ roots = roots_of(g)
11
+ comps = [n for n, a in g.nodes(data=True) if a.get("kind") == "component"]
12
+ reachable: set[str] = set()
13
+ for r in roots:
14
+ reachable |= nx.descendants(g, r)
15
+ unreachable = [n for n in comps if n not in reachable]
16
+ sccs = [sorted(c) for c in nx.strongly_connected_components(g) if len(c) > 1]
17
+ prov: dict[str, int] = {}
18
+ for _, _, a in g.edges(data=True):
19
+ p = a.get("provenance", "unknown").split(":")[0]
20
+ prov[p] = prov.get(p, 0) + 1
21
+ warnings = []
22
+ if build_info["dangling_refs"]:
23
+ warnings.append(f"{len(set(build_info['dangling_refs']))} dependency reference(s) point to components not present in the SBOM")
24
+ if build_info["duplicate_refs"]:
25
+ warnings.append(f"{len(build_info['duplicate_refs'])} duplicate bom-ref record(s) were ignored")
26
+ if sccs:
27
+ warnings.append(f"{len(sccs)} dependency cycle group(s) detected (handled safely)")
28
+ if build_info["inferred_edges"]:
29
+ warnings.append(f"{build_info['inferred_edges']} root->package edge(s) are inferred (package has no recorded parent); "
30
+ "direct/transitive status for those packages is 'direct (inferred)'")
31
+ if unreachable:
32
+ warnings.append(f"{len(unreachable)} component(s) are not reachable from any service root")
33
+ if build_info["ambiguous_lockfile_edges"]:
34
+ warnings.append(f"{len(build_info['ambiguous_lockfile_edges'])} lockfile relationship(s) were ambiguous and not added")
35
+ if build_info["malformed"]:
36
+ warnings.append(f"{len(build_info['malformed'])} malformed relationship record(s) skipped")
37
+ return {
38
+ "nodes": g.number_of_nodes(), "edges": g.number_of_edges(), "components": len(comps), "roots": roots,
39
+ "is_acyclic": nx.is_directed_acyclic_graph(g), "cycle_groups": sccs[:20],
40
+ "dangling_refs": sorted(set(build_info["dangling_refs"]))[:50],
41
+ "duplicate_refs": sorted(set(build_info["duplicate_refs"]))[:50],
42
+ "self_loops": build_info["self_loops"][:20], "malformed": build_info["malformed"][:20],
43
+ "unreachable_components": unreachable[:100], "unreachable_count": len(unreachable),
44
+ "edge_provenance": prov, "ambiguous_lockfile_edges": build_info["ambiguous_lockfile_edges"][:20],
45
+ "warnings": warnings,
46
+ }
@@ -0,0 +1,23 @@
1
+ """Impact analysis: how widely a (vulnerable) component is used across roots."""
2
+ from __future__ import annotations
3
+
4
+ import networkx as nx
5
+
6
+ from graph.graph_builder import roots_of
7
+
8
+
9
+ def impact_of(g: nx.DiGraph, ref: str) -> dict:
10
+ if ref not in g:
11
+ return {"affected_roots": [], "root_count": 0, "dependents": 0, "direct_roots": [], "transitive_roots": [],
12
+ "blast_radius_components": 0}
13
+ anc = nx.ancestors(g, ref)
14
+ roots = [r for r in roots_of(g) if r in anc]
15
+ direct = [r for r in roots if g.has_edge(r, ref)]
16
+ return {
17
+ "affected_roots": [g.nodes[r].get("label", r) for r in roots],
18
+ "root_count": len(roots),
19
+ "direct_roots": [g.nodes[r].get("label", r) for r in direct],
20
+ "transitive_roots": [g.nodes[r].get("label", r) for r in roots if r not in direct],
21
+ "dependents": len([a for a in anc if g.nodes[a].get("kind") == "component"]),
22
+ "blast_radius_components": len([d for d in nx.descendants(g, ref) if g.nodes[d].get("kind") == "component"]),
23
+ }