fix: add nil check to CycloneDX toBomProperties (#3119)

Signed-off-by: Lucas Rodriguez <lucas.rodriguez9616@gmail.com>
This commit is contained in:
Lucas Rodriguez 2024-08-13 15:02:15 -05:00 committed by GitHub
parent 3161e1847e
commit cd3b828905
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 53 additions and 0 deletions

View File

@ -211,6 +211,12 @@ func toBomProperties(srcMetadata source.Description) *[]cyclonedx.Property {
metadata, ok := srcMetadata.Metadata.(source.ImageMetadata)
if ok {
props := 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

View File

@ -236,6 +236,53 @@ func Test_toBomDescriptor(t *testing.T) {
}
}
func Test_toBomProperties(t *testing.T) {
tests := []struct {
name string
srcMetadata source.Description
props *[]cyclonedx.Property
}{
{
name: "ImageMetadata without labels",
srcMetadata: source.Description{
Metadata: source.ImageMetadata{
Labels: map[string]string{},
},
},
props: nil,
},
{
name: "ImageMetadata with labels",
srcMetadata: source.Description{
Metadata: source.ImageMetadata{
Labels: map[string]string{
"label1": "value1",
"label2": "value2",
},
},
},
props: &[]cyclonedx.Property{
{Name: "syft:image:labels:label1", Value: "value1"},
{Name: "syft:image:labels:label2", Value: "value2"},
},
},
{
name: "not ImageMetadata",
srcMetadata: source.Description{
Metadata: source.FileMetadata{},
},
props: nil,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
t.Parallel()
props := toBomProperties(test.srcMetadata)
require.Equal(t, test.props, props)
})
}
}
func Test_toOsComponent(t *testing.T) {
tests := []struct {
name string