diff --git a/syft/cataloger/javascript/parse_package_json.go b/syft/cataloger/javascript/parse_package_json.go index 077c433e7..0bccb100c 100644 --- a/syft/cataloger/javascript/parse_package_json.go +++ b/syft/cataloger/javascript/parse_package_json.go @@ -4,6 +4,7 @@ import ( "encoding/json" "errors" "fmt" + "github.com/anchore/syft/internal/log" "io" "regexp" @@ -172,6 +173,12 @@ func parsePackageJSON(_ string, reader io.Reader) ([]pkg.Package, error) { return nil, fmt.Errorf("failed to parse package.json file: %w", err) } + if !p.hasMinimumRequiredValues() { + log.Debug("encountered package.json file without the minimum number of field values required for" + + " consideration as a package") + return nil, nil + } + licenses, err := licensesFromJSON(p) if err != nil { return nil, fmt.Errorf("failed to parse package.json file: %w", err) @@ -195,3 +202,7 @@ func parsePackageJSON(_ string, reader io.Reader) ([]pkg.Package, error) { return packages, nil } + +func (p PackageJSON) hasMinimumRequiredValues() bool { + return p.Name != "" && p.Version != "" +} diff --git a/syft/cataloger/javascript/parse_package_json_test.go b/syft/cataloger/javascript/parse_package_json_test.go index c2940a7a2..6ac5f162a 100644 --- a/syft/cataloger/javascript/parse_package_json_test.go +++ b/syft/cataloger/javascript/parse_package_json_test.go @@ -142,3 +142,20 @@ func TestParsePackageJSON(t *testing.T) { }) } } + +func TestParsePackageJSON_Partial(t *testing.T) { // see https://github.com/anchore/syft/issues/311 + const fixtureFile = "test-fixtures/pkg-json/package-partial.json" + fixture, err := os.Open(fixtureFile) + if err != nil { + t.Fatalf("failed to open fixture: %+v", err) + } + + actual, err := parsePackageJSON("", fixture) + if err != nil { + t.Fatalf("failed to parse package-lock.json: %+v", err) + } + + if len(actual) != 0 { + t.Errorf("no packages should've been returned") + } +} diff --git a/syft/cataloger/javascript/test-fixtures/pkg-json/package-partial.json b/syft/cataloger/javascript/test-fixtures/pkg-json/package-partial.json new file mode 100644 index 000000000..db7a90b51 --- /dev/null +++ b/syft/cataloger/javascript/test-fixtures/pkg-json/package-partial.json @@ -0,0 +1,5 @@ +{ + "sideEffects": false, + "module": "../../esm/fp/isSaturday/index.js", + "typings": "../../typings.d.ts" +}