diff --git a/config.yaml.example b/config.yaml.example index 79c640f..f9de0d4 100644 --- a/config.yaml.example +++ b/config.yaml.example @@ -110,6 +110,8 @@ security: block_on_severity: "high" # none, low, medium, high, critical scan_on_download: true # Scan packages on first download rescan_interval: "24h" # How often to re-scan packages (e.g., 24h, 168h for weekly) + rescan_active_window: "0s" # Rescan only packages requested within this window (e.g., 720h); 0 = all packages + rescan_concurrency: 1 # Scans run in parallel during one rescan cycle; values below 1 mean 1 # When a scan fails on infrastructure (timeout, upstream 5xx) the package is served and the # scan is retried every scan_retry_interval. Set fail_closed to refuse such packages instead. fail_closed: false diff --git a/pkg/app/app.go b/pkg/app/app.go index 236a680..00ea39d 100644 --- a/pkg/app/app.go +++ b/pkg/app/app.go @@ -320,7 +320,10 @@ func (a *App) initializeComponents() error { // Initialize rescan worker if enabled if a.config.Security.Enabled && a.config.Security.RescanInterval > 0 { log.Info().Dur("interval", a.config.Security.RescanInterval).Msg("Initializing package rescan worker") - a.rescanWorker = scanner.NewRescanWorker(a.scanManager, a.metadata, a.config.Security.RescanInterval) + a.rescanWorker = scanner.NewRescanWorker(a.scanManager, a.metadata, a.config.Security.RescanInterval, + scanner.WithActiveWindow(a.config.Security.RescanActiveWindow), + scanner.WithConcurrency(a.config.Security.RescanConcurrency), + ) } // Initialize WebSocket server diff --git a/pkg/config/config.go b/pkg/config/config.go index 3c97bc0..e77eaca 100644 --- a/pkg/config/config.go +++ b/pkg/config/config.go @@ -174,18 +174,20 @@ type CacheConfig struct { // SecurityConfig contains security scanning configuration type SecurityConfig struct { - BlockOnSeverity string `mapstructure:"block_on_severity" json:"block_on_severity"` - AllowedPackages []string `mapstructure:"allowed_packages" json:"allowed_packages"` - IgnoredCVEs []string `mapstructure:"ignored_cves" json:"ignored_cves"` - Scanners ScannersConfig `mapstructure:"scanners" json:"scanners"` - BlockThresholds VulnerabilityThresholds `mapstructure:"block_thresholds" json:"block_thresholds"` - RescanInterval time.Duration `mapstructure:"rescan_interval" json:"rescan_interval"` - 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 - 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"` - UpdateDBOnStartup bool `mapstructure:"update_db_on_startup" json:"update_db_on_startup"` + BlockOnSeverity string `mapstructure:"block_on_severity" json:"block_on_severity"` + AllowedPackages []string `mapstructure:"allowed_packages" json:"allowed_packages"` + IgnoredCVEs []string `mapstructure:"ignored_cves" json:"ignored_cves"` + Scanners ScannersConfig `mapstructure:"scanners" json:"scanners"` + BlockThresholds VulnerabilityThresholds `mapstructure:"block_thresholds" json:"block_thresholds"` + RescanInterval time.Duration `mapstructure:"rescan_interval" json:"rescan_interval"` + RescanActiveWindow time.Duration `mapstructure:"rescan_active_window" json:"rescan_active_window"` // rescan only packages accessed within this window; 0 = all + 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 + 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"` + UpdateDBOnStartup bool `mapstructure:"update_db_on_startup" json:"update_db_on_startup"` } // VulnerabilityThresholds defines max allowed vulnerabilities per severity diff --git a/pkg/scanner/rescanner.go b/pkg/scanner/rescanner.go index b753b06..abd1a77 100644 --- a/pkg/scanner/rescanner.go +++ b/pkg/scanner/rescanner.go @@ -3,6 +3,7 @@ package scanner import ( "context" "sync" + "sync/atomic" "time" "github.com/lukaszraczylo/gohoarder/pkg/metadata" @@ -16,16 +17,41 @@ type RescanWorker struct { stopCh chan struct{} stopOnce sync.Once interval time.Duration + activeWindow time.Duration + concurrency int +} + +// RescanOption tunes a RescanWorker. +type RescanOption func(*RescanWorker) + +// WithActiveWindow skips packages not accessed within window (0 = scan all). +func WithActiveWindow(window time.Duration) RescanOption { + return func(w *RescanWorker) { w.activeWindow = window } +} + +// WithConcurrency sets the scans run in parallel within a cycle; values below 1 mean 1. +func WithConcurrency(n int) RescanOption { + return func(w *RescanWorker) { + if n < 1 { + n = 1 + } + w.concurrency = n + } } // NewRescanWorker creates a new rescan worker -func NewRescanWorker(manager *Manager, metadataStore metadata.MetadataStore, interval time.Duration) *RescanWorker { - return &RescanWorker{ +func NewRescanWorker(manager *Manager, metadataStore metadata.MetadataStore, interval time.Duration, opts ...RescanOption) *RescanWorker { + w := &RescanWorker{ manager: manager, metadataStore: metadataStore, interval: interval, + concurrency: 1, stopCh: make(chan struct{}), } + for _, opt := range opts { + opt(w) + } + return w } // Start begins the periodic re-scanning process @@ -70,115 +96,161 @@ func (w *RescanWorker) Stop() { }) } +// rescanCounts tallies one rescan cycle; workers update it concurrently. +type rescanCounts struct { + scanned atomic.Int64 + failed atomic.Int64 + skipMetadata atomic.Int64 + skipIdle atomic.Int64 + skipFresh atomic.Int64 + skipNoSource atomic.Int64 +} + // rescanPackages re-scans packages that need updating func (w *RescanWorker) rescanPackages(ctx context.Context) { log.Info().Msg("Starting package rescan cycle - checking all packages for scan status") - // Get all packages packages, err := w.metadataStore.ListPackages(ctx, &metadata.ListOptions{}) if err != nil { log.Error().Err(err).Msg("Failed to list packages for rescan") return } - scanned := 0 - skipped := 0 - failed := 0 - - for _, pkg := range packages { - // Metadata pages and Go .mod/.info rows are not scannable artifacts. - if metadata.IsMetadataEntry(pkg.Registry, pkg.Name, pkg.Version) { - skipped++ - continue - } - - // Check if package needs rescanning - needsRescan, err := w.needsRescan(ctx, pkg) - if err != nil { - log.Error(). - Err(err). - Str("package", pkg.Name). - Str("version", pkg.Version). - Msg("Failed to check rescan status") - failed++ - continue - } - - if !needsRescan { - log.Debug(). - Str("package", pkg.Name). - Str("version", pkg.Version). - Bool("security_scanned", pkg.SecurityScanned). - Msg("Package does not need rescanning, skipping") - skipped++ - continue - } - - log.Info(). - Str("registry", pkg.Registry). - Str("package", pkg.Name). - Str("version", pkg.Version). - Msg("Package needs rescanning") - - if pkg.StorageKey == "" { - log.Warn(). - Str("registry", pkg.Registry). - Str("package", pkg.Name). - Str("version", pkg.Version). - Msg("Package has no storage key, skipping rescan") - failed++ - continue - } - - source := w.manager.currentFileSource() - if source == nil { - log.Debug(). - Str("registry", pkg.Registry). - Str("package", pkg.Name). - Str("version", pkg.Version). - Msg("No file source configured, skipping rescan") - skipped++ - continue - } - - filePath, cleanup, err := source(ctx, pkg.Registry, pkg.Name, pkg.Version) - if err != nil { - log.Warn(). - Err(err). - Str("registry", pkg.Registry). - Str("package", pkg.Name). - Str("version", pkg.Version). - Str("storage_key", pkg.StorageKey). - Msg("Failed to read package file, skipping rescan") - failed++ - continue - } - - // Perform the actual scan - err = w.manager.ScanPackage(ctx, pkg.Registry, pkg.Name, pkg.Version, filePath) - cleanup() - if err != nil { - log.Error(). - Err(err). - Str("registry", pkg.Registry). - Str("package", pkg.Name). - Str("version", pkg.Version). - Msg("Failed to rescan package") - failed++ - continue - } - - scanned++ + var counts rescanCounts + jobs := make(chan *metadata.Package) + var wg sync.WaitGroup + for i := 0; i < w.concurrency; i++ { + wg.Add(1) + go func() { + defer wg.Done() + for pkg := range jobs { + w.rescanOne(ctx, pkg, &counts) + } + }() } +dispatch: + for _, pkg := range packages { + if metadata.IsMetadataEntry(pkg.Registry, pkg.Name, pkg.Version) { + counts.skipMetadata.Add(1) + continue + } + if w.idle(pkg) { + counts.skipIdle.Add(1) + continue + } + select { + case jobs <- pkg: + case <-ctx.Done(): + break dispatch + case <-w.stopCh: + break dispatch + } + } + close(jobs) + wg.Wait() + log.Info(). Int("total", len(packages)). - Int("scanned", scanned). - Int("skipped", skipped). - Int("failed", failed). + Int64("scanned", counts.scanned.Load()). + Int64("failed", counts.failed.Load()). + Int64("skipped_metadata", counts.skipMetadata.Load()). + Int64("skipped_idle", counts.skipIdle.Load()). + Int64("skipped_fresh", counts.skipFresh.Load()). + Int64("skipped_no_source", counts.skipNoSource.Load()). + Int("concurrency", w.concurrency). + Dur("active_window", w.activeWindow). Msg("Rescan cycle completed") } +// idle reports whether a package was last served longer ago than the active window. +// A zero LastAccessed is unknown, so the package is scanned. +func (w *RescanWorker) idle(pkg *metadata.Package) bool { + if w.activeWindow <= 0 || pkg.LastAccessed.IsZero() { + return false + } + return time.Since(pkg.LastAccessed) > w.activeWindow +} + +// rescanOne scans a single package when its result is missing or stale. +func (w *RescanWorker) rescanOne(ctx context.Context, pkg *metadata.Package, counts *rescanCounts) { + needsRescan, err := w.needsRescan(ctx, pkg) + if err != nil { + log.Error(). + Err(err). + Str("package", pkg.Name). + Str("version", pkg.Version). + Msg("Failed to check rescan status") + counts.failed.Add(1) + return + } + + if !needsRescan { + log.Debug(). + Str("package", pkg.Name). + Str("version", pkg.Version). + Bool("security_scanned", pkg.SecurityScanned). + Msg("Package does not need rescanning, skipping") + counts.skipFresh.Add(1) + return + } + + log.Info(). + Str("registry", pkg.Registry). + Str("package", pkg.Name). + Str("version", pkg.Version). + Msg("Package needs rescanning") + + if pkg.StorageKey == "" { + log.Warn(). + Str("registry", pkg.Registry). + Str("package", pkg.Name). + Str("version", pkg.Version). + Msg("Package has no storage key, skipping rescan") + counts.failed.Add(1) + return + } + + source := w.manager.currentFileSource() + if source == nil { + log.Debug(). + Str("registry", pkg.Registry). + Str("package", pkg.Name). + Str("version", pkg.Version). + Msg("No file source configured, skipping rescan") + counts.skipNoSource.Add(1) + return + } + + filePath, cleanup, err := source(ctx, pkg.Registry, pkg.Name, pkg.Version) + if err != nil { + log.Warn(). + Err(err). + Str("registry", pkg.Registry). + Str("package", pkg.Name). + Str("version", pkg.Version). + Str("storage_key", pkg.StorageKey). + Msg("Failed to read package file, skipping rescan") + counts.failed.Add(1) + return + } + + err = w.manager.ScanPackage(ctx, pkg.Registry, pkg.Name, pkg.Version, filePath) + cleanup() + if err != nil { + log.Error(). + Err(err). + Str("registry", pkg.Registry). + Str("package", pkg.Name). + Str("version", pkg.Version). + Msg("Failed to rescan package") + counts.failed.Add(1) + return + } + + counts.scanned.Add(1) +} + // needsRescan checks if a package needs to be rescanned func (w *RescanWorker) needsRescan(ctx context.Context, pkg *metadata.Package) (bool, error) { // Get latest scan result diff --git a/pkg/scanner/rescanner_test.go b/pkg/scanner/rescanner_test.go index 275c9a5..2db3d52 100644 --- a/pkg/scanner/rescanner_test.go +++ b/pkg/scanner/rescanner_test.go @@ -9,6 +9,7 @@ import ( hoardererrors "github.com/lukaszraczylo/gohoarder/pkg/errors" "github.com/lukaszraczylo/gohoarder/pkg/metadata" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) // rescanStore serves a fixed package list and keeps saved scan results. @@ -76,7 +77,7 @@ func pkgRow(registry, name, version string, lastAccessed time.Time) *metadata.Pa } } -func runRescan(t *testing.T, pkgs []*metadata.Package) map[string]int { +func runRescan(t *testing.T, pkgs []*metadata.Package, opts ...RescanOption) map[string]int { t.Helper() store := &rescanStore{results: map[string]*metadata.ScanResult{}, packages: pkgs} mgr := newTestManager(t, store) @@ -85,7 +86,7 @@ func runRescan(t *testing.T, pkgs []*metadata.Package) map[string]int { mgr.SetFileSource(func(context.Context, string, string, string) (string, func(), error) { return "/tmp/dummy", func() {}, nil }) - NewRescanWorker(mgr, store, time.Hour).rescanPackages(context.Background()) + NewRescanWorker(mgr, store, time.Hour, opts...).rescanPackages(context.Background()) return cs.snapshot() } @@ -106,3 +107,55 @@ func TestRescanSkipsMetadataEntries(t *testing.T) { scanKey("npm", "weird.mod", "1.0.0"): 1, }, got) } + +func TestRescanActiveWindow(t *testing.T) { + now := time.Now() + pkgs := []*metadata.Package{ + pkgRow("npm", "hot", "1.0.0", now.Add(-time.Hour)), + pkgRow("npm", "cold", "1.0.0", now.Add(-72*time.Hour)), + pkgRow("npm", "unknown", "1.0.0", time.Time{}), + } + tests := []struct { + name string + want []string + window time.Duration + }{ + {"window off scans everything", []string{"hot", "cold", "unknown"}, 0}, + {"window skips idle only", []string{"hot", "unknown"}, 24 * time.Hour}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := runRescan(t, pkgs, WithActiveWindow(tt.window)) + want := map[string]int{} + for _, n := range tt.want { + want[scanKey("npm", n, "1.0.0")] = 1 + } + assert.Equal(t, want, got) + }) + } +} + +func TestRescanConcurrencyScansEachOnce(t *testing.T) { + now := time.Now() + var pkgs []*metadata.Package + want := map[string]int{} + for i := 0; i < 40; i++ { + name := string(rune('a'+i%26)) + string(rune('a'+i/26)) + pkgs = append(pkgs, pkgRow("npm", name, "1.0.0", now)) + want[scanKey("npm", name, "1.0.0")] = 1 + } + pkgs = append(pkgs, pkgRow("go", "m/@v/v1.mod", "v1", now)) + + for _, n := range []int{-2, 0, 1, 3, 8} { + got := runRescan(t, pkgs, WithConcurrency(n)) + require.Equal(t, want, got, "concurrency %d", n) + } +} + +func TestRescanConcurrencyFloor(t *testing.T) { + for _, n := range []int{-1, 0} { + w := NewRescanWorker(nil, nil, time.Hour, WithConcurrency(n)) + assert.Equal(t, 1, w.concurrency) + } + assert.Equal(t, 1, NewRescanWorker(nil, nil, time.Hour).concurrency) +}