Rust SBOM Guide for Cargo and Security Workflows
Quick Answer
For Rust projects, start withCargo.lock because it records the resolved crate versions that should appear in the SBOM. Use cargo-cyclonedx or a filesystem scanner such as Syft, then validate the CycloneDX or SPDX output with the SBOM Validator before attaching it to a release.
Introduction: Rust's Modern Approach to Dependencies
Rust's cargo package manager and crates.io ecosystem represent one of the most modern and well-designed dependency management systems in programming. Built with security and reproducibility in mind from the start, Cargo provides features like lock files, semantic versioning, and cryptographic verification by default. The crates.io registry, hosting over 130,000 packages, enforces strict naming conventions and immutability - once published, a crate version can never be changed, ensuring reproducible builds.
Rust's unique features create both opportunities and challenges for SBOM generation. The language's emphasis on zero-cost abstractions means extensive use of external crates for functionality that might be built-in elsewhere. It's common for a Rust project to have 100-200 dependencies, many providing compile-time functionality through macros and code generation. Additionally, Rust's powerful feature flag system allows conditional compilation, meaning different build configurations can result in vastly different dependency trees.
This guide covers the main tools and techniques for generating high-quality SBOMs for Rust applications, from simple CLI tools to larger services and containerized workloads. The goal is practical: capture Rust's build, dev, runtime, and feature-gated dependencies accurately, validate the result with the SBOM Validator, and use it in security and compliance workflows.Why SBOMs Matter for Rust Applications
The Complexity of Rust Dependencies
Rust's dependency model is more nuanced than most languages, with multiple dependency types serving different purposes in the build process. Understanding these distinctions is crucial for accurate SBOM generation, as each type has different security implications and may or may not be present in the final binary.
Rust applications typically include several categories of dependencies:
- Direct dependencies: Crates explicitly listed in
Cargo.tomlthat your code directly uses. These are version-constrained and form the primary API surface of your application. - Transitive dependencies: Dependencies of your dependencies, often making up 70-90% of your total dependency count. Cargo automatically resolves these using a sophisticated algorithm that ensures compatibility.
- Build dependencies: Tools and libraries needed only during compilation, such as code generators, bindgen for C interop, or procedural macro helpers. These don't appear in the final binary but can introduce supply chain risks.
- Development dependencies: Testing frameworks, benchmarking tools, and development utilities. While not deployed, these can access your source code and development environment.
- Target-specific dependencies: Platform-specific crates that are only included when building for certain operating systems or architectures. These create different SBOMs for different deployment targets.
- Feature-gated dependencies: Optional dependencies enabled by Cargo features, allowing users to customize functionality. A single crate might have dozens of possible dependency combinations.
Rust's focus on zero-cost abstractions means developers rely heavily on external crates for functionality, from basic data structures to complex async runtimes. This extensive use of dependencies, combined with Rust's growing adoption in critical infrastructure and security-sensitive applications, makes dependency tracking crucial for security and compliance. The recent memory safety initiatives by major organizations have increased scrutiny on Rust projects, making comprehensive SBOMs essential for demonstrating security posture.
Understanding Cargo Dependencies
The Foundation: Cargo.toml and Cargo.lock
Cargo's dependency management revolves around two key files that work together to provide both flexibility and reproducibility. TheCargo.toml manifest declares your project's dependencies with version constraints, while Cargo.lock records the exact versions resolved for reproducible builds. This two-file system balances the need for flexible version specifications with the requirement for deterministic builds.
Understanding how Cargo resolves dependencies is crucial for SBOM generation. Cargo uses a sophisticated resolution algorithm that considers version constraints, feature flags, and target platforms to build a dependency graph. This graph can change based on build configuration, making it important to generate SBOMs for each distinct build configuration you use.
Cargo.toml Structure
TheCargo.toml file is more than a simple dependency list - it's a comprehensive manifest that describes your project's metadata, dependencies, and build configuration:
[package]
name = "my-rust-app"
version = "0.1.0"
edition = "2021"
license = "MIT OR Apache-2.0"
authors = ["Your Name <you@example.com>"]
description = "A sample Rust application"
[dependencies]
# Runtime dependencies
tokio = { version = "1.0", features = ["full"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
reqwest = { version = "0.11", features = ["json"] }
clap = { version = "4.0", features = ["derive"] }
# Optional dependencies
redis = { version = "0.23", optional = true }
mongodb = { version = "2.0", optional = true }
[dev-dependencies]
# Development and testing dependencies
tokio-test = "0.4"
pretty_assertions = "1.0"
criterion = "0.5"
[build-dependencies]
# Build script dependencies
cc = "1.0"
pkg-config = "0.3"
[target.'cfg(unix)'.dependencies]
# Unix-specific dependencies
nix = "0.26"
[target.'cfg(windows)'.dependencies]
# Windows-specific dependencies
winapi = "0.3"
[features]
default = ["redis-cache"]
redis-cache = ["redis"]
mongo-storage = ["mongodb"]
full = ["redis-cache", "mongo-storage"]Cargo.lock File
TheCargo.lock file is Cargo's solution to reproducible builds, containing exact versions, source information, and cryptographic checksums for every dependency in your project. This file is automatically generated and updated by Cargo, and should be committed to version control for applications (but not for libraries). For SBOM generation, Cargo.lock is the authoritative source of what dependencies are actually used:
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "addr2line"
version = "0.20.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f4fa78e18c64fce05e902adecd7a5eed15a5e0a3439f7b0e169f0252214865e3"
dependencies = [
"gimli",
]SBOM Generation Tools
Choosing the Right Tool for Rust SBOMs
The Rust ecosystem offers several approaches to SBOM generation, each with different strengths. The primary tool is cargo-cyclonedx, which integrates directly with Cargo and understands Rust's dependency model. However, universal tools like Syft also provide excellent Rust support and can analyze both source code and compiled binaries.
cargo-cyclonedx - The Rust Standard
cargo-cyclonedx is the official CycloneDX plugin for Cargo, developed specifically for Rust projects. It leverages Cargo's metadata API to extract comprehensive dependency information, including features, targets, and build configurations. The tool's deep integration with Cargo ensures accurate representation of Rust's complex dependency model:
# Install cargo-cyclonedx
cargo install cargo-cyclonedx
# Generate SBOM for current project
cargo cyclonedx
# Generate specific format
cargo cyclonedx --format json --output sbom.json
cargo cyclonedx --format xml --output sbom.xml
# Generate for specific target
cargo cyclonedx --target x86_64-unknown-linux-gnu --output linux-sbom.jsonAdvanced cargo-cyclonedx Usage
Beyond basic SBOM generation, cargo-cyclonedx supports advanced scenarios common in Rust development. These include workspace management, feature flag combinations, and cross-compilation targets. Understanding these advanced features is essential for generating accurate SBOMs in complex Rust projects:
# Generate SBOM with specific features enabled
cargo cyclonedx --features "redis-cache,mongo-storage" --output featured-sbom.json
# Generate for workspace
cargo cyclonedx --workspace --output workspace-sbom.json
# Generate with all crate features enabled
cargo cyclonedx --all-features --output all-features-sbom.json
# Generate with default features disabled
cargo cyclonedx --no-default-features --output minimal-sbom.jsonSyft for Rust
Syft provides excellent Rust support:
# Install Syft
curl -sSfL https://get.anchore.io/syft | sh -s -- -b /usr/local/bin
# Generate SBOM from Rust project directory
syft dir:. -o cyclonedx-json=sbom.json
# Generate from Cargo.toml
syft rust-cargo:Cargo.toml -o cyclonedx-json=cargo-sbom.json
# Generate from compiled binary
syft rust-binary:target/release/my-app -o cyclonedx-json=binary-sbom.json
# Generate SPDX format
syft dir:. -o spdx-json=sbom.spdx.json
# Include all catalogers
syft dir:. --catalogers all -o cyclonedx-json=comprehensive-sbom.json
# Generate from Docker container with Rust app
syft docker:my-rust-app:latest -o cyclonedx-json=container-sbom.jsonCustom Rust SBOM Tools
Create custom tooling for specific needs:
// Custom SBOM generator using cargo metadata
use cargo_metadata::{MetadataCommand, Package};
use serde_json::{json, Value};
use std::collections::HashMap;
use std::fs;
#[derive(Debug)]
struct RustSBOM {
packages: Vec<Package>,
metadata: cargo_metadata::Metadata,
}
impl RustSBOM {
fn new() -> Result<Self, Box<dyn std::error::Error>> {
let metadata = MetadataCommand::new().exec()?;
let packages = metadata.packages.clone();
Ok(RustSBOM { packages, metadata })
}
fn to_cyclonedx(&self) -> Value {
let mut components = Vec::new();
for package in &self.packages {
// Skip workspace members (include only dependencies)
if self.metadata.workspace_members.contains(&package.id) {
continue;
}
let component = json!({
"type": "library",
"bom-ref": format!("{}@{}", package.name, package.version),
"name": package.name,
"version": package.version.to_string(),
"description": package.description,
"purl": format!("pkg:cargo/{}@{}", package.name, package.version),
"licenses": package.license.as_ref().map(|l| vec![json!({
"license": {
"name": l
}
})]),
"externalReferences": vec![
json!({
"type": "website",
"url": package.homepage.as_ref().or(package.repository.as_ref())
})
],
"properties": vec![
json!({
"name": "rust:edition",
"value": package.edition
}),
json!({
"name": "rust:keywords",
"value": package.keywords.join(",")
})
]
});
components.push(component);
}
json!({
"bomFormat": "CycloneDX",
"specVersion": "1.7",
"serialNumber": format!("urn:uuid:{}", uuid::Uuid::new_v4()),
"version": 1,
"metadata": {
"timestamp": chrono::Utc::now().to_rfc3339(),
"tools": [{
"vendor": "Custom",
"name": "rust-sbom-generator",
"version": "1.0.0"
}],
"component": {
"type": "application",
"name": self.metadata.root_package().map(|p| &p.name).unwrap_or(&"unknown".to_string()),
"version": self.metadata.root_package().map(|p| p.version.to_string()).unwrap_or_else(|| "0.0.0".to_string())
}
},
"components": components
})
}
fn save_to_file(&self, filename: &str) -> Result<(), Box<dyn std::error::Error>> {
let sbom = self.to_cyclonedx();
let json_string = serde_json::to_string_pretty(&sbom)?;
fs::write(filename, json_string)?;
Ok(())
}
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let sbom = RustSBOM::new()?;
sbom.save_to_file("custom-rust-sbom.json")?;
println!("SBOM generated successfully!");
println!("Packages analyzed: {}", sbom.packages.len());
Ok(())
}Cargo.toml:
[dependencies]
cargo_metadata = "0.18"
serde_json = "1.0"
uuid = { version = "1.0", features = ["v4"] }
chrono = { version = "0.4", features = ["serde"] }Framework-Specific Configurations
Axum Web Framework
// Axum application with SBOM endpoint
use axum::{
extract::Query,
http::StatusCode,
response::Json,
routing::{get, Router},
};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use tokio;
#[derive(Serialize, Deserialize)]
struct SBOMResponse {
available: bool,
sbom: Option<serde_json::Value>,
error: Option<String>,
}
#[derive(Deserialize)]
struct SBOMQuery {
format: Option<String>,
}
async fn sbom_handler(Query(params): Query<SBOMQuery>) -> Result<Json<SBOMResponse>, StatusCode> {
let format = params.format.unwrap_or_else(|| "json".to_string());
match format.as_str() {
"json" => {
match tokio::fs::read_to_string("sbom.json").await {
Ok(content) => {
match serde_json::from_str::<serde_json::Value>(&content) {
Ok(sbom) => Ok(Json(SBOMResponse {
available: true,
sbom: Some(sbom),
error: None,
})),
Err(_) => Ok(Json(SBOMResponse {
available: false,
sbom: None,
error: Some("Invalid SBOM format".to_string()),
})),
}
},
Err(_) => Ok(Json(SBOMResponse {
available: false,
sbom: None,
error: Some("SBOM not available".to_string()),
})),
}
},
_ => Err(StatusCode::BAD_REQUEST),
}
}
async fn health_handler() -> Json<HashMap<String, String>> {
let mut response = HashMap::new();
response.insert("status".to_string(), "healthy".to_string());
// Include SBOM availability in health check
if tokio::fs::metadata("sbom.json").await.is_ok() {
response.insert("sbom_available".to_string(), "true".to_string());
} else {
response.insert("sbom_available".to_string(), "false".to_string());
}
Json(response)
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/health", get(health_handler))
.route("/sbom", get(sbom_handler));
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
.await
.unwrap();
println!("Server running on http://0.0.0.0:3000");
println!("SBOM endpoint: http://0.0.0.0:3000/sbom");
axum::serve(listener, app).await.unwrap();
}Actix Web Framework
use actix_web::{web, App, HttpResponse, HttpServer, Result};
use serde_json::{json, Value};
use std::fs;
async fn sbom_handler() -> Result<HttpResponse> {
match fs::read_to_string("sbom.json") {
Ok(content) => {
match serde_json::from_str::<Value>(&content) {
Ok(sbom) => Ok(HttpResponse::Ok().json(json!({
"available": true,
"sbom": sbom
}))),
Err(_) => Ok(HttpResponse::InternalServerError().json(json!({
"available": false,
"error": "Invalid SBOM format"
}))),
}
},
Err(_) => Ok(HttpResponse::NotFound().json(json!({
"available": false,
"error": "SBOM not available"
}))),
}
}
async fn sbom_info_handler() -> Result<HttpResponse> {
match fs::read_to_string("sbom.json") {
Ok(content) => {
match serde_json::from_str::<Value>(&content) {
Ok(sbom) => {
let components_count = sbom["components"]
.as_array()
.map(|arr| arr.len())
.unwrap_or(0);
Ok(HttpResponse::Ok().json(json!({
"available": true,
"component_count": components_count,
"spec_version": sbom["specVersion"],
"bom_format": sbom["bomFormat"]
})))
},
Err(_) => Ok(HttpResponse::InternalServerError().json(json!({
"error": "Invalid SBOM format"
}))),
}
},
Err(_) => Ok(HttpResponse::NotFound().json(json!({
"available": false,
"error": "SBOM not available"
}))),
}
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
App::new()
.route("/sbom", web::get().to(sbom_handler))
.route("/sbom/info", web::get().to(sbom_info_handler))
})
.bind("127.0.0.1:8080")?
.run()
.await
}Warp Web Framework
use warp::{Filter, Reply};
use serde_json::{json, Value};
use std::fs;
async fn sbom_handler() -> Result<impl Reply, warp::Rejection> {
match fs::read_to_string("sbom.json") {
Ok(content) => {
match serde_json::from_str::<Value>(&content) {
Ok(sbom) => Ok(warp::reply::json(&json!({
"available": true,
"sbom": sbom
}))),
Err(_) => Ok(warp::reply::json(&json!({
"available": false,
"error": "Invalid SBOM format"
}))),
}
},
Err(_) => Ok(warp::reply::json(&json!({
"available": false,
"error": "SBOM not available"
}))),
}
}
#[tokio::main]
async fn main() {
let sbom_route = warp::path("sbom")
.and(warp::get())
.and_then(sbom_handler);
let routes = sbom_route;
println!("Server running on http://127.0.0.1:3030");
warp::serve(routes)
.run(([127, 0, 0, 1], 3030))
.await;
}CLI Applications with Clap
use clap::{Arg, Command, ArgMatches};
use serde_json::Value;
use std::fs;
fn sbom_command() -> Command {
Command::new("sbom")
.about("Display Software Bill of Materials")
.arg(
Arg::new("format")
.short('f')
.long("format")
.value_name("FORMAT")
.help("Output format (json, summary)")
.default_value("json")
)
.arg(
Arg::new("pretty")
.short('p')
.long("pretty")
.help("Pretty print JSON output")
.action(clap::ArgAction::SetTrue)
)
}
fn handle_sbom_command(matches: &ArgMatches) -> Result<(), Box<dyn std::error::Error>> {
let format = matches.get_one::<String>("format").unwrap();
let pretty = matches.get_flag("pretty");
let content = fs::read_to_string("sbom.json")
.map_err(|_| "SBOM file not found. Generate SBOM first with 'cargo cyclonedx'")?;
let sbom: Value = serde_json::from_str(&content)
.map_err(|_| "Invalid SBOM format")?;
match format.as_str() {
"json" => {
if pretty {
println!("{}", serde_json::to_string_pretty(&sbom)?);
} else {
println!("{}", content);
}
},
"summary" => {
print_sbom_summary(&sbom)?;
},
_ => return Err("Unsupported format".into()),
}
Ok(())
}
fn print_sbom_summary(sbom: &Value) -> Result<(), Box<dyn std::error::Error>> {
println!("SBOM Summary");
println!("============");
if let Some(metadata) = sbom.get("metadata") {
if let Some(component) = metadata.get("component") {
if let Some(name) = component.get("name") {
println!("Application: {}", name.as_str().unwrap_or("Unknown"));
}
if let Some(version) = component.get("version") {
println!("Version: {}", version.as_str().unwrap_or("Unknown"));
}
}
if let Some(timestamp) = metadata.get("timestamp") {
println!("Generated: {}", timestamp.as_str().unwrap_or("Unknown"));
}
}
if let Some(components) = sbom.get("components").and_then(|c| c.as_array()) {
println!("Dependencies: {}", components.len());
// Count by license
let mut license_counts = std::collections::HashMap::new();
for component in components {
if let Some(licenses) = component.get("licenses").and_then(|l| l.as_array()) {
for license in licenses {
if let Some(license_obj) = license.get("license") {
let license_name = license_obj.get("name")
.or_else(|| license_obj.get("id"))
.and_then(|l| l.as_str())
.unwrap_or("Unknown");
*license_counts.entry(license_name.to_string()).or_insert(0) += 1;
}
}
}
}
if !license_counts.is_empty() {
println!("\nLicense Distribution:");
for (license, count) in license_counts {
println!(" {}: {}", license, count);
}
}
}
Ok(())
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let app = Command::new("my-rust-app")
.version("1.0.0")
.about("A Rust application with SBOM support")
.subcommand(sbom_command());
let matches = app.get_matches();
match matches.subcommand() {
Some(("sbom", sub_matches)) => handle_sbom_command(sub_matches),
_ => {
println!("Running main application...");
// Main application logic here
Ok(())
}
}
}CI/CD Integration
GitHub Actions
name: Rust SBOM Generation
on:
push:
branches: [main, develop]
pull_request:
branches: [main]
env:
CARGO_TERM_COLOR: always
jobs:
build-and-sbom:
runs-on: ubuntu-latest
strategy:
matrix:
rust-version: [stable, beta, nightly]
target:
- x86_64-unknown-linux-gnu
- x86_64-pc-windows-gnu
- x86_64-apple-darwin
- aarch64-unknown-linux-gnu
exclude:
# Exclude some combinations to reduce matrix size
- rust-version: beta
target: x86_64-pc-windows-gnu
- rust-version: nightly
target: x86_64-apple-darwin
steps:
- uses: actions/checkout@v4
- name: Setup Rust ${{ matrix.rust-version }}
uses: dtolnay/rust-toolchain@master
with:
toolchain: ${{ matrix.rust-version }}
targets: ${{ matrix.target }}
- name: Cache cargo registry
uses: actions/cache@v4
with:
path: |
~/.cargo/registry
~/.cargo/git
target
key: ${{ runner.os }}-cargo-${{ matrix.rust-version }}-${{ hashFiles('**/Cargo.lock') }}
restore-keys: |
${{ runner.os }}-cargo-${{ matrix.rust-version }}-
- name: Install cargo-cyclonedx
run: cargo install cargo-cyclonedx --locked
- name: Install additional tools
run: |
# Install Syft
curl -sSfL https://get.anchore.io/syft | sh -s -- -b /usr/local/bin
# Install security audit tools
cargo install cargo-audit --locked
cargo install cargo-deny --locked
- name: Check code formatting
if: matrix.rust-version == 'stable'
run: cargo fmt --all -- --check
- name: Run clippy
run: cargo clippy --all-targets --all-features -- -D warnings
- name: Run tests
run: cargo test --verbose --all-features
- name: Build for target
run: cargo build --release --target ${{ matrix.target }}
- name: Generate SBOM with cargo-cyclonedx
run: |
# Generate basic SBOM
cargo cyclonedx --format json --output sbom-${{ matrix.target }}.json
# Generate XML format
cargo cyclonedx --format xml --output sbom-${{ matrix.target }}.xml
- name: Generate SBOM with Syft
run: |
# Generate from source directory
syft dir:. -o cyclonedx-json=syft-source-${{ matrix.target }}.json
# Generate from built binary (if exists)
if [ -f "target/${{ matrix.target }}/release/my-rust-app" ]; then
syft rust-binary:target/${{ matrix.target }}/release/my-rust-app \
-o cyclonedx-json=syft-binary-${{ matrix.target }}.json
fi
- name: Security audit
run: |
# Cargo audit for known vulnerabilities
cargo audit --json --output audit-report-${{ matrix.target }}.json || true
# Cargo deny for license and security policy checking
cargo deny check --format json 2> deny-report-${{ matrix.target }}.json || true
- name: Validate SBOMs
run: |
# Validate JSON format
jq empty sbom-${{ matrix.target }}.json
jq empty sbom-complete-${{ matrix.target }}.json
# Basic SBOM analysis
echo "Components in basic SBOM: $(jq '.components | length' sbom-${{ matrix.target }}.json)"
echo "Components in complete SBOM: $(jq '.components | length' sbom-complete-${{ matrix.target }}.json)"
# License analysis
jq -r '.components[]?.licenses[]?.license.name // .components[]?.licenses[]?.license.id // "Unknown"' \
sbom-complete-${{ matrix.target }}.json | sort | uniq -c | sort -nr > license-summary-${{ matrix.target }}.txt
echo "License distribution:"
cat license-summary-${{ matrix.target }}.txt
- name: Security scanning with Grype
run: |
# Install Grype
curl -sSfL https://raw.githubusercontent.com/anchore/grype/main/install.sh | sh -s -- -b /usr/local/bin
# Scan SBOM for vulnerabilities
grype sbom-complete-${{ matrix.target }}.json -o table || true
grype sbom-complete-${{ matrix.target }}.json -o json --file grype-results-${{ matrix.target }}.json || true
# Scan binary directly if available
if [ -f "target/${{ matrix.target }}/release/my-rust-app" ]; then
grype target/${{ matrix.target }}/release/my-rust-app -o table || true
fi
- name: Upload SBOM artifacts
uses: actions/upload-artifact@v4
with:
name: sbom-${{ matrix.rust-version }}-${{ matrix.target }}
path: |
sbom-*.json
sbom-*.xml
syft-*.json
audit-report-*.json
deny-report-*.json
grype-results-*.json
license-summary-*.txt
retention-days: 30
- name: Create GitHub Release with SBOMs
if: github.event_name == 'push' && github.ref == 'refs/heads/main' && matrix.rust-version == 'stable'
uses: softprops/action-gh-release@v1
with:
tag_name: v${{ github.run_number }}
name: Release v${{ github.run_number }}
files: |
target/${{ matrix.target }}/release/my-rust-app*
sbom-*.json
sbom-*.xml
draft: true
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
aggregate-security-report:
needs: build-and-sbom
runs-on: ubuntu-latest
if: always()
steps:
- name: Download all artifacts
uses: actions/download-artifact@v4
- name: Aggregate security analysis
run: |
echo "# Security Analysis Summary" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
# Aggregate vulnerability counts
total_vulns=0
critical_vulns=0
high_vulns=0
for file in */grype-results-*.json; do
if [ -f "$file" ]; then
target=$(basename "$file" | sed 's/grype-results-//' | sed 's/.json//')
vulns=$(jq '.matches | length' "$file" 2>/dev/null || echo "0")
critical=$(jq '.matches[] | select(.vulnerability.severity == "Critical") | length' "$file" 2>/dev/null | wc -l)
high=$(jq '.matches[] | select(.vulnerability.severity == "High") | length' "$file" 2>/dev/null | wc -l)
echo "## $target" >> $GITHUB_STEP_SUMMARY
echo "- Total vulnerabilities: $vulns" >> $GITHUB_STEP_SUMMARY
echo "- Critical: $critical" >> $GITHUB_STEP_SUMMARY
echo "- High: $high" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
total_vulns=$((total_vulns + vulns))
critical_vulns=$((critical_vulns + critical))
high_vulns=$((high_vulns + high))
fi
done
echo "## Overall Summary" >> $GITHUB_STEP_SUMMARY
echo "- Total vulnerabilities across all targets: $total_vulns" >> $GITHUB_STEP_SUMMARY
echo "- Critical vulnerabilities: $critical_vulns" >> $GITHUB_STEP_SUMMARY
echo "- High vulnerabilities: $high_vulns" >> $GITHUB_STEP_SUMMARY
# Fail if critical vulnerabilities found
if [ "$critical_vulns" -gt 0 ]; then
echo "❌ Critical vulnerabilities found!" >> $GITHUB_STEP_SUMMARY
exit 1
fiGitLab CI
stages:
- test
- build
- sbom
- security
- deploy
variables:
RUST_VERSION: "1.75.0"
CARGO_HOME: $CI_PROJECT_DIR/.cargo
cache:
paths:
- .cargo/
- target/
.rust_template: &rust_template
image: rust:${RUST_VERSION}
before_script:
- rustc --version
- cargo --version
- rustup component add rustfmt clippy
test:
<<: *rust_template
stage: test
script:
- cargo fmt --all -- --check
- cargo clippy --all-targets --all-features -- -D warnings
- cargo test --verbose --all-features
artifacts:
reports:
junit: target/junit.xml
expire_in: 1 hour
build:
<<: *rust_template
stage: build
parallel:
matrix:
- TARGET:
- x86_64-unknown-linux-gnu
- x86_64-unknown-linux-musl
- aarch64-unknown-linux-gnu
script:
- rustup target add $TARGET
- cargo build --release --target $TARGET
artifacts:
paths:
- target/$TARGET/release/
expire_in: 1 day
generate-sbom:
<<: *rust_template
stage: sbom
dependencies:
- build
before_script:
- cargo install cargo-cyclonedx --locked
- curl -sSfL https://get.anchore.io/syft | sh -s -- -b /usr/local/bin
- apt-get update && apt-get install -y jq
parallel:
matrix:
- TARGET:
- x86_64-unknown-linux-gnu
- x86_64-unknown-linux-musl
- aarch64-unknown-linux-gnu
script:
# Generate SBOMs with cargo-cyclonedx
- cargo cyclonedx --format json --output sbom-${TARGET}.json
- cargo cyclonedx --format xml --output sbom-${TARGET}.xml
# Generate SBOMs with Syft
- syft dir:. -o cyclonedx-json=syft-source-${TARGET}.json
- |
if [ -f "target/${TARGET}/release/my-rust-app" ]; then
syft rust-binary:target/${TARGET}/release/my-rust-app \
-o cyclonedx-json=syft-binary-${TARGET}.json
fi
# Validate SBOMs
- jq empty sbom-${TARGET}.json
- jq empty sbom-complete-${TARGET}.json
# Generate summary
- echo "Target: ${TARGET}" > sbom-summary-${TARGET}.txt
- echo "Basic SBOM components: $(jq '.components | length' sbom-${TARGET}.json)" >> sbom-summary-${TARGET}.txt
- echo "Complete SBOM components: $(jq '.components | length' sbom-complete-${TARGET}.json)" >> sbom-summary-${TARGET}.txt
# License analysis
- |
jq -r '.components[]?.licenses[]?.license.name // .components[]?.licenses[]?.license.id // "Unknown"' \
sbom-complete-${TARGET}.json | sort | uniq -c | sort -nr > license-analysis-${TARGET}.txt
echo "License distribution for ${TARGET}:"
cat license-analysis-${TARGET}.txt
artifacts:
paths:
- sbom-*.json
- sbom-*.xml
- syft-*.json
- sbom-summary-*.txt
- license-analysis-*.txt
reports:
cyclonedx: sbom-*.json
expire_in: 1 week
security-audit:
<<: *rust_template
stage: security
dependencies:
- generate-sbom
before_script:
- cargo install cargo-audit cargo-deny --locked
- curl -sSfL https://raw.githubusercontent.com/anchore/grype/main/install.sh | sh -s -- -b /usr/local/bin
- apt-get update && apt-get install -y jq
parallel:
matrix:
- TARGET:
- x86_64-unknown-linux-gnu
- x86_64-unknown-linux-musl
- aarch64-unknown-linux-gnu
script:
# Cargo audit for vulnerabilities
- cargo audit --json --output audit-${TARGET}.json || true
# Cargo deny for policy checking
- cargo deny check --format json 2> deny-${TARGET}.json || true
# Grype vulnerability scanning
- grype sbom-complete-${TARGET}.json -o table || true
- grype sbom-complete-${TARGET}.json -o json --file grype-${TARGET}.json || true
# Generate security summary
- |
echo "Security Audit Summary for ${TARGET}" > security-summary-${TARGET}.txt
echo "====================================" >> security-summary-${TARGET}.txt
# Audit results
if [ -f "audit-${TARGET}.json" ]; then
AUDIT_VULNS=$(jq '.vulnerabilities.found | length' audit-${TARGET}.json 2>/dev/null || echo "0")
echo "Cargo audit vulnerabilities: $AUDIT_VULNS" >> security-summary-${TARGET}.txt
fi
# Grype results
if [ -f "grype-${TARGET}.json" ]; then
GRYPE_VULNS=$(jq '.matches | length' grype-${TARGET}.json 2>/dev/null || echo "0")
CRITICAL=$(jq '.matches[] | select(.vulnerability.severity == "Critical") | length' grype-${TARGET}.json 2>/dev/null | wc -l)
HIGH=$(jq '.matches[] | select(.vulnerability.severity == "High") | length' grype-${TARGET}.json 2>/dev/null | wc -l)
echo "Grype vulnerabilities: $GRYPE_VULNS" >> security-summary-${TARGET}.txt
echo "Critical: $CRITICAL" >> security-summary-${TARGET}.txt
echo "High: $HIGH" >> security-summary-${TARGET}.txt
fi
cat security-summary-${TARGET}.txt
artifacts:
paths:
- audit-*.json
- deny-*.json
- grype-*.json
- security-summary-*.txt
expire_in: 1 week
allow_failure: true
deploy:
stage: deploy
image: alpine:latest
dependencies:
- build
- generate-sbom
- security-audit
before_script:
- apk add --no-cache curl jq
script:
- echo "Deploying application with SBOMs..."
# Upload SBOMs to artifact repository
- |
for sbom in sbom-*.json; do
if [ -f "$sbom" ]; then
echo "Uploading $sbom to artifact repository"
curl -X POST \
-H "Authorization: Bearer $ARTIFACT_REPO_TOKEN" \
-F "file=@$sbom" \
-F "project=$CI_PROJECT_NAME" \
-F "version=$CI_COMMIT_SHA" \
"$ARTIFACT_REPO_URL/api/v1/sbom"
fi
done
# Deploy application (your deployment logic here)
- echo "Application deployed successfully"
only:
- main
environment:
name: productionJenkins Pipeline
pipeline {
agent any
environment {
RUST_VERSION = '1.75.0'
CARGO_HOME = "${WORKSPACE}/.cargo"
PATH = "${CARGO_HOME}/bin:${PATH}"
}
parameters {
choice(
name: 'BUILD_TARGETS',
choices: [
'x86_64-unknown-linux-gnu',
'x86_64-unknown-linux-musl',
'aarch64-unknown-linux-gnu',
'x86_64-pc-windows-gnu',
'x86_64-apple-darwin'
],
description: 'Target architectures to build'
)
}
stages {
stage('Setup Rust') {
steps {
sh '''
# Install Rust if not present
if ! command -v rustc &> /dev/null; then
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain ${RUST_VERSION}
source $HOME/.cargo/env
fi
# Add target
rustup target add ${BUILD_TARGETS}
# Install required tools
cargo install cargo-cyclonedx cargo-audit cargo-deny --locked
# Install Syft
curl -sSfL https://get.anchore.io/syft | sh -s -- -b ${WORKSPACE}/bin
# Install Grype
curl -sSfL https://raw.githubusercontent.com/anchore/grype/main/install.sh | sh -s -- -b ${WORKSPACE}/bin
export PATH="${WORKSPACE}/bin:$PATH"
'''
}
}
stage('Code Quality') {
parallel {
stage('Format Check') {
steps {
sh 'cargo fmt --all -- --check'
}
}
stage('Clippy') {
steps {
sh 'cargo clippy --all-targets --all-features -- -D warnings'
}
}
stage('Tests') {
steps {
sh 'cargo test --verbose --all-features'
}
post {
always {
// Publish test results if using a test reporter
publishTestResults testResultsPattern: 'target/junit.xml'
}
}
}
}
}
stage('Build') {
steps {
script {
def targets = params.BUILD_TARGETS.split(',')
def builds = [:]
targets.each { target ->
builds[target.trim()] = {
sh """
rustup target add ${target.trim()}
cargo build --release --target ${target.trim()}
"""
}
}
parallel builds
}
}
}
stage('Generate SBOMs') {
steps {
script {
def targets = params.BUILD_TARGETS.split(',')
targets.each { target ->
target = target.trim()
sh """
export PATH="${WORKSPACE}/bin:\$PATH"
echo "Generating SBOMs for ${target}"
# cargo-cyclonedx SBOMs
cargo cyclonedx --format json --output sbom-${target}.json
cargo cyclonedx --format xml --output sbom-${target}.xml
# Syft SBOMs
syft dir:. -o cyclonedx-json=syft-source-${target}.json
if [ -f "target/${target}/release/my-rust-app" ]; then
syft rust-binary:target/${target}/release/my-rust-app \\
-o cyclonedx-json=syft-binary-${target}.json
fi
# Validate SBOMs
jq empty sbom-${target}.json
jq empty sbom-complete-${target}.json
# Generate statistics
echo "SBOM Statistics for ${target}:" > sbom-stats-${target}.txt
echo "Basic components: \$(jq '.components | length' sbom-${target}.json)" >> sbom-stats-${target}.txt
echo "Complete components: \$(jq '.components | length' sbom-complete-${target}.json)" >> sbom-stats-${target}.txt
"""
}
}
}
}
stage('Security Analysis') {
steps {
script {
def targets = params.BUILD_TARGETS.split(',')
targets.each { target ->
target = target.trim()
sh """
export PATH="${WORKSPACE}/bin:\$PATH"
echo "Security analysis for ${target}"
# Cargo audit
cargo audit --json --output audit-${target}.json || true
# Cargo deny
cargo deny check --format json 2> deny-${target}.json || true
# Grype scanning
grype sbom-complete-${target}.json -o table || true
grype sbom-complete-${target}.json -o json --file grype-${target}.json || true
# Generate security report
cat > security-report-${target}.txt << EOF
Security Report for ${target}
============================
Cargo Audit:
\$(if [ -f audit-${target}.json ]; then jq -r '.vulnerabilities.found | length' audit-${target}.json 2>/dev/null || echo "0"; else echo "No data"; fi) vulnerabilities found
Grype Scan:
\$(if [ -f grype-${target}.json ]; then jq -r '.matches | length' grype-${target}.json 2>/dev/null || echo "0"; else echo "No data"; fi) vulnerabilities found
Critical: \$(if [ -f grype-${target}.json ]; then jq '.matches[] | select(.vulnerability.severity == "Critical") | length' grype-${target}.json 2>/dev/null | wc -l; else echo "0"; fi)
High: \$(if [ -f grype-${target}.json ]; then jq '.matches[] | select(.vulnerability.severity == "High") | length' grype-${target}.json 2>/dev/null | wc -l; else echo "0"; fi)
EOF
cat security-report-${target}.txt
"""
}
}
}
}
stage('SBOM Quality Assessment') {
steps {
sh '''
cat > assess_sbom_quality.rs << 'EOF'
use std::env;
use std::fs;
use serde_json::Value;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let args: Vec<String> = env::args().collect();
if args.len() < 2 {
eprintln!("Usage: {} <sbom.json>", args[0]);
std::process::exit(1);
}
let content = fs::read_to_string(&args[1])?;
let sbom: Value = serde_json::from_str(&content)?;
let components = sbom["components"].as_array().unwrap_or(&vec![]);
let total_components = components.len();
let with_licenses = components.iter()
.filter(|c| c["licenses"].as_array().map_or(false, |l| !l.is_empty()))
.count();
let with_purls = components.iter()
.filter(|c| c["purl"].as_str().is_some())
.count();
let with_hashes = components.iter()
.filter(|c| c["hashes"].as_array().map_or(false, |h| !h.is_empty()))
.count();
let license_coverage = (with_licenses as f64 / total_components as f64) * 100.0;
let purl_coverage = (with_purls as f64 / total_components as f64) * 100.0;
let hash_coverage = (with_hashes as f64 / total_components as f64) * 100.0;
let quality_score = (license_coverage + purl_coverage + hash_coverage) / 3.0;
println!("SBOM Quality Report for {}", args[1]);
println!("=======================");
println!("Total components: {}", total_components);
println!("License coverage: {:.1}%", license_coverage);
println!("PURL coverage: {:.1}%", purl_coverage);
println!("Hash coverage: {:.1}%", hash_coverage);
println!("Overall quality score: {:.1}%", quality_score);
if quality_score >= 80.0 {
println!("✅ Excellent SBOM quality");
} else if quality_score >= 60.0 {
println!("⚠️ Good SBOM quality");
} else {
println!("❌ Poor SBOM quality - consider improvements");
}
Ok(())
}
EOF
# Compile and run quality assessment for each SBOM
rustc assess_sbom_quality.rs
for sbom in sbom-complete-*.json; do
if [ -f "$sbom" ]; then
echo "Assessing quality of $sbom"
./assess_sbom_quality "$sbom" > quality-report-$(basename "$sbom").txt
cat quality-report-$(basename "$sbom").txt
fi
done
'''
}
}
}
post {
always {
// Archive all artifacts
archiveArtifacts artifacts: '''
target/*/release/my-rust-app*,
sbom-*.json,
sbom-*.xml,
syft-*.json,
audit-*.json,
deny-*.json,
grype-*.json,
security-report-*.txt,
quality-report-*.txt,
sbom-stats-*.txt
''', fingerprint: true
// Publish HTML reports
publishHTML([
allowMissing: false,
alwaysLinkToLastBuild: true,
keepAll: true,
reportDir: '.',
reportFiles: 'sbom-complete-*.json',
reportName: 'SBOM Reports'
])
}
success {
script {
if (env.BRANCH_NAME == 'main') {
// Upload to artifact repository
sh '''
for sbom in sbom-*.json; do
if [ -f "$sbom" ]; then
curl -X POST \\
-H "Authorization: Bearer ${ARTIFACT_REPO_TOKEN}" \\
-F "file=@$sbom" \\
-F "project=${JOB_NAME}" \\
-F "version=${BUILD_NUMBER}" \\
"${ARTIFACT_REPO_URL}/api/v1/sbom"
fi
done
'''
}
}
}
failure {
emailext (
subject: "Rust SBOM Pipeline Failed: ${env.JOB_NAME} - ${env.BUILD_NUMBER}",
body: """
The Rust SBOM generation pipeline has failed.
Job: ${env.JOB_NAME}
Build: ${env.BUILD_NUMBER}
Branch: ${env.BRANCH_NAME}
Please check the Jenkins console output for details.
""",
to: "${env.CHANGE_AUTHOR_EMAIL}"
)
}
}
}Docker Integration
Multi-stage Docker Build
# Multi-stage Rust build with comprehensive SBOM generation
FROM rust:1.75.0 AS chef
RUN cargo install cargo-chef --locked
WORKDIR /app
# Planner stage - analyze dependencies
FROM chef AS planner
COPY . .
RUN cargo chef prepare --recipe-path recipe.json
# Builder stage
FROM chef AS builder
COPY --from=planner /app/recipe.json recipe.json
# Install SBOM tools
RUN cargo install cargo-cyclonedx --locked
RUN curl -sSfL https://get.anchore.io/syft | sh -s -- -b /usr/local/bin
# Build dependencies (cached layer)
RUN cargo chef cook --release --recipe-path recipe.json
# Copy source and build application
COPY . .
RUN cargo build --release
# Generate comprehensive SBOMs
RUN cargo cyclonedx --format json --output sbom-runtime.json
RUN cargo cyclonedx --format xml --output sbom.xml
RUN syft dir:. -o cyclonedx-json=syft-source.json
RUN syft rust-binary:target/release/my-rust-app -o cyclonedx-json=syft-binary.json
# Runtime stage
FROM debian:bookworm-slim AS runtime
# Install CA certificates and other runtime dependencies
RUN apt-get update && \
apt-get install -y --no-install-recommends \
ca-certificates \
libssl3 \
&& \
rm -rf /var/lib/apt/lists/*
# Create non-root user
RUN groupadd -r rust && useradd -r -g rust rust
WORKDIR /app
# Copy binary and SBOMs
COPY --from=builder /app/target/release/my-rust-app /usr/local/bin/my-rust-app
COPY --from=builder /app/sbom-*.json ./
COPY --from=builder /app/sbom.xml ./
COPY --from=builder /app/syft-*.json ./
# Set ownership
RUN chown -R rust:rust /app
# Add metadata labels
LABEL org.opencontainers.image.title="My Rust Application"
LABEL org.opencontainers.image.description="Rust application with embedded SBOMs"
LABEL org.opencontainers.image.vendor="Your Company"
LABEL org.opencontainers.image.licenses="MIT OR Apache-2.0"
LABEL org.opencontainers.image.source="https://github.com/yourcompany/my-rust-app"
# Health check that includes SBOM verification
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
CMD test -f /app/sbom-complete.json && test -f /app/syft-binary.json || exit 1
USER rust
EXPOSE 8080
ENTRYPOINT ["my-rust-app"]
# Development stage with additional tools
FROM rust:1.75.0 AS development
# Install development tools
RUN cargo install cargo-watch cargo-audit cargo-deny cargo-cyclonedx --locked
RUN curl -sSfL https://get.anchore.io/syft | sh -s -- -b /usr/local/bin
RUN curl -sSfL https://raw.githubusercontent.com/anchore/grype/main/install.sh | sh -s -- -b /usr/local/bin
# Install additional debugging tools
RUN apt-get update && \
apt-get install -y --no-install-recommends \
gdb \
valgrind \
strace \
&& \
rm -rf /var/lib/apt/lists/*
WORKDIR /app
# Development server with hot reload
CMD ["cargo", "watch", "-x", "run"]Distroless Runtime
# Distroless Rust application with SBOM
FROM rust:1.75.0 AS builder
WORKDIR /app
# Install SBOM tools
RUN cargo install cargo-cyclonedx --locked
RUN curl -sSfL https://get.anchore.io/syft | sh -s -- -b /usr/local/bin
COPY Cargo.toml Cargo.lock ./
COPY src ./src
# Build static binary
ENV RUSTFLAGS="-C target-feature=+crt-static"
RUN cargo build --release --target x86_64-unknown-linux-gnu
# Generate SBOMs
RUN cargo cyclonedx --format json --output sbom.json
RUN syft rust-binary:target/x86_64-unknown-linux-gnu/release/my-rust-app \
-o cyclonedx-json=binary-sbom.json
# Distroless runtime
FROM gcr.io/distroless/static-debian12:nonroot
COPY --from=builder /app/target/x86_64-unknown-linux-gnu/release/my-rust-app /
COPY --from=builder /app/sbom.json /
COPY --from=builder /app/binary-sbom.json /
# Metadata
LABEL org.opencontainers.image.source="https://github.com/yourcompany/my-rust-app"
USER nonroot:nonroot
ENTRYPOINT ["/my-rust-app"]Advanced Use Cases
Workspace SBOM Management
// workspace-sbom-manager/src/main.rs
use cargo_metadata::{MetadataCommand, Metadata};
use serde_json::{json, Value};
use std::collections::HashMap;
use std::fs;
use std::path::Path;
#[derive(Debug)]
struct WorkspaceSBOMManager {
metadata: Metadata,
}
impl WorkspaceSBOMManager {
fn new() -> Result<Self, Box<dyn std::error::Error>> {
let metadata = MetadataCommand::new().exec()?;
Ok(WorkspaceSBOMManager { metadata })
}
fn generate_workspace_sbom(&self) -> Result<Value, Box<dyn std::error::Error>> {
let mut workspace_components = HashMap::new();
let mut workspace_members = Vec::new();
// Process each workspace member
for member_id in &self.metadata.workspace_members {
if let Some(package) = self.metadata.packages.iter().find(|p| &p.id == member_id) {
workspace_members.push(json!({
"type": "application",
"name": package.name,
"version": package.version.to_string(),
"description": package.description,
"purl": format!("pkg:cargo/{}@{}", package.name, package.version),
"licenses": package.license.as_ref().map(|l| vec![json!({
"license": { "name": l }
})]),
"externalReferences": vec![
json!({
"type": "vcs",
"url": package.repository
})
]
}));
// Collect all dependencies from this member
for dep in &package.dependencies {
if let Some(dep_package) = self.metadata.packages.iter()
.find(|p| p.name == dep.name) {
let key = format!("{}@{}", dep_package.name, dep_package.version);
workspace_components.insert(key, json!({
"type": "library",
"name": dep_package.name,
"version": dep_package.version.to_string(),
"description": dep_package.description,
"purl": format!("pkg:cargo/{}@{}", dep_package.name, dep_package.version),
"licenses": dep_package.license.as_ref().map(|l| vec![json!({
"license": { "name": l }
})]),
"scope": match dep.kind {
cargo_metadata::DependencyKind::Normal => "required",
cargo_metadata::DependencyKind::Development => "optional",
cargo_metadata::DependencyKind::Build => "optional",
_ => "optional"
}
}));
}
}
}
}
let components: Vec<Value> = workspace_components.into_values().collect();
Ok(json!({
"bomFormat": "CycloneDX",
"specVersion": "1.7",
"serialNumber": format!("urn:uuid:{}", uuid::Uuid::new_v4()),
"version": 1,
"metadata": {
"timestamp": chrono::Utc::now().to_rfc3339(),
"tools": [{
"vendor": "Custom",
"name": "workspace-sbom-manager",
"version": "1.0.0"
}],
"component": {
"type": "application",
"name": self.metadata.workspace_root.file_name()
.and_then(|n| n.to_str())
.unwrap_or("workspace"),
"description": "Rust workspace"
}
},
"components": components,
"dependencies": workspace_members.iter().map(|member| {
json!({
"ref": format!("{}@{}", member["name"], member["version"]),
"dependsOn": []
})
}).collect::<Vec<_>>()
}))
}
fn generate_member_sboms(&self) -> Result<(), Box<dyn std::error::Error>> {
for member_id in &self.metadata.workspace_members {
if let Some(package) = self.metadata.packages.iter().find(|p| &p.id == member_id) {
let member_dir = package.manifest_path.parent().unwrap();
// Generate SBOM for this member
let output = std::process::Command::new("cargo")
.args(["cyclonedx", "--format", "json", "--output"])
.arg(format!("{}/sbom.json", member_dir.display()))
.current_dir(member_dir)
.output()?;
if !output.status.success() {
eprintln!("Failed to generate SBOM for {}: {}",
package.name, String::from_utf8_lossy(&output.stderr));
}
}
}
Ok(())
}
fn save_workspace_sbom(&self, filename: &str) -> Result<(), Box<dyn std::error::Error>> {
let sbom = self.generate_workspace_sbom()?;
let json_string = serde_json::to_string_pretty(&sbom)?;
fs::write(filename, json_string)?;
Ok(())
}
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let manager = WorkspaceSBOMManager::new()?;
println!("Generating workspace SBOM...");
manager.save_workspace_sbom("workspace-sbom.json")?;
println!("Generating individual member SBOMs...");
manager.generate_member_sboms()?;
println!("SBOM generation completed!");
Ok(())
}License Compliance Tool
// license-compliance/src/main.rs
use serde_json::Value;
use std::collections::{HashMap, HashSet};
use std::fs;
#[derive(Debug, Clone)]
struct LicensePolicy {
allowed: HashSet<String>,
restricted: HashSet<String>,
requires_review: HashSet<String>,
}
impl Default for LicensePolicy {
fn default() -> Self {
let mut allowed = HashSet::new();
allowed.insert("MIT".to_string());
allowed.insert("Apache-2.0".to_string());
allowed.insert("BSD-2-Clause".to_string());
allowed.insert("BSD-3-Clause".to_string());
allowed.insert("ISC".to_string());
let mut restricted = HashSet::new();
restricted.insert("GPL-2.0".to_string());
restricted.insert("GPL-3.0".to_string());
restricted.insert("AGPL-3.0".to_string());
restricted.insert("SSPL-1.0".to_string());
let mut requires_review = HashSet::new();
requires_review.insert("LGPL-2.1".to_string());
requires_review.insert("LGPL-3.0".to_string());
requires_review.insert("MPL-2.0".to_string());
LicensePolicy {
allowed,
restricted,
requires_review,
}
}
}
#[derive(Debug)]
struct ComplianceReport {
total_components: usize,
compliant_components: usize,
non_compliant_components: Vec<String>,
review_required_components: Vec<String>,
unknown_license_components: Vec<String>,
license_distribution: HashMap<String, usize>,
}
struct LicenseComplianceChecker {
policy: LicensePolicy,
}
impl LicenseComplianceChecker {
fn new(policy: LicensePolicy) -> Self {
LicenseComplianceChecker { policy }
}
fn check_sbom(&self, sbom_path: &str) -> Result<ComplianceReport, Box<dyn std::error::Error>> {
let content = fs::read_to_string(sbom_path)?;
let sbom: Value = serde_json::from_str(&content)?;
let components = sbom["components"].as_array()
.ok_or("No components found in SBOM")?;
let mut report = ComplianceReport {
total_components: components.len(),
compliant_components: 0,
non_compliant_components: Vec::new(),
review_required_components: Vec::new(),
unknown_license_components: Vec::new(),
license_distribution: HashMap::new(),
};
for component in components {
let name = component["name"].as_str().unwrap_or("unknown");
let version = component["version"].as_str().unwrap_or("unknown");
let component_id = format!("{}@{}", name, version);
let licenses = self.extract_licenses(component);
if licenses.is_empty() {
report.unknown_license_components.push(component_id);
continue;
}
let mut is_compliant = true;
let mut needs_review = false;
for license in &licenses {
// Update distribution
*report.license_distribution.entry(license.clone()).or_insert(0) += 1;
if self.policy.restricted.contains(license) {
report.non_compliant_components.push(format!("{} ({})", component_id, license));
is_compliant = false;
} else if self.policy.requires_review.contains(license) {
report.review_required_components.push(format!("{} ({})", component_id, license));
needs_review = true;
} else if !self.policy.allowed.contains(license) {
report.unknown_license_components.push(format!("{} ({})", component_id, license));
is_compliant = false;
}
}
if is_compliant && !needs_review {
report.compliant_components += 1;
}
}
Ok(report)
}
fn extract_licenses(&self, component: &Value) -> Vec<String> {
let mut licenses = Vec::new();
if let Some(license_array) = component["licenses"].as_array() {
for license_obj in license_array {
if let Some(license) = license_obj["license"].as_object() {
if let Some(id) = license["id"].as_str() {
licenses.push(id.to_string());
} else if let Some(name) = license["name"].as_str() {
licenses.push(name.to_string());
}
}
}
}
licenses
}
fn print_report(&self, report: &ComplianceReport) {
println!("License Compliance Report");
println!("========================");
println!("Total components: {}", report.total_components);
println!("Compliant components: {}", report.compliant_components);
println!("Non-compliant components: {}", report.non_compliant_components.len());
println!("Components requiring review: {}", report.review_required_components.len());
println!("Components with unknown licenses: {}", report.unknown_license_components.len());
println!();
if !report.non_compliant_components.is_empty() {
println!("❌ Non-compliant components:");
for component in &report.non_compliant_components {
println!(" - {}", component);
}
println!();
}
if !report.review_required_components.is_empty() {
println!("⚠️ Components requiring review:");
for component in &report.review_required_components {
println!(" - {}", component);
}
println!();
}
if !report.unknown_license_components.is_empty() {
println!("❓ Components with unknown licenses:");
for component in &report.unknown_license_components {
println!(" - {}", component);
}
println!();
}
println!("License distribution:");
let mut licenses: Vec<_> = report.license_distribution.iter().collect();
licenses.sort_by(|a, b| b.1.cmp(a.1));
for (license, count) in licenses {
let status = if self.policy.allowed.contains(license) {
"✅"
} else if self.policy.restricted.contains(license) {
"❌"
} else if self.policy.requires_review.contains(license) {
"⚠️"
} else {
"❓"
};
println!(" {} {}: {}", status, license, count);
}
}
fn generate_json_report(&self, report: &ComplianceReport) -> Value {
json!({
"compliance_summary": {
"total_components": report.total_components,
"compliant_components": report.compliant_components,
"non_compliant_count": report.non_compliant_components.len(),
"review_required_count": report.review_required_components.len(),
"unknown_license_count": report.unknown_license_components.len(),
"compliance_percentage": (report.compliant_components as f64 / report.total_components as f64) * 100.0
},
"non_compliant_components": report.non_compliant_components,
"review_required_components": report.review_required_components,
"unknown_license_components": report.unknown_license_components,
"license_distribution": report.license_distribution,
"policy": {
"allowed_licenses": self.policy.allowed.iter().collect::<Vec<_>>(),
"restricted_licenses": self.policy.restricted.iter().collect::<Vec<_>>(),
"review_required_licenses": self.policy.requires_review.iter().collect::<Vec<_>>()
}
})
}
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let args: Vec<String> = std::env::args().collect();
if args.len() < 2 {
eprintln!("Usage: {} <sbom.json> [--json]", args[0]);
std::process::exit(1);
}
let sbom_path = &args[1];
let json_output = args.get(2).map_or(false, |arg| arg == "--json");
let policy = LicensePolicy::default();
let checker = LicenseComplianceChecker::new(policy);
let report = checker.check_sbom(sbom_path)?;
if json_output {
let json_report = checker.generate_json_report(&report);
println!("{}", serde_json::to_string_pretty(&json_report)?);
} else {
checker.print_report(&report);
}
// Exit with error code if there are compliance issues
if !report.non_compliant_components.is_empty() {
std::process::exit(1);
}
Ok(())
}Frequently Asked Questions (FAQ)
General Rust SBOM Questions
Q: How do I handle workspace dependencies in Rust SBOMs?A: Rust workspaces share dependencies across multiple crates, requiring special consideration:
- Use
cargo cyclonedx --workspaceto generate a combined SBOM - For individual crate SBOMs:
cargo cyclonedx -p specific-crate - Workspace dependencies are deduplicated in Cargo.lock
- Consider generating both workspace-level and crate-level SBOMs
- Document internal workspace dependencies separately from external ones
A: These compile-time dependencies require special handling:
- Procedural macros run during compilation and can execute arbitrary code
- Build.rs dependencies (build-dependencies) don't appear in the final binary
- Generate and review an SBOM during the build stage, not only from the final binary
- Consider security implications of build-time code execution
- Document which dependencies are compile-time only
A: Rust's feature flags create different dependency trees:
# Default features
cargo cyclonedx --output default-sbom.json
# Specific features
cargo cyclonedx --features "feature1,feature2" --output featured-sbom.json
# All features
cargo cyclonedx --all-features --output all-features-sbom.json
# No default features
cargo cyclonedx --no-default-features --output minimal-sbom.jsonSecurity and Compliance Questions
Q: How do I identify vulnerable Rust dependencies?A: Use multiple tools for comprehensive coverage:
cargo audit- Checks against RustSec Advisory Databasecargo deny- More comprehensive policy enforcement- Grype with SBOM:
grype sbom:sbom.json - Include vulnerability info in SBOM generation where supported
- Monitor crates.io security advisories
A: Unsafe code requires special attention in Rust:
- Use
cargo geigerto identify unsafe code usage - Document unsafe dependencies in SBOM metadata
- Consider security implications of FFI dependencies
- Review unsafe blocks in critical dependencies
- Include safety documentation in your SBOM
A: Private registries need authentication configuration:
- Configure .cargo/config.toml with registry credentials
- Set CARGO_REGISTRIES_YOUR_REGISTRY_TOKEN environment variable
- SBOM tools respect Cargo's authentication
- Consider including registry source in SBOM metadata
- Be cautious about exposing internal crate names
Best Practices
Essential Best Practices for Rust SBOM Generation
- Always use Cargo.lock: Commit Cargo.lock for applications to ensure reproducible builds and accurate SBOMs
- Generate SBOMs for each configuration: Different features and targets produce different dependency trees
- Review build-time dependencies separately: source-based SBOMs and binary-based SBOMs answer different questions
- Automate SBOM generation: Integrate into CI/CD to ensure SBOMs stay current with code changes
- Validate generated SBOMs: Use schema validation and quality checks to ensure completeness
Conclusion
Generating accurate SBOMs for Rust applications is essential for managing the growing complexity of the crates.io ecosystem. Rust's modern dependency management system, with its strong emphasis on reproducibility and security, provides an excellent foundation for comprehensive SBOM generation.
The key to successful Rust SBOM generation is understanding the nuances of Cargo's dependency model - from feature flags to build dependencies to platform-specific code. Tools like cargo-cyclonedx and Syft provide excellent support for these Rust-specific features, enabling accurate supply chain visibility.
As Rust continues to grow in critical domains like systems programming, embedded development, and cloud infrastructure, the importance of comprehensive SBOMs will only increase. Establishing robust SBOM generation practices now will position your Rust projects for success in an increasingly security-conscious software landscape.
Next Steps
After establishing Rust SBOM generation:
- Integrate security scanning: Combine cargo-audit, cargo-deny, and vulnerability databases
- Automate updates: Use Dependabot or Renovate for dependency management
- Implement policy gates: Use cargo-deny for license and security policies
- Monitor the RustSec database: Stay informed about Rust-specific vulnerabilities
- Share SBOMs: Provide to customers and security teams as part of releases
Related Resources
- CI/CD SBOM Integration Guide - Automate Rust SBOM generation
- Docker SBOM Guide - SBOMs for containerized Rust applications
- Security Best Practices - Comprehensive security for Rust projects
---
Last updated: March 9, 2026 Reading time: 22 minutes Expertise level: Beginner to Advanced