Buckets:

download
raw
12.6 kB
"""
tests/security/test_sbom.py
Validates that a generated CycloneDX SBOM:
1. Is schema-compliant (has required top-level fields).
2. Contains every runtime dependency declared in pyproject.toml.
3. All components have a name and version.
These tests can run in two modes:
- With an existing sbom.cdx.json (generated by CI or manually).
- By invoking cyclonedx-bom on the fly (if installed).
If neither is available the tests that need a real SBOM are skipped.
"""
import json
import shutil
import subprocess
import sys
import tempfile
import tomllib
from pathlib import Path
import pytest
# ---------------------------------------------------------------------------
# Paths
# ---------------------------------------------------------------------------
REPO_ROOT = Path(__file__).resolve().parents[2]
PYPROJECT = REPO_ROOT / "pyproject.toml"
DEFAULT_SBOM_PATH = REPO_ROOT / "sbom.cdx.json"
OUTPUT_SBOM_PATH = REPO_ROOT / "dist" / "sbom.cdx.json"
# ---------------------------------------------------------------------------
# SBOM generation helper
# ---------------------------------------------------------------------------
def _generate_sbom(output_path: Path) -> bool:
"""
Generate a CycloneDX SBOM using cyclonedx-py CLI.
Returns True on success.
"""
cyclonedx = shutil.which("cyclonedx-py") or shutil.which("cyclonedx-bom")
if cyclonedx is None:
# Try the Python module path
result = subprocess.run(
[sys.executable, "-m", "cyclonedx_py.client", "--help"],
capture_output=True,
)
if result.returncode != 0:
return False
cyclonedx_cmd = [sys.executable, "-m", "cyclonedx_py.client"]
else:
cyclonedx_cmd = [cyclonedx]
result = subprocess.run(
cyclonedx_cmd
+ [
"environment",
"--of",
"json", # cyclonedx-py 7.x uses --of instead of --output-format
"--sv",
"1.5", # --sv instead of --schema-version
"-o",
str(output_path),
],
capture_output=True,
text=True,
)
return result.returncode == 0 and output_path.exists()
def _load_or_generate_sbom() -> tuple[dict | None, str]:
"""
Load an existing SBOM or generate one. Returns (sbom_dict, source_path).
Returns (None, reason) if unavailable.
"""
# Check existing outputs first
for candidate in [DEFAULT_SBOM_PATH, OUTPUT_SBOM_PATH]:
if candidate.exists():
try:
with open(candidate) as f:
return json.load(f), str(candidate)
except (json.JSONDecodeError, OSError):
pass
# Try generating on the fly
tmp = Path(tempfile.mktemp(suffix=".cdx.json"))
if _generate_sbom(tmp):
try:
with open(tmp) as f:
sbom = json.load(f)
# Save to outputs for subsequent tests
OUTPUT_SBOM_PATH.parent.mkdir(parents=True, exist_ok=True)
import shutil as _sh
_sh.copy(tmp, OUTPUT_SBOM_PATH)
return sbom, str(tmp)
except (json.JSONDecodeError, OSError):
pass
finally:
tmp.unlink(missing_ok=True)
return None, "cyclonedx-bom not available and no pre-generated sbom.cdx.json found"
# ---------------------------------------------------------------------------
# Fixtures
# ---------------------------------------------------------------------------
@pytest.fixture(scope="module")
def sbom() -> dict:
"""Load or generate the SBOM once for all tests in this module."""
data, source = _load_or_generate_sbom()
if data is None:
pytest.skip(f"SBOM not available: {source}")
return data
@pytest.fixture(scope="module")
def pyproject_runtime_deps() -> list[str]:
"""Parse the runtime dependency names from pyproject.toml."""
with open(PYPROJECT, "rb") as f:
cfg = tomllib.load(f)
deps = cfg.get("project", {}).get("dependencies", [])
names = []
for dep in deps:
# Extract package name: strip version specifiers and extras
# e.g. "openai>=1.3.0" -> "openai", "torch>=2.0.0" -> "torch"
name = dep.split(";")[0].strip() # drop markers
name = name.split(">=")[0].split("<=")[0].split("==")[0]
name = name.split(">")[0].split("<")[0].split("!=")[0]
name = name.split("[")[0].strip() # drop extras
# Normalize: lowercase, replace - with _
name = name.lower().replace("-", "_")
if name:
names.append(name)
return names
# ---------------------------------------------------------------------------
# Schema compliance tests
# ---------------------------------------------------------------------------
class TestSBOMSchemaCompliance:
"""The SBOM must conform to CycloneDX JSON schema."""
def test_bom_format_is_cyclonedx(self, sbom):
assert (
sbom.get("bomFormat") == "CycloneDX"
), f"bomFormat must be 'CycloneDX', got: {sbom.get('bomFormat')}"
def test_spec_version_present(self, sbom):
spec = sbom.get("specVersion")
assert spec is not None, "specVersion field is missing"
# Accept 1.4, 1.5, 1.6
major, minor = str(spec).split(".")[:2]
assert int(major) >= 1 and int(minor) >= 4, f"specVersion must be >= 1.4, got: {spec}"
def test_serial_number_present(self, sbom):
sn = sbom.get("serialNumber") or sbom.get("version")
assert sn is not None, "SBOM must have a serialNumber or version field"
def test_metadata_present(self, sbom):
assert "metadata" in sbom, "SBOM must have a metadata section"
def test_components_present(self, sbom):
comps = sbom.get("components", [])
assert len(comps) > 0, "SBOM must contain at least one component"
def test_components_have_name_and_version(self, sbom):
"""Every component must have a name; warn if version is missing."""
comps = sbom.get("components", [])
missing_name = [c for c in comps if not c.get("name")]
missing_version = [c.get("name") for c in comps if not c.get("version")]
assert len(missing_name) == 0, f"{len(missing_name)} components are missing a 'name' field"
if missing_version:
# This is a warning, not a failure — some components lack a published version
import warnings
warnings.warn(
f"{len(missing_version)} SBOM components are missing a version: "
f"{missing_version[:10]}{'...' if len(missing_version) > 10 else ''}",
stacklevel=2,
)
def test_components_have_type(self, sbom):
"""Components should declare their type."""
comps = sbom.get("components", [])
with_type = [c for c in comps if c.get("type")]
# At least 80% should have a type
if comps:
pct = len(with_type) / len(comps)
assert (
pct >= 0.5
), f"Only {pct:.0%} of SBOM components have a 'type' field (expected >= 50%)"
def test_sbom_validates_against_cyclonedx_schema(self, sbom):
"""The SBOM must validate against the official CycloneDX JSON schema.
Field-presence checks are not enough — this runs the SBOM through the
strict CycloneDX JSON schema validator bundled with cyclonedx-python-lib
(a dependency of cyclonedx-bom). This is the exit criterion:
"SBOM generates and validates against CycloneDX schema."
"""
try:
from cyclonedx.schema import SchemaVersion
from cyclonedx.validation.json import JsonStrictValidator
except ImportError:
pytest.skip("cyclonedx-python-lib not installed; install cyclonedx-bom")
spec = str(sbom.get("specVersion"))
version_map = {
"1.4": SchemaVersion.V1_4,
"1.5": SchemaVersion.V1_5,
"1.6": SchemaVersion.V1_6,
}
schema_version = version_map.get(spec)
assert schema_version is not None, f"Unsupported specVersion for validation: {spec}"
validator = JsonStrictValidator(schema_version)
errors = validator.validate_str(json.dumps(sbom))
assert errors is None, f"SBOM failed CycloneDX {spec} schema validation: {errors}"
# ---------------------------------------------------------------------------
# Dependency coverage tests
# ---------------------------------------------------------------------------
class TestSBOMDependencyCoverage:
"""The SBOM must cover all runtime dependencies from pyproject.toml."""
def test_sbom_covers_core_runtime_deps(self, sbom, pyproject_runtime_deps):
"""Core runtime deps from pyproject.toml must appear in the SBOM."""
comp_names = {
c["name"].lower().replace("-", "_") for c in sbom.get("components", []) if c.get("name")
}
# High-value deps we absolutely must track
critical_deps = [
"fastapi",
"pydantic",
"openai",
"requests",
"httpx",
"aiohttp",
"click",
"rich",
]
missing_critical = [d for d in critical_deps if d not in comp_names]
assert len(missing_critical) == 0, (
f"Critical deps missing from SBOM: {missing_critical}\n"
f"SBOM has {len(comp_names)} components"
)
def test_sbom_size_reasonable(self, sbom):
"""A real environment install should produce > 50 components."""
comps = sbom.get("components", [])
assert (
len(comps) >= 50
), f"SBOM has only {len(comps)} components — expected >= 50 for a full install"
def test_pyproject_deps_in_sbom(self, sbom, pyproject_runtime_deps):
"""At least 70% of pyproject runtime deps appear in the SBOM."""
comp_names = {
c["name"].lower().replace("-", "_") for c in sbom.get("components", []) if c.get("name")
}
present = [d for d in pyproject_runtime_deps if d in comp_names]
missing = [d for d in pyproject_runtime_deps if d not in comp_names]
coverage = len(present) / len(pyproject_runtime_deps) if pyproject_runtime_deps else 1.0
# Log which are missing for visibility
if missing:
import warnings
warnings.warn(
f"pyproject deps not in SBOM ({len(missing)}): {missing}",
stacklevel=2,
)
assert coverage >= 0.70, (
f"SBOM coverage of pyproject runtime deps is only {coverage:.0%} "
f"(missing: {missing})"
)
# ---------------------------------------------------------------------------
# Generation test — invoke cyclonedx-bom and check output
# ---------------------------------------------------------------------------
class TestSBOMGeneration:
"""Test that we can generate a fresh SBOM from the current environment."""
def test_cyclonedx_bom_installed(self):
"""cyclonedx-bom or cyclonedx-py must be importable."""
try:
import cyclonedx_py # noqa: F401
except ImportError:
try:
import cyclonedx # noqa: F401
except ImportError:
pytest.skip("cyclonedx_py not installed; install with: pip install cyclonedx-bom")
def test_generate_sbom_produces_valid_json(self, tmp_path):
"""Generate SBOM into a temp file and validate it's parseable."""
out = tmp_path / "test-sbom.cdx.json"
generated = _generate_sbom(out)
if not generated:
pytest.skip("cyclonedx-bom CLI not available")
assert out.exists(), "SBOM file was not created"
with open(out) as f:
sbom = json.load(f)
assert sbom.get("bomFormat") == "CycloneDX"
assert len(sbom.get("components", [])) > 0
def test_sbom_output_saved_to_build_outputs(self):
"""The SBOM output file must exist after generation."""
if not OUTPUT_SBOM_PATH.exists():
# Generate it now
OUTPUT_SBOM_PATH.parent.mkdir(parents=True, exist_ok=True)
success = _generate_sbom(OUTPUT_SBOM_PATH)
if not success:
pytest.skip("Could not generate SBOM — cyclonedx-bom not available")
assert OUTPUT_SBOM_PATH.exists(), f"SBOM output not found at {OUTPUT_SBOM_PATH}"
with open(OUTPUT_SBOM_PATH) as f:
sbom = json.load(f)
assert sbom.get("bomFormat") == "CycloneDX"

Xet Storage Details

Size:
12.6 kB
·
Xet hash:
8f3b578dfe24f67c6af92790847b32d12cbc4dffe72b4183523c81c2562c38e5

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.