|
| 1 | +"""CycloneDX SBOM generation for ``.dryadepkg`` bundles. |
| 2 | +
|
| 3 | +The packager calls :func:`build_sbom` to produce a CycloneDX 1.5 JSON |
| 4 | +document describing the plugin and its declared dependencies. The SBOM |
| 5 | +is embedded in the ``.dryadepkg`` tarball as ``sbom.cdx.json`` next to |
| 6 | +``dryade.json``. |
| 7 | +
|
| 8 | +Two production paths: |
| 9 | +
|
| 10 | + 1. **Full SBOM**: ``cyclonedx-py`` shells out from the active venv and |
| 11 | + produces a complete CycloneDX 1.5 document from the plugin's |
| 12 | + ``pyproject.toml`` + installed deps. Falls back to (2) on any |
| 13 | + non-zero exit. |
| 14 | + 2. **Minimal shim**: a hand-built skeleton with just the component |
| 15 | + metadata. The shim is flagged in the SBOM's ``metadata.properties`` |
| 16 | + so consumers can tell a shim from a full SBOM. |
| 17 | +""" |
| 18 | + |
| 19 | +from __future__ import annotations |
| 20 | + |
| 21 | +import json |
| 22 | +import shutil |
| 23 | +import subprocess |
| 24 | +import tempfile |
| 25 | +from pathlib import Path |
| 26 | +from typing import Any |
| 27 | + |
| 28 | + |
| 29 | +def _minimal_shim(name: str, version: str) -> dict[str, Any]: |
| 30 | + """Return a CycloneDX 1.5-shaped doc with only the component metadata.""" |
| 31 | + return { |
| 32 | + "bomFormat": "CycloneDX", |
| 33 | + "specVersion": "1.5", |
| 34 | + "version": 1, |
| 35 | + "metadata": { |
| 36 | + "component": { |
| 37 | + "type": "library", |
| 38 | + "name": name, |
| 39 | + "version": version, |
| 40 | + "bom-ref": f"{name}@{version}", |
| 41 | + }, |
| 42 | + "properties": [ |
| 43 | + {"name": "dryade:sbom-source", "value": "minimal-shim"}, |
| 44 | + ], |
| 45 | + }, |
| 46 | + "components": [], |
| 47 | + } |
| 48 | + |
| 49 | + |
| 50 | +def _run_cyclonedx(pyproject_path: Path, output_path: Path) -> bool: |
| 51 | + """Run cyclonedx-py against a plugin's pyproject.toml. |
| 52 | +
|
| 53 | + Returns True on success (output file populated with a valid SBOM), |
| 54 | + False on any failure (caller should fall back to the minimal shim). |
| 55 | + """ |
| 56 | + cli = shutil.which("cyclonedx-py") |
| 57 | + if cli is None: |
| 58 | + return False |
| 59 | + cmd = [ |
| 60 | + cli, |
| 61 | + "poetry", # subcommand is moot for pure pyproject parse below; |
| 62 | + # but most cyclonedx-py builds accept `requirements` or `environment`. |
| 63 | + ] |
| 64 | + # cyclonedx-py 4+ has subcommands: poetry / requirements / environment. |
| 65 | + # Use `requirements -` to read from stdin would need a requirements |
| 66 | + # file; the cleanest path is `environment` against the active venv. |
| 67 | + cmd = [cli, "environment", "-o", str(output_path), "--output-format", "JSON"] |
| 68 | + try: |
| 69 | + proc = subprocess.run( |
| 70 | + cmd, |
| 71 | + cwd=pyproject_path.parent, |
| 72 | + capture_output=True, |
| 73 | + text=True, |
| 74 | + timeout=60, |
| 75 | + ) |
| 76 | + except (subprocess.TimeoutExpired, OSError): |
| 77 | + return False |
| 78 | + if proc.returncode != 0: |
| 79 | + return False |
| 80 | + if not output_path.exists() or output_path.stat().st_size == 0: |
| 81 | + return False |
| 82 | + # Sanity-check structure. |
| 83 | + try: |
| 84 | + doc = json.loads(output_path.read_text()) |
| 85 | + except (OSError, json.JSONDecodeError): |
| 86 | + return False |
| 87 | + if doc.get("bomFormat") != "CycloneDX": |
| 88 | + return False |
| 89 | + return True |
| 90 | + |
| 91 | + |
| 92 | +def build_sbom(plugin_dir: Path, name: str, version: str) -> dict[str, Any]: |
| 93 | + """Produce a CycloneDX SBOM dict for the plugin at ``plugin_dir``. |
| 94 | +
|
| 95 | + Tries the full ``cyclonedx-py`` path first; falls back to a minimal |
| 96 | + shim with a ``dryade:sbom-source = minimal-shim`` property so |
| 97 | + consumers can distinguish full vs shim at audit time. |
| 98 | +
|
| 99 | + Returns a dict ready to ``json.dumps``. |
| 100 | + """ |
| 101 | + pyproject = plugin_dir / "pyproject.toml" |
| 102 | + if pyproject.exists(): |
| 103 | + with tempfile.NamedTemporaryFile( |
| 104 | + "w", suffix=".cdx.json", delete=False, encoding="utf-8" |
| 105 | + ) as tmp: |
| 106 | + tmp_path = Path(tmp.name) |
| 107 | + try: |
| 108 | + if _run_cyclonedx(pyproject, tmp_path): |
| 109 | + try: |
| 110 | + doc = json.loads(tmp_path.read_text()) |
| 111 | + except (OSError, json.JSONDecodeError): |
| 112 | + doc = None |
| 113 | + if isinstance(doc, dict) and doc.get("bomFormat") == "CycloneDX": |
| 114 | + # Tag the doc so consumers can tell the source apart. |
| 115 | + meta = doc.setdefault("metadata", {}) |
| 116 | + props = meta.setdefault("properties", []) |
| 117 | + if not any( |
| 118 | + p.get("name") == "dryade:sbom-source" for p in props |
| 119 | + ): |
| 120 | + props.append( |
| 121 | + {"name": "dryade:sbom-source", "value": "cyclonedx-py"} |
| 122 | + ) |
| 123 | + return doc |
| 124 | + finally: |
| 125 | + try: |
| 126 | + tmp_path.unlink(missing_ok=True) |
| 127 | + except OSError: |
| 128 | + pass |
| 129 | + |
| 130 | + # Fallback path: minimal shim. |
| 131 | + return _minimal_shim(name, version) |
0 commit comments