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,76 @@
1
+ """Trivy CycloneDX adapter.
2
+
3
+ Trivy emits one ``application`` component per lockfile (named by its path), a root component, and libraries whose
4
+ bom-ref is the PURL. The canonical form folds this into Syft-like shape:
5
+
6
+ * application components and the root record are removed; each library gets ``sc-guardian:location:0:path`` = its lockfile
7
+ * a library referenced by several lockfiles (monorepo) is cloned per lockfile (``<purl>#<n>``) with its dependency records
8
+ remapped, so every service keeps its own node instead of losing it to a duplicate bom-ref
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import copy
13
+
14
+ NAME = "trivy"
15
+ LOC = "sc-guardian:location:0:path"
16
+
17
+
18
+ def _prop(c: dict, name: str) -> list[str]:
19
+ return [p.get("value", "") for p in c.get("properties", []) or [] if isinstance(p, dict) and p.get("name") == name]
20
+
21
+
22
+ def canonicalize(raw: dict) -> dict:
23
+ d = copy.deepcopy(raw)
24
+ comps = d.get("components") or []
25
+ deps = d.get("dependencies") or []
26
+ apps = {c.get("bom-ref"): c for c in comps if c.get("type") == "application" and not c.get("purl")}
27
+ meta_root = ((d.get("metadata") or {}).get("component") or {}).get("bom-ref")
28
+ dep_of = {r.get("ref"): list(r.get("dependsOn") or []) for r in deps}
29
+
30
+ members: dict[str, list[str]] = {} # app ref -> library refs belonging to that lockfile
31
+ for aref in apps:
32
+ members[aref] = [t for t in dep_of.get(aref, []) if t not in apps]
33
+ owners: dict[str, list[str]] = {}
34
+ for aref, libs in members.items():
35
+ for t in libs:
36
+ owners.setdefault(t, []).append(aref)
37
+
38
+ by_ref = {c.get("bom-ref"): c for c in comps if c.get("bom-ref") not in apps}
39
+ out_comps, out_deps = [], []
40
+ new_ref = {} # (app, original ref) -> canonical ref
41
+ for ref, c in by_ref.items():
42
+ apps_for = owners.get(ref) or [None]
43
+ multi = len(apps_for) > 1
44
+ for i, a in enumerate(apps_for):
45
+ nr = f"{ref}#{i}" if multi else ref
46
+ new_ref[(a, ref)] = nr
47
+ cc = copy.deepcopy(c)
48
+ cc["bom-ref"] = nr
49
+ if a is not None:
50
+ cc.setdefault("properties", []).append({"name": LOC, "value": apps[a].get("name", "")})
51
+ out_comps.append(cc)
52
+ for ref in by_ref:
53
+ for a in owners.get(ref) or [None]:
54
+ targets = []
55
+ for t in dep_of.get(ref, []):
56
+ if t in apps:
57
+ continue
58
+ targets.append(new_ref.get((a, t)) or new_ref.get((None, t)) or t)
59
+ out_deps.append({"ref": new_ref[(a, ref)], "dependsOn": targets})
60
+ d["components"], d["dependencies"] = out_comps, out_deps
61
+ return d
62
+
63
+
64
+ def locations(c: dict) -> list[str]:
65
+ out = []
66
+ for i in range(20):
67
+ v = _prop(c, f"sc-guardian:location:{i}:path")
68
+ if not v:
69
+ break
70
+ out.append(v[0])
71
+ return out
72
+
73
+
74
+ def found_by(c: dict):
75
+ t = _prop(c, "aquasecurity:trivy:PkgType")
76
+ return f"trivy:{t[0]}" if t else None
@@ -0,0 +1,227 @@
1
+ """Built-in rule-based SBOM generator: lockfile/manifest records -> CycloneDX 1.5 JSON.
2
+
3
+ First-class baseline capability requiring no external binaries (Syft/Trivy).
4
+ Supports npm/yarn/pnpm, pip/poetry/uv/Pipfile, Go, Cargo, Composer, NuGet, Maven, Gradle.
5
+
6
+ Refined Rules (R1-R6):
7
+ R1 Preserve unresolved manifest dependencies (no fabricated version; tagged resolution_status=unresolved)
8
+ R2 Use go.sum as supplementary checksum evidence for go.mod components rather than duplicate inventory
9
+ R3 One component per (service_dir, ecosystem, normalized_name, version); repeats merge lockfile locations
10
+ R4 Component identity is PURL (or ecosystem:name); distinct services keep distinct bom-refs
11
+ R5 Record resolved edges plus explicit unresolved and ambiguous dependency relationships
12
+ R6 Distinguish development/build dependencies from CycloneDX optional scope and preserve them for security analysis
13
+ """
14
+ from __future__ import annotations
15
+
16
+ import uuid
17
+ from datetime import datetime, timezone
18
+ from typing import Optional
19
+
20
+ from core.models import LockDependency
21
+ from sbom.package_extractors.common import make_purl, normalize_name, parse_purl
22
+
23
+ TOOL_NAME = "stackparity-rule-engine"
24
+ TOOL_VERSION = "1.1"
25
+ PROP = "stackparity"
26
+
27
+
28
+ def _parse_integrity_hash(integrity: Optional[str]) -> list[dict[str, str]]:
29
+ if not integrity:
30
+ return []
31
+ if integrity.startswith("sha512-"):
32
+ return [{"alg": "SHA-512", "content": integrity[7:]}]
33
+ if integrity.startswith("sha256-"):
34
+ return [{"alg": "SHA-256", "content": integrity[7:]}]
35
+ if integrity.startswith("h1:"):
36
+ return [{"alg": "SHA-256", "content": integrity}]
37
+ if ":" in integrity:
38
+ alg, val = integrity.split(":", 1)
39
+ return [{"alg": alg.upper(), "content": val}]
40
+ return []
41
+
42
+
43
+ def generate_cyclonedx(
44
+ lock_deps: list[LockDependency],
45
+ repo_name: str,
46
+ commit_sha: str = "",
47
+ own_version: Optional[str] = None,
48
+ ) -> tuple[dict, dict]:
49
+ """Return (cyclonedx_document, stats). Never raises on odd records."""
50
+ stats: dict = {
51
+ "records": len(lock_deps),
52
+ "skipped_unpinned": 0, # kept for backward-compatible stat consumers
53
+ "unresolved_declarations": 0,
54
+ "go_sum_enriched": 0,
55
+ "skipped_go_sum": 0,
56
+ "merged_duplicates": 0,
57
+ "edges": 0,
58
+ "ambiguous_edges": 0,
59
+ "unresolved_edges": 0,
60
+ "ambiguous_relationship_details": [],
61
+ "unresolved_relationship_details": [],
62
+ }
63
+ has_go_mod = {d.service_dir for d in lock_deps if d.lockfile.endswith("go.mod")}
64
+
65
+ # R2: index go.sum integrity hashes as supplementary checksum evidence
66
+ go_sum_hashes: dict[tuple[str, str, str], str] = {}
67
+ for d in lock_deps:
68
+ if d.lockfile.endswith("go.sum") and d.version and d.integrity:
69
+ go_sum_hashes[(d.service_dir, normalize_name(d.ecosystem, d.name), d.version)] = d.integrity
70
+
71
+ comps: dict[tuple, dict] = {}
72
+ meta: dict[tuple, LockDependency] = {}
73
+ used_refs: set[str] = set()
74
+
75
+ for d in lock_deps:
76
+ if d.lockfile.endswith("go.sum") and d.service_dir in has_go_mod:
77
+ stats["skipped_go_sum"] += 1 # R2: supplementary checksums merged onto go.mod components
78
+ continue
79
+
80
+ is_resolved = bool(d.version)
81
+ if not is_resolved:
82
+ stats["skipped_unpinned"] += 1
83
+ stats["unresolved_declarations"] += 1
84
+
85
+ ver_key = d.version or "__unresolved__"
86
+ key = (d.service_dir, d.ecosystem, normalize_name(d.ecosystem, d.name), ver_key)
87
+ if key in comps:
88
+ stats["merged_duplicates"] += 1 # R3
89
+ c = comps[key]
90
+ n = sum(1 for p in c["properties"] if p["name"].startswith(f"{PROP}:location:"))
91
+ if not any(p["value"] == d.lockfile for p in c["properties"] if p["name"].startswith(f"{PROP}:location:")):
92
+ c["properties"].append({"name": f"{PROP}:location:{n}:path", "value": d.lockfile})
93
+ if d.direct:
94
+ _set_prop(c, f"{PROP}:direct", "true")
95
+ if d.dev:
96
+ _set_prop(c, f"{PROP}:dev", "true")
97
+ _set_prop(c, f"{PROP}:dependency_role", "development")
98
+ continue
99
+
100
+ purl = d.purl or (make_purl(d.ecosystem, d.name, d.version) if is_resolved else None)
101
+ pp = parse_purl(purl) if purl else None
102
+ ref = purl or f"{d.ecosystem}:{d.name}@{d.version or 'unresolved'}"
103
+ if ref in used_refs: # R4
104
+ ref = f"{ref}#{d.service_dir}"
105
+ used_refs.add(ref)
106
+
107
+ props = [
108
+ {"name": f"{PROP}:package:foundBy", "value": f"{TOOL_NAME}:{d.lockfile.rsplit('/', 1)[-1]}"},
109
+ {"name": f"{PROP}:location:0:path", "value": d.lockfile},
110
+ {"name": f"{PROP}:service", "value": d.service_dir},
111
+ {"name": f"{PROP}:resolution_status", "value": "resolved" if is_resolved else "unresolved"},
112
+ {"name": f"{PROP}:origin", "value": "resolved" if is_resolved else "declared"},
113
+ ]
114
+ c: dict = {
115
+ "bom-ref": ref,
116
+ "type": "library",
117
+ "name": pp["name"] if pp else d.name,
118
+ "properties": props,
119
+ }
120
+ if is_resolved and d.version:
121
+ c["version"] = d.version # R1: never fabricate version for unresolved declarations
122
+ if pp and pp.get("namespace"):
123
+ c["group"] = pp["namespace"]
124
+ if purl:
125
+ c["purl"] = purl
126
+
127
+ # R6: distinguish development dependencies from CycloneDX optional scope
128
+ if d.dev:
129
+ c["scope"] = "required"
130
+ props.append({"name": f"{PROP}:dev", "value": "true"})
131
+ props.append({"name": f"{PROP}:dependency_role", "value": "development"})
132
+ else:
133
+ c["scope"] = "required"
134
+ props.append({"name": f"{PROP}:dependency_role", "value": "runtime"})
135
+
136
+ if d.direct:
137
+ props.append({"name": f"{PROP}:direct", "value": "true"})
138
+ if d.integrity:
139
+ props.append({"name": f"{PROP}:integrity", "value": d.integrity})
140
+ hashes = _parse_integrity_hash(d.integrity)
141
+ if hashes:
142
+ c["hashes"] = hashes
143
+ elif d.ecosystem == "Go" and d.version:
144
+ gs = go_sum_hashes.get((d.service_dir, normalize_name(d.ecosystem, d.name), d.version))
145
+ if gs:
146
+ stats["go_sum_enriched"] += 1
147
+ props.append({"name": f"{PROP}:go_sum_integrity", "value": gs})
148
+ hashes = _parse_integrity_hash(gs)
149
+ if hashes:
150
+ c["hashes"] = hashes
151
+
152
+ if d.resolved:
153
+ props.append({"name": f"{PROP}:resolved", "value": d.resolved[:300]})
154
+ comps[key] = c
155
+ meta[key] = d
156
+
157
+ # R5: relationships recorded by lockfiles + explicit ambiguous/unresolved tracking
158
+ by_name: dict[tuple, list[str]] = {}
159
+ for key, c in comps.items():
160
+ by_name.setdefault((key[0], key[1], key[2]), []).append(c["bom-ref"])
161
+ dependsOn: dict[str, list[str]] = {c["bom-ref"]: [] for c in comps.values()}
162
+ for key, d in meta.items():
163
+ parent = comps[key]["bom-ref"]
164
+ for req in d.requires or []:
165
+ cands = [r for r in by_name.get((d.service_dir, d.ecosystem, normalize_name(d.ecosystem, req)), []) if r != parent]
166
+ if len(cands) == 1:
167
+ if cands[0] not in dependsOn[parent]:
168
+ dependsOn[parent].append(cands[0])
169
+ stats["edges"] += 1
170
+ elif len(cands) > 1:
171
+ stats["ambiguous_edges"] += 1
172
+ if len(stats["ambiguous_relationship_details"]) < 50:
173
+ stats["ambiguous_relationship_details"].append({
174
+ "parent": parent,
175
+ "requires": req,
176
+ "candidates": len(cands),
177
+ })
178
+ else:
179
+ stats["unresolved_edges"] += 1
180
+ if len(stats["unresolved_relationship_details"]) < 50:
181
+ stats["unresolved_relationship_details"].append({
182
+ "parent": parent,
183
+ "requires": req,
184
+ })
185
+
186
+ doc = {
187
+ "bomFormat": "CycloneDX",
188
+ "specVersion": "1.5",
189
+ "serialNumber": f"urn:uuid:{uuid.uuid4()}",
190
+ "version": 1,
191
+ "metadata": {
192
+ "timestamp": datetime.now(timezone.utc).isoformat(timespec="seconds"),
193
+ "tools": {
194
+ "components": [
195
+ {
196
+ "type": "application",
197
+ "name": TOOL_NAME,
198
+ "version": TOOL_VERSION,
199
+ "description": "StackParity built-in rule-based SBOM generator (lockfile/manifest parsing)",
200
+ }
201
+ ]
202
+ },
203
+ "component": {
204
+ "bom-ref": f"app:{repo_name}",
205
+ "type": "application",
206
+ "name": repo_name,
207
+ **({"version": commit_sha[:12]} if commit_sha else {}),
208
+ },
209
+ "properties": [
210
+ {"name": f"{PROP}:generator", "value": "lockfile rules R1-R6 (see sbom/builtin_generator.py)"},
211
+ {"name": f"{PROP}:unresolved_declarations", "value": str(stats["unresolved_declarations"])},
212
+ {"name": f"{PROP}:ambiguous_edges", "value": str(stats["ambiguous_edges"])},
213
+ {"name": f"{PROP}:unresolved_edges", "value": str(stats["unresolved_edges"])},
214
+ ],
215
+ },
216
+ "components": list(comps.values()),
217
+ "dependencies": [{"ref": ref, "dependsOn": deps} for ref, deps in dependsOn.items()],
218
+ }
219
+ return doc, stats
220
+
221
+
222
+ def _set_prop(c: dict, name: str, value: str) -> None:
223
+ for p in c["properties"]:
224
+ if p["name"] == name:
225
+ p["value"] = value
226
+ return
227
+ c["properties"].append({"name": name, "value": value})
@@ -0,0 +1,166 @@
1
+ """CycloneDX validation (structural profile + referential integrity) and normalization to Component models.
2
+
3
+ Note: this validates a JSON-Schema *profile* of the fields the scanner relies on (CycloneDX 1.4-1.7 shape) plus
4
+ bom-ref integrity. It is not a byte-for-byte validation against every optional part of the official schema.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import json
9
+ import re
10
+ from pathlib import Path
11
+ from typing import Any
12
+
13
+ import jsonschema
14
+
15
+ from config.constants import PURL_TO_OSV
16
+ from core.models import Component
17
+ from core.repository_inspector import service_for_path
18
+ from sbom.package_extractors.common import parse_purl
19
+
20
+ SELF_MANIFESTS = {"package.json", "pyproject.toml", "setup.py", "pom.xml", "Cargo.toml", "composer.json", "build.gradle", "build.gradle.kts"}
21
+ SUPPORTED_SPECS = ("1.4", "1.5", "1.6", "1.7")
22
+
23
+ PROFILE_SCHEMA = {
24
+ "type": "object",
25
+ "required": ["bomFormat", "specVersion"],
26
+ "properties": {
27
+ "bomFormat": {"const": "CycloneDX"},
28
+ "specVersion": {"type": "string", "pattern": r"^1\.\d+$"},
29
+ "version": {"type": "integer"},
30
+ "metadata": {"type": "object"},
31
+ "components": {
32
+ "type": "array",
33
+ "items": {
34
+ "type": "object",
35
+ "required": ["type", "name"],
36
+ "properties": {
37
+ "type": {"type": "string"}, "name": {"type": "string", "minLength": 1},
38
+ "version": {"type": "string"}, "purl": {"type": "string"}, "bom-ref": {"type": "string"},
39
+ "licenses": {"type": "array"}, "hashes": {"type": "array"}, "properties": {"type": "array"},
40
+ },
41
+ },
42
+ },
43
+ "dependencies": {
44
+ "type": "array",
45
+ "items": {
46
+ "type": "object", "required": ["ref"],
47
+ "properties": {"ref": {"type": "string"}, "dependsOn": {"type": "array", "items": {"type": "string"}}},
48
+ },
49
+ },
50
+ },
51
+ }
52
+
53
+
54
+ def validate_cyclonedx(doc: Any) -> dict:
55
+ """Return {valid, errors[], warnings[], stats{}}. Never raises on malformed input."""
56
+ errors: list[str] = []
57
+ warnings: list[str] = []
58
+ stats = {"components": 0, "dependencies": 0, "spec_version": None}
59
+ if not isinstance(doc, dict):
60
+ return {"valid": False, "errors": ["document is not a JSON object"], "warnings": [], "stats": stats}
61
+ v = jsonschema.Draft7Validator(PROFILE_SCHEMA)
62
+ for e in sorted(v.iter_errors(doc), key=lambda e: list(e.path))[:25]:
63
+ errors.append(f"{'/'.join(str(p) for p in e.path) or '<root>'}: {e.message[:160]}")
64
+ spec = doc.get("specVersion")
65
+ stats["spec_version"] = spec
66
+ if isinstance(spec, str) and spec not in SUPPORTED_SPECS:
67
+ warnings.append(f"specVersion {spec} is outside the tested range {SUPPORTED_SPECS[0]}-{SUPPORTED_SPECS[-1]}")
68
+ comps = doc.get("components") if isinstance(doc.get("components"), list) else []
69
+ deps = doc.get("dependencies") if isinstance(doc.get("dependencies"), list) else []
70
+ stats["components"], stats["dependencies"] = len(comps), len(deps)
71
+ refs: dict[str, int] = {}
72
+ meta_comp = (doc.get("metadata") or {}).get("component") if isinstance(doc.get("metadata"), dict) else None
73
+ if isinstance(meta_comp, dict) and meta_comp.get("bom-ref"):
74
+ refs[meta_comp["bom-ref"]] = 1
75
+ for c in comps:
76
+ if isinstance(c, dict):
77
+ r = c.get("bom-ref")
78
+ if r:
79
+ refs[r] = refs.get(r, 0) + 1
80
+ else:
81
+ warnings.append(f"component {c.get('name')!r} has no bom-ref")
82
+ if c.get("purl") and not str(c["purl"]).startswith("pkg:"):
83
+ errors.append(f"component {c.get('name')!r} has a malformed purl")
84
+ dup = [r for r, n in refs.items() if n > 1]
85
+ if dup:
86
+ errors.append(f"duplicate bom-ref values: {dup[:5]}")
87
+ dangling = set()
88
+ for d in deps:
89
+ if not isinstance(d, dict):
90
+ continue
91
+ if d.get("ref") not in refs:
92
+ dangling.add(d.get("ref"))
93
+ for t in d.get("dependsOn", []) or []:
94
+ if t not in refs:
95
+ dangling.add(t)
96
+ if dangling:
97
+ warnings.append(f"{len(dangling)} dependency reference(s) point to unknown components, e.g. {sorted(map(str, dangling))[:3]}")
98
+ return {"valid": not errors, "errors": errors, "warnings": warnings, "stats": stats}
99
+
100
+
101
+ def _prop(c: dict, name: str) -> list[str]:
102
+ return [p.get("value", "") for p in c.get("properties", []) or [] if isinstance(p, dict) and p.get("name") == name]
103
+
104
+
105
+ def _rel_location(loc: str, repo_root: Path) -> str:
106
+ p = loc.replace("\\", "/")
107
+ root = str(Path(repo_root).resolve()).replace("\\", "/").rstrip("/")
108
+ if p.lower().startswith(root.lower() + "/"):
109
+ p = p[len(root) + 1:]
110
+ return p.lstrip("/")
111
+
112
+
113
+ def _licenses(c: dict) -> list[str]:
114
+ out = []
115
+ for l in c.get("licenses", []) or []:
116
+ if not isinstance(l, dict):
117
+ continue
118
+ if "expression" in l:
119
+ out.append(str(l["expression"]))
120
+ lic = l.get("license") or {}
121
+ val = lic.get("id") or lic.get("name")
122
+ if val:
123
+ out.append(str(val))
124
+ return out
125
+
126
+
127
+ def normalize_components(doc: dict, repo_root: Path, service_dirs: list[str], tool: str = "syft") -> list[Component]:
128
+ """Convert a canonical CycloneDX document (see ``sbom.adapters``) to Component models, mapping each to its owning service directory."""
129
+ from sbom.adapters import get_adapter
130
+ ad = get_adapter(tool)
131
+ result: list[Component] = []
132
+ for c in doc.get("components", []) or []:
133
+ if not isinstance(c, dict) or not c.get("name"):
134
+ continue
135
+ purl = c.get("purl")
136
+ pp = parse_purl(purl) if purl else None
137
+ found_locations, found_by = ad.locations(c), ad.found_by(c)
138
+ augmented = False
139
+ if not found_locations and tool != "builtin":
140
+ # components the built-in engine added to an external scanner's inventory carry its location properties
141
+ builtin = get_adapter("builtin")
142
+ found_locations, found_by = builtin.locations(c), found_by or builtin.found_by(c)
143
+ augmented = bool(found_locations) # a dependency parsed from a manifest, never the application itself
144
+ locs = [_rel_location(x, repo_root) for x in found_locations]
145
+ svc = None
146
+ if locs:
147
+ # a lockfile/manifest location decides the service; use the nearest ancestor service dir
148
+ svc = service_for_path(locs[0], service_dirs)
149
+ supplier = (c.get("supplier") or {}).get("name") if isinstance(c.get("supplier"), dict) else None
150
+ supplier = supplier or c.get("publisher") or (c.get("author") if isinstance(c.get("author"), str) else None)
151
+ own = bool(tool != "builtin" and not augmented and svc is not None and locs and locs[0] in {(f"{svc}/{m}" if svc != "." else m) for m in SELF_MANIFESTS})
152
+ result.append(Component(
153
+ bom_ref=c.get("bom-ref") or f"gen:{c['name']}@{c.get('version', '')}",
154
+ name=(pp["osv_name"] if pp and pp["ecosystem"] in ("npm", "Maven", "Go", "Packagist") else c["name"]),
155
+ version=c.get("version"), group=c.get("group"), type=c.get("type", "library"), purl=purl,
156
+ ecosystem=pp["ecosystem"] if pp else None, purl_type=pp["type"] if pp else None,
157
+ licenses=_licenses(c), supplier=supplier, cpe=c.get("cpe"),
158
+ hashes=[h for h in c.get("hashes", []) or [] if isinstance(h, dict)],
159
+ locations=locs, service_dir=svc, found_by=found_by, sources=[ad.NAME], is_self=own,
160
+ ))
161
+ return result
162
+
163
+
164
+ def load_sbom(path: str | Path) -> dict:
165
+ return json.loads(Path(path).read_text(encoding="utf-8"))
166
+
@@ -0,0 +1,153 @@
1
+ """Format-independent normalized inventory model and versioned SBOM exporters (CycloneDX 1.5, SPDX 2.3)."""
2
+ from __future__ import annotations
3
+
4
+ import uuid
5
+ from datetime import datetime, timezone
6
+ from pathlib import Path
7
+ from typing import Any, Literal, Optional
8
+
9
+ from pydantic import BaseModel, Field
10
+
11
+ from core.models import Component
12
+
13
+ OriginKind = Literal["declared", "resolved", "installed", "inferred", "scanner_discovered"]
14
+
15
+
16
+ def _tool_version() -> str:
17
+ try:
18
+ from stackparity import __version__
19
+ return __version__
20
+ except ImportError:
21
+ return "unknown"
22
+
23
+
24
+ def stored_sbom_path(result: dict, artifacts_dir: Path) -> Path:
25
+ """Resolve a persisted scan's generated CycloneDX file inside the configured SBOM store."""
26
+ raw = result.get("sbom_path")
27
+ if not isinstance(raw, str) or not raw:
28
+ raise FileNotFoundError("Scan has no stored SBOM")
29
+ path = Path(raw).resolve()
30
+ scan_id = (result.get("repo") or {}).get("scan_id")
31
+ if not isinstance(scan_id, str) or not path.name.startswith(scan_id + "-"):
32
+ raise FileNotFoundError("SBOM artifact does not belong to this scan")
33
+ if path.parent != (artifacts_dir / "sbom").resolve() or not path.name.endswith(".json") or not path.is_file():
34
+ raise FileNotFoundError("Stored SBOM unavailable in the configured artifact directory")
35
+ return path
36
+
37
+
38
+ class NormalizedComponent(BaseModel):
39
+ bom_ref: str
40
+ name: str
41
+ version: Optional[str] = None
42
+ ecosystem: Optional[str] = None
43
+ purl: Optional[str] = None
44
+ service_dir: str = "."
45
+ origin: OriginKind = "resolved"
46
+ dependency_role: str = "runtime" # runtime | development | optional
47
+ licenses: list[str] = Field(default_factory=list)
48
+ hashes: list[dict[str, str]] = Field(default_factory=list)
49
+ sources: list[str] = Field(default_factory=list)
50
+
51
+
52
+ class NormalizedInventory(BaseModel):
53
+ repo_name: str
54
+ commit_sha: str = ""
55
+ timestamp: str = Field(default_factory=lambda: datetime.now(timezone.utc).isoformat(timespec="seconds"))
56
+ components: list[NormalizedComponent] = Field(default_factory=list)
57
+ edges: list[tuple[str, str]] = Field(default_factory=list)
58
+
59
+
60
+ def from_components(
61
+ components: list[Component],
62
+ repo_name: str,
63
+ commit_sha: str = "",
64
+ sbom_doc: Optional[dict[str, Any]] = None,
65
+ ) -> NormalizedInventory:
66
+ """Build a format-independent NormalizedInventory from Component models."""
67
+ norm_comps: list[NormalizedComponent] = []
68
+ for c in components:
69
+ if c.is_self:
70
+ continue
71
+ origin: OriginKind = "resolved"
72
+ if not c.version:
73
+ origin = "declared"
74
+ elif c.resolution == "registry-resolved":
75
+ origin = "inferred"
76
+ elif any(s in (c.sources or []) for s in ("syft", "trivy")) and "lockfile" not in (c.sources or []):
77
+ origin = "scanner_discovered"
78
+ role = "development" if c.scope == "dev" else ("optional" if c.scope == "optional" else "runtime")
79
+ norm_comps.append(
80
+ NormalizedComponent(
81
+ bom_ref=c.bom_ref,
82
+ name=c.name,
83
+ version=c.version,
84
+ ecosystem=c.ecosystem,
85
+ purl=c.purl,
86
+ service_dir=c.service_dir or ".",
87
+ origin=origin,
88
+ dependency_role=role,
89
+ licenses=list(c.licenses or []),
90
+ hashes=list(c.hashes or []),
91
+ sources=list(c.sources or []),
92
+ )
93
+ )
94
+ edges: list[tuple[str, str]] = []
95
+ for d in (sbom_doc or {}).get("dependencies") or []:
96
+ ref = d.get("ref")
97
+ for tgt in d.get("dependsOn") or []:
98
+ if ref and tgt:
99
+ edges.append((ref, tgt))
100
+ return NormalizedInventory(repo_name=repo_name, commit_sha=commit_sha, components=norm_comps, edges=edges)
101
+
102
+
103
+ def to_spdx_json(inv: NormalizedInventory) -> dict[str, Any]:
104
+ """Export a NormalizedInventory as an SPDX 2.3 JSON document."""
105
+ doc_ns = f"https://stackparity.dev/spdx/{inv.repo_name}/{uuid.uuid4()}"
106
+ packages = []
107
+ rels = []
108
+ package_ids = {}
109
+ for idx, c in enumerate(inv.components, start=1):
110
+ spdx_id = f"SPDXRef-Package-{idx}"
111
+ pkg: dict[str, Any] = {
112
+ "SPDXID": spdx_id,
113
+ "name": c.name,
114
+ "downloadLocation": "NOASSERTION",
115
+ "filesAnalyzed": False,
116
+ "licenseConcluded": " AND ".join(c.licenses) if c.licenses else "NOASSERTION",
117
+ "licenseDeclared": " AND ".join(c.licenses) if c.licenses else "NOASSERTION",
118
+ "copyrightText": "NOASSERTION",
119
+ }
120
+ if c.version:
121
+ pkg["versionInfo"] = c.version
122
+ if c.purl:
123
+ pkg["externalRefs"] = [
124
+ {
125
+ "referenceCategory": "PACKAGE-MANAGER",
126
+ "referenceType": "purl",
127
+ "referenceLocator": c.purl,
128
+ }
129
+ ]
130
+ package_ids[c.bom_ref] = spdx_id
131
+ packages.append(pkg)
132
+ rels.append({
133
+ "spdxElementId": "SPDXRef-DOCUMENT",
134
+ "relationshipType": "DESCRIBES",
135
+ "relatedSpdxElement": spdx_id,
136
+ })
137
+ for parent, child in dict.fromkeys(inv.edges):
138
+ if parent in package_ids and child in package_ids:
139
+ rels.append({"spdxElementId": package_ids[parent], "relationshipType": "DEPENDS_ON",
140
+ "relatedSpdxElement": package_ids[child]})
141
+ return {
142
+ "spdxVersion": "SPDX-2.3",
143
+ "dataLicense": "CC0-1.0",
144
+ "SPDXID": "SPDXRef-DOCUMENT",
145
+ "name": inv.repo_name,
146
+ "documentNamespace": doc_ns,
147
+ "creationInfo": {
148
+ "created": inv.timestamp,
149
+ "creators": [f"Tool: stackparity-{_tool_version()}"],
150
+ },
151
+ "packages": packages,
152
+ "relationships": rels,
153
+ }
@@ -0,0 +1,5 @@
1
+ """Metadata fusion: field-level, provenance-tracked reconciliation of everything we know about each component.
2
+
3
+ Sources, in the order they are consulted (see ``engine.py``): lockfile (native) -> manifest -> SBOM scanner -> registry (deps.dev,
4
+ ecosystem registries). A value from a more trusted source is never overwritten; disagreements are recorded as conflicts.
5
+ """