feat(security): defer scans when the disk is low on space

Scanners unpack packages in the temp dir. When the volume is full, every
scan fails, and the same full volume can stop the metadata database.

The new security.min_free_bytes setting defers a scan while the temp dir
has less free space than the limit. The deferred scan records an
infrastructure error, so the existing retry path scans it again later.
A failed measurement does not block scans. The default is 0, which
keeps the check off.
This commit is contained in:
2026-11-27 10:48:03 +00:00
parent 17d7bebf88
commit 2de0bf029d
4 changed files with 121 additions and 1 deletions
+1
View File
@@ -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"`
+72
View File
@@ -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)
}
+38
View File
@@ -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
}
+10 -1
View File
@@ -99,6 +99,7 @@ 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
@@ -216,6 +217,7 @@ 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{}),
}
@@ -331,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().