fix(nodejs): do not detect lock file in node_modules as an app (#4949)

* fix(npm): do not detect lock file in node_modules as an app

* refactor: add x/path.Contains

---------

Co-authored-by: knqyf263 <knqyf263@gmail.com>
This commit is contained in:
Nikita Pivkin
2023-08-06 11:59:18 +03:00
committed by GitHub
parent e6d7705a51
commit 067a0fcb9c
4 changed files with 71 additions and 2 deletions

View File

@@ -20,6 +20,7 @@ import (
"github.com/aquasecurity/trivy/pkg/fanal/types"
"github.com/aquasecurity/trivy/pkg/log"
"github.com/aquasecurity/trivy/pkg/utils/fsutils"
xpath "github.com/aquasecurity/trivy/pkg/x/path"
)
func init() {
@@ -85,7 +86,7 @@ func (a npmLibraryAnalyzer) PostAnalyze(_ context.Context, input analyzer.PostAn
func (a npmLibraryAnalyzer) Required(filePath string, _ os.FileInfo) bool {
fileName := filepath.Base(filePath)
if fileName == types.NpmPkgLock {
if fileName == types.NpmPkgLock && !xpath.Contains(filePath, "node_modules") {
return true
}
// The file path to package.json - */node_modules/<package_name>/package.json
@@ -122,7 +123,7 @@ func (a npmLibraryAnalyzer) parseNpmPkgLock(fsys fs.FS, path string) (*types.App
}
func (a npmLibraryAnalyzer) findLicenses(fsys fs.FS, lockPath string) (map[string]string, error) {
dir := filepath.Dir(lockPath)
dir := path.Dir(lockPath)
root := path.Join(dir, "node_modules")
if _, err := fs.Stat(fsys, root); errors.Is(err, fs.ErrNotExist) {
log.Logger.Infof(`To collect the license information of packages in %q, "npm install" needs to be performed beforehand`, lockPath)

View File

@@ -211,6 +211,11 @@ func Test_nodePkgLibraryAnalyzer_Required(t *testing.T) {
filePath: "npm/node_modules/package.json",
want: false,
},
{
name: "lock file in node_modules",
filePath: "npm/node_modules/html2canvas/package-lock.json",
want: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {

13
pkg/x/path/path.go Normal file
View File

@@ -0,0 +1,13 @@
package path
import (
"strings"
"golang.org/x/exp/slices"
)
// Contains reports whether the path contains the subpath.
func Contains(filePath, subpath string) bool {
ss := strings.Split(filePath, "/")
return slices.Contains(ss, subpath)
}

50
pkg/x/path/path_test.go Normal file
View File

@@ -0,0 +1,50 @@
package path
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestContains(t *testing.T) {
type args struct {
filePath string
subpath string
}
tests := []struct {
name string
args args
want bool
}{
{
name: "file",
args: args{
filePath: "go.mod",
subpath: "go.mod",
},
want: true,
},
{
name: "dir",
args: args{
filePath: "app/node_modules/express/package.json",
subpath: "node_modules",
},
want: true,
},
{
name: "path",
args: args{
filePath: "app/node_modules/express/package.json",
subpath: "app/node_modules",
},
want: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := Contains(tt.args.filePath, tt.args.subpath)
assert.Equal(t, tt.want, got)
})
}
}