mirror of
https://github.com/lukaszraczylo/gohoarder.git
synced 2026-11-25 06:35:21 +00:00
fix(scanner): leave failed scanner results out of the merge
A scanner that returns a result with status error now counts as a failed scanner, like one that returns an error. Its result no longer joins the merge, and the manager counts it as an infrastructure failure or another failure by its cause. The merged status is error only when every applicable scanner failed. The fail_closed setting then decides that case as before. One scanner failing while another returns clean now reads clean.
This commit is contained in:
@@ -0,0 +1,118 @@
|
|||||||
|
package scanner
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/lukaszraczylo/gohoarder/pkg/config"
|
||||||
|
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
)
|
||||||
|
|
||||||
|
func stubResult(name string, status metadata.ScanStatus, details map[string]interface{}, vulns ...metadata.Vulnerability) *stubScanner {
|
||||||
|
return &stubScanner{name: name, result: &metadata.ScanResult{
|
||||||
|
ID: name, Scanner: name, ScannedAt: time.Now(), Status: status, Details: details,
|
||||||
|
Vulnerabilities: vulns, VulnerabilityCount: len(vulns),
|
||||||
|
}}
|
||||||
|
}
|
||||||
|
|
||||||
|
func scanWith(t *testing.T, cfg config.SecurityConfig, scanners ...Scanner) *metadata.ScanResult {
|
||||||
|
t.Helper()
|
||||||
|
store := &stubMetadataStore{}
|
||||||
|
mgr, err := New(cfg, store)
|
||||||
|
require.NoError(t, err)
|
||||||
|
t.Cleanup(mgr.Stop)
|
||||||
|
for _, s := range scanners {
|
||||||
|
mgr.RegisterScanner(s)
|
||||||
|
}
|
||||||
|
require.NoError(t, mgr.ScanPackage(context.Background(), "npm", "left-pad", "1.0.0", "/tmp/x"))
|
||||||
|
require.Len(t, store.savedResults, 1)
|
||||||
|
return store.savedResults[0]
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestScanPackage_ErrorResultPlusCleanReadsClean(t *testing.T) {
|
||||||
|
for _, failClosed := range []bool{false, true} {
|
||||||
|
saved := scanWith(t, config.SecurityConfig{Enabled: true, FailClosed: failClosed},
|
||||||
|
stubResult("npm-audit", metadata.ScanStatusError, map[string]interface{}{"error": "parse"}),
|
||||||
|
stubResult("osv", metadata.ScanStatusClean, nil))
|
||||||
|
|
||||||
|
assert.Equal(t, metadata.ScanStatusClean, saved.Status, "fail_closed=%v", failClosed)
|
||||||
|
assert.Equal(t, "osv", saved.Scanner, "a failed scanner is not part of the merge")
|
||||||
|
assert.NotContains(t, saved.Details, "npm-audit")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestScanPackage_ErrorResultDoesNotHideFindings(t *testing.T) {
|
||||||
|
saved := scanWith(t, config.SecurityConfig{Enabled: true},
|
||||||
|
stubResult("npm-audit", metadata.ScanStatusError, nil),
|
||||||
|
stubResult("osv", metadata.ScanStatusVulnerable, nil, vuln("CVE-1", "HIGH")))
|
||||||
|
|
||||||
|
assert.Equal(t, metadata.ScanStatusVulnerable, saved.Status)
|
||||||
|
assert.Len(t, saved.Vulnerabilities, 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestScanPackage_AllErrorResultsReadError(t *testing.T) {
|
||||||
|
saved := scanWith(t, config.SecurityConfig{Enabled: true},
|
||||||
|
stubResult("npm-audit", metadata.ScanStatusError, map[string]interface{}{"error": "parse"}),
|
||||||
|
stubResult("grype", metadata.ScanStatusError, nil))
|
||||||
|
|
||||||
|
assert.Equal(t, metadata.ScanStatusError, saved.Status)
|
||||||
|
assert.NotEqual(t, true, saved.Details[DetailInfrastructureError], "no failure was infrastructure")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestScanPackage_InfrastructureErrorResultsCountAsInfrastructure(t *testing.T) {
|
||||||
|
infra := map[string]interface{}{DetailInfrastructureError: true}
|
||||||
|
|
||||||
|
t.Run("all infrastructure", func(t *testing.T) {
|
||||||
|
saved := scanWith(t, config.SecurityConfig{Enabled: true},
|
||||||
|
stubResult("npm-audit", metadata.ScanStatusError, infra),
|
||||||
|
stubResult("trivy", metadata.ScanStatusError, infra))
|
||||||
|
assert.Equal(t, metadata.ScanStatusError, saved.Status)
|
||||||
|
assert.Equal(t, true, saved.Details[DetailInfrastructureError])
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("one other failure makes it a package failure", func(t *testing.T) {
|
||||||
|
saved := scanWith(t, config.SecurityConfig{Enabled: true},
|
||||||
|
stubResult("npm-audit", metadata.ScanStatusError, infra),
|
||||||
|
stubResult("grype", metadata.ScanStatusError, nil))
|
||||||
|
assert.NotEqual(t, true, saved.Details[DetailInfrastructureError])
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestScanPackage_ErrorPlusCleanIsServedEvenWhenFailClosed(t *testing.T) {
|
||||||
|
cfg := config.SecurityConfig{Enabled: true, FailClosed: true}
|
||||||
|
saved := scanWith(t, cfg,
|
||||||
|
stubResult("npm-audit", metadata.ScanStatusError, nil),
|
||||||
|
stubResult("osv", metadata.ScanStatusClean, nil))
|
||||||
|
|
||||||
|
mgr, err := New(cfg, &resultStore{stubMetadataStore: &stubMetadataStore{}, scan: saved})
|
||||||
|
require.NoError(t, err)
|
||||||
|
blocked, reason, err := mgr.CheckVulnerabilities(context.Background(), "npm", "left-pad", "1.0.0")
|
||||||
|
require.NoError(t, err)
|
||||||
|
assert.False(t, blocked, "reason %q", reason)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestScanPackage_BlockingStillAppliesToRealFindings(t *testing.T) {
|
||||||
|
cfg := config.SecurityConfig{Enabled: true, BlockOnSeverity: "high",
|
||||||
|
BlockThresholds: config.VulnerabilityThresholds{Critical: -1, High: -1, Medium: -1, Low: -1}}
|
||||||
|
saved := scanWith(t, cfg,
|
||||||
|
stubResult("npm-audit", metadata.ScanStatusError, nil),
|
||||||
|
stubResult("osv", metadata.ScanStatusVulnerable, nil, vuln("CVE-1", "HIGH")))
|
||||||
|
|
||||||
|
mgr, err := New(cfg, &resultStore{stubMetadataStore: &stubMetadataStore{}, scan: saved})
|
||||||
|
require.NoError(t, err)
|
||||||
|
blocked, _, err := mgr.CheckVulnerabilities(context.Background(), "npm", "left-pad", "1.0.0")
|
||||||
|
require.NoError(t, err)
|
||||||
|
assert.True(t, blocked)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMergeResults_IgnoresErrorResults(t *testing.T) {
|
||||||
|
mgr := newTestManager(t, &stubMetadataStore{})
|
||||||
|
ok := stubResult("osv", metadata.ScanStatusClean, nil).result
|
||||||
|
bad := stubResult("grype", metadata.ScanStatusError, nil).result
|
||||||
|
|
||||||
|
assert.Equal(t, metadata.ScanStatusClean, mgr.mergeResults([]*metadata.ScanResult{bad, ok}, []string{"grype", "osv"}).Status)
|
||||||
|
assert.Equal(t, metadata.ScanStatusError, mgr.mergeResults([]*metadata.ScanResult{bad, bad}, []string{"a", "b"}).Status)
|
||||||
|
}
|
||||||
@@ -1,35 +0,0 @@
|
|||||||
package pipaudit
|
|
||||||
|
|
||||||
import (
|
|
||||||
"os"
|
|
||||||
"path/filepath"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"github.com/stretchr/testify/require"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestCopyInto(t *testing.T) {
|
|
||||||
s := &Scanner{}
|
|
||||||
src := filepath.Join(t.TempDir(), "pkg.whl")
|
|
||||||
require.NoError(t, os.WriteFile(src, []byte("wheel"), 0600))
|
|
||||||
|
|
||||||
t.Run("copies inside dir", func(t *testing.T) {
|
|
||||||
dir := t.TempDir()
|
|
||||||
require.NoError(t, s.copyInto(src, dir, "pkg.whl"))
|
|
||||||
got, err := os.ReadFile(filepath.Join(dir, "pkg.whl"))
|
|
||||||
require.NoError(t, err)
|
|
||||||
require.Equal(t, "wheel", string(got))
|
|
||||||
})
|
|
||||||
|
|
||||||
t.Run("refuses name escaping dir", func(t *testing.T) {
|
|
||||||
parent := t.TempDir()
|
|
||||||
dir := filepath.Join(parent, "sub")
|
|
||||||
require.NoError(t, os.Mkdir(dir, 0750))
|
|
||||||
require.Error(t, s.copyInto(src, dir, "../escape.whl"))
|
|
||||||
require.NoFileExists(t, filepath.Join(parent, "escape.whl"))
|
|
||||||
})
|
|
||||||
|
|
||||||
t.Run("missing source", func(t *testing.T) {
|
|
||||||
require.Error(t, s.copyInto(filepath.Join(t.TempDir(), "none"), t.TempDir(), "x"))
|
|
||||||
})
|
|
||||||
}
|
|
||||||
@@ -8,6 +8,7 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
// ErrInfrastructure marks a failure of the scanning machinery (timeout,
|
// ErrInfrastructure marks a failure of the scanning machinery (timeout,
|
||||||
@@ -44,3 +45,23 @@ func IsInfrastructure(err error) bool {
|
|||||||
}
|
}
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// DetailInfrastructure is the scan-result detail key that marks an error result as infrastructure.
|
||||||
|
const DetailInfrastructure = "infrastructure_error"
|
||||||
|
|
||||||
|
// ErrorDetails builds the Details of a scan-error result.
|
||||||
|
func ErrorDetails(reason string, infra bool) map[string]interface{} {
|
||||||
|
return map[string]interface{}{"error": reason, DetailInfrastructure: infra}
|
||||||
|
}
|
||||||
|
|
||||||
|
var networkMarkers = []string{"ENOTFOUND", "ETIMEDOUT", "ECONNREFUSED", "ECONNRESET", "EAI_AGAIN", "i/o timeout", "no such host", "connection refused"}
|
||||||
|
|
||||||
|
// NetworkFailure reports whether a tool's output shows it could not reach the network.
|
||||||
|
func NetworkFailure(output string) bool {
|
||||||
|
for _, m := range networkMarkers {
|
||||||
|
if strings.Contains(output, m) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|||||||
+44
-11
@@ -48,7 +48,7 @@ type DatabaseUpdater interface {
|
|||||||
const (
|
const (
|
||||||
// DetailInfrastructureError marks a stored scan-error result as caused by
|
// DetailInfrastructureError marks a stored scan-error result as caused by
|
||||||
// scanner infrastructure (timeout, upstream 5xx) rather than by the package.
|
// scanner infrastructure (timeout, upstream 5xx) rather than by the package.
|
||||||
DetailInfrastructureError = "infrastructure_error"
|
DetailInfrastructureError = scanerr.DetailInfrastructure
|
||||||
|
|
||||||
defaultScanRetryInterval = 5 * time.Minute
|
defaultScanRetryInterval = 5 * time.Minute
|
||||||
maxScanRetries = 6
|
maxScanRetries = 6
|
||||||
@@ -326,6 +326,22 @@ func (m *Manager) scan(ctx context.Context, registry, packageName, version strin
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// A scanner that returns an error-status result failed exactly like one
|
||||||
|
// that returns an error: another scanner's verdict still stands.
|
||||||
|
if result.Status == metadata.ScanStatusError {
|
||||||
|
log.Error().
|
||||||
|
Str("scanner", scanner.Name()).
|
||||||
|
Str("package", packageName).
|
||||||
|
Interface("details", result.Details).
|
||||||
|
Msg("Scanner returned an error result")
|
||||||
|
if infra, _ := result.Details[DetailInfrastructureError].(bool); infra {
|
||||||
|
infraFailures++
|
||||||
|
} else {
|
||||||
|
otherFailures++
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
scanResults = append(scanResults, result)
|
scanResults = append(scanResults, result)
|
||||||
scannerNames = append(scannerNames, scanner.Name())
|
scannerNames = append(scannerNames, scanner.Name())
|
||||||
|
|
||||||
@@ -430,13 +446,36 @@ func (m *Manager) scanVersion(ctx context.Context, registry, packageName, versio
|
|||||||
return pkg.ReleaseVersion
|
return pkg.ReleaseVersion
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// succeeded drops error-status results; a failed scanner leaves no trace in the merge.
|
||||||
|
func succeeded(results []*metadata.ScanResult, names []string) ([]*metadata.ScanResult, []string) {
|
||||||
|
okResults := make([]*metadata.ScanResult, 0, len(results))
|
||||||
|
okNames := make([]string, 0, len(results))
|
||||||
|
for i, r := range results {
|
||||||
|
if r.Status == metadata.ScanStatusError {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
okResults = append(okResults, r)
|
||||||
|
okNames = append(okNames, names[i])
|
||||||
|
}
|
||||||
|
return okResults, okNames
|
||||||
|
}
|
||||||
|
|
||||||
// mergeResults merges and deduplicates scan results from multiple scanners
|
// mergeResults merges and deduplicates scan results from multiple scanners
|
||||||
func (m *Manager) mergeResults(results []*metadata.ScanResult, scannerNames []string) *metadata.ScanResult {
|
func (m *Manager) mergeResults(results []*metadata.ScanResult, scannerNames []string) *metadata.ScanResult {
|
||||||
if len(results) == 0 {
|
if len(results) == 0 {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Use first result as base
|
results, scannerNames = succeeded(results, scannerNames)
|
||||||
|
|
||||||
|
// Use first result as base, or the failure itself when none succeeded
|
||||||
|
if len(results) == 0 {
|
||||||
|
return &metadata.ScanResult{
|
||||||
|
Status: metadata.ScanStatusError,
|
||||||
|
Vulnerabilities: make([]metadata.Vulnerability, 0),
|
||||||
|
Details: map[string]interface{}{"error": "all scanners failed"},
|
||||||
|
}
|
||||||
|
}
|
||||||
merged := &metadata.ScanResult{
|
merged := &metadata.ScanResult{
|
||||||
ID: results[0].ID,
|
ID: results[0].ID,
|
||||||
Registry: results[0].Registry,
|
Registry: results[0].Registry,
|
||||||
@@ -506,19 +545,13 @@ func (m *Manager) mergeResults(results []*metadata.ScanResult, scannerNames []st
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Update status to worst case.
|
// Update status to worst case: vulnerable > pending > clean.
|
||||||
// Order: vulnerable > error > pending > clean. Vulnerable wins because
|
// Error results never reach this loop (see succeeded).
|
||||||
// the cache layer must surface the actual vulns. Otherwise, if any
|
|
||||||
// scanner errored, propagate so CheckVulnerabilities can fail closed.
|
|
||||||
switch result.Status {
|
switch result.Status {
|
||||||
case metadata.ScanStatusVulnerable:
|
case metadata.ScanStatusVulnerable:
|
||||||
merged.Status = metadata.ScanStatusVulnerable
|
merged.Status = metadata.ScanStatusVulnerable
|
||||||
case metadata.ScanStatusError:
|
|
||||||
if merged.Status != metadata.ScanStatusVulnerable {
|
|
||||||
merged.Status = metadata.ScanStatusError
|
|
||||||
}
|
|
||||||
case metadata.ScanStatusPending:
|
case metadata.ScanStatusPending:
|
||||||
if merged.Status != metadata.ScanStatusVulnerable && merged.Status != metadata.ScanStatusError {
|
if merged.Status != metadata.ScanStatusVulnerable {
|
||||||
merged.Status = metadata.ScanStatusPending
|
merged.Status = metadata.ScanStatusPending
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,65 @@
|
|||||||
|
// Package scannertest supplies fake scanner binaries for tests of the CLI wrappers.
|
||||||
|
package scannertest
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strconv"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Fake puts an executable called name first on PATH. It records its arguments, one per line, in
|
||||||
|
// the returned file, writes stdoutFile to stdout and stderr to stderr, and exits with code.
|
||||||
|
func Fake(t *testing.T, name, stdoutFile, stderr string, code int) (argsFile string) {
|
||||||
|
t.Helper()
|
||||||
|
dir := t.TempDir()
|
||||||
|
argsFile = filepath.Join(dir, "args")
|
||||||
|
script := "#!/bin/sh\n" +
|
||||||
|
"for a in \"$@\"; do printf '%s\\n' \"$a\" >> '" + argsFile + "'; done\n" +
|
||||||
|
"pwd > '" + filepath.Join(dir, "cwd") + "'\n"
|
||||||
|
if stdoutFile != "" {
|
||||||
|
abs, err := filepath.Abs(stdoutFile)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
script += "cat '" + abs + "'\n"
|
||||||
|
}
|
||||||
|
if stderr != "" {
|
||||||
|
script += "printf '%s' '" + stderr + "' >&2\n"
|
||||||
|
}
|
||||||
|
script += "exit " + strconv.Itoa(code) + "\n"
|
||||||
|
install(t, dir, name, script)
|
||||||
|
return argsFile
|
||||||
|
}
|
||||||
|
|
||||||
|
// Script puts a shell executable called name, with the given body, first on PATH.
|
||||||
|
func Script(t *testing.T, name, body string) {
|
||||||
|
t.Helper()
|
||||||
|
install(t, t.TempDir(), name, "#!/bin/sh\n"+body+"\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
func install(t *testing.T, dir, name, script string) {
|
||||||
|
t.Helper()
|
||||||
|
if err := os.WriteFile(filepath.Join(dir, name), []byte(script), 0o700); err != nil { // #nosec G306 -- test helper must be executable
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH"))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Args returns the arguments the fake was called with.
|
||||||
|
func Args(t *testing.T, argsFile string) []string {
|
||||||
|
t.Helper()
|
||||||
|
data, err := os.ReadFile(argsFile) // #nosec G304 -- test temp file
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var out []string
|
||||||
|
start := 0
|
||||||
|
for i, b := range data {
|
||||||
|
if b == '\n' {
|
||||||
|
out = append(out, string(data[start:i]))
|
||||||
|
start = i + 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
@@ -13,6 +13,7 @@ import (
|
|||||||
|
|
||||||
"github.com/lukaszraczylo/gohoarder/pkg/config"
|
"github.com/lukaszraczylo/gohoarder/pkg/config"
|
||||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||||
|
"github.com/lukaszraczylo/gohoarder/pkg/scanner/scanerr"
|
||||||
"github.com/lukaszraczylo/gohoarder/pkg/uuid"
|
"github.com/lukaszraczylo/gohoarder/pkg/uuid"
|
||||||
"github.com/rs/zerolog/log"
|
"github.com/rs/zerolog/log"
|
||||||
)
|
)
|
||||||
@@ -140,9 +141,7 @@ func (s *Scanner) Scan(ctx context.Context, registry, packageName, version strin
|
|||||||
Scanner: s.Name(),
|
Scanner: s.Name(),
|
||||||
ScannedAt: time.Now(),
|
ScannedAt: time.Now(),
|
||||||
Status: metadata.ScanStatusError,
|
Status: metadata.ScanStatusError,
|
||||||
Details: map[string]interface{}{
|
Details: scanerr.ErrorDetails("scan timeout", true),
|
||||||
"error": "scan timeout",
|
|
||||||
},
|
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,24 @@
|
|||||||
|
package trivy
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/lukaszraczylo/gohoarder/pkg/config"
|
||||||
|
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||||
|
"github.com/lukaszraczylo/gohoarder/pkg/scanner/scanerr"
|
||||||
|
"github.com/lukaszraczylo/gohoarder/pkg/scanner/scannertest"
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestScanTimeoutIsAnInfrastructureErrorResult(t *testing.T) {
|
||||||
|
scannertest.Script(t, "trivy", "exec sleep 5")
|
||||||
|
|
||||||
|
res, err := New(config.TrivyConfig{Timeout: 100 * time.Millisecond}).Scan(context.Background(), "npm", "p", "1", "/x")
|
||||||
|
|
||||||
|
require.NoError(t, err)
|
||||||
|
assert.Equal(t, metadata.ScanStatusError, res.Status)
|
||||||
|
assert.Equal(t, true, res.Details[scanerr.DetailInfrastructure])
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user