Skip to content

Commit

Permalink
Add nil check to CycloneDX enumeration (#320)
Browse files Browse the repository at this point in the history
Fix #319
  • Loading branch information
michaelkedar committed Mar 30, 2023
1 parent cfe6d75 commit 3812a9b
Show file tree
Hide file tree
Showing 4 changed files with 92 additions and 0 deletions.
4 changes: 4 additions & 0 deletions internal/sbom/cyclonedx.go
Expand Up @@ -69,6 +69,10 @@ func (c *CycloneDX) enumerateComponents(components []cyclonedx.Component, callba
}

func (c *CycloneDX) enumeratePackages(bom *cyclonedx.BOM, callback func(Identifier) error) error {
if bom.Components == nil {
return nil
}

return c.enumerateComponents(*bom.Components, callback)
}

Expand Down
60 changes: 60 additions & 0 deletions internal/sbom/cyclonedx_test.go
@@ -0,0 +1,60 @@
package sbom_test

import (
"os"
"path/filepath"
"testing"

"github.com/google/go-cmp/cmp"
"github.com/google/osv-scanner/internal/sbom"
)

func runCycloneGetPackages(t *testing.T, bomFile string, want []sbom.Identifier) {
t.Helper()

f, err := os.Open(filepath.Join("fixtures", bomFile))
if err != nil {
t.Fatalf("Failed to read fixture file: %v", err)
}
defer f.Close()

got := []sbom.Identifier{}
callback := func(id sbom.Identifier) error {
got = append(got, id)
return nil
}

cdx := &sbom.CycloneDX{}
err = cdx.GetPackages(f, callback)
if err != nil {
t.Errorf("GetPackages returned an error: %v", err)
}

if diff := cmp.Diff(want, got); diff != "" {
t.Errorf("GetPackages() returned an unexpected result (-want, +got):\n%s", diff)
}
}

func TestCycloneDXGetPackages(t *testing.T) {
t.Parallel()
tests := []struct {
bomFile string
identifiers []sbom.Identifier
}{
{
bomFile: "cyclonedx.json",
identifiers: []sbom.Identifier{
{PURL: "pkg:maven/org.hdrhistogram/HdrHistogram@2.1.12"},
{PURL: "pkg:maven/org.apache.logging.log4j/log4j-core@2.16.0"},
},
},
{
bomFile: "cyclonedx-empty.json",
identifiers: []sbom.Identifier{},
},
}

for _, tt := range tests {
runCycloneGetPackages(t, tt.bomFile, tt.identifiers)
}
}
5 changes: 5 additions & 0 deletions internal/sbom/fixtures/cyclonedx-empty.json
@@ -0,0 +1,5 @@
{
"bomFormat": "CycloneDX",
"specVersion": "1.4",
"version": 1
}
23 changes: 23 additions & 0 deletions internal/sbom/fixtures/cyclonedx.json
@@ -0,0 +1,23 @@
{
"bomFormat": "CycloneDX",
"specVersion": "1.4",
"version": 1,
"components": [
{
"type": "container",
"name": "/target.tar",
"components": [
{
"type": "library",
"name": "HdrHistogram",
"purl": "pkg:maven/org.hdrhistogram/HdrHistogram@2.1.12"
}
]
},
{
"type": "library",
"name": "Apache Log4j Core",
"purl": "pkg:maven/org.apache.logging.log4j/log4j-core@2.16.0"
}
]
}

0 comments on commit 3812a9b

Please sign in to comment.