Skip to content

Commit ec5ea08

Browse files
committed
move to initscanner
Signed-off-by: Sertac Ozercan <[email protected]>
1 parent 082ae3b commit ec5ea08

File tree

3 files changed

+52
-102
lines changed

3 files changed

+52
-102
lines changed

pkg/scanners/trivy/trivy.go

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -147,6 +147,21 @@ func runProfileServer() {
147147
log.Error(err, "pprof server failed")
148148
}
149149

150+
func findTrivyExecutable() (string, error) {
151+
// First, check if trivy exists at the hardcoded path
152+
if _, err := os.Stat(trivyCommandName); err == nil {
153+
return trivyCommandName, nil
154+
}
155+
156+
// If not found at hardcoded path, try to find it in PATH
157+
path, err := currentExecutingLookPath("trivy")
158+
if err != nil {
159+
return "", fmt.Errorf("trivy executable not found at %s and not found in PATH: %w", trivyCommandName, err)
160+
}
161+
162+
return path, nil
163+
}
164+
150165
func initScanner(userConfig *Config) (Scanner, error) {
151166
if userConfig == nil {
152167
return nil, fmt.Errorf("invalid trivy scanner config")
@@ -165,12 +180,19 @@ func initScanner(userConfig *Config) (Scanner, error) {
165180
Address: utils.CRIPath,
166181
}
167182

183+
// Find trivy executable path during initialization
184+
trivyPath, err := findTrivyExecutable()
185+
if err != nil {
186+
return nil, err
187+
}
188+
168189
totalTimeout := time.Duration(userConfig.Timeout.Total)
169190
timer := time.NewTimer(totalTimeout)
170191

171192
var s Scanner = &ImageScanner{
172-
config: *userConfig,
173-
timer: timer,
193+
config: *userConfig,
194+
timer: timer,
195+
trivyPath: trivyPath,
174196
}
175197
return s, nil
176198
}

pkg/scanners/trivy/types.go

Lines changed: 5 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -172,23 +172,9 @@ func (c *Config) getRuntimeVar() (string, error) {
172172
}
173173

174174
type ImageScanner struct {
175-
config Config
176-
timer *time.Timer
177-
}
178-
179-
func (s *ImageScanner) findTrivyExecutable() (string, error) {
180-
// First, check if trivy exists at the hardcoded path
181-
if _, err := os.Stat(trivyCommandName); err == nil {
182-
return trivyCommandName, nil
183-
}
184-
185-
// If not found at hardcoded path, try to find it in PATH
186-
path, err := currentExecutingLookPath("trivy")
187-
if err != nil {
188-
return "", fmt.Errorf("trivy executable not found at %s and not found in PATH: %w", trivyCommandName, err)
189-
}
190-
191-
return path, nil
175+
config Config
176+
timer *time.Timer
177+
trivyPath string
192178
}
193179

194180
func (s *ImageScanner) Scan(img unversioned.Image) (ScanStatus, error) {
@@ -197,12 +183,6 @@ func (s *ImageScanner) Scan(img unversioned.Image) (ScanStatus, error) {
197183
refs = append(refs, img.Names...)
198184
scanSucceeded := false
199185

200-
// Find trivy executable path
201-
trivyPath, err := s.findTrivyExecutable()
202-
if err != nil {
203-
return StatusFailed, err
204-
}
205-
206186
log.Info("scanning image with id", "imageID", img.ImageID, "refs", refs)
207187
for i := 0; i < len(refs) && !scanSucceeded; i++ {
208188
log.Info("scanning image with ref", "ref", refs[i])
@@ -211,13 +191,13 @@ func (s *ImageScanner) Scan(img unversioned.Image) (ScanStatus, error) {
211191
stderr := new(bytes.Buffer)
212192

213193
cliArgs := s.config.cliArgs(refs[i])
214-
cmd := exec.Command(trivyPath, cliArgs...)
194+
cmd := exec.Command(s.trivyPath, cliArgs...) // nolint:gosec // G204: Subprocess launched with variable
215195
cmd.Stdout = stdout
216196
cmd.Stderr = stderr
217197
cmd.Env = append(cmd.Env, os.Environ()...)
218198
cmd.Env = setRuntimeSocketEnvVars(cmd, s.config.Runtime)
219199

220-
log.V(1).Info("scanning image ref", "ref", refs[i], "cli_invocation", fmt.Sprintf("%s %s", trivyPath, strings.Join(cliArgs, " ")), "env", cmd.Env)
200+
log.V(1).Info("scanning image ref", "ref", refs[i], "cli_invocation", fmt.Sprintf("%s %s", s.trivyPath, strings.Join(cliArgs, " ")), "env", cmd.Env)
221201
if err := cmd.Run(); err != nil {
222202
log.Error(err, "error scanning image", "imageID", img.ImageID, "reference", refs[i], "stderr", stderr.String())
223203
continue

pkg/scanners/trivy/types_test.go

Lines changed: 23 additions & 75 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@ package main
22

33
import (
44
"errors"
5-
"fmt"
65
"strings"
76
"testing"
87

@@ -174,14 +173,12 @@ func TestCLIArgs(t *testing.T) {
174173
}
175174
}
176175

177-
// TestImageScanner_findTrivyExecutable tests the findTrivyExecutable method in isolation.
178-
func TestImageScanner_findTrivyExecutable(t *testing.T) {
176+
// TestFindTrivyExecutable tests the findTrivyExecutable function in isolation.
177+
func TestFindTrivyExecutable(t *testing.T) {
179178
// Store original function to restore after tests
180179
originalLookPath := currentExecutingLookPath
181180
defer func() { currentExecutingLookPath = originalLookPath }()
182181

183-
scanner := &ImageScanner{}
184-
185182
testCases := []struct {
186183
name string
187184
lookPathSetup func()
@@ -219,7 +216,7 @@ func TestImageScanner_findTrivyExecutable(t *testing.T) {
219216
t.Run(tc.name, func(t *testing.T) {
220217
tc.lookPathSetup()
221218

222-
path, err := scanner.findTrivyExecutable()
219+
path, err := findTrivyExecutable()
223220

224221
if tc.expectedError {
225222
assert.Error(t, err)
@@ -233,94 +230,45 @@ func TestImageScanner_findTrivyExecutable(t *testing.T) {
233230
}
234231
}
235232

236-
// TestImageScanner_Scan_TrivyPathLookup tests the logic for finding the trivy executable.
233+
// TestImageScanner_Scan_TrivyPathLookup tests the logic for using the trivy executable path.
237234
func TestImageScanner_Scan_TrivyPathLookup(t *testing.T) {
238-
// Store original function to restore after tests
239-
originalLookPath := currentExecutingLookPath
240-
defer func() { currentExecutingLookPath = originalLookPath }()
241-
242235
// Base configuration for the scanner
243236
baseConfig := DefaultConfig()
244-
scanner := &ImageScanner{
245-
config: *baseConfig,
246-
}
247237
// Dummy image for testing
248238
img := unversioned.Image{ImageID: "test-image-id", Names: []string{"test-image:latest"}}
249239

250-
// Expected error message prefix when trivy is not found
251-
expectedNotFoundErrorMsgPrefix := fmt.Sprintf("trivy executable not found at %s", trivyCommandName)
252-
253240
testCases := []struct {
254-
name string
255-
lookPathSetup func() // Sets up the mock for exec.LookPath
256-
expectedStatus ScanStatus
257-
expectNotFoundError bool // True if we expect the specific "trivy not found by LookPath" error
258-
expectedErrorMsgContains string // The prefix for the "not found" error message
241+
name string
242+
trivyPath string
243+
expectedStatus ScanStatus
259244
}{
260245
{
261-
name: "Trivy found at hardcoded path /trivy",
262-
lookPathSetup: func() {
263-
currentExecutingLookPath = func(file string) (string, error) {
264-
if file == trivyExecutableName {
265-
return trivyPathBin, nil // Found in PATH
266-
}
267-
return originalLookPath(file) // Fallback for any other calls
268-
}
269-
},
270-
// Scan will likely still fail due to inability to run actual scan in test,
271-
// but it should not be the "trivy not found by LookPath" error.
272-
expectedStatus: StatusFailed,
273-
expectNotFoundError: false,
246+
name: "Trivy path set to hardcoded path /trivy",
247+
trivyPath: trivyCommandName,
248+
expectedStatus: StatusFailed, // Will fail during actual execution but not due to path issues
274249
},
275250
{
276-
name: "Trivy found in $PATH, not at /trivy",
277-
lookPathSetup: func() {
278-
currentExecutingLookPath = func(file string) (string, error) {
279-
if file == trivyExecutableName {
280-
return trivyPathBin, nil // Found in $PATH
281-
}
282-
return originalLookPath(file)
283-
}
284-
},
285-
expectedStatus: StatusFailed, // Similar to above, subsequent scan steps will fail.
286-
expectNotFoundError: false,
287-
},
288-
{
289-
name: "Trivy not found anywhere",
290-
lookPathSetup: func() {
291-
currentExecutingLookPath = func(file string) (string, error) {
292-
if file == trivyExecutableName {
293-
return "", errors.New("mock: trivy not in $PATH")
294-
}
295-
return originalLookPath(file)
296-
}
297-
},
298-
expectedStatus: StatusFailed,
299-
expectNotFoundError: true,
300-
expectedErrorMsgContains: expectedNotFoundErrorMsgPrefix,
251+
name: "Trivy path set to system PATH location",
252+
trivyPath: trivyPathBin,
253+
expectedStatus: StatusFailed, // Will fail during actual execution but not due to path issues
301254
},
302255
}
303256

304257
for _, tc := range testCases {
305258
t.Run(tc.name, func(t *testing.T) {
306-
tc.lookPathSetup()
259+
scanner := &ImageScanner{
260+
config: *baseConfig,
261+
trivyPath: tc.trivyPath,
262+
}
307263

308264
status, err := scanner.Scan(img)
309265

310-
if tc.expectNotFoundError {
311-
assert.Error(t, err, "Expected an error when trivy is not found")
312-
if err != nil { // Check prefix only if error is not nil
313-
assert.True(t, strings.HasPrefix(err.Error(), tc.expectedErrorMsgContains),
314-
"Error message should start with '%s'. Got: %s", tc.expectedErrorMsgContains, err.Error())
315-
}
316-
assert.Equal(t, tc.expectedStatus, status, "ScanStatus should be StatusFailed")
317-
} else if err != nil {
318-
// If trivy was "found" by LookPath, any error should be from subsequent operations (e.g., cmd.Run, JSON unmarshal),
319-
// not the specific "trivy executable not found by LookPath..." error.
320-
assert.False(t, strings.HasPrefix(err.Error(), expectedNotFoundErrorMsgPrefix),
321-
"Error should not be the 'trivy not found by LookPath' error. Got: %s", err.Error())
322-
// The status might still be StatusFailed due to these subsequent errors,
323-
// which is acceptable for this test's focus on path lookup.
266+
// The scan will likely fail due to inability to run actual scan in test,
267+
// but it should not be a "trivy not found" error since the path is already set
268+
assert.Equal(t, tc.expectedStatus, status, "ScanStatus should be StatusFailed")
269+
if err != nil {
270+
assert.NotContains(t, err.Error(), "trivy executable not found",
271+
"Error should not be about trivy not being found since path is pre-set")
324272
}
325273
})
326274
}

0 commit comments

Comments
 (0)