fix: typed nil hashes in cyclonedx

Signed-off-by: Keith Zantow <kzantow@gmail.com>
This commit is contained in:
Keith Zantow 2025-02-24 20:46:46 -05:00
parent 46522bcc5d
commit 823723f510
No known key found for this signature in database
GPG Key ID: 735988DA57708682

View File

@ -70,27 +70,16 @@ func ToFormatModel(s sbom.SBOM) *cyclonedx.BOM {
continue continue
} }
metadata = &fileMetadata metadata = &fileMetadata
// Digests
var digests []file.Digest
if digestsForLocation, exists := artifacts.FileDigests[coordinate]; exists {
digests = digestsForLocation
}
cdxHashes := digestsToHashes(digests)
components = append(components, cyclonedx.Component{ components = append(components, cyclonedx.Component{
BOMRef: string(coordinate.ID()), BOMRef: string(coordinate.ID()),
Type: cyclonedx.ComponentTypeFile, Type: cyclonedx.ComponentTypeFile,
Name: metadata.Path, Name: metadata.Path,
Hashes: &cdxHashes, Hashes: slicePtr(digestsToHashes(artifacts.FileDigests[coordinate])),
}) })
} }
cdxBOM.Components = &components cdxBOM.Components = slicePtr(components)
dependencies := toDependencies(s.Relationships) cdxBOM.Dependencies = slicePtr(toDependencies(s.Relationships))
if len(dependencies) > 0 {
cdxBOM.Dependencies = &dependencies
}
return cdxBOM return cdxBOM
} }
@ -277,14 +266,7 @@ func toDependencies(relationships []artifact.Relationship) []cyclonedx.Dependenc
func toBomProperties(srcMetadata source.Description) *[]cyclonedx.Property { func toBomProperties(srcMetadata source.Description) *[]cyclonedx.Property {
metadata, ok := srcMetadata.Metadata.(source.ImageMetadata) metadata, ok := srcMetadata.Metadata.(source.ImageMetadata)
if ok { if ok {
props := helpers.EncodeProperties(metadata.Labels, "syft:image:labels") return slicePtr(helpers.EncodeProperties(metadata.Labels, "syft:image:labels"))
// return nil if props is nil to avoid creating a pointer to a nil slice,
// which results in a null JSON value that does not comply with the CycloneDX schema.
// https://github.com/anchore/grype/issues/1759
if props == nil {
return nil
}
return &props
} }
return nil return nil
} }
@ -344,3 +326,14 @@ func toBomDescriptorComponent(srcMetadata source.Description) *cyclonedx.Compone
return nil return nil
} }
// Every slice pointer needs to either be a valid slice or nil,
// otherwise we will create a pointer that is not nil but references
// a nil slice, which results in a `null` JSON value that does not
// comply with the CycloneDX schema. See: https://github.com/anchore/grype/issues/1759
func slicePtr[T any](values []T) *[]T {
if len(values) == 0 {
return nil
}
return &values
}