From e1ce040eade1038678aa259cac339a1c9204f6f5 Mon Sep 17 00:00:00 2001 From: Alfredo Deza Date: Fri, 24 Jul 2020 12:48:53 -0400 Subject: [PATCH] scope: do not create scope if path is invalid Signed-off-by: Alfredo Deza --- syft/scope/scope.go | 22 +++++++++++++++++++++- syft/scope/scope_test.go | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+), 1 deletion(-) diff --git a/syft/scope/scope.go b/syft/scope/scope.go index 8254d8fd3..49000d152 100644 --- a/syft/scope/scope.go +++ b/syft/scope/scope.go @@ -2,6 +2,7 @@ package scope import ( "fmt" + "os" "github.com/anchore/stereoscope" @@ -32,7 +33,11 @@ func NewScope(userInput string, o Option) (Scope, func(), error) { switch protocol.Type { case directoryProtocol: - // populate the scope object for dir + err := isValidPath(protocol.Value) + if err != nil { + return Scope{}, func() {}, fmt.Errorf("unable to process path, must exist and be a directory: %w", err) + } + s, err := NewScopeFromDir(protocol.Value, o) if err != nil { return Scope{}, func() {}, fmt.Errorf("could not populate scope from path (%s): %w", protocol.Value, err) @@ -115,3 +120,18 @@ func (s Scope) Source() interface{} { return nil } + +// isValidPath ensures that the user-provided input will correspond to a path +// that exists and is a directory +func isValidPath(userInput string) error { + fileMeta, err := os.Stat(userInput) + if err != nil { + return err + } + + if fileMeta.IsDir() { + return nil + } + + return fmt.Errorf("path is not a directory: %s", userInput) +} diff --git a/syft/scope/scope_test.go b/syft/scope/scope_test.go index c0b0783dc..67e3d1b12 100644 --- a/syft/scope/scope_test.go +++ b/syft/scope/scope_test.go @@ -213,3 +213,40 @@ func TestFilesByGlob(t *testing.T) { }) } } + +func TestIsValidPath(t *testing.T) { + testCases := []struct { + desc string + input string + isError bool + }{ + { + desc: "path is valid", + input: "test-fixtures", + isError: false, + }, + { + desc: "file is invalid", + input: "test-fixtures/.vimrc", + isError: true, + }, + { + desc: "path does not exist", + input: "foo/bar/baz", + isError: true, + }, + } + for _, test := range testCases { + t.Run(test.desc, func(t *testing.T) { + err := isValidPath(test.input) + if err != nil && !test.isError { + t.Errorf("did not expect and error, got: %w", err) + } + + if err == nil && test.isError { + t.Errorf("expected an error but didn't get one") + } + + }) + } +}