mirror of
https://github.com/lukaszraczylo/gohoarder.git
synced 2026-11-26 06:37:07 +00:00
fix(proxy): serve escaped npm scopes and unscanned packages
npm and pnpm request scoped packages as @scope%2fname. Fiber's adaptor answers 404 to an escaped slash, so a route middleware now rewrites the scope separator before the adaptor runs. With scanning off, the cache still waited 30 s for a scan result and then refused the package. A scanner that is off is now treated as absent. A scan that fails on infrastructure (timeout, network error, upstream 5xx) no longer blocks the package until its entry expires. The package is served and the scan is retried every scan_retry_interval. Set security.fail_closed to refuse such packages. The OSV api_url default and the docs named the host, which answers 404 to a query. They now name https://api.osv.dev/v1/query, and a bare host is completed with the query path.
This commit is contained in:
@@ -15,6 +15,7 @@ import (
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/config"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner/scanerr"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/uuid"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
@@ -164,7 +165,7 @@ func (s *Scanner) queryAdvisories(ctx context.Context, ecosystem, packageName st
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
return nil, fmt.Errorf("github api returned status %d: %s", resp.StatusCode, string(body))
|
||||
return nil, &scanerr.StatusError{Service: "github api", Code: resp.StatusCode, Body: string(body)}
|
||||
}
|
||||
|
||||
var advisories []GHSAAdvisory
|
||||
|
||||
+15
-5
@@ -13,6 +13,7 @@ import (
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/config"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner/scanerr"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/uuid"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
@@ -94,10 +95,7 @@ type OSVEvent struct {
|
||||
|
||||
// New creates a new OSV scanner
|
||||
func New(cfg config.OSVConfig) *Scanner {
|
||||
apiURL := cfg.APIURL
|
||||
if apiURL == "" {
|
||||
apiURL = defaultOSVAPIURL
|
||||
}
|
||||
cfg.APIURL = queryURL(cfg.APIURL)
|
||||
|
||||
timeout := cfg.Timeout
|
||||
if timeout == 0 {
|
||||
@@ -113,6 +111,18 @@ func New(cfg config.OSVConfig) *Scanner {
|
||||
}
|
||||
|
||||
// Name returns the scanner name
|
||||
// queryURL returns the OSV query endpoint. A bare host is what older docs
|
||||
// listed as api_url, and it answers 404 to a POST, so the path is added.
|
||||
func queryURL(apiURL string) string {
|
||||
if apiURL == "" {
|
||||
return defaultOSVAPIURL
|
||||
}
|
||||
if strings.TrimRight(apiURL, "/") == "" || !strings.Contains(strings.TrimPrefix(strings.TrimPrefix(apiURL, "https://"), "http://"), "/") {
|
||||
return strings.TrimRight(apiURL, "/") + "/v1/query"
|
||||
}
|
||||
return apiURL
|
||||
}
|
||||
|
||||
func (s *Scanner) Name() string {
|
||||
return ScannerName
|
||||
}
|
||||
@@ -169,7 +179,7 @@ func (s *Scanner) Scan(ctx context.Context, registry, packageName, version strin
|
||||
|
||||
// Check status code
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("OSV API returned status %d: %s", resp.StatusCode, string(body))
|
||||
return nil, &scanerr.StatusError{Service: "OSV API", Code: resp.StatusCode, Body: string(body)}
|
||||
}
|
||||
|
||||
// Parse response
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
package osv
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/config"
|
||||
)
|
||||
|
||||
// A host-only api_url (the previously documented value) must still reach the
|
||||
// query endpoint.
|
||||
func TestScan_HostOnlyAPIURLUsesQueryEndpoint(t *testing.T) {
|
||||
var gotPath string
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
gotPath = r.URL.Path
|
||||
_, _ = w.Write([]byte(`{}`))
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
|
||||
s := New(config.OSVConfig{APIURL: srv.URL})
|
||||
if _, err := s.Scan(context.Background(), "npm", "left-pad", "1.0.0", ""); err != nil {
|
||||
t.Fatalf("Scan: %v", err)
|
||||
}
|
||||
if gotPath != "/v1/query" {
|
||||
t.Errorf("request path = %q, want /v1/query", gotPath)
|
||||
}
|
||||
}
|
||||
|
||||
func TestScan_FullQueryURLIsKept(t *testing.T) {
|
||||
var gotPath string
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
gotPath = r.URL.Path
|
||||
_, _ = w.Write([]byte(`{}`))
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
|
||||
s := New(config.OSVConfig{APIURL: srv.URL + "/v1/query"})
|
||||
if _, err := s.Scan(context.Background(), "npm", "left-pad", "1.0.0", ""); err != nil {
|
||||
t.Fatalf("Scan: %v", err)
|
||||
}
|
||||
if gotPath != "/v1/query" {
|
||||
t.Errorf("request path = %q, want /v1/query", gotPath)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
// Package scanerr classifies scanner failures so callers can tell an
|
||||
// unavailable scanner from a scan that found the package unsafe.
|
||||
package scanerr
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// ErrInfrastructure marks a failure of the scanning machinery (timeout,
|
||||
// unreachable service) as opposed to a verdict on the package.
|
||||
var ErrInfrastructure = errors.New("scanner infrastructure failure")
|
||||
|
||||
// StatusError is an HTTP status returned by a scanner's backing service.
|
||||
type StatusError struct {
|
||||
Service string
|
||||
Body string
|
||||
Code int
|
||||
}
|
||||
|
||||
func (e *StatusError) Error() string {
|
||||
return fmt.Sprintf("%s returned status %d: %s", e.Service, e.Code, e.Body)
|
||||
}
|
||||
|
||||
// IsInfrastructure reports whether err means the scanner could not run
|
||||
// (timeout, network failure, upstream 5xx or rate limit).
|
||||
func IsInfrastructure(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
if errors.Is(err, ErrInfrastructure) || errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) {
|
||||
return true
|
||||
}
|
||||
var netErr net.Error
|
||||
if errors.As(err, &netErr) {
|
||||
return true
|
||||
}
|
||||
var statusErr *StatusError
|
||||
if errors.As(err, &statusErr) {
|
||||
return statusErr.Code >= http.StatusInternalServerError || statusErr.Code == http.StatusTooManyRequests
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package scanerr
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/url"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestIsInfrastructure(t *testing.T) {
|
||||
tests := []struct {
|
||||
err error
|
||||
name string
|
||||
want bool
|
||||
}{
|
||||
{name: "nil", err: nil, want: false},
|
||||
{name: "deadline", err: fmt.Errorf("scan: %w", context.DeadlineExceeded), want: true},
|
||||
{name: "canceled", err: fmt.Errorf("scan: %w", context.Canceled), want: true},
|
||||
{name: "net error", err: &url.Error{Op: "Post", URL: "http://x", Err: &net.OpError{Op: "dial", Err: errors.New("refused")}}, want: true},
|
||||
{name: "upstream 503", err: fmt.Errorf("wrapped: %w", &StatusError{Service: "OSV API", Code: 503}), want: true},
|
||||
{name: "upstream 429", err: &StatusError{Service: "OSV API", Code: 429}, want: true},
|
||||
{name: "upstream 404", err: &StatusError{Service: "OSV API", Code: 404}, want: false},
|
||||
{name: "marked", err: fmt.Errorf("trivy: %w", ErrInfrastructure), want: true},
|
||||
{name: "plain", err: errors.New("scanner exploded"), want: false},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := IsInfrastructure(tt.err); got != tt.want {
|
||||
t.Errorf("IsInfrastructure(%v) = %v, want %v", tt.err, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestStatusErrorMessage(t *testing.T) {
|
||||
err := &StatusError{Service: "OSV API", Code: 500, Body: "boom"}
|
||||
if got, want := err.Error(), "OSV API returned status 500: boom"; got != want {
|
||||
t.Errorf("Error() = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
+113
-2
@@ -20,6 +20,7 @@ import (
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner/npmaudit"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner/osv"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner/pipaudit"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner/scanerr"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner/trivy"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/uuid"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/websocket"
|
||||
@@ -43,14 +44,88 @@ type DatabaseUpdater interface {
|
||||
UpdateDatabase(ctx context.Context) error
|
||||
}
|
||||
|
||||
const (
|
||||
// DetailInfrastructureError marks a stored scan-error result as caused by
|
||||
// scanner infrastructure (timeout, upstream 5xx) rather than by the package.
|
||||
DetailInfrastructureError = "infrastructure_error"
|
||||
|
||||
defaultScanRetryInterval = 5 * time.Minute
|
||||
maxScanRetries = 6
|
||||
)
|
||||
|
||||
// Manager manages multiple security scanners
|
||||
type Manager struct {
|
||||
metadataStore metadata.MetadataStore
|
||||
broadcaster events.Broadcaster
|
||||
retryTimers map[string]*time.Timer
|
||||
inflight map[string]int
|
||||
scanners []Scanner
|
||||
config config.SecurityConfig
|
||||
bcMu sync.RWMutex
|
||||
stateMu sync.Mutex
|
||||
enabled bool
|
||||
stopped bool
|
||||
}
|
||||
|
||||
// Enabled reports whether security scanning is on.
|
||||
func (m *Manager) Enabled() bool {
|
||||
return m.enabled
|
||||
}
|
||||
|
||||
// Stop cancels pending scan retries.
|
||||
func (m *Manager) Stop() {
|
||||
m.stateMu.Lock()
|
||||
defer m.stateMu.Unlock()
|
||||
m.stopped = true
|
||||
for key, timer := range m.retryTimers {
|
||||
timer.Stop()
|
||||
delete(m.retryTimers, key)
|
||||
}
|
||||
}
|
||||
|
||||
func scanKey(registry, packageName, version string) string {
|
||||
return registry + "/" + packageName + "@" + version
|
||||
}
|
||||
|
||||
func (m *Manager) markInflight(key string, delta int) {
|
||||
m.stateMu.Lock()
|
||||
defer m.stateMu.Unlock()
|
||||
m.inflight[key] += delta
|
||||
if m.inflight[key] <= 0 {
|
||||
delete(m.inflight, key)
|
||||
}
|
||||
}
|
||||
|
||||
func (m *Manager) isInflight(key string) bool {
|
||||
m.stateMu.Lock()
|
||||
defer m.stateMu.Unlock()
|
||||
return m.inflight[key] > 0
|
||||
}
|
||||
|
||||
// scheduleRetry rescans a package whose scan failed on infrastructure.
|
||||
func (m *Manager) scheduleRetry(registry, packageName, version, filePath string, attempt int) {
|
||||
interval := m.config.ScanRetryInterval
|
||||
if interval <= 0 {
|
||||
interval = defaultScanRetryInterval
|
||||
}
|
||||
key := scanKey(registry, packageName, version)
|
||||
|
||||
m.stateMu.Lock()
|
||||
defer m.stateMu.Unlock()
|
||||
if m.stopped {
|
||||
return
|
||||
}
|
||||
if old, ok := m.retryTimers[key]; ok {
|
||||
old.Stop()
|
||||
}
|
||||
m.retryTimers[key] = time.AfterFunc(interval, func() {
|
||||
m.stateMu.Lock()
|
||||
delete(m.retryTimers, key)
|
||||
m.stateMu.Unlock()
|
||||
if err := m.scan(context.Background(), registry, packageName, version, filePath, attempt); err != nil {
|
||||
log.Warn().Err(err).Str("package", packageName).Int("attempt", attempt).Msg("Scan retry failed")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// SetBroadcaster wires an events.Broadcaster onto the scanner so scan
|
||||
@@ -81,6 +156,8 @@ func New(cfg config.SecurityConfig, metadataStore metadata.MetadataStore) (*Mana
|
||||
enabled: cfg.Enabled,
|
||||
config: cfg,
|
||||
metadataStore: metadataStore,
|
||||
retryTimers: make(map[string]*time.Timer),
|
||||
inflight: make(map[string]int),
|
||||
}
|
||||
|
||||
if !cfg.Enabled {
|
||||
@@ -165,10 +242,20 @@ func (m *Manager) RegisterScanner(scanner Scanner) {
|
||||
|
||||
// ScanPackage scans a package using all registered scanners and saves results
|
||||
func (m *Manager) ScanPackage(ctx context.Context, registry, packageName, version string, filePath string) error {
|
||||
return m.scan(ctx, registry, packageName, version, filePath, 0)
|
||||
}
|
||||
|
||||
// scan runs every applicable scanner. attempt is 0 for the first scan and
|
||||
// counts retries after an infrastructure failure.
|
||||
func (m *Manager) scan(ctx context.Context, registry, packageName, version string, filePath string, attempt int) error {
|
||||
if !m.enabled {
|
||||
return nil
|
||||
}
|
||||
|
||||
key := scanKey(registry, packageName, version)
|
||||
m.markInflight(key, 1)
|
||||
defer m.markInflight(key, -1)
|
||||
|
||||
log.Info().
|
||||
Str("registry", registry).
|
||||
Str("package", packageName).
|
||||
@@ -178,6 +265,7 @@ func (m *Manager) ScanPackage(ctx context.Context, registry, packageName, versio
|
||||
// Collect results from all scanners
|
||||
var scanResults []*metadata.ScanResult
|
||||
scannerNames := make([]string, 0)
|
||||
var infraFailures, otherFailures int
|
||||
|
||||
for _, scanner := range m.scanners {
|
||||
// Skip scanners that don't support this registry
|
||||
@@ -196,6 +284,11 @@ func (m *Manager) ScanPackage(ctx context.Context, registry, packageName, versio
|
||||
Str("scanner", scanner.Name()).
|
||||
Str("package", packageName).
|
||||
Msg("Scanner failed")
|
||||
if scanerr.IsInfrastructure(err) {
|
||||
infraFailures++
|
||||
} else {
|
||||
otherFailures++
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -214,9 +307,16 @@ func (m *Manager) ScanPackage(ctx context.Context, registry, packageName, versio
|
||||
// fail closed (no scan == blocked) rather than silently leaving
|
||||
// SecurityScanned=false which would allow the package to be served.
|
||||
if len(scanResults) == 0 {
|
||||
infraOnly := infraFailures > 0 && otherFailures == 0
|
||||
if attempt > 0 && !infraOnly {
|
||||
// Keep the earlier infrastructure-error result rather than
|
||||
// replacing it with a failure the package did not cause.
|
||||
return nil
|
||||
}
|
||||
log.Warn().
|
||||
Str("package", packageName).
|
||||
Msg("All scanners failed, saving scan-error result for fail-closed enforcement")
|
||||
Bool("infrastructure", infraOnly).
|
||||
Msg("All scanners failed, saving scan-error result")
|
||||
|
||||
errResult := &metadata.ScanResult{
|
||||
ID: uuid.New().String(),
|
||||
@@ -229,7 +329,8 @@ func (m *Manager) ScanPackage(ctx context.Context, registry, packageName, versio
|
||||
VulnerabilityCount: 0,
|
||||
Vulnerabilities: []metadata.Vulnerability{},
|
||||
Details: map[string]interface{}{
|
||||
"error": "all configured scanners failed for this package",
|
||||
"error": "all configured scanners failed for this package",
|
||||
DetailInfrastructureError: infraOnly,
|
||||
},
|
||||
}
|
||||
if err := m.metadataStore.SaveScanResult(ctx, errResult); err != nil {
|
||||
@@ -246,6 +347,9 @@ func (m *Manager) ScanPackage(ctx context.Context, registry, packageName, versio
|
||||
"status": string(errResult.Status),
|
||||
"vulnerability_count": errResult.VulnerabilityCount,
|
||||
})
|
||||
if infraOnly && attempt < maxScanRetries {
|
||||
m.scheduleRetry(registry, packageName, version, filePath, attempt+1)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -468,6 +572,9 @@ func (m *Manager) CheckVulnerabilities(ctx context.Context, registry, packageNam
|
||||
if err != nil {
|
||||
var hErr *hoardererrors.Error
|
||||
if stderrors.As(err, &hErr) && hErr.Code == hoardererrors.ErrCodeNotFound {
|
||||
if !m.config.FailClosed && m.isInflight(scanKey(registry, packageName, version)) {
|
||||
return false, "", nil
|
||||
}
|
||||
return true, "no scan available - fail closed", nil
|
||||
}
|
||||
// Real backend error (DB transient, etc.) — also block.
|
||||
@@ -486,6 +593,10 @@ func (m *Manager) CheckVulnerabilities(ctx context.Context, registry, packageNam
|
||||
// block. A scan-error record means we don't actually know whether the
|
||||
// package is safe.
|
||||
if result.Status == metadata.ScanStatusError {
|
||||
if infra, _ := result.Details[DetailInfrastructureError].(bool); infra && !m.config.FailClosed {
|
||||
log.Warn().Str("package", packageName).Msg("Scan failed on infrastructure, serving package; scan will be retried")
|
||||
return false, "", nil
|
||||
}
|
||||
return true, "scan failed - fail closed", nil
|
||||
}
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ package scanner
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -330,3 +331,125 @@ func TestCheckVulnerabilities_GoPackageBypassNotFound(t *testing.T) {
|
||||
require.NoError(t, err)
|
||||
assert.True(t, blocked, "a non-matching bypass should not unblock the package")
|
||||
}
|
||||
|
||||
// resultStore returns a fixed scan result from GetScanResult and records saves.
|
||||
type resultStore struct {
|
||||
*stubMetadataStore
|
||||
scan *metadata.ScanResult
|
||||
}
|
||||
|
||||
func (m *resultStore) GetScanResult(context.Context, string, string, string) (*metadata.ScanResult, error) {
|
||||
return m.scan, nil
|
||||
}
|
||||
|
||||
func (m *resultStore) saved() []*metadata.ScanResult {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
return append([]*metadata.ScanResult(nil), m.savedResults...)
|
||||
}
|
||||
|
||||
func TestScanPackage_InfrastructureErrorIsMarked(t *testing.T) {
|
||||
store := &stubMetadataStore{}
|
||||
mgr := newTestManager(t, store)
|
||||
mgr.RegisterScanner(&stubScanner{name: "osv", err: fmt.Errorf("OSV API request failed: %w", context.DeadlineExceeded)})
|
||||
|
||||
require.NoError(t, mgr.ScanPackage(context.Background(), "npm", "left-pad", "1.0.0", "/tmp/x"))
|
||||
|
||||
require.Len(t, store.savedResults, 1)
|
||||
assert.Equal(t, metadata.ScanStatusError, store.savedResults[0].Status)
|
||||
assert.Equal(t, true, store.savedResults[0].Details[DetailInfrastructureError])
|
||||
}
|
||||
|
||||
func TestScanPackage_NonInfrastructureErrorIsNotMarked(t *testing.T) {
|
||||
store := &stubMetadataStore{}
|
||||
mgr := newTestManager(t, store)
|
||||
mgr.RegisterScanner(&stubScanner{name: "broken", err: errors.New("scanner exploded")})
|
||||
|
||||
require.NoError(t, mgr.ScanPackage(context.Background(), "npm", "left-pad", "1.0.0", "/tmp/x"))
|
||||
|
||||
require.Len(t, store.savedResults, 1)
|
||||
assert.NotEqual(t, true, store.savedResults[0].Details[DetailInfrastructureError])
|
||||
}
|
||||
|
||||
func infraErrorScan() *metadata.ScanResult {
|
||||
return &metadata.ScanResult{
|
||||
ID: "r", Scanner: "all", ScannedAt: time.Now(), Status: metadata.ScanStatusError,
|
||||
Details: map[string]interface{}{DetailInfrastructureError: true},
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckVulnerabilities_InfrastructureErrorServesByDefault(t *testing.T) {
|
||||
store := &resultStore{stubMetadataStore: &stubMetadataStore{}, scan: infraErrorScan()}
|
||||
mgr := newTestManager(t, store)
|
||||
|
||||
blocked, reason, err := mgr.CheckVulnerabilities(context.Background(), "npm", "left-pad", "1.0.0")
|
||||
require.NoError(t, err)
|
||||
assert.False(t, blocked, "infrastructure scan error must not block, got reason %q", reason)
|
||||
}
|
||||
|
||||
func TestCheckVulnerabilities_InfrastructureErrorBlocksWhenFailClosed(t *testing.T) {
|
||||
store := &resultStore{stubMetadataStore: &stubMetadataStore{}, scan: infraErrorScan()}
|
||||
mgr, err := New(config.SecurityConfig{Enabled: true, FailClosed: true}, store)
|
||||
require.NoError(t, err)
|
||||
|
||||
blocked, _, err := mgr.CheckVulnerabilities(context.Background(), "npm", "left-pad", "1.0.0")
|
||||
require.NoError(t, err)
|
||||
assert.True(t, blocked)
|
||||
}
|
||||
|
||||
func TestCheckVulnerabilities_PlainScanErrorStillBlocks(t *testing.T) {
|
||||
scan := infraErrorScan()
|
||||
scan.Details = map[string]interface{}{}
|
||||
store := &resultStore{stubMetadataStore: &stubMetadataStore{}, scan: scan}
|
||||
mgr := newTestManager(t, store)
|
||||
|
||||
blocked, _, err := mgr.CheckVulnerabilities(context.Background(), "npm", "left-pad", "1.0.0")
|
||||
require.NoError(t, err)
|
||||
assert.True(t, blocked)
|
||||
}
|
||||
|
||||
// flakyScanner fails with an infrastructure error until failures is exhausted.
|
||||
type flakyScanner struct {
|
||||
failures int
|
||||
calls int
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
func (f *flakyScanner) Name() string { return "osv" }
|
||||
func (f *flakyScanner) Scan(_ context.Context, registry, name, version, _ string) (*metadata.ScanResult, error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.calls++
|
||||
if f.calls <= f.failures {
|
||||
return nil, fmt.Errorf("OSV API request failed: %w", context.DeadlineExceeded)
|
||||
}
|
||||
return &metadata.ScanResult{
|
||||
ID: "ok", Registry: registry, PackageName: name, PackageVersion: version,
|
||||
Scanner: "osv", ScannedAt: time.Now(), Status: metadata.ScanStatusClean,
|
||||
}, nil
|
||||
}
|
||||
func (f *flakyScanner) Health(context.Context) error { return nil }
|
||||
|
||||
func TestScanPackage_InfrastructureErrorIsRetried(t *testing.T) {
|
||||
store := &stubMetadataStore{}
|
||||
mgr, err := New(config.SecurityConfig{Enabled: true, ScanRetryInterval: 10 * time.Millisecond}, store)
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(mgr.Stop)
|
||||
mgr.RegisterScanner(&flakyScanner{failures: 1})
|
||||
|
||||
require.NoError(t, mgr.ScanPackage(context.Background(), "npm", "left-pad", "1.0.0", "/tmp/x"))
|
||||
|
||||
require.Eventually(t, func() bool {
|
||||
store.mu.Lock()
|
||||
defer store.mu.Unlock()
|
||||
n := len(store.savedResults)
|
||||
return n == 2 && store.savedResults[1].Status == metadata.ScanStatusClean
|
||||
}, 2*time.Second, 10*time.Millisecond, "retry must save a clean result after the infrastructure error")
|
||||
}
|
||||
|
||||
func TestScanner_DisabledReportsNotEnabled(t *testing.T) {
|
||||
mgr, err := New(config.SecurityConfig{Enabled: false}, &stubMetadataStore{})
|
||||
require.NoError(t, err)
|
||||
assert.False(t, mgr.Enabled())
|
||||
assert.True(t, newTestManager(t, &stubMetadataStore{}).Enabled())
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user