Skip to content

Commit

Permalink
Implement conversion from cargo-lock hash format to cyclonedx-bom has…
Browse files Browse the repository at this point in the history
…h format and wire up emitting the data to the final SBOM
  • Loading branch information
Shnatsel committed Feb 18, 2024
1 parent 01aef0a commit e5017a1
Showing 1 changed file with 30 additions and 0 deletions.
30 changes: 30 additions & 0 deletions cargo-cyclonedx/src/generator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,7 @@ impl SbomGenerator {
component.scope = Some(Scope::Required);
component.external_references = Self::get_external_references(package);
component.licenses = self.get_licenses(package);
component.hashes = self.get_hashes(package);

component.description = package
.description
Expand Down Expand Up @@ -414,6 +415,19 @@ impl SbomGenerator {
Some(Licenses(licenses))
}

fn get_hashes(&self, package: &Package) -> Option<cyclonedx_bom::models::hash::Hashes> {
match self.crate_hashes.get(&package.id) {
Some(hash) => Some(cyclonedx_bom::models::hash::Hashes(vec![to_bom_hash(hash)])),
None => {
log::debug!(
"Hash for package ID {} not found in Cargo.lock",
&package.id
);
None
}
}
}

fn create_metadata(&self, package: &Package) -> Result<Metadata, GeneratorError> {
let authors = Self::create_authors(package);

Expand Down Expand Up @@ -821,6 +835,22 @@ fn pkgid(pkg: &cargo_lock::Package) -> String {
}
}

/// Converts a checksum from the `cargo-lock` crate format to `cyclonedx-bom` crate format
fn to_bom_hash(hash: &Checksum) -> cyclonedx_bom::models::hash::Hash {
use cyclonedx_bom::models::hash::{Hash, HashAlgorithm, HashValue};
// use a match statement to get a compile-time error
// if/when more variants are added
match hash {
Checksum::Sha256(_) => {
Hash {
alg: HashAlgorithm::SHA256,
// {:x} means "format as lowercase hex"
content: HashValue(format!("{hash:x}")),
}
}
}
}

#[derive(Error, Debug)]
pub enum SbomWriterError {
#[error("I/O error")]
Expand Down

0 comments on commit e5017a1

Please sign in to comment.