From f367ce618eb14ce9cb977403c7d760194e2c11d8 Mon Sep 17 00:00:00 2001 From: Lukasz Raczylo Date: Tue, 1 Dec 2026 03:20:49 +0000 Subject: [PATCH] fix(scanner): stop trivy scans from updating the database Each trivy scan updated the vulnerability database when the database was stale. Six concurrent rescans then downloaded it at the same time. A download took about 11 seconds alone and 38 seconds under contention. Five of six trivy processes crashed with SIGBUS, because they read a database that another process replaced. The other scans hit their timeout. Scans now run with --skip-db-update. A refresh loop updates the database every 6 hours (trivy.db_update_interval). Scans hold a read lock and an update holds the write lock, so an update never replaces the database under a running scan. A scan that finds no database downloads it once before it scans. The grype refresh loop moves to the dbrefresh package, which both scanners use. --- pkg/config/config.go | 14 ++-- pkg/scanner/dbrefresh/dbrefresh.go | 45 +++++++++++ pkg/scanner/grype/db.go | 33 +-------- pkg/scanner/leftovers_test.go | 11 ++- pkg/scanner/scanner.go | 2 + pkg/scanner/trivy/db_test.go | 115 +++++++++++++++++++++++++++++ pkg/scanner/trivy/trivy.go | 64 +++++++++++++++- pkg/scanner/trivy/trivy_test.go | 10 +-- 8 files changed, 250 insertions(+), 44 deletions(-) create mode 100644 pkg/scanner/dbrefresh/dbrefresh.go create mode 100644 pkg/scanner/trivy/db_test.go diff --git a/pkg/config/config.go b/pkg/config/config.go index f681700..8aa58a9 100644 --- a/pkg/config/config.go +++ b/pkg/config/config.go @@ -214,9 +214,10 @@ type ScannersConfig struct { // TrivyConfig contains Trivy scanner configuration type TrivyConfig struct { - CacheDB string `mapstructure:"cache_db" json:"cache_db"` - Timeout time.Duration `mapstructure:"timeout" json:"timeout"` - Enabled bool `mapstructure:"enabled" json:"enabled"` + CacheDB string `mapstructure:"cache_db" json:"cache_db"` + Timeout time.Duration `mapstructure:"timeout" json:"timeout"` + DBUpdateInterval time.Duration `mapstructure:"db_update_interval" json:"db_update_interval"` // 0 = 6h + Enabled bool `mapstructure:"enabled" json:"enabled"` } // OSVConfig contains OSV scanner configuration @@ -410,9 +411,10 @@ func Default() *Config { }, Scanners: ScannersConfig{ Trivy: TrivyConfig{ - Enabled: false, - Timeout: 5 * time.Minute, - CacheDB: "/var/lib/trivy", + Enabled: false, + Timeout: 5 * time.Minute, + CacheDB: "/var/lib/trivy", + DBUpdateInterval: 6 * time.Hour, }, OSV: OSVConfig{ Enabled: false, diff --git a/pkg/scanner/dbrefresh/dbrefresh.go b/pkg/scanner/dbrefresh/dbrefresh.go new file mode 100644 index 0000000..08c73dd --- /dev/null +++ b/pkg/scanner/dbrefresh/dbrefresh.go @@ -0,0 +1,45 @@ +// Package dbrefresh runs a scanner's vulnerability database update on a fixed interval. +package dbrefresh + +import ( + "context" + "time" + + "github.com/rs/zerolog/log" +) + +// DefaultInterval applies when the configured interval is 0. +const DefaultInterval = 6 * time.Hour + +// Run calls update every interval until stop closes. immediate runs the first update at once; +// otherwise it waits one interval. +func Run(stop <-chan struct{}, interval time.Duration, immediate bool, scanner string, update func(context.Context) error) { + if interval <= 0 { + interval = DefaultInterval + } + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + go func() { + <-stop + cancel() + }() + + once := func() { + if err := update(ctx); err != nil { + log.Error().Err(err).Str("scanner", scanner).Msg("Scheduled database update failed") + } + } + if immediate { + once() + } + ticker := time.NewTicker(interval) + defer ticker.Stop() + for { + select { + case <-ticker.C: + once() + case <-ctx.Done(): + return + } + } +} diff --git a/pkg/scanner/grype/db.go b/pkg/scanner/grype/db.go index 45ab6ad..b8403b5 100644 --- a/pkg/scanner/grype/db.go +++ b/pkg/scanner/grype/db.go @@ -1,7 +1,6 @@ package grype import ( - "context" "errors" "io/fs" "os" @@ -9,11 +8,11 @@ import ( "strings" "time" + "github.com/lukaszraczylo/gohoarder/pkg/scanner/dbrefresh" "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. @@ -27,35 +26,7 @@ const ( // 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") - } + dbrefresh.Run(stop, interval, immediate, ScannerName, s.UpdateDatabase) } // dbCacheDir mirrors grype's db.cache-dir default and its GRYPE_DB_CACHE_DIR override. diff --git a/pkg/scanner/leftovers_test.go b/pkg/scanner/leftovers_test.go index ee584e3..32b40be 100644 --- a/pkg/scanner/leftovers_test.go +++ b/pkg/scanner/leftovers_test.go @@ -19,6 +19,15 @@ import ( "github.com/stretchr/testify/require" ) +// trivyCache returns a trivy cache dir that already holds a database. +func trivyCache(t *testing.T) string { + t.Helper() + dir := t.TempDir() + require.NoError(t, os.MkdirAll(filepath.Join(dir, "db"), 0o750)) + require.NoError(t, os.WriteFile(filepath.Join(dir, "db", "trivy.db"), nil, 0o600)) + return dir +} + type scanFunc func(ctx context.Context, registry, packageName, version, filePath string) (*metadata.ScanResult, error) // A scanner binary killed by its timeout never removes its own temp files: a killed trivy @@ -31,7 +40,7 @@ func TestScanLeavesNothingInTheTempDir(t *testing.T) { registry, pkg, ver string }{ {name: "trivy timeout", bin: "trivy", body: leave + "\nexec sleep 5", registry: "pypi", pkg: "p", ver: "1", - scan: trivy.New(config.TrivyConfig{Timeout: time.Second}).Scan}, + scan: trivy.New(config.TrivyConfig{Timeout: time.Second, CacheDB: trivyCache(t)}).Scan}, {name: "grype failure", bin: "grype", body: leave + "\nexit 1", registry: "npm", pkg: "p", ver: "1.0.0", scan: grype.New(config.GrypeConfig{}).Scan}, {name: "npm audit failure", bin: "npm", body: leave + "\nexit 1", registry: "npm", pkg: "p", ver: "1.0.0", diff --git a/pkg/scanner/scanner.go b/pkg/scanner/scanner.go index d9b9709..0e1b26a 100644 --- a/pkg/scanner/scanner.go +++ b/pkg/scanner/scanner.go @@ -238,6 +238,8 @@ func New(cfg config.SecurityConfig, metadataStore metadata.MetadataStore) (*Mana log.Warn().Err(err).Msg("Failed to update Trivy database on startup") } } + // Scans never update the database, so without this loop it ages past its NextUpdate. + go trivyScanner.RefreshDatabase(manager.stopCh, cfg.Scanners.Trivy.DBUpdateInterval, !cfg.UpdateDBOnStartup) } // Initialize OSV scanner diff --git a/pkg/scanner/trivy/db_test.go b/pkg/scanner/trivy/db_test.go new file mode 100644 index 0000000..091b85c --- /dev/null +++ b/pkg/scanner/trivy/db_test.go @@ -0,0 +1,115 @@ +package trivy + +import ( + "context" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + "github.com/lukaszraczylo/gohoarder/pkg/config" + "github.com/lukaszraczylo/gohoarder/pkg/metadata" + "github.com/lukaszraczylo/gohoarder/pkg/scanner/scannertest" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// withDB returns cfg with a cache dir that already holds a database. +func withDB(t *testing.T, cfg config.TrivyConfig) config.TrivyConfig { + t.Helper() + cfg.CacheDB = t.TempDir() + require.NoError(t, os.MkdirAll(filepath.Join(cfg.CacheDB, "db"), 0o750)) + require.NoError(t, os.WriteFile(filepath.Join(cfg.CacheDB, "db", "trivy.db"), nil, 0o600)) + return cfg +} + +// fakeTrivy downloads a database on `trivy image` and scans clean otherwise, logging each step. +func fakeTrivy(t *testing.T, scanSleep string) (logFile string) { + t.Helper() + logFile = filepath.Join(t.TempDir(), "log") + scannertest.Script(t, "trivy", ` +if [ "$1" = image ]; then + echo update >> '`+logFile+`' + mkdir -p "$TRIVY_CACHE_DIR/db" && : > "$TRIVY_CACHE_DIR/db/trivy.db" + exit 0 +fi +echo scan-start >> '`+logFile+`' +sleep `+scanSleep+` +echo scan-end >> '`+logFile+`' +echo '{"Results":[]}'`) + return logFile +} + +func readLog(t *testing.T, logFile string) []string { + t.Helper() + data, err := os.ReadFile(logFile) // #nosec G304 -- test temp file + require.NoError(t, err) + return strings.Fields(string(data)) +} + +func TestScansDownloadAMissingDatabaseOnce(t *testing.T) { + logFile := fakeTrivy(t, "0") + s := New(config.TrivyConfig{CacheDB: t.TempDir()}) + + var wg sync.WaitGroup + for range 4 { + wg.Add(1) + go func() { + defer wg.Done() + res, err := s.Scan(context.Background(), "pypi", "p", "1", "/x/p.whl") + if assert.NoError(t, err) { + assert.Equal(t, metadata.ScanStatusClean, res.Status) + } + }() + } + wg.Wait() + + lines := readLog(t, logFile) + assert.Equal(t, "update", lines[0]) + assert.Equal(t, 1, strings.Count(strings.Join(lines, " "), "update")) +} + +// Concurrent trivy processes replacing the database under running scans crashed them with SIGBUS. +func TestUpdateWaitsForRunningScans(t *testing.T) { + logFile := fakeTrivy(t, "0.3") + s := New(withDB(t, config.TrivyConfig{})) + + done := make(chan struct{}) + go func() { + defer close(done) + _, err := s.Scan(context.Background(), "pypi", "p", "1", "/x/p.whl") + assert.NoError(t, err) + }() + require.Eventually(t, func() bool { + data, _ := os.ReadFile(logFile) // #nosec G304 -- test temp file + return strings.Contains(string(data), "scan-start") + }, 5*time.Second, 5*time.Millisecond) + require.NoError(t, s.UpdateDatabase(context.Background())) + <-done + + assert.Equal(t, []string{"scan-start", "scan-end", "update"}, readLog(t, logFile)) +} + +func TestRefreshDatabaseRunsOnInterval(t *testing.T) { + logFile := fakeTrivy(t, "0") + stop := make(chan struct{}) + exited := make(chan struct{}) + + go func() { + New(config.TrivyConfig{CacheDB: t.TempDir()}).RefreshDatabase(stop, 20*time.Millisecond, true) + close(exited) + }() + + require.Eventually(t, func() bool { + data, _ := os.ReadFile(logFile) // #nosec G304 -- test temp file + return strings.Count(string(data), "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") + } +} diff --git a/pkg/scanner/trivy/trivy.go b/pkg/scanner/trivy/trivy.go index b0ee657..e8ca23b 100644 --- a/pkg/scanner/trivy/trivy.go +++ b/pkg/scanner/trivy/trivy.go @@ -8,11 +8,14 @@ import ( "fmt" "os" "os/exec" + "path/filepath" "strings" + "sync" "time" "github.com/lukaszraczylo/gohoarder/pkg/config" "github.com/lukaszraczylo/gohoarder/pkg/metadata" + "github.com/lukaszraczylo/gohoarder/pkg/scanner/dbrefresh" "github.com/lukaszraczylo/gohoarder/pkg/scanner/scanerr" "github.com/lukaszraczylo/gohoarder/pkg/scanner/scanver" "github.com/lukaszraczylo/gohoarder/pkg/scanner/workdir" @@ -23,10 +26,16 @@ import ( // ScannerName is the name of this scanner const ScannerName = "trivy" +// A full download takes about 11s; this bounds a hung one, during which scans wait. +const dbUpdateTimeout = 10 * time.Minute + // Scanner implements the Scanner interface using Trivy type Scanner struct { version scanver.Cache config config.TrivyConfig + // Scans hold the read lock, updates the write lock: trivy processes that read the database + // while another replaced it crashed with SIGBUS. + dbMu sync.RWMutex } // TrivyResult represents Trivy JSON output structure @@ -86,8 +95,52 @@ func (s *Scanner) Name() string { return ScannerName } -// UpdateDatabase updates Trivy's vulnerability database +// UpdateDatabase updates Trivy's vulnerability database. It waits for running scans, and +// scans wait for it. func (s *Scanner) UpdateDatabase(ctx context.Context) error { + s.dbMu.Lock() + defer s.dbMu.Unlock() + return s.download(ctx) +} + +// 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) { + dbrefresh.Run(stop, interval, immediate, ScannerName, s.UpdateDatabase) +} + +// ensureDatabase downloads the database when the cache has none: a scan never updates it. +func (s *Scanner) ensureDatabase(ctx context.Context) error { + if s.hasDatabase() { + return nil + } + s.dbMu.Lock() + defer s.dbMu.Unlock() + if s.hasDatabase() { + return nil + } + return s.download(ctx) +} + +// hasDatabase reports whether trivy's cache dir holds a vulnerability database. +func (s *Scanner) hasDatabase() bool { + dir := s.config.CacheDB + if dir == "" { + dir = os.Getenv("TRIVY_CACHE_DIR") + } + if dir == "" { + cache, err := os.UserCacheDir() + if err != nil { + return false + } + dir = filepath.Join(cache, "trivy") + } + _, err := os.Stat(filepath.Join(dir, "db", "trivy.db")) // #nosec G703 -- cache dir from config or env + return err == nil +} + +// download runs the database update. The caller holds the write lock. +func (s *Scanner) download(ctx context.Context) error { log.Info().Msg("Updating Trivy vulnerability database") wd, err := workdir.New(ScannerName) @@ -95,6 +148,8 @@ func (s *Scanner) UpdateDatabase(ctx context.Context) error { return err } defer wd.Remove() + ctx, cancel := context.WithTimeout(ctx, dbUpdateTimeout) + defer cancel() cmd := exec.CommandContext(ctx, "trivy", "image", "--download-db-only") cmd.Env = s.env(wd) @@ -109,6 +164,12 @@ func (s *Scanner) UpdateDatabase(ctx context.Context) error { // Scan scans a package for vulnerabilities using Trivy func (s *Scanner) Scan(ctx context.Context, registry, packageName, version string, filePath string) (*metadata.ScanResult, error) { + if err := s.ensureDatabase(ctx); err != nil { + return nil, fmt.Errorf("%w: %w", scanerr.ErrInfrastructure, err) + } + s.dbMu.RLock() + defer s.dbMu.RUnlock() + // Set timeout if s.config.Timeout > 0 { var cancel context.CancelFunc @@ -135,6 +196,7 @@ func (s *Scanner) Scan(ctx context.Context, registry, packageName, version strin scanType, "--format", "json", "--quiet", + "--skip-db-update", // RefreshDatabase owns updates target, } diff --git a/pkg/scanner/trivy/trivy_test.go b/pkg/scanner/trivy/trivy_test.go index 6eaca79..f154a03 100644 --- a/pkg/scanner/trivy/trivy_test.go +++ b/pkg/scanner/trivy/trivy_test.go @@ -23,7 +23,7 @@ import ( func TestScanTimeoutIsAnInfrastructureErrorResult(t *testing.T) { scannertest.Script(t, "trivy", "exec sleep 5") - res, err := New(config.TrivyConfig{Timeout: 100 * time.Millisecond}).Scan(context.Background(), "pypi", "p", "1", "/x") + res, err := New(withDB(t, config.TrivyConfig{Timeout: 100 * time.Millisecond})).Scan(context.Background(), "pypi", "p", "1", "/x") require.NoError(t, err) assert.Equal(t, metadata.ScanStatusError, res.Status) @@ -76,7 +76,7 @@ echo '{"Results":[]}'`, rec)) entry{name: "package/lib/index.js", body: "x"}, ) - res, err := New(config.TrivyConfig{}).Scan(context.Background(), "npm", "@scope/pkg", "1.0.0", archive) + res, err := New(withDB(t, config.TrivyConfig{})).Scan(context.Background(), "npm", "@scope/pkg", "1.0.0", archive) require.NoError(t, err) assert.Equal(t, metadata.ScanStatusClean, res.Status) @@ -85,7 +85,7 @@ echo '{"Results":[]}'`, rec)) root, err := os.ReadFile(filepath.Join(rec, "root")) // #nosec G304 -- test temp dir require.NoError(t, err) lines := strings.Split(strings.TrimSpace(string(args)), "\n") - assert.Equal(t, []string{"rootfs", "--format", "json", "--quiet", strings.TrimSpace(string(root))}, lines) + assert.Equal(t, []string{"rootfs", "--format", "json", "--quiet", "--skip-db-update", strings.TrimSpace(string(root))}, lines) pkg, err := os.ReadFile(filepath.Join(rec, "package.json")) // #nosec G304 -- test temp dir require.NoError(t, err) assert.JSONEq(t, `{"name":"@scope/pkg"}`, string(pkg)) @@ -95,9 +95,9 @@ echo '{"Results":[]}'`, rec)) func TestNonNPMScansTheFileWithFS(t *testing.T) { argsFile := scannertest.Fake(t, "trivy", "", "", 0) - _, err := New(config.TrivyConfig{}).Scan(context.Background(), "pypi", "p", "1", "/x/p.whl") + _, err := New(withDB(t, config.TrivyConfig{})).Scan(context.Background(), "pypi", "p", "1", "/x/p.whl") require.Error(t, err) // empty output is not JSON - assert.Equal(t, []string{"fs", "--format", "json", "--quiet", "/x/p.whl"}, scannertest.Args(t, argsFile)) + assert.Equal(t, []string{"fs", "--format", "json", "--quiet", "--skip-db-update", "/x/p.whl"}, scannertest.Args(t, argsFile)) } func TestExtractRejectsUnsafeArchives(t *testing.T) {