Skip to content

Commit

Permalink
fix: add nil check to CycloneDX toBomProperties (#3119)
Browse files Browse the repository at this point in the history
Signed-off-by: Lucas Rodriguez <[email protected]>
  • Loading branch information
lucasrod16 authored Aug 13, 2024
1 parent 3161e18 commit cd3b828
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 0 deletions.
6 changes: 6 additions & 0 deletions syft/format/common/cyclonedxhelpers/to_format_model.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
47 changes: 47 additions & 0 deletions syft/format/common/cyclonedxhelpers/to_format_model_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit cd3b828

Please sign in to comment.