mirror of
https://github.com/lukaszraczylo/gohoarder.git
synced 2026-11-28 06:46:26 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7fcbbcab0b | ||
|
|
2de0bf029d | ||
|
|
17d7bebf88 |
@@ -184,6 +184,7 @@ type SecurityConfig struct {
|
||||
RescanConcurrency int `mapstructure:"rescan_concurrency" json:"rescan_concurrency"` // scans run in parallel per rescan cycle; <1 = 1
|
||||
ScanRetryInterval time.Duration `mapstructure:"scan_retry_interval" json:"scan_retry_interval"` // wait before retrying a scan that failed on infrastructure; 0 = 5m
|
||||
ScanWaitTimeout time.Duration `mapstructure:"scan_wait_timeout" json:"scan_wait_timeout"` // how long a first download waits for its scan; 0 = 30s
|
||||
MinFreeBytes int64 `mapstructure:"min_free_bytes" json:"min_free_bytes"` // defer scans while the temp dir has less free space; 0 = off
|
||||
FailClosed bool `mapstructure:"fail_closed" json:"fail_closed"` // refuse packages whose scan failed on infrastructure
|
||||
Enabled bool `mapstructure:"enabled" json:"enabled"`
|
||||
ScanOnDownload bool `mapstructure:"scan_on_download" json:"scan_on_download"`
|
||||
@@ -236,8 +237,9 @@ type StaticConfig struct {
|
||||
|
||||
// GrypeConfig contains Grype scanner configuration
|
||||
type GrypeConfig struct {
|
||||
Enabled bool `mapstructure:"enabled" json:"enabled"`
|
||||
Timeout time.Duration `mapstructure:"timeout" json:"timeout"`
|
||||
Enabled bool `mapstructure:"enabled" json:"enabled"`
|
||||
Timeout time.Duration `mapstructure:"timeout" json:"timeout"`
|
||||
DBUpdateInterval time.Duration `mapstructure:"db_update_interval" json:"db_update_interval"` // must stay under grype's 120h max database age; 0 = 6h
|
||||
}
|
||||
|
||||
// GovulncheckConfig contains govulncheck scanner configuration
|
||||
@@ -424,8 +426,9 @@ func Default() *Config {
|
||||
BlockSuspicious: false,
|
||||
},
|
||||
Grype: GrypeConfig{
|
||||
Enabled: false,
|
||||
Timeout: 5 * time.Minute,
|
||||
Enabled: false,
|
||||
Timeout: 5 * time.Minute,
|
||||
DBUpdateInterval: 6 * time.Hour,
|
||||
},
|
||||
Govulncheck: GovulncheckConfig{
|
||||
Enabled: false,
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
package scanner
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/config"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
type diskProbeScanner struct {
|
||||
stubScanner
|
||||
calls int
|
||||
}
|
||||
|
||||
func (c *diskProbeScanner) Scan(ctx context.Context, registry, packageName, version, path string) (*metadata.ScanResult, error) {
|
||||
c.calls++
|
||||
return c.stubScanner.Scan(ctx, registry, packageName, version, path)
|
||||
}
|
||||
|
||||
func diskGuardManager(t *testing.T, minFree int64, free uint64, freeErr error) (*Manager, *stubMetadataStore, *diskProbeScanner) {
|
||||
t.Helper()
|
||||
store := &stubMetadataStore{}
|
||||
mgr, err := New(config.SecurityConfig{Enabled: true, MinFreeBytes: minFree, ScanRetryInterval: time.Hour}, store)
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(mgr.Stop)
|
||||
mgr.freeBytes = func(string) (uint64, error) { return free, freeErr }
|
||||
s := &diskProbeScanner{stubScanner: *stubResult("trivy", metadata.ScanStatusClean, nil)}
|
||||
mgr.RegisterScanner(s)
|
||||
return mgr, store, s
|
||||
}
|
||||
|
||||
func TestScanIsDeferredWhenDiskIsLow(t *testing.T) {
|
||||
mgr, store, s := diskGuardManager(t, 1<<30, 1<<20, nil)
|
||||
|
||||
require.NoError(t, mgr.ScanPackage(context.Background(), "npm", "left-pad", "1.0.0", "/tmp/x"))
|
||||
|
||||
assert.Zero(t, s.calls, "no scanner may run on a full disk")
|
||||
require.Len(t, store.savedResults, 1)
|
||||
assert.Equal(t, metadata.ScanStatusError, store.savedResults[0].Status)
|
||||
assert.Equal(t, true, store.savedResults[0].Details[DetailInfrastructureError], "low disk is retried, not blamed on the package")
|
||||
}
|
||||
|
||||
func TestScanRunsWhenDiskHasRoom(t *testing.T) {
|
||||
mgr, store, s := diskGuardManager(t, 1<<30, 2<<30, nil)
|
||||
|
||||
require.NoError(t, mgr.ScanPackage(context.Background(), "npm", "left-pad", "1.0.0", "/tmp/x"))
|
||||
|
||||
assert.Equal(t, 1, s.calls)
|
||||
require.Len(t, store.savedResults, 1)
|
||||
assert.Equal(t, metadata.ScanStatusClean, store.savedResults[0].Status)
|
||||
}
|
||||
|
||||
func TestDiskGuardOffByDefault(t *testing.T) {
|
||||
mgr, _, s := diskGuardManager(t, 0, 0, nil)
|
||||
|
||||
require.NoError(t, mgr.ScanPackage(context.Background(), "npm", "left-pad", "1.0.0", "/tmp/x"))
|
||||
|
||||
assert.Equal(t, 1, s.calls)
|
||||
}
|
||||
|
||||
func TestDiskGuardMeasurementFailureDoesNotBlockScans(t *testing.T) {
|
||||
mgr, _, s := diskGuardManager(t, 1<<30, 0, errors.New("statfs failed"))
|
||||
|
||||
require.NoError(t, mgr.ScanPackage(context.Background(), "npm", "left-pad", "1.0.0", "/tmp/x"))
|
||||
|
||||
assert.Equal(t, 1, s.calls)
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package scanner
|
||||
|
||||
import (
|
||||
stderrors "errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"syscall"
|
||||
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
var errLowDiskSpace = stderrors.New("not enough free disk space to scan")
|
||||
|
||||
// checkDiskSpace refuses a scan while the temp dir, where scanners unpack packages, is short
|
||||
// of space. A failed measurement never blocks scans.
|
||||
func (m *Manager) checkDiskSpace() error {
|
||||
if m.config.MinFreeBytes <= 0 || m.freeBytes == nil {
|
||||
return nil
|
||||
}
|
||||
dir := os.TempDir()
|
||||
free, err := m.freeBytes(dir)
|
||||
if err != nil {
|
||||
log.Warn().Err(err).Str("dir", dir).Msg("Cannot measure free disk space")
|
||||
return nil
|
||||
}
|
||||
if need := uint64(m.config.MinFreeBytes); free < need {
|
||||
return fmt.Errorf("%w: %d bytes free in %s, need %d", errLowDiskSpace, free, dir, need)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func diskFree(path string) (uint64, error) {
|
||||
var st syscall.Statfs_t
|
||||
if err := syscall.Statfs(path, &st); err != nil {
|
||||
return 0, fmt.Errorf("statfs %s: %w", path, err)
|
||||
}
|
||||
return st.Bavail * uint64(st.Bsize), nil // #nosec G115 -- block size is never negative
|
||||
}
|
||||
@@ -83,14 +83,21 @@ func (s *Scanner) Scan(ctx context.Context, registry, packageName, version strin
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create temp dir: %w", err)
|
||||
}
|
||||
defer func() { _ = os.RemoveAll(tmpDir) }()
|
||||
defer func() {
|
||||
if rmErr := os.RemoveAll(tmpDir); rmErr != nil {
|
||||
log.Warn().Err(rmErr).Str("scanner", ScannerName).Str("dir", tmpDir).Msg("Cannot remove scan directory")
|
||||
}
|
||||
}()
|
||||
|
||||
// govulncheck never reports advisories against the main module of the tree it scans, so
|
||||
// scanning the module's own source reports a vulnerable module clean. The module is
|
||||
// scanned as a dependency of a wrapper module instead, and the wrapper imports its
|
||||
// packages because module-mode scanning only considers modules that provide an import.
|
||||
// Resolving the module reaches the module proxy.
|
||||
env := append(os.Environ(), "GOFLAGS=-mod=mod", "GOTOOLCHAIN=local", "GOWORK=off")
|
||||
// The dependency tree goes to a module cache inside tmpDir, so the scan keeps nothing on disk;
|
||||
// -modcacherw leaves that cache writable, or RemoveAll cannot delete it.
|
||||
env := append(os.Environ(), "GOFLAGS=-mod=mod -modcacherw", "GOTOOLCHAIN=local", "GOWORK=off",
|
||||
"GOMODCACHE="+filepath.Join(tmpDir, "modcache"))
|
||||
goMod := fmt.Sprintf("module gohoarder.audit\n\nrequire %s %s\n", module, version)
|
||||
if err = os.WriteFile(filepath.Join(tmpDir, "go.mod"), []byte(goMod), 0o600); err != nil {
|
||||
return nil, fmt.Errorf("failed to write go.mod: %w", err)
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/config"
|
||||
@@ -132,7 +133,7 @@ func TestScanAuditsTheModuleItself(t *testing.T) {
|
||||
|
||||
env, err := os.ReadFile(filepath.Join(rec, "env")) // #nosec G304 -- test temp dir
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "-mod=mod|local\n", string(env))
|
||||
assert.Equal(t, "-mod=mod -modcacherw|local\n", string(env))
|
||||
|
||||
assert.Equal(t, []string{"-json", "-scan", "module"}, scannertest.Args(t, args))
|
||||
|
||||
@@ -144,6 +145,32 @@ func TestScanAuditsTheModuleItself(t *testing.T) {
|
||||
assert.NotContains(t, imports, "/internal", "internal packages cannot be imported")
|
||||
}
|
||||
|
||||
func TestScanRemovesTheModulesItDownloaded(t *testing.T) {
|
||||
rec := t.TempDir()
|
||||
// Like go, the fake leaves the module cache read-only unless GOFLAGS has -modcacherw.
|
||||
scannertest.Script(t, "go", fmt.Sprintf(`
|
||||
[ -n "$GOMODCACHE" ] || exit 1
|
||||
mkdir -p "$GOMODCACHE/example.com/[email protected]"
|
||||
touch "$GOMODCACHE/example.com/[email protected]/dep.go"
|
||||
case "$GOFLAGS" in *-modcacherw*) ;; *) chmod 0555 "$GOMODCACHE/example.com/[email protected]" ;; esac
|
||||
echo "$GOMODCACHE" > %q/go
|
||||
echo "github.com/google/uuid uuid 12 0 "`, rec))
|
||||
scannertest.Script(t, "govulncheck", fmt.Sprintf(`
|
||||
echo "$GOMODCACHE" > %q/govulncheck
|
||||
cat %q`, rec, abs(t, "google-uuid-v1.6.0.stream")))
|
||||
|
||||
res, err := New(config.GovulncheckConfig{}).Scan(context.Background(), "go", "github.com/google/uuid/@v/v1.6.0.zip", "v1.6.0", module(t))
|
||||
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, metadata.ScanStatusClean, res.Status)
|
||||
listCache, err := os.ReadFile(filepath.Join(rec, "go")) // #nosec G304 -- test temp dir
|
||||
require.NoError(t, err)
|
||||
scanCache, err := os.ReadFile(filepath.Join(rec, "govulncheck")) // #nosec G304 -- test temp dir
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, string(listCache), string(scanCache), "govulncheck reads the modules go list downloaded")
|
||||
assert.NoDirExists(t, strings.TrimSpace(string(listCache)), "the scan keeps no downloaded modules")
|
||||
}
|
||||
|
||||
func TestScanCleanModule(t *testing.T) {
|
||||
scannertest.Script(t, "go", `echo "github.com/google/uuid uuid 12 0 "`)
|
||||
_, _ = fakeGovulncheck(t, abs(t, "google-uuid-v1.6.0.stream"), 0, "")
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
package grype
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultDBUpdateInterval = 6 * time.Hour
|
||||
// grype's own limits are 30s for the update check and 5m for the download.
|
||||
dbUpdateTimeout = 10 * time.Minute
|
||||
// Far past dbUpdateTimeout, so only a download whose grype process died is removed.
|
||||
abandonedAfter = time.Hour
|
||||
|
||||
downloadPrefix = "grype-db-download"
|
||||
// go-getter, which grype downloads through, stages the archive in the temp dir.
|
||||
getterPrefix = "getter"
|
||||
)
|
||||
|
||||
// RefreshDatabase updates the database every interval until stop closes. immediate runs
|
||||
// the first update at once; otherwise it waits one interval. interval 0 means 6h.
|
||||
func (s *Scanner) RefreshDatabase(stop <-chan struct{}, interval time.Duration, immediate bool) {
|
||||
if interval <= 0 {
|
||||
interval = defaultDBUpdateInterval
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
go func() {
|
||||
<-stop
|
||||
cancel()
|
||||
}()
|
||||
|
||||
if immediate {
|
||||
s.refreshOnce(ctx)
|
||||
}
|
||||
ticker := time.NewTicker(interval)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ticker.C:
|
||||
s.refreshOnce(ctx)
|
||||
case <-ctx.Done():
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Scanner) refreshOnce(ctx context.Context) {
|
||||
if err := s.UpdateDatabase(ctx); err != nil {
|
||||
log.Error().Err(err).Str("scanner", ScannerName).Msg("Scheduled Grype database update failed")
|
||||
}
|
||||
}
|
||||
|
||||
// dbCacheDir mirrors grype's db.cache-dir default and its GRYPE_DB_CACHE_DIR override.
|
||||
func dbCacheDir() (string, error) {
|
||||
if dir := os.Getenv("GRYPE_DB_CACHE_DIR"); dir != "" {
|
||||
return dir, nil
|
||||
}
|
||||
home, err := os.UserHomeDir()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return filepath.Join(home, ".cache", "grype", "db"), nil
|
||||
}
|
||||
|
||||
// removeAbandonedDownloads deletes database downloads last touched before cutoff. A grype
|
||||
// process killed mid-download never removes its staging dirs.
|
||||
func removeAbandonedDownloads(cutoff time.Time) {
|
||||
if dir, err := dbCacheDir(); err != nil {
|
||||
log.Warn().Err(err).Str("scanner", ScannerName).Msg("Cannot locate the Grype database cache")
|
||||
} else {
|
||||
removeStaleDirs(dir, downloadPrefix, cutoff)
|
||||
}
|
||||
removeStaleDirs(os.TempDir(), getterPrefix, cutoff)
|
||||
}
|
||||
|
||||
func removeStaleDirs(dir, prefix string, cutoff time.Time) {
|
||||
entries, err := os.ReadDir(dir)
|
||||
if err != nil {
|
||||
if !errors.Is(err, fs.ErrNotExist) {
|
||||
log.Warn().Err(err).Str("dir", dir).Msg("Cannot list dir for abandoned Grype downloads")
|
||||
}
|
||||
return
|
||||
}
|
||||
for _, e := range entries {
|
||||
if !e.IsDir() || !strings.HasPrefix(e.Name(), prefix) {
|
||||
continue
|
||||
}
|
||||
info, err := e.Info()
|
||||
if err != nil || !info.ModTime().Before(cutoff) {
|
||||
continue
|
||||
}
|
||||
path := filepath.Join(dir, e.Name())
|
||||
if err := os.RemoveAll(path); err != nil {
|
||||
log.Warn().Err(err).Str("path", path).Msg("Cannot remove abandoned Grype download")
|
||||
continue
|
||||
}
|
||||
log.Info().Str("path", path).Msg("Removed abandoned Grype download")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
package grype
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/config"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner/scannertest"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestScanDisablesDatabaseAutoUpdate(t *testing.T) {
|
||||
envFile := filepath.Join(t.TempDir(), "env")
|
||||
fix, err := filepath.Abs(fixture("purl-minimist-0.0.8.json"))
|
||||
require.NoError(t, err)
|
||||
scannertest.Script(t, "grype", "printf '%s' \"$GRYPE_DB_AUTO_UPDATE\" > '"+envFile+"'\ncat '"+fix+"'")
|
||||
|
||||
_, err = New(config.GrypeConfig{}).Scan(context.Background(), "npm", "minimist", "0.0.8", "/tmp/artifact")
|
||||
|
||||
require.NoError(t, err)
|
||||
got, err := os.ReadFile(envFile) // #nosec G304 -- test temp file
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "false", string(got), "a scan must never download the database itself")
|
||||
}
|
||||
|
||||
func mkdirAged(t *testing.T, path string, age time.Duration) {
|
||||
t.Helper()
|
||||
require.NoError(t, os.MkdirAll(path, 0o750))
|
||||
require.NoError(t, os.WriteFile(filepath.Join(path, "archive"), []byte("x"), 0o600))
|
||||
when := time.Now().Add(-age)
|
||||
require.NoError(t, os.Chtimes(path, when, when))
|
||||
}
|
||||
|
||||
func TestUpdateDatabaseRemovesAbandonedDownloads(t *testing.T) {
|
||||
cacheDir, tmpDir := t.TempDir(), t.TempDir()
|
||||
t.Setenv("GRYPE_DB_CACHE_DIR", cacheDir)
|
||||
t.Setenv("TMPDIR", tmpDir)
|
||||
scannertest.Fake(t, "grype", "", "", 0)
|
||||
|
||||
mkdirAged(t, filepath.Join(cacheDir, "grype-db-download111"), 2*time.Hour)
|
||||
mkdirAged(t, filepath.Join(cacheDir, "grype-db-download222"), time.Minute)
|
||||
mkdirAged(t, filepath.Join(cacheDir, "6"), 48*time.Hour)
|
||||
mkdirAged(t, filepath.Join(tmpDir, "getter333"), 2*time.Hour)
|
||||
mkdirAged(t, filepath.Join(tmpDir, "getter444"), time.Minute)
|
||||
mkdirAged(t, filepath.Join(tmpDir, "npm-audit-555"), 2*time.Hour)
|
||||
|
||||
require.NoError(t, New(config.GrypeConfig{}).UpdateDatabase(context.Background()))
|
||||
|
||||
assert.NoDirExists(t, filepath.Join(cacheDir, "grype-db-download111"))
|
||||
assert.NoDirExists(t, filepath.Join(tmpDir, "getter333"))
|
||||
assert.DirExists(t, filepath.Join(cacheDir, "grype-db-download222"), "a download in progress stays")
|
||||
assert.DirExists(t, filepath.Join(tmpDir, "getter444"), "a download in progress stays")
|
||||
assert.DirExists(t, filepath.Join(cacheDir, "6"), "the live database stays")
|
||||
assert.DirExists(t, filepath.Join(tmpDir, "npm-audit-555"), "other tools' temp dirs stay")
|
||||
}
|
||||
|
||||
func TestUpdateDatabaseNeverOverlaps(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
lock, overlap := filepath.Join(dir, "lock"), filepath.Join(dir, "overlap")
|
||||
scannertest.Script(t, "grype",
|
||||
"mkdir '"+lock+"' 2>/dev/null || echo x >> '"+overlap+"'\nsleep 0.2\nrmdir '"+lock+"' 2>/dev/null\nexit 0")
|
||||
s := New(config.GrypeConfig{})
|
||||
|
||||
done := make(chan error, 4)
|
||||
for range 4 {
|
||||
go func() { done <- s.UpdateDatabase(context.Background()) }()
|
||||
}
|
||||
for range 4 {
|
||||
require.NoError(t, <-done)
|
||||
}
|
||||
|
||||
assert.NoFileExists(t, overlap, "two database downloads ran at once")
|
||||
}
|
||||
|
||||
func TestUpdateDatabaseOutlivesCallerCancel(t *testing.T) {
|
||||
marker := filepath.Join(t.TempDir(), "finished")
|
||||
scannertest.Script(t, "grype", "sleep 0.3\ntouch '"+marker+"'")
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
|
||||
defer cancel()
|
||||
|
||||
_ = New(config.GrypeConfig{}).UpdateDatabase(ctx)
|
||||
|
||||
assert.FileExists(t, marker, "a cancelled caller must not kill the download half way")
|
||||
}
|
||||
|
||||
func TestRefreshDatabaseRunsOnInterval(t *testing.T) {
|
||||
calls := filepath.Join(t.TempDir(), "calls")
|
||||
scannertest.Script(t, "grype", "echo \"$1 $2\" >> '"+calls+"'")
|
||||
stop := make(chan struct{})
|
||||
exited := make(chan struct{})
|
||||
|
||||
go func() {
|
||||
New(config.GrypeConfig{}).RefreshDatabase(stop, 20*time.Millisecond, true)
|
||||
close(exited)
|
||||
}()
|
||||
|
||||
require.Eventually(t, func() bool {
|
||||
data, _ := os.ReadFile(calls) // #nosec G304 -- test temp file
|
||||
return strings.Count(string(data), "db update\n") >= 3
|
||||
}, 5*time.Second, 10*time.Millisecond)
|
||||
close(stop)
|
||||
select {
|
||||
case <-exited:
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("refresh loop did not stop")
|
||||
}
|
||||
}
|
||||
@@ -7,8 +7,10 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/config"
|
||||
@@ -26,6 +28,7 @@ const ScannerName = "grype"
|
||||
type Scanner struct {
|
||||
version scanver.Cache
|
||||
config config.GrypeConfig
|
||||
dbMu sync.Mutex
|
||||
}
|
||||
|
||||
// New creates a new Grype scanner
|
||||
@@ -54,6 +57,8 @@ func (s *Scanner) Scan(ctx context.Context, registry, packageName, version strin
|
||||
target = filePath
|
||||
}
|
||||
cmd := exec.CommandContext(ctx, "grype", target, "-o", "json", "-q") // #nosec G204 -- target is a purl or the stored artifact path
|
||||
// Concurrent scans each downloading the database filled the disk; RefreshDatabase owns updates.
|
||||
cmd.Env = append(os.Environ(), "GRYPE_DB_AUTO_UPDATE=false")
|
||||
var stderr bytes.Buffer
|
||||
cmd.Stderr = &stderr
|
||||
output, err := cmd.Output()
|
||||
@@ -116,10 +121,17 @@ func (s *Scanner) Health(ctx context.Context) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// UpdateDatabase updates Grype's vulnerability database
|
||||
// UpdateDatabase updates Grype's vulnerability database. Calls are serialised, and the
|
||||
// download outlives a cancelled ctx so it never leaves a half-written database behind.
|
||||
func (s *Scanner) UpdateDatabase(ctx context.Context) error {
|
||||
log.Info().Str("scanner", ScannerName).Msg("Updating Grype database")
|
||||
s.dbMu.Lock()
|
||||
defer s.dbMu.Unlock()
|
||||
|
||||
log.Info().Str("scanner", ScannerName).Msg("Updating Grype database")
|
||||
removeAbandonedDownloads(time.Now().Add(-abandonedAfter))
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), dbUpdateTimeout)
|
||||
defer cancel()
|
||||
cmd := exec.CommandContext(ctx, "grype", "db", "update")
|
||||
output, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
|
||||
+18
-2
@@ -99,6 +99,8 @@ type Manager struct {
|
||||
broadcaster events.Broadcaster
|
||||
retryTimers map[string]*time.Timer
|
||||
fileSource FileSource
|
||||
freeBytes func(path string) (uint64, error)
|
||||
stopCh chan struct{}
|
||||
inflight map[string]int
|
||||
scanners []Scanner
|
||||
config config.SecurityConfig
|
||||
@@ -113,10 +115,13 @@ func (m *Manager) Enabled() bool {
|
||||
return m.enabled
|
||||
}
|
||||
|
||||
// Stop cancels pending scan retries.
|
||||
// Stop cancels pending scan retries and background database refreshes.
|
||||
func (m *Manager) Stop() {
|
||||
m.stateMu.Lock()
|
||||
defer m.stateMu.Unlock()
|
||||
if !m.stopped && m.stopCh != nil {
|
||||
close(m.stopCh)
|
||||
}
|
||||
m.stopped = true
|
||||
for key, timer := range m.retryTimers {
|
||||
timer.Stop()
|
||||
@@ -212,6 +217,8 @@ func New(cfg config.SecurityConfig, metadataStore metadata.MetadataStore) (*Mana
|
||||
metadataStore: metadataStore,
|
||||
retryTimers: make(map[string]*time.Timer),
|
||||
inflight: make(map[string]int),
|
||||
freeBytes: diskFree,
|
||||
stopCh: make(chan struct{}),
|
||||
}
|
||||
|
||||
if !cfg.Enabled {
|
||||
@@ -252,6 +259,8 @@ func New(cfg config.SecurityConfig, metadataStore metadata.MetadataStore) (*Mana
|
||||
log.Warn().Err(err).Msg("Failed to update Grype database on startup")
|
||||
}
|
||||
}
|
||||
// Scans never update the database, so without this loop it ages past grype's limit.
|
||||
go grypeScanner.RefreshDatabase(manager.stopCh, cfg.Scanners.Grype.DBUpdateInterval, !cfg.UpdateDBOnStartup)
|
||||
}
|
||||
|
||||
// Initialize govulncheck scanner
|
||||
@@ -324,7 +333,14 @@ func (m *Manager) scan(ctx context.Context, registry, packageName, version strin
|
||||
scannerNames := make([]string, 0)
|
||||
var infraFailures, otherFailures int
|
||||
|
||||
for _, scanner := range m.scanners {
|
||||
scanners := m.scanners
|
||||
if err := m.checkDiskSpace(); err != nil {
|
||||
log.Warn().Err(err).Str("package", packageName).Msg("Deferring security scan")
|
||||
infraFailures++
|
||||
scanners = nil
|
||||
}
|
||||
|
||||
for _, scanner := range scanners {
|
||||
// Skip scanners that don't support this registry
|
||||
if !m.shouldRunScanner(scanner.Name(), registry) {
|
||||
log.Debug().
|
||||
|
||||
Reference in New Issue
Block a user