Compare two CycloneDX 1.4-1.6 JSON SBOMs and report added, removed, upgraded, downgraded components and license changes by purl. Use when the user has two SBOMs, asks what a release changed, or wants a CI gate on dependency changes.
97%
Does it follow best practices?
Run evals on this skill
Adds up to 20 points to the overall score
Low
Low-risk findings worth noting
#!/usr/bin/env python3
"""Compare two CycloneDX 1.4-1.6 JSON SBOMs using only the standard library.
Usage:
python3 sbom_diff.py BASE.json HEAD.json [--format text|json] [--fail-on added,downgrade]
Components are matched by normalised package URL. Categories for --fail-on: added, removed,
upgrade, downgrade, changed, license. Exit codes: 0 nothing failing, 1 a --fail-on category is
not empty, 2 invalid input or flags. Everything runs on local files; there is no network access.
"""
from __future__ import annotations
import argparse
import json
import re
import sys
from collections.abc import Iterable
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Literal
from urllib.parse import unquote
ErrorCode = Literal["format", "unsupported_version", "too_large", "too_deep", "invalid_json"]
MAX_MESSAGE_LENGTH = 200
class SbomDiffError(Exception):
"""Base error of the library.
Attributes:
code: stable machine-readable error code.
"""
def __init__(self, code: ErrorCode, message: str) -> None:
if len(message) > MAX_MESSAGE_LENGTH:
limit = MAX_MESSAGE_LENGTH - 3
message = message[:limit] + "..."
super().__init__(message)
self.code: ErrorCode = code
def quote(value: object, limit: int = 60) -> str:
"""Return a short, safe representation of ``value`` for use in messages."""
if not isinstance(value, str):
return f"<{type(value).__name__}>"
suffix = "..." if len(value) > limit else ""
return repr(value[:limit]) + suffix
ChangeKind = Literal["upgrade", "downgrade", "changed"]
CATEGORIES: tuple[str, ...] = (
"added",
"removed",
"upgrade",
"downgrade",
"changed",
"license",
)
@dataclass(frozen=True)
class Component:
"""A dependency listed in an SBOM.
``key`` is the normalised identity used to match components across SBOMs.
"""
key: str
name: str
group: str = ""
version: str = ""
purl: str = ""
licenses: tuple[str, ...] = ()
@dataclass(frozen=True)
class ComponentEntry:
"""A component key present on only one side of the comparison.
``version`` is the comma-joined sorted set of versions seen for the key.
"""
key: str
version: str
licenses: tuple[str, ...] = ()
@dataclass(frozen=True)
class VersionChange:
"""A key present on both sides whose version set differs."""
key: str
before: str
after: str
kind: ChangeKind
@dataclass(frozen=True)
class LicenseChange:
"""A key present on both sides whose license set differs."""
key: str
before: tuple[str, ...]
after: tuple[str, ...]
@dataclass(frozen=True)
class SbomDiff:
"""The result of comparing two SBOMs; every list is sorted by key."""
added: list[ComponentEntry] = field(default_factory=list)
removed: list[ComponentEntry] = field(default_factory=list)
changed: list[VersionChange] = field(default_factory=list)
license_changes: list[LicenseChange] = field(default_factory=list)
def category_counts(self) -> dict[str, int]:
"""Return how many items each ``--fail-on`` category currently holds."""
return {
"added": len(self.added),
"removed": len(self.removed),
"upgrade": self._count("upgrade"),
"downgrade": self._count("downgrade"),
"changed": self._count("changed"),
"license": len(self.license_changes),
}
def _count(self, kind: ChangeKind) -> int:
return sum(1 for change in self.changed if change.kind == kind)
MAX_VERSION_LENGTH = 256
_IDENTIFIER = re.compile(r"[0-9A-Za-z-]+")
_PreKey = tuple[tuple[int, int, str], ...]
@dataclass(frozen=True)
class _Parsed:
release: tuple[int, ...]
pre: _PreKey
def _identifier_key(identifier: str) -> tuple[int, int, str]:
"""Numeric identifiers sort below alphanumeric ones and compare as numbers."""
if identifier.isdigit():
return (0, int(identifier), "")
return (1, 0, identifier)
def _parse(text: str) -> _Parsed | None:
if len(text) > MAX_VERSION_LENGTH:
raise SbomDiffError(
"too_large",
f"version is longer than {MAX_VERSION_LENGTH} characters",
)
value = text.strip()
if value[:1] in ("v", "V"):
value = value[1:]
value = value.split("+", 1)[0]
release, separator, pre = value.partition("-")
segments = release.split(".")
if not all(part.isascii() and part.isdigit() for part in segments):
return None
numbers = tuple(int(part) for part in segments)
if not separator:
return _Parsed(numbers, ())
identifiers = pre.split(".")
if not all(_IDENTIFIER.fullmatch(part) for part in identifiers):
return None
return _Parsed(numbers, tuple(_identifier_key(part) for part in identifiers))
def _sign(left: tuple[Any, ...], right: tuple[Any, ...]) -> int:
if left < right:
return -1
if left > right:
return 1
return 0
def _pad(values: tuple[int, ...], width: int) -> tuple[int, ...]:
return values + tuple(0 for _ in range(width - len(values)))
def compare_versions(a: str, b: str) -> int | None:
"""Compare two version strings.
A leading ``v`` and ``+build`` metadata are ignored. The release part must be dot-separated
digits (trailing zeros are padded, so ``1.2`` equals ``1.2.0``); a release with a pre-release
is lower than the same release without one, and pre-releases follow SemVer 2.0.0 section 11.
Returns:
-1, 0 or 1, or ``None`` when either version is not comparable.
Raises:
SbomDiffError: code ``too_large`` if a version is longer than 256 characters.
"""
left = _parse(a)
right = _parse(b)
if left is None or right is None:
return None
width = max(len(left.release), len(right.release))
result = _sign(_pad(left.release, width), _pad(right.release, width))
if result != 0:
return result
if not left.pre and not right.pre:
return 0
if not left.pre:
return 1
if not right.pre:
return -1
return _sign(left.pre, right.pre)
DEFAULT_MAX_BYTES = 52_428_800
MAX_COMPONENT_DEPTH = 32
MAX_COMPONENTS = 100_000
MAX_JSON_DEPTH = 128
SUPPORTED_SPEC_VERSIONS = ("1.4", "1.5", "1.6")
_TOKEN = re.compile("[" + re.escape('"[]{}') + "]")
_SEPARATORS = re.compile(r"[-_.]+")
def _string_end(text: str, start: int) -> int:
"""Return the index of the quote closing the string opened at ``start``, or -1."""
position = start + 1
while True:
position = text.find('"', position)
if position == -1:
return -1
backslashes = 0
while text[position - 1 - backslashes] == "\\":
backslashes += 1
if backslashes % 2 == 0:
return position
position += 1
def _check_json_depth(text: str) -> None:
"""Reject excessive bracket nesting iteratively, before the JSON parser can recurse."""
depth = 0
position = 0
while True:
match = _TOKEN.search(text, position)
if match is None:
return
index = match.start()
char = text[index]
if char == '"':
end = _string_end(text, index)
if end == -1:
return
position = end + 1
continue
position = index + 1
if char in "[{":
depth += 1
if depth > MAX_JSON_DEPTH:
raise SbomDiffError(
"too_deep",
f"JSON nesting exceeds {MAX_JSON_DEPTH} levels",
)
else:
depth -= 1
def _parse_purl(purl: str) -> tuple[str, str] | None:
"""Return ``(key, version)`` for a package URL, or ``None`` when it is not usable."""
text = purl.strip()
if text[:4].lower() != "pkg:":
return None
rest = text[4:].split("#", 1)[0].split("?", 1)[0].lstrip("/")
version = ""
at = rest.find("@", rest.rfind("/") + 1)
if at != -1:
start = at + 1
version = unquote(rest[start:])
rest = rest[:at]
segments = rest.split("/")
if len(segments) < 2:
return None
purl_type = segments[0].strip().lower()
name = unquote(segments[-1])
if not purl_type or not name:
return None
if purl_type == "pypi":
name = _SEPARATORS.sub("-", name).lower()
namespace = "/".join(unquote(part) for part in segments[1:-1] if part)
prefix = f"pkg:{purl_type}/"
key = f"{prefix}{namespace}/{name}" if namespace else f"{prefix}{name}"
return key, version
def _text_field(raw: dict[str, Any], field_name: str, *, required: bool = False) -> str:
value: object = raw.get(field_name)
if value is None:
text = ""
elif isinstance(value, str):
text = value
else:
raise SbomDiffError("format", f"component field {field_name!r} must be a string")
if required and not text:
raise SbomDiffError("format", f"component field {field_name!r} is required")
return text
def _licenses(raw: dict[str, Any]) -> tuple[str, ...]:
items: object = raw.get("licenses")
if items is None:
return ()
if not isinstance(items, list):
raise SbomDiffError("format", "component licenses must be an array")
found: set[str] = set()
for item in items:
if not isinstance(item, dict):
raise SbomDiffError("format", "license entries must be objects")
value: object = None
entry = item.get("license")
if isinstance(entry, dict):
value = entry.get("id") or entry.get("name")
if not value:
value = item.get("expression")
if isinstance(value, str) and value:
found.add(value)
return tuple(sorted(found))
def _build_component(raw: dict[str, Any]) -> Component:
name = _text_field(raw, "name", required=True)
group = _text_field(raw, "group")
version = _text_field(raw, "version")
purl = _text_field(raw, "purl")
parsed = _parse_purl(purl) if purl else None
if parsed is None:
key = f"{group}/{name}" if group else name
else:
key = parsed[0]
version = version or parsed[1]
if len(version) > MAX_VERSION_LENGTH:
raise SbomDiffError(
"too_large",
f"component version exceeds {MAX_VERSION_LENGTH} characters",
)
return Component(key, name, group, version, purl, _licenses(raw))
def _collect(top: list[Any]) -> list[Component]:
"""Flatten components and nested components iteratively, in document order."""
result: list[Component] = []
stack: list[tuple[object, int]] = [(item, 1) for item in reversed(top)]
while stack:
raw, level = stack.pop()
if level > MAX_COMPONENT_DEPTH:
raise SbomDiffError(
"too_deep",
f"components are nested deeper than {MAX_COMPONENT_DEPTH} levels",
)
if not isinstance(raw, dict):
raise SbomDiffError("format", "every component must be an object")
if len(result) >= MAX_COMPONENTS:
raise SbomDiffError("too_large", f"more than {MAX_COMPONENTS} components")
result.append(_build_component(raw))
children = raw.get("components")
if children is None:
continue
if not isinstance(children, list):
raise SbomDiffError("format", "nested components must be an array")
stack.extend((child, level + 1) for child in reversed(children))
return result
def _parse_document(document: object) -> list[Component]:
if not isinstance(document, dict):
raise SbomDiffError("format", "SBOM must be a JSON object")
bom_format = document.get("bomFormat")
if bom_format != "CycloneDX":
raise SbomDiffError(
"format",
f"bomFormat must be 'CycloneDX', got {quote(bom_format)}",
)
spec_version = document.get("specVersion")
if spec_version not in SUPPORTED_SPEC_VERSIONS:
raise SbomDiffError(
"unsupported_version",
f"unsupported specVersion {quote(spec_version)}; supported: 1.4, 1.5, 1.6",
)
top = document.get("components")
if top is None:
return []
if not isinstance(top, list):
raise SbomDiffError("format", "components must be an array")
return _collect(top)
def _read_path(path: Path, max_bytes: int) -> str:
try:
with path.open("rb") as handle:
data = handle.read(max_bytes + 1)
except OSError as exc:
raise SbomDiffError("format", "cannot read SBOM file") from exc
if len(data) > max_bytes:
raise SbomDiffError("too_large", f"SBOM file is larger than {max_bytes} bytes")
try:
return data.decode("utf-8")
except UnicodeDecodeError:
raise SbomDiffError("invalid_json", "SBOM file is not valid UTF-8") from None
def _read_text(text: str, max_bytes: int) -> str:
if len(text) > max_bytes or len(text.encode("utf-8", "surrogatepass")) > max_bytes:
raise SbomDiffError("too_large", f"SBOM text is larger than {max_bytes} bytes")
return text
def _read_source(source: Path | str, max_bytes: int) -> str:
if isinstance(source, Path):
return _read_path(source, max_bytes)
return _read_text(source, max_bytes)
def load_sbom(source: Path | str, *, max_bytes: int = DEFAULT_MAX_BYTES) -> list[Component]:
"""Load a CycloneDX 1.4-1.6 JSON SBOM and return its flattened components.
Args:
source: a ``Path`` to read, or a ``str`` holding the JSON text.
max_bytes: maximum size of the document in bytes (checked before parsing).
Components and nested components are flattened (at most 32 levels and 100,000 components);
``metadata.component`` is the subject of the SBOM and is never returned.
Raises:
SbomDiffError: ``format``, ``unsupported_version``, ``too_large``, ``too_deep`` or
``invalid_json``.
ValueError: if ``max_bytes`` is smaller than 1.
"""
if max_bytes < 1:
raise ValueError("max_bytes must be a positive integer")
text = _read_source(source, max_bytes)
_check_json_depth(text)
try:
document = json.loads(text.removeprefix("\ufeff"))
except RecursionError:
raise SbomDiffError("too_deep", "JSON nesting is too deep to parse") from None
except ValueError:
raise SbomDiffError("invalid_json", "document is not valid JSON") from None
return _parse_document(document)
_Index = dict[str, set[str]]
def _index(components: Iterable[Component]) -> tuple[_Index, _Index]:
versions: _Index = {}
licenses: _Index = {}
for component in components:
versions.setdefault(component.key, set()).add(component.version)
licenses.setdefault(component.key, set()).update(component.licenses)
return versions, licenses
def _join(versions: set[str]) -> str:
return ",".join(sorted(versions))
def _kind(before: set[str], after: set[str]) -> ChangeKind:
if len(before) == 1 and len(after) == 1:
result = compare_versions(next(iter(before)), next(iter(after)))
if result == -1:
return "upgrade"
if result == 1:
return "downgrade"
return "changed"
def _entries(keys: Iterable[str], versions: _Index, licenses: _Index) -> list[ComponentEntry]:
return [
ComponentEntry(key, _join(versions[key]), tuple(sorted(licenses[key])))
for key in sorted(keys)
]
def diff(base: Iterable[Component], head: Iterable[Component]) -> SbomDiff:
"""Compare the components of a base SBOM with those of a head SBOM.
Components are matched by ``Component.key``. A key with several versions on one side is a
version set: when the sets differ the change kind is ``changed`` and the versions are
reported comma-joined and sorted. Every list of the result is sorted by key.
Raises:
SbomDiffError: code ``too_large`` if a version exceeds 256 characters.
"""
base_versions, base_licenses = _index(base)
head_versions, head_licenses = _index(head)
added_keys = head_versions.keys() - base_versions.keys()
removed_keys = base_versions.keys() - head_versions.keys()
changed: list[VersionChange] = []
license_changes: list[LicenseChange] = []
for key in sorted(base_versions.keys() & head_versions.keys()):
before = base_versions[key]
after = head_versions[key]
if before != after:
kind = _kind(before, after)
changed.append(VersionChange(key, _join(before), _join(after), kind))
old_licenses = tuple(sorted(base_licenses[key]))
new_licenses = tuple(sorted(head_licenses[key]))
if old_licenses != new_licenses:
license_changes.append(LicenseChange(key, old_licenses, new_licenses))
return SbomDiff(
added=_entries(added_keys, head_versions, head_licenses),
removed=_entries(removed_keys, base_versions, base_licenses),
changed=changed,
license_changes=license_changes,
)
_NONE = "(none)"
def _clean(text: str) -> str:
"""Escape non-printable characters so SBOM data cannot forge report lines."""
return "".join(ch if ch.isprintable() else f"\\u{ord(ch):04x}" for ch in text)
def _label(text: str) -> str:
return _clean(text) if text else _NONE
def _license_text(values: tuple[str, ...]) -> str:
return ", ".join(_clean(value) for value in values) if values else _NONE
def _entry_line(marker: str, entry: ComponentEntry) -> str:
line = f" {marker} {_clean(entry.key)} {_label(entry.version)}"
if entry.licenses:
line += f" [{_license_text(entry.licenses)}]"
return line
def _change_line(marker: str, change: VersionChange) -> str:
return f" {marker} {_clean(change.key)} {_label(change.before)} -> {_label(change.after)}"
def _license_line(change: LicenseChange) -> str:
before = _license_text(change.before)
after = _license_text(change.after)
return f" ! {_clean(change.key)} {before} -> {after}"
def _render_text(result: SbomDiff) -> str:
lines: list[str] = []
def section(title: str, items: list[str]) -> None:
if items:
lines.append(f"{title} ({len(items)})")
lines.extend(items)
section("Added", [_entry_line("+", entry) for entry in result.added])
section("Removed", [_entry_line("-", entry) for entry in result.removed])
for title, kind, marker in (
("Upgraded", "upgrade", "^"),
("Downgraded", "downgrade", "v"),
("Changed", "changed", "~"),
):
section(title, [_change_line(marker, c) for c in result.changed if c.kind == kind])
section("License changes", [_license_line(change) for change in result.license_changes])
return "\n".join(lines) if lines else "No differences."
def _entry_dict(entry: ComponentEntry) -> dict[str, object]:
return {"key": entry.key, "licenses": list(entry.licenses), "version": entry.version}
def _render_json(result: SbomDiff) -> str:
payload: dict[str, object] = {
"added": [_entry_dict(entry) for entry in result.added],
"removed": [_entry_dict(entry) for entry in result.removed],
"changed": [
{"key": c.key, "before": c.before, "after": c.after, "kind": c.kind}
for c in result.changed
],
"license_changes": [
{"key": c.key, "before": list(c.before), "after": list(c.after)}
for c in result.license_changes
],
}
return json.dumps(payload, sort_keys=True, indent=2)
def render(result: SbomDiff, fmt: Literal["text", "json"]) -> str:
"""Render ``result`` as human-readable ``text`` or as ``json`` (sorted keys, indent 2).
The returned string has no trailing newline. Text output escapes control characters.
Raises:
ValueError: if ``fmt`` is neither ``text`` nor ``json``.
"""
if fmt == "text":
return _render_text(result)
if fmt == "json":
return _render_json(result)
raise ValueError("fmt must be 'text' or 'json'")
def _categories(value: str) -> tuple[str, ...]:
names = tuple(part.strip() for part in value.split(","))
for name in names:
if name not in CATEGORIES:
raise argparse.ArgumentTypeError(f"unknown category {quote(name)}")
return names
def _build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
prog="sbom-diff",
description="Compare two CycloneDX 1.4-1.6 JSON SBOMs.",
)
parser.add_argument("base", help="path of the base SBOM (JSON)")
parser.add_argument("head", help="path of the head SBOM (JSON)")
parser.add_argument(
"--format",
choices=("text", "json"),
default="text",
help="report format",
)
parser.add_argument(
"--fail-on",
type=_categories,
default=(),
metavar="CATEGORIES",
help="comma list of " + ", ".join(CATEGORIES) + "; exit 1 when one of them is non-empty",
)
return parser
def main(argv: list[str] | None = None) -> int:
"""Run the CLI and return the exit code: 0 ok, 1 failing category, 2 invalid input or flags."""
parser = _build_parser()
try:
args = parser.parse_args(argv)
except SystemExit as exc:
return exc.code if isinstance(exc.code, int) else 2
try:
result = diff(load_sbom(Path(args.base)), load_sbom(Path(args.head)))
except SbomDiffError as exc:
print(f"sbom-diff: error ({exc.code}): {exc}", file=sys.stderr)
return 2
print(render(result, args.format))
counts = result.category_counts()
return 1 if any(counts[name] for name in args.fail_on) else 0
if __name__ == "__main__":
sys.exit(main())