The user wants a "software supply-chain SBOM diff service."
This is a complex system with four distinct components:
Format Ingestion: Handling various SBOM formats (SPDX, CycloneDX, etc.).
Change Detection: Comparing two SBOMs (diffing) to find added, removed, or changed components (and versions/licenses).
Risk Scoring: Evaluating the impact of those changes (e.g., did a critical CVE get introduced? Did a license change from MIT to GPL?).
Notification Pipeline: Alerting stakeholders (Slack, Email, Webhook) about the results.
Architectural Approach:
I need to design a modular system. A monolithic script won't suffice for a robust "service," but for the purpose of a code example, a structured Python application with clear classes or functions is best. I will assume an API-driven approach (REST) for submitting SBOMs to compare.
Technology Stack:
Language: Python is the de facto standard for security tooling and data processing.
Libraries:
cyclonedx-python-lib or spdx-tools for parsing. (I'll try to keep it generic or focus on CycloneDX as it's very JSON-friendly).
json / dict for internal representation.
requests for external API calls (OSV/NVD for risk scoring).
fastapi or flask for the service wrapper.
Step-by-Step Design:
Ingestion & Normalization:
The input could be JSON or XML. Let's stick to JSON CycloneDX for simplicity in the example, but write the code to be adaptable.
Refining the Diff Logic:
Comparing lists of dictionaries can be tricky. Using a dictionary keyed by PURL (Package URL) is the most efficient way.
Map A: {purl: component}
Map B: {purl: component}
Iterate through keys.
If in A and not B -> Removed.
If in B and not A -> Added.
If in both -> Check Version/License.
Refining Risk Scoring:
Real-time vulnerability scanning against NVD is slow. For a demo, I should mock the API or use OSV's lightweight API, but put it behind an interface so it can be swapped for a cached database later.
License Risk: Simple allow/block list.
The Output:
I will provide a complete Python project structure.
Let's write the code mentally first.
DiffResult needs to carry added, removed, updated.
RiskResult needs to carry vulnerabilities, license_violations, score.
Self-Correction during thought process:
Issue: Real SBOMs are messy. Names might not match exactly if PURLs are missing.
Solution: I will enforce PURL requirements for the example to keep code readable, but note that fuzzy matching is needed in production.
Issue: Risk scoring usually requires a database lookup.
Solution: I'll implement a mock VulnerabilityProvider and a real OSVProvider so the user sees how it works without needing an API key immediately.
Final Plan:
Define the data models (Pydantic).
Implement the SBOMDiffer class.
Implement the RiskAnalyzer class.
Implement the NotificationDispatcher.
Wrap it all in a FastAPI app.
This covers all requirements: Ingestion, Diffing, Scoring, Notification.
Let's structure the response:
High-Level Architecture Diagram (Text-based)
Project Structure
Core Implementation (Python)
Testing/Usage Guide
This looks solid. I will write the code to be clean, type-hinted, and modular.
This is a comprehensive design and implementation for a Software Supply Chain SBOM Diff Service. This service monitors changes in your software dependencies (SBOMs), calculates the risk associated with those changes, and alerts your team.
I will use Python with FastAPI for the service, as Python has the best ecosystem for SBOM parsing (via cyclonedx-python-lib or spdx-tools) and vulnerability scanning (via osv or safety).
System Architecture
Ingestion: Accepts CycloneDX/SPDX files (JSON) via REST API.
Diff Engine: Normalizes components and performs a set-theory comparison (Added, Removed, Version Changed).
Risk Scorer: Queries vulnerability databases (like OSV) for the new components and checks for "High Risk" license changes (e.g., introduction of GPL).
Notification: Dispatches alerts to Slack/Webhook.
Project Structure
text
sbom-diff-service/
├── app/
│ ├── __init__.py
│ ├── main.py # FastAPI Entry point
│ ├── models.py # Pydantic models for data
│ ├── differ.py # Logic to compare SBOMs
│ ├── risk_scorer.py # Logic to score vulnerabilities
│ └── notifier.py # Logic to send alerts
├── Dockerfile
├── requirements.txt
└── README.md
Implementation
1. Dependencies (requirements.txt)
We need FastAPI for the web server, cyclonedx-python-lib for robust parsing, and httpx for external API calls.
from pydantic import BaseModel
from typing import List, Optional
from enum import Enum
class RiskLevel(str, Enum):
LOW = "LOW"
MEDIUM = "MEDIUM"
HIGH = "HIGH"
CRITICAL = "CRITICAL"
class ComponentChange(BaseModel):
name: str
purl: str # Package URL (unique identifier)
old_version: Optional[str] = None
new_version: Optional[str] = None
change_type: str # "ADDED", "REMOVED", "UPDATED"
class VulnerabilityInfo(BaseModel):
id: str
severity: float
description: str
class RiskAssessment(BaseModel):
score: float # 0.0 to 10.0
level: RiskLevel
vulnerabilities_found: List[VulnerabilityInfo]
license_violations: List[str]
class DiffReport(BaseModel):
added: List[ComponentChange]
removed: List[ComponentChange]
updated: List[ComponentChange]
risk: RiskAssessment
3. The Diff Engine (app/differ.py)
This module ingests raw JSON SBOMs and normalizes them. For this example, we focus on CycloneDX JSON format.
python
from cyclonedx.model.bom import Bom
from cyclonedx.parser import JsonParser
from .models import ComponentChange
def parse_sbom_to_components(json_data: dict) -> dict:
"""
Ingests CycloneDX JSON and returns a dict keyed by PURL (Package URL).
"""
# Note: In a real prod environment, handle strict validation here
parser = JsonParser(json_data)
bom = Bom.from_parser(parser=parser)
components = {}
for component in bom.components:
# Use PURL as the unique key; fallback to name+version if missing
key = component.purl if component.purl else f"{component.name}@{component.version}"
components[str(key)] = {
"name": component.name,
"version": component.version,
"purl": str(component.purl),
"license": component.licenses[0].expression if component.licenses else "UNKNOWN"
}
return components
def compute_diff(old_sbom: dict, new_sbom: dict) -> dict:
"""
Computes the difference between two SBOM dictionaries.
"""
old_comps = parse_sbom_to_components(old_sbom)
new_comps = parse_sbom_to_components(new_sbom)
old_keys = set(old_comps.keys())
new_keys = set(new_comps.keys())
# Set Theory Operations
added_keys = new_keys - old_keys
removed_keys = old_keys - new_keys
common_keys = old_keys & new_keys
changes = {
"added": [],
"removed": [],
"updated": []
}
# Added
for key in added_keys:
c = new_comps[key]
changes["added"].append(ComponentChange(
name=c['name'], purl=c['purl'], new_version=c['version'], change_type="ADDED"
))
# Removed
for key in removed_keys:
c = old_comps[key]
changes["removed"].append(ComponentChange(
name=c['name'], purl=c['purl'], old_version=c['version'], change_type="REMOVED"
))
# Updated (Version Check)
for key in common_keys:
old_c = old_comps[key]
new_c = new_comps[key]
if old_c['version'] != new_c['version']:
changes["updated"].append(ComponentChange(
name=old_c['name'],
purl=old_c['purl'],
old_version=old_c['version'],
new_version=new_c['version'],
change_type="UPDATED"
))
return changes
4. Risk Scoring (app/risk_scorer.py)
This module takes the changes and determines the risk. It simulates checking an external vulnerability DB (like OSV or Snyk) and checks for license compliance.
python
from .models import RiskAssessment, RiskLevel, VulnerabilityInfo, ComponentChange
import httpx
import os
# Example blocklist licenses
COPYLEFT_LICENSES = ["GPL-3.0", "GPL-2.0", "AGPL-3.0", "LGPL-2.1"]
async def analyze_risk(changes: dict) -> RiskAssessment:
vulnerabilities = []
license_issues = []
total_score = 0.0
# 1. Vulnerability Analysis (Focus on Added/Updated)
# In a real scenario, you query a database like OSV (osv.dev)
targets = changes['added'] + changes['updated']
async with httpx.AsyncClient() as client:
for item in targets:
# Mocking a query to a Vulnerability DB
# Real implementation: POST to https://api.osv.dev/v1/query
# Here we simulate finding a critical CVE in a specific package
if "lodash" in item.name and item.new_version == "4.17.15":
vuln = VulnerabilityInfo(
id="CVE-2021-23337",
severity=9.8,
description="Command Injection in lodash"
)
vulnerabilities.append(vuln)
total_score += 5.0
# 2. License Compliance
# Note: This requires accessing the parsed component data which we simplified in differ.py
# For this snippet, we assume license data is available in the changes or re-parsed.
# Let's simulate detecting a license violation.
# (Pseudo-code logic)
# for component in changes['added']:
# if component.license in COPYLEFT_LICENSES:
# license_issues.append(component.name)
# total_score += 2.0
# 3. Determine Level
level = RiskLevel.LOW
if total_score > 8: level = RiskLevel.CRITICAL
elif total_score > 5: level = RiskLevel.HIGH
elif total_score > 2: level = RiskLevel.MEDIUM
return RiskAssessment(
score=min(total_score, 10.0),
level=level,
vulnerabilities_found=vulnerabilities,
license_violations=license_issues
)
Ingest Initial SBOM (POST A):
Send a POST request to http://localhost:8000/api/v1/sbom/my-project with a CycloneDX JSON body containing express@4.17.0.
Ingest Updated SBOM (POST B):
Send a second POST request to the same URL with a CycloneDX JSON body containing express@4.18.0 and a new library lodash@4.17.15.
Result:
The API returns a JSON diff showing express updated and lodash added.
The risk_scorer detects lodash@4.17.15 (simulated CVE match).
The notifier sends a Slack alert warning of the High Risk change.