mirror of
https://github.com/lukaszraczylo/gohoarder.git
synced 2026-11-30 06:57:10 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4870f243fc | ||
|
|
fac30f59e6 | ||
|
|
775ed8a4aa | ||
|
|
e6d8ed0f2e | ||
|
|
40ed8f8213 | ||
|
|
ecf750adbb | ||
|
|
41f8369c43 | ||
|
|
d6044cdd2e |
@@ -110,6 +110,9 @@ 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_on_access: false # Rescan a cached package on download when its scan is older than rescan_interval, before serving it
|
||||
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
|
||||
|
||||
@@ -30,6 +30,9 @@ Currency: `sh lean4/scripts/check_currency.sh origin/main`.
|
||||
| GH-23 | PyPI sidecar | pip's PEP 658 request (`<link>.metadata`, suffix on `original_url`) is served as its wheel's sidecar; another file's sidecar is still refused | correctness (pip install failed with 400) | medium (every pip install through the proxy) | `Access.pip_form_keeps_key_binding`, `pip_sidecar_of_other_file_rejected`, `pip_sidecar_of_same_file_accepted` / `TestPipSidecarFormIsStreamed`, `TestHandlePackageFile_OriginalURLFilenameBound` | 501bf1a |
|
||||
| GH-24 | rescan | with `security.rescan_interval` set, artifacts whose scan never completed are scanned and old results refreshed | correctness (scans lost to a restart stayed unscanned; new CVEs never picked up) | medium | not modelled (worker wiring) / `TestWorkersStartTheRescanWorker` | 378b873 |
|
||||
| GH-25 | scanners | an error result from one scanner is left out of the merge, so the row reads error only when every scanner failed; grype, npm-audit, govulncheck and pip-audit give correct results with the scanner image tool versions | correctness (false error, false clean) | high (grype, npm-audit and pip-audit failed on every package; govulncheck and a bare-archive grype scan read vulnerable packages clean) | `Security.old_error_poisons_clean`, `error_and_clean_reads_clean`, `all_error_reads_error`, `merged_not_error_when_one_ran` / `TestScanPackage_ErrorResultPlusCleanReadsClean`, `TestScanPackage_AllErrorResultsReadError`, `TestScanPackage_InfrastructureErrorResultsCountAsInfrastructure`, `TestScanMapsRealOutput`, `TestParseKeepsBothViaShapes`, `TestScanReadsPrettyPrintedFindings`, `TestScanAuditsTheReleaseFromARequirement` | 3731ca0 |
|
||||
| GH-26 | rescan | the rescan worker skips the entries the serve path skips, so Go `.mod` and `.info` rows are no longer scanned | cost (1316 of about 2780 rescans on production were these rows, about 3.3 s each) | low | `Cache.old_rescan_scanned_go_metadata`, `rescan_skips_what_serve_skips` / `TestRescanSkipsMetadataEntries` | d6044cd |
|
||||
| GH-27 | scanners | govulncheck counts findings in the scanned module only; dependency findings (minimum versions from its go.mod) and stdlib findings (the scanner toolchain) no longer attach to it | correctness (false vulnerable, and a false block when a dependency finding is critical) | medium (golang.org/x/net v0.56.0 carried x/crypto and x/text advisories on production) | `TestScanIgnoresFindingsInDependencies`, `TestScanReadsPrettyPrintedFindings` | 775ed8a |
|
||||
| GH-28 | scanners | OSV takes the fixed version from the range of the queried package | display (x/net findings showed the stdlib fix 1.26.9 instead of 0.60.0) | low | `TestScan_FixedVersionComesFromTheQueriedPackage` | fac30f5 |
|
||||
|
||||
### Exploit paths and reach
|
||||
|
||||
@@ -84,6 +87,11 @@ Currency: `sh lean4/scripts/check_currency.sh origin/main`.
|
||||
as clean the same way grype did.
|
||||
- **GH-17 cleanup.** The per-handler `Access-Control-*` lines in `pkg/app/handlers*.go` are removed; `apiOriginGuard` is the only CORS
|
||||
source. `TestHandlersSetNoCORSHeaders` and `TestAPIResponsesNeverCarryWildcardOrigin` guard it.
|
||||
- **GH-26.** `rescanPackages` kept its own list of metadata versions and never called `IsMetadataEntry`, so Go `.mod` and `.info`
|
||||
rows were scanned every cycle. Related options, whose defaults keep the old behaviour: `rescan_active_window` skips packages idle longer than the
|
||||
window, `rescan_concurrency` runs scans in parallel, and `rescan_on_access` rescans a stale cache hit before serving it.
|
||||
Model of the last: `Security.finished_rescan_verdict_younger_than_interval`, `old_verdict_only_on_timeout`,
|
||||
`stale_clean_fresh_vulnerable_blocked`, `timeout_keeps_previous`, `timeout_without_previous_is_miss_rule`, `off_is_old_hit_path`.
|
||||
|
||||
## Not fixed
|
||||
|
||||
|
||||
@@ -208,4 +208,16 @@ theorem old_exempted_npm_package : scanExemptOld true "1.0.0" = true := by decid
|
||||
|
||||
theorem go_metadata_still_exempt : scanExempt "go" true "v1.0.0" = true := by decide
|
||||
|
||||
/-- `pkg/scanner/rescanner.go` before the fix: the worker skipped only the version names, not the Go suffixes. -/
|
||||
def rescanSkipOld (version : String) : Bool := decide (version ∈ metaVersions)
|
||||
|
||||
/-- After the fix the worker asks `IsMetadataEntry`, the same predicate as the serve path. -/
|
||||
def rescanSkip : String → Bool → String → Bool := scanExempt
|
||||
|
||||
theorem old_rescan_scanned_go_metadata :
|
||||
rescanSkipOld "v1.0.0" = false ∧ scanExempt "go" true "v1.0.0" = true := by decide
|
||||
|
||||
theorem rescan_skips_what_serve_skips (registry : String) (suffixMeta : Bool) (version : String) :
|
||||
rescanSkip registry suffixMeta version = scanExempt registry suffixMeta version := rfl
|
||||
|
||||
end Gohoarder.Cache
|
||||
|
||||
@@ -271,4 +271,90 @@ theorem one_package_failure_is_not_infra : infraOnly [true, false] = false := by
|
||||
|
||||
theorem all_infra_failures_are_infra : infraOnly [true, true] = true := by decide
|
||||
|
||||
/-! ### Rescan on access (`pkg/cache/rescan_on_access.go` `refreshStaleScan`)
|
||||
|
||||
Ages are seconds since `ScannedAt`; `interval` is `Config.RescanAfter` (0 = off). A rescan that timed out
|
||||
or failed is `none`: the previous verdict stands, and with no previous verdict the first-download rule applies. -/
|
||||
|
||||
structure Verdict where
|
||||
scan : Scan
|
||||
age : ℕ
|
||||
|
||||
/-- The hit is rescanned when the feature is on and its result is missing or at least `interval` old. -/
|
||||
def rescans (interval : ℕ) (prev : Option Verdict) : Bool :=
|
||||
decide (0 < interval) && (match prev with
|
||||
| none => true
|
||||
| some v => decide (interval ≤ v.age))
|
||||
|
||||
/-- The verdict the gate decides on; a finished rescan is brand new (age 0). -/
|
||||
def hitVerdict (interval : ℕ) (prev : Option Verdict) (rescan : Option Scan) : Option Verdict :=
|
||||
if rescans interval prev then
|
||||
(match rescan with
|
||||
| some s => some ⟨s, 0⟩
|
||||
| none => prev)
|
||||
else prev
|
||||
|
||||
/-- No verdict at all is a scan still in flight: `fail_closed` refuses, otherwise the package is served. -/
|
||||
def servesOnAccess (failClosed pkgBypass : Bool) (policy : Option ℕ) (now : ℤ) (bs : List Bypass)
|
||||
(interval : ℕ) (prev : Option Verdict) (rescan : Option Scan) : Bool :=
|
||||
match hitVerdict interval prev rescan with
|
||||
| some v => serves failClosed pkgBypass policy now bs v.scan
|
||||
| none => serves failClosed pkgBypass policy now bs (Scan.missing true)
|
||||
|
||||
/-- Key property: with the feature on, a rescan that finished leaves no verdict as old as `interval`. -/
|
||||
theorem finished_rescan_verdict_younger_than_interval (interval : ℕ) (hi : 0 < interval)
|
||||
(prev : Option Verdict) (s : Scan) (v : Verdict)
|
||||
(h : hitVerdict interval prev (some s) = some v) : v.age < interval := by
|
||||
unfold hitVerdict at h
|
||||
by_cases hr : rescans interval prev = true
|
||||
· simp only [hr, ite_true, Option.some.injEq] at h
|
||||
subst h
|
||||
simpa using hi
|
||||
· simp only [hr] at h
|
||||
subst h
|
||||
simp only [rescans, hi, decide_true, Bool.true_and, Bool.not_eq_true] at hr
|
||||
simpa using hr
|
||||
|
||||
/-- A verdict older than `interval` survives only when the rescan timed out or failed. -/
|
||||
theorem old_verdict_only_on_timeout (interval : ℕ) (hi : 0 < interval) (prev : Option Verdict)
|
||||
(rescan : Option Scan) (v : Verdict) (h : hitVerdict interval prev rescan = some v)
|
||||
(hold : interval ≤ v.age) : rescan = none := by
|
||||
cases rescan with
|
||||
| none => rfl
|
||||
| some s => exact absurd (finished_rescan_verdict_younger_than_interval interval hi prev s v h) (not_lt.mpr hold)
|
||||
|
||||
/-- A stale hit is judged on the fresh scan: a clean result that now holds a blocked vulnerability is refused. -/
|
||||
theorem stale_clean_fresh_vulnerable_blocked (policy : Option ℕ) (t : ℕ) (hp : policy = some t)
|
||||
(failClosed : Bool) (now : ℤ) (bs : List Bypass) (interval age : ℕ) (hi : 0 < interval)
|
||||
(hage : interval ≤ age) (vs : List Vuln) (v : Vuln) (hv : v ∈ vs) (hsev : t ≤ v.sev)
|
||||
(hun : v.id ∉ bypassedIds now bs) :
|
||||
servesOnAccess failClosed false policy now bs interval (some ⟨Scan.ok [], age⟩) (some (Scan.ok vs)) = false := by
|
||||
have hr : rescans interval (some ⟨Scan.ok [], age⟩) = true := by simp [rescans, hi, hage]
|
||||
simp only [servesOnAccess, hitVerdict, hr, ite_true]
|
||||
exact vulnerable_not_served policy t hp failClosed now bs vs v hv hsev hun
|
||||
|
||||
/-- A fresh result is served as is: no rescan, whatever the rescan outcome. -/
|
||||
theorem fresh_hit_not_rescanned (interval : ℕ) (v : Verdict) (hfresh : v.age < interval)
|
||||
(rescan : Option Scan) : hitVerdict interval (some v) rescan = some v := by
|
||||
have : rescans interval (some v) = false := by simp [rescans, not_le.mpr hfresh]
|
||||
simp [hitVerdict, this]
|
||||
|
||||
/-- A timeout keeps the previous verdict. -/
|
||||
theorem timeout_keeps_previous (interval : ℕ) (prev : Option Verdict) :
|
||||
hitVerdict interval prev none = prev := by
|
||||
unfold hitVerdict
|
||||
split <;> rfl
|
||||
|
||||
/-- A timeout with no previous verdict follows the first-download rule. -/
|
||||
theorem timeout_without_previous_is_miss_rule (failClosed pkgBypass : Bool) (policy : Option ℕ) (now : ℤ)
|
||||
(bs : List Bypass) (interval : ℕ) :
|
||||
servesOnAccess failClosed pkgBypass policy now bs interval none none = (pkgBypass || !failClosed) := by
|
||||
simp only [servesOnAccess, timeout_keeps_previous]
|
||||
cases failClosed <;> cases pkgBypass <;> simp [serves]
|
||||
|
||||
/-- `rescan_on_access` off (`RescanAfter` 0) is the old hit path: the stored verdict decides. -/
|
||||
theorem off_is_old_hit_path (prev : Option Verdict) (rescan : Option Scan) :
|
||||
hitVerdict 0 prev rescan = prev := by
|
||||
simp [hitVerdict, rescans]
|
||||
|
||||
end Gohoarder.Security
|
||||
|
||||
+9
-1
@@ -234,7 +234,12 @@ func (a *App) initializeComponents() error {
|
||||
if cleanupInterval == 0 {
|
||||
cleanupInterval = 5 * time.Minute
|
||||
}
|
||||
var rescanAfter time.Duration
|
||||
if a.config.Security.RescanOnAccess {
|
||||
rescanAfter = a.config.Security.RescanInterval
|
||||
}
|
||||
a.cache, err = cache.New(a.storage, a.metadata, a.scanManager, a.analyticsEngine, cache.Config{
|
||||
RescanAfter: rescanAfter,
|
||||
DefaultTTL: a.config.Cache.DefaultTTL,
|
||||
TTLOverrides: a.config.Cache.MetadataTTLOverrides(),
|
||||
CleanupInterval: cleanupInterval,
|
||||
@@ -320,7 +325,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
|
||||
|
||||
Vendored
+5
@@ -47,6 +47,7 @@ type Manager struct {
|
||||
bgCtx context.Context // cancelled by Close; parent of background scans
|
||||
bgCancel context.CancelFunc
|
||||
sf singleflight.Group
|
||||
rescanSF singleflight.Group
|
||||
config Config
|
||||
cleanupWG sync.WaitGroup
|
||||
bcMu sync.RWMutex
|
||||
@@ -91,6 +92,7 @@ type Config struct {
|
||||
MaxPackageSize int64 // Maximum package size in bytes (0 = default 2GB)
|
||||
ScanWaitTimeout time.Duration // How long the first download waits for its scan (0 = 30s)
|
||||
FailClosed bool // Refuse a package whose scan did not finish in time
|
||||
RescanAfter time.Duration // Rescan a cache hit whose scan result is older than this before serving (0 = off)
|
||||
}
|
||||
|
||||
const defaultScanWaitTimeout = 30 * time.Second
|
||||
@@ -332,6 +334,9 @@ func (m *Manager) getOrFetch(ctx context.Context, registry, name, version string
|
||||
// the extra database round-trip.
|
||||
isMetadataEntry := metadata.IsMetadataEntry(registry, name, version)
|
||||
if m.scanner != nil && !isMetadataEntry {
|
||||
if rescanErr := m.refreshStaleScan(ctx, registry, name, version); rescanErr != nil {
|
||||
return nil, rescanErr
|
||||
}
|
||||
blocked, reason, vulnErr := m.scanner.CheckVulnerabilities(ctx, registry, name, version)
|
||||
if vulnErr != nil {
|
||||
log.Warn().Err(vulnErr).Str("package", name).Msg("Failed to check vulnerabilities")
|
||||
|
||||
Vendored
+71
@@ -0,0 +1,71 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/errors"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
// refreshStaleScan rescans a cache hit whose scan result is missing or older than
|
||||
// Config.RescanAfter, so the verdict served is never older than that interval. It
|
||||
// waits up to ScanWaitTimeout; on a timeout or scan failure the previous verdict
|
||||
// stands, or the miss-path rule applies when there is none.
|
||||
func (m *Manager) refreshStaleScan(ctx context.Context, registry, name, version string) error {
|
||||
if m.config.RescanAfter <= 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
prev, err := m.metadata.GetScanResult(ctx, registry, name, version)
|
||||
hasPrev := err == nil && prev != nil
|
||||
if hasPrev && m.now().Sub(prev.ScannedAt) < m.config.RescanAfter {
|
||||
return nil
|
||||
}
|
||||
|
||||
key := fmt.Sprintf("%s/%s/%s", registry, name, version)
|
||||
done := m.rescanSF.DoChan(key, func() (interface{}, error) {
|
||||
return nil, m.rescanArtifact(registry, name, version)
|
||||
})
|
||||
|
||||
timer := time.NewTimer(m.config.ScanWaitTimeout)
|
||||
defer timer.Stop()
|
||||
|
||||
select {
|
||||
case res := <-done:
|
||||
if res.Err == nil {
|
||||
return nil
|
||||
}
|
||||
log.Warn().Err(res.Err).Str("package", name).Str("version", version).Msg("Rescan on access failed")
|
||||
case <-timer.C:
|
||||
log.Warn().Str("package", name).Str("version", version).Msg("Rescan on access timed out, scan continues in background")
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
|
||||
if hasPrev {
|
||||
log.Warn().Str("package", name).Str("version", version).Time("scanned_at", prev.ScannedAt).
|
||||
Msg("Serving decision uses the previous scan result")
|
||||
return nil
|
||||
}
|
||||
if m.config.FailClosed {
|
||||
log.Warn().Str("package", name).Str("version", version).
|
||||
Msg("No scan result and rescan unfinished - refusing to serve (fail-closed)")
|
||||
return errors.New(errors.ErrCodeServiceUnavailable, "package scan in progress, retry shortly")
|
||||
}
|
||||
log.Warn().Str("package", name).Str("version", version).
|
||||
Msg("No scan result and rescan unfinished - serving package, scan continues in background")
|
||||
return nil
|
||||
}
|
||||
|
||||
// rescanArtifact scans the cached artifact under the manager's background context so a
|
||||
// client disconnect does not abort it.
|
||||
func (m *Manager) rescanArtifact(registry, name, version string) error {
|
||||
path, cleanup, err := m.ScanFile(m.bgCtx, registry, name, version)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer cleanup()
|
||||
return m.scanner.ScanPackage(m.bgCtx, registry, name, version, path)
|
||||
}
|
||||
Vendored
+176
@@ -0,0 +1,176 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
hoardererrors "github.com/lukaszraczylo/gohoarder/pkg/errors"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/mock"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
const rescanInterval = 24 * time.Hour
|
||||
|
||||
// rescanScanner blocks a scan until release closes and blocks the package once scanned.
|
||||
type rescanScanner struct {
|
||||
release chan struct{}
|
||||
scanCtx atomic.Pointer[context.Context]
|
||||
scans atomic.Int32
|
||||
blockOnScan atomic.Bool
|
||||
}
|
||||
|
||||
func (s *rescanScanner) ScanPackage(ctx context.Context, _, _, _, _ string) error {
|
||||
s.scans.Add(1)
|
||||
s.scanCtx.Store(&ctx)
|
||||
if s.release != nil {
|
||||
<-s.release
|
||||
}
|
||||
s.blockOnScan.Store(true)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *rescanScanner) CheckVulnerabilities(context.Context, string, string, string) (bool, string, error) {
|
||||
if s.scans.Load() > 0 && s.release == nil {
|
||||
return s.blockOnScan.Load(), "critical vulnerability", nil
|
||||
}
|
||||
return false, "", nil
|
||||
}
|
||||
|
||||
func newHitManager(t *testing.T, sc ScannerInterface, cfg Config, registry, name, version string, prev *metadata.ScanResult) (*Manager, *MockMetadataStore) {
|
||||
t.Helper()
|
||||
st := &MockStorageBackend{}
|
||||
md := &MockMetadataStore{}
|
||||
key := registry + "/" + name + "/" + version
|
||||
|
||||
md.On("GetPackage", mock.Anything, registry, name, version).
|
||||
Return(&metadata.Package{Registry: registry, Name: name, Version: version, StorageKey: key}, nil)
|
||||
st.On("Get", mock.Anything, key).Return(io.NopCloser(strings.NewReader("data")), nil)
|
||||
md.On("UpdateDownloadCount", mock.Anything, registry, name, version).Return(nil)
|
||||
if prev == nil {
|
||||
md.On("GetScanResult", mock.Anything, registry, name, version).Return(nil, hoardererrors.NotFound("none")).Maybe()
|
||||
} else {
|
||||
md.On("GetScanResult", mock.Anything, registry, name, version).Return(prev, nil).Maybe()
|
||||
}
|
||||
st.On("Close").Return(nil)
|
||||
md.On("Close").Return(nil)
|
||||
|
||||
m, err := New(st, md, sc, nil, cfg)
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { _ = m.Close() })
|
||||
return m, md
|
||||
}
|
||||
|
||||
func scanAged(age time.Duration) *metadata.ScanResult {
|
||||
return &metadata.ScanResult{ScannedAt: time.Now().Add(-age), Status: metadata.ScanStatusClean}
|
||||
}
|
||||
|
||||
func errorCode(err error) string {
|
||||
var appErr *hoardererrors.Error
|
||||
if errors.As(err, &appErr) {
|
||||
return appErr.Code
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func TestGetHit_RescanOnAccess(t *testing.T) {
|
||||
tests := []struct {
|
||||
prev *metadata.ScanResult
|
||||
name string
|
||||
wantCode string
|
||||
rescan time.Duration
|
||||
wantScans int32
|
||||
hang bool
|
||||
failClose bool
|
||||
}{
|
||||
{name: "stale clean result, fresh scan finds critical: blocked before serve", prev: scanAged(48 * time.Hour), rescan: rescanInterval, wantScans: 1, wantCode: hoardererrors.ErrCodeSecurityViolation},
|
||||
{name: "missing result is scanned before serving", prev: nil, rescan: rescanInterval, wantScans: 1, wantCode: hoardererrors.ErrCodeSecurityViolation},
|
||||
{name: "fresh result is not rescanned", prev: scanAged(time.Hour), rescan: rescanInterval, wantScans: 0},
|
||||
{name: "rescan_on_access off keeps the old hit path", prev: scanAged(48 * time.Hour), rescan: 0, wantScans: 0},
|
||||
{name: "timeout with previous result serves", prev: scanAged(48 * time.Hour), rescan: rescanInterval, wantScans: 1, hang: true},
|
||||
{name: "timeout with previous result serves under fail-closed", prev: scanAged(48 * time.Hour), rescan: rescanInterval, wantScans: 1, hang: true, failClose: true},
|
||||
{name: "timeout without result serves when fail-open", prev: nil, rescan: rescanInterval, wantScans: 1, hang: true},
|
||||
{name: "timeout without result is 503 when fail-closed", prev: nil, rescan: rescanInterval, wantScans: 1, hang: true, failClose: true, wantCode: hoardererrors.ErrCodeServiceUnavailable},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
sc := &rescanScanner{}
|
||||
if tt.hang {
|
||||
sc.release = make(chan struct{})
|
||||
t.Cleanup(func() { close(sc.release) })
|
||||
}
|
||||
m, _ := newHitManager(t, sc, Config{RescanAfter: tt.rescan, ScanWaitTimeout: 150 * time.Millisecond, FailClosed: tt.failClose},
|
||||
"npm", "lodash", "4.17.21", tt.prev)
|
||||
|
||||
entry, err := m.Get(context.Background(), "npm", "lodash", "4.17.21", nil)
|
||||
|
||||
if tt.wantCode != "" {
|
||||
require.Error(t, err)
|
||||
assert.Equal(t, tt.wantCode, errorCode(err))
|
||||
} else {
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, entry)
|
||||
_ = entry.Data.Close()
|
||||
}
|
||||
assert.Equal(t, tt.wantScans, sc.scans.Load())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetHit_RescanOffDoesNotReadScanResult(t *testing.T) {
|
||||
sc := &rescanScanner{}
|
||||
m, md := newHitManager(t, sc, Config{}, "npm", "lodash", "4.17.21", scanAged(48*time.Hour))
|
||||
entry, err := m.Get(context.Background(), "npm", "lodash", "4.17.21", nil)
|
||||
require.NoError(t, err)
|
||||
_ = entry.Data.Close()
|
||||
md.AssertNotCalled(t, "GetScanResult", mock.Anything, mock.Anything, mock.Anything, mock.Anything)
|
||||
}
|
||||
|
||||
func TestGetHit_RescanSkipsGoMetadataRows(t *testing.T) {
|
||||
sc := &rescanScanner{}
|
||||
m, _ := newHitManager(t, sc, Config{RescanAfter: rescanInterval}, "go", "example.com/m/@v/v1.0.0.mod", "v1.0.0", nil)
|
||||
entry, err := m.Get(context.Background(), "go", "example.com/m/@v/v1.0.0.mod", "v1.0.0", nil)
|
||||
require.NoError(t, err)
|
||||
_ = entry.Data.Close()
|
||||
assert.Zero(t, sc.scans.Load())
|
||||
}
|
||||
|
||||
// Concurrent stale hits share one scan, and a client that disconnects does not cancel it.
|
||||
func TestRefreshStaleScan_SingleflightAndBackgroundContext(t *testing.T) {
|
||||
sc := &rescanScanner{release: make(chan struct{})}
|
||||
m, _ := newHitManager(t, sc, Config{RescanAfter: rescanInterval, ScanWaitTimeout: 5 * time.Second},
|
||||
"npm", "lodash", "4.17.21", scanAged(48*time.Hour))
|
||||
|
||||
const callers = 5
|
||||
ctx, cancelClient := context.WithCancel(context.Background())
|
||||
errs := make(chan error, callers)
|
||||
var wg sync.WaitGroup
|
||||
for i := 0; i < callers; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
errs <- m.refreshStaleScan(ctx, "npm", "lodash", "4.17.21")
|
||||
}()
|
||||
}
|
||||
|
||||
require.Eventually(t, func() bool { return sc.scans.Load() >= 1 }, 2*time.Second, 5*time.Millisecond)
|
||||
cancelClient()
|
||||
wg.Wait()
|
||||
close(errs)
|
||||
for err := range errs {
|
||||
assert.ErrorIs(t, err, context.Canceled)
|
||||
}
|
||||
|
||||
scanCtx := sc.scanCtx.Load()
|
||||
require.NotNil(t, scanCtx)
|
||||
assert.NoError(t, (*scanCtx).Err(), "scan must outlive the client request")
|
||||
close(sc.release)
|
||||
assert.Equal(t, int32(1), sc.scans.Load(), "concurrent hits must share one scan")
|
||||
}
|
||||
+15
-12
@@ -174,18 +174,21 @@ 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"`
|
||||
RescanOnAccess bool `mapstructure:"rescan_on_access" json:"rescan_on_access"` // rescan a stale cache hit before serving it; needs rescan_interval
|
||||
UpdateDBOnStartup bool `mapstructure:"update_db_on_startup" json:"update_db_on_startup"`
|
||||
}
|
||||
|
||||
// VulnerabilityThresholds defines max allowed vulnerabilities per severity
|
||||
|
||||
@@ -126,7 +126,7 @@ func (s *Scanner) Scan(ctx context.Context, registry, packageName, version strin
|
||||
cmd.Stderr = &stderr
|
||||
output, _ := cmd.Output() // govulncheck -json exits 0 whether or not it finds anything
|
||||
|
||||
vulns, err := parseFindings(output)
|
||||
vulns, err := parseFindings(output, module)
|
||||
if err != nil {
|
||||
return s.errorResult(ctx, registry, packageName, version,
|
||||
fmt.Sprintf("govulncheck failed: %v: %s", err, strings.TrimSpace(stderr.String())), stderr.String()), nil
|
||||
@@ -175,8 +175,10 @@ func hasPathElement(importPath, element string) bool {
|
||||
}
|
||||
|
||||
// parseFindings reads govulncheck's stream of JSON messages. An output without the config
|
||||
// message did not come from a completed run.
|
||||
func parseFindings(output []byte) ([]GovulncheckVuln, error) {
|
||||
// message did not come from a completed run. Only findings in the scanned module count:
|
||||
// dependency findings come from the minimum versions in its go.mod, which a consuming build
|
||||
// replaces with its own, and stdlib findings describe the scanner's toolchain.
|
||||
func parseFindings(output []byte, module string) ([]GovulncheckVuln, error) {
|
||||
summaries := make(map[string]string)
|
||||
var vulns []GovulncheckVuln
|
||||
seen := make(map[string]bool)
|
||||
@@ -194,14 +196,15 @@ func parseFindings(output []byte) ([]GovulncheckVuln, error) {
|
||||
sawConfig = true
|
||||
case msg.OSV != nil:
|
||||
summaries[msg.OSV.ID] = msg.OSV.Summary
|
||||
case msg.Finding != nil && msg.Finding.OSV != "" && !seen[msg.Finding.OSV]:
|
||||
case msg.Finding != nil && msg.Finding.OSV != "" && !seen[msg.Finding.OSV] &&
|
||||
len(msg.Finding.Trace) > 0 && msg.Finding.Trace[0].Module == module:
|
||||
seen[msg.Finding.OSV] = true
|
||||
v := GovulncheckVuln{OSV: msg.Finding.OSV, FixedVersion: msg.Finding.FixedVersion}
|
||||
if len(msg.Finding.Trace) > 0 {
|
||||
v.Module = msg.Finding.Trace[0].Module
|
||||
v.ModuleVersion = msg.Finding.Trace[0].Version
|
||||
}
|
||||
vulns = append(vulns, v)
|
||||
vulns = append(vulns, GovulncheckVuln{
|
||||
OSV: msg.Finding.OSV,
|
||||
FixedVersion: msg.Finding.FixedVersion,
|
||||
Module: msg.Finding.Trace[0].Module,
|
||||
ModuleVersion: msg.Finding.Trace[0].Version,
|
||||
})
|
||||
}
|
||||
}
|
||||
if !sawConfig {
|
||||
|
||||
@@ -86,16 +86,28 @@ func ids(res *metadata.ScanResult) map[string]string {
|
||||
func TestScanReadsPrettyPrintedFindings(t *testing.T) {
|
||||
// govulncheck -json prints indented objects, not one object per line.
|
||||
fakeGo(t, abs(t, "golist-gin-v1.6.0.txt"), 0, "")
|
||||
fakeGovulncheck(t, abs(t, "gin-v1.6.0-source-scan.stream"), 0, "")
|
||||
fakeGovulncheck(t, abs(t, "gin-v1.6.0.stream"), 0, "")
|
||||
|
||||
res, err := New(config.GovulncheckConfig{}).Scan(context.Background(), "go", "github.com/gin-gonic/gin/@v/v1.6.0.zip", "v1.6.0", module(t))
|
||||
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, metadata.ScanStatusVulnerable, res.Status)
|
||||
assert.Equal(t, map[string]string{
|
||||
"GO-2022-0493": "v0.0.0-20220412211240-33da011f77ad",
|
||||
"GO-2026-5024": "v0.44.0",
|
||||
}, ids(res), "one entry per advisory, with the fixed version")
|
||||
"GO-2021-0052": "v1.7.7",
|
||||
"GO-2023-1737": "v1.9.1",
|
||||
}, ids(res), "one entry per advisory against gin, with the fixed version; the x/sys findings belong to a dependency")
|
||||
}
|
||||
|
||||
func TestScanIgnoresFindingsInDependencies(t *testing.T) {
|
||||
// gin's go.mod requires an old x/sys; a build that uses gin resolves its own x/sys version.
|
||||
fakeGo(t, abs(t, "golist-gin-v1.6.0.txt"), 0, "")
|
||||
fakeGovulncheck(t, abs(t, "gin-v1.6.0-source-scan.stream"), 0, "")
|
||||
|
||||
res, err := New(config.GovulncheckConfig{}).Scan(context.Background(), "go", "github.com/gin-gonic/gin/@v/v1.6.0.zip", "v1.6.0", module(t))
|
||||
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, metadata.ScanStatusClean, res.Status)
|
||||
assert.Empty(t, res.Vulnerabilities)
|
||||
}
|
||||
|
||||
func TestScanAuditsTheModuleItself(t *testing.T) {
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
package scanner
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
)
|
||||
|
||||
type healthProbe struct {
|
||||
err error
|
||||
calls atomic.Int32
|
||||
}
|
||||
|
||||
func (s *healthProbe) Name() string { return "counting" }
|
||||
|
||||
func (s *healthProbe) Scan(context.Context, string, string, string, string) (*metadata.ScanResult, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (s *healthProbe) Health(context.Context) error {
|
||||
s.calls.Add(1)
|
||||
return s.err
|
||||
}
|
||||
|
||||
// Health runs each scanner's version command; under scan load that took over a second, so
|
||||
// repeated probes must reuse a recent result.
|
||||
func TestHealthReusesRecentResult(t *testing.T) {
|
||||
tests := []struct {
|
||||
err error
|
||||
name string
|
||||
}{
|
||||
{name: "healthy", err: nil},
|
||||
{name: "unhealthy", err: errors.New("grype missing")},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
s := &healthProbe{err: tt.err}
|
||||
m := &Manager{enabled: true, scanners: []Scanner{s}}
|
||||
for range 3 {
|
||||
if err := m.Health(context.Background()); (err != nil) != (tt.err != nil) {
|
||||
t.Fatalf("Health() error = %v, want error %v", err, tt.err != nil)
|
||||
}
|
||||
}
|
||||
if got := s.calls.Load(); got != 1 {
|
||||
t.Fatalf("scanner health ran %d times, want 1", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A probe whose context was cancelled must not pin its failure for the cache period.
|
||||
func TestHealthDoesNotCacheCancelledProbe(t *testing.T) {
|
||||
s := &healthProbe{err: context.Canceled}
|
||||
m := &Manager{enabled: true, scanners: []Scanner{s}}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
_ = m.Health(ctx)
|
||||
s.err = nil
|
||||
if err := m.Health(context.Background()); err != nil {
|
||||
t.Fatalf("Health() after cancelled probe = %v, want nil", err)
|
||||
}
|
||||
if got := s.calls.Load(); got != 2 {
|
||||
t.Fatalf("scanner health ran %d times, want 2", got)
|
||||
}
|
||||
}
|
||||
+25
-8
@@ -264,6 +264,7 @@ func (s *Scanner) cleanGoModuleName(packageName, version, ecosystem string) (str
|
||||
func (s *Scanner) convertOSVResult(osvResp *OSVResponse, registry, packageName, version string) *metadata.ScanResult {
|
||||
vulnerabilities := make([]metadata.Vulnerability, 0, len(osvResp.Vulns))
|
||||
severityCounts := make(map[string]int)
|
||||
queryName, _ := s.cleanGoModuleName(packageName, version, s.registryToEcosystem(registry))
|
||||
|
||||
for _, vuln := range osvResp.Vulns {
|
||||
// Determine severity from various sources
|
||||
@@ -277,7 +278,7 @@ func (s *Scanner) convertOSVResult(osvResp *OSVResponse, registry, packageName,
|
||||
}
|
||||
|
||||
// Find fixed version
|
||||
fixedVersion := s.findFixedVersion(&vuln, version)
|
||||
fixedVersion := s.findFixedVersion(&vuln, queryName)
|
||||
|
||||
vulnerabilities = append(vulnerabilities, metadata.Vulnerability{
|
||||
ID: vuln.ID,
|
||||
@@ -352,14 +353,30 @@ func (s *Scanner) determineSeverity(vuln *OSVVulnerability) string {
|
||||
return metadata.NormalizeSeverity(rawSeverity)
|
||||
}
|
||||
|
||||
// findFixedVersion extracts the fixed version from OSV affected ranges
|
||||
func (s *Scanner) findFixedVersion(vuln *OSVVulnerability, currentVersion string) string {
|
||||
// findFixedVersion returns the first fixed version in the ranges for the queried package; an
|
||||
// advisory can cover several packages (stdlib and golang.org/x/net) with different fixes.
|
||||
func (s *Scanner) findFixedVersion(vuln *OSVVulnerability, name string) string {
|
||||
fallback := ""
|
||||
for _, affected := range vuln.Affected {
|
||||
for _, r := range affected.Ranges {
|
||||
for _, event := range r.Events {
|
||||
if event.Fixed != "" {
|
||||
return event.Fixed
|
||||
}
|
||||
fixed := firstFixed(affected.Ranges)
|
||||
if fixed == "" {
|
||||
continue
|
||||
}
|
||||
if strings.EqualFold(affected.Package.Name, name) {
|
||||
return fixed
|
||||
}
|
||||
if fallback == "" {
|
||||
fallback = fixed
|
||||
}
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
|
||||
func firstFixed(ranges []OSVRange) string {
|
||||
for _, r := range ranges {
|
||||
for _, event := range r.Events {
|
||||
if event.Fixed != "" {
|
||||
return event.Fixed
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -44,3 +44,22 @@ func TestScan_FullQueryURLIsKept(t *testing.T) {
|
||||
t.Errorf("request path = %q, want /v1/query", gotPath)
|
||||
}
|
||||
}
|
||||
|
||||
// An advisory that covers the stdlib and x/net lists the stdlib range first; the fixed version
|
||||
// shown for x/net must come from the x/net range.
|
||||
func TestScan_FixedVersionComesFromTheQueriedPackage(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
_, _ = w.Write([]byte(`{"vulns":[{"id":"GO-2026-6612","summary":"s","affected":[
|
||||
{"package":{"name":"stdlib","ecosystem":"Go"},"ranges":[{"type":"SEMVER","events":[{"introduced":"0"},{"fixed":"1.26.9"}]}]},
|
||||
{"package":{"name":"golang.org/x/net","ecosystem":"Go"},"ranges":[{"type":"SEMVER","events":[{"introduced":"0"},{"fixed":"0.60.0"}]}]}]}]}`))
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
|
||||
res, err := New(config.OSVConfig{APIURL: srv.URL}).Scan(context.Background(), "go", "golang.org/x/net/@v/v0.56.0.zip", "v0.56.0", "")
|
||||
if err != nil {
|
||||
t.Fatalf("Scan: %v", err)
|
||||
}
|
||||
if len(res.Vulnerabilities) != 1 || res.Vulnerabilities[0].FixedIn != "0.60.0" {
|
||||
t.Fatalf("vulnerabilities = %+v, want one fixed in 0.60.0", res.Vulnerabilities)
|
||||
}
|
||||
}
|
||||
|
||||
+166
-94
@@ -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 {
|
||||
// Skip metadata entries (npm metadata pages, pypi pages, etc.)
|
||||
if pkg.Version == "list" || pkg.Version == "latest" || pkg.Version == "metadata" || pkg.Version == "page" {
|
||||
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
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
package scanner
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
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.
|
||||
type rescanStore struct {
|
||||
results map[string]*metadata.ScanResult
|
||||
packages []*metadata.Package
|
||||
stubMetadataStore
|
||||
rmu sync.Mutex
|
||||
}
|
||||
|
||||
func (s *rescanStore) ListPackages(context.Context, *metadata.ListOptions) ([]*metadata.Package, error) {
|
||||
return s.packages, nil
|
||||
}
|
||||
|
||||
func (s *rescanStore) GetScanResult(_ context.Context, registry, name, version string) (*metadata.ScanResult, error) {
|
||||
s.rmu.Lock()
|
||||
defer s.rmu.Unlock()
|
||||
if r, ok := s.results[scanKey(registry, name, version)]; ok {
|
||||
return r, nil
|
||||
}
|
||||
return nil, hoardererrors.NotFound("no scan result")
|
||||
}
|
||||
|
||||
func (s *rescanStore) SaveScanResult(ctx context.Context, r *metadata.ScanResult) error {
|
||||
s.rmu.Lock()
|
||||
s.results[scanKey(r.Registry, r.PackageName, r.PackageVersion)] = r
|
||||
s.rmu.Unlock()
|
||||
return s.stubMetadataStore.SaveScanResult(ctx, r)
|
||||
}
|
||||
|
||||
// countingScanner records how often each package is scanned.
|
||||
type countingScanner struct {
|
||||
calls map[string]int
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
func (c *countingScanner) Name() string { return "counting" }
|
||||
|
||||
func (c *countingScanner) Scan(_ context.Context, registry, name, version, _ string) (*metadata.ScanResult, error) {
|
||||
c.mu.Lock()
|
||||
c.calls[scanKey(registry, name, version)]++
|
||||
c.mu.Unlock()
|
||||
return &metadata.ScanResult{
|
||||
Registry: registry, PackageName: name, PackageVersion: version,
|
||||
Scanner: "counting", ScannedAt: time.Now(), Status: metadata.ScanStatusClean,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (c *countingScanner) Health(context.Context) error { return nil }
|
||||
|
||||
func (c *countingScanner) snapshot() map[string]int {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
out := make(map[string]int, len(c.calls))
|
||||
for k, v := range c.calls {
|
||||
out[k] = v
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func pkgRow(registry, name, version string, lastAccessed time.Time) *metadata.Package {
|
||||
return &metadata.Package{
|
||||
Registry: registry, Name: name, Version: version,
|
||||
StorageKey: registry + "/" + name + "/" + version, LastAccessed: lastAccessed,
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
cs := &countingScanner{calls: map[string]int{}}
|
||||
mgr.RegisterScanner(cs)
|
||||
mgr.SetFileSource(func(context.Context, string, string, string) (string, func(), error) {
|
||||
return "/tmp/dummy", func() {}, nil
|
||||
})
|
||||
NewRescanWorker(mgr, store, time.Hour, opts...).rescanPackages(context.Background())
|
||||
return cs.snapshot()
|
||||
}
|
||||
|
||||
func TestRescanSkipsMetadataEntries(t *testing.T) {
|
||||
now := time.Now()
|
||||
pkgs := []*metadata.Package{
|
||||
pkgRow("go", "example.com/m/@v/v1.0.0.mod", "v1.0.0", now),
|
||||
pkgRow("go", "example.com/m/@v/v1.0.0.info", "v1.0.0", now),
|
||||
pkgRow("go", "example.com/m/@v/v1.0.0.zip", "v1.0.0", now),
|
||||
pkgRow("npm", "left-pad", "list", now),
|
||||
pkgRow("npm", "left-pad", "1.3.0", now),
|
||||
pkgRow("npm", "weird.mod", "1.0.0", now),
|
||||
}
|
||||
got := runRescan(t, pkgs)
|
||||
assert.Equal(t, map[string]int{
|
||||
scanKey("go", "example.com/m/@v/v1.0.0.zip", "v1.0.0"): 1,
|
||||
scanKey("npm", "left-pad", "1.3.0"): 1,
|
||||
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)
|
||||
}
|
||||
@@ -71,8 +71,18 @@ func (m *Manager) currentFileSource() FileSource {
|
||||
return m.fileSource
|
||||
}
|
||||
|
||||
// healthTTL bounds how often /health forks each scanner's version command; under scan load one round took over a second.
|
||||
const healthTTL = 30 * time.Second
|
||||
|
||||
type healthCache struct {
|
||||
at time.Time
|
||||
err error
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
// Manager manages multiple security scanners
|
||||
type Manager struct {
|
||||
health healthCache
|
||||
metadataStore metadata.MetadataStore
|
||||
broadcaster events.Broadcaster
|
||||
retryTimers map[string]*time.Timer
|
||||
@@ -913,6 +923,20 @@ func (m *Manager) Health(ctx context.Context) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
m.health.mu.Lock()
|
||||
defer m.health.mu.Unlock()
|
||||
if !m.health.at.IsZero() && time.Since(m.health.at) < healthTTL {
|
||||
return m.health.err
|
||||
}
|
||||
err := m.checkScanners(ctx)
|
||||
if ctx.Err() != nil {
|
||||
return err
|
||||
}
|
||||
m.health.at, m.health.err = time.Now(), err
|
||||
return err
|
||||
}
|
||||
|
||||
func (m *Manager) checkScanners(ctx context.Context) error {
|
||||
for _, scanner := range m.scanners {
|
||||
if err := scanner.Health(ctx); err != nil {
|
||||
return fmt.Errorf("scanner %s health check failed: %w", scanner.Name(), err)
|
||||
|
||||
Reference in New Issue
Block a user