feat(scanner): report per-scanner health and the bypass behind a decision

The manager now exposes the cached health, and the CLI version, of every
registered scanner. A scan decision also names the admin bypass that
applied to the package, so callers can tell a bypassed package from a
cleared one.
This commit is contained in:
2026-11-24 00:42:41 +00:00
parent 916e2b0aa5
commit 2b6f3bd892
10 changed files with 272 additions and 48 deletions
+30
View File
@@ -169,3 +169,33 @@ func TestScanDecisionsVerdicts(t *testing.T) {
"github.com/a/b/@v/v1.0.0.zip": true, "six": true,
}, blocked)
}
// A decision names the bypass that applied, so the dashboard can say who waved the package through.
func TestScanDecisionsReportAppliedBypass(t *testing.T) {
store, err := gormstore.NewV2(gormstore.Config{
Driver: "sqlite", DSN: fmt.Sprintf("file:decbp_%d?mode=memory&cache=shared", time.Now().UnixNano()),
MaxOpenConns: 1, MaxIdleConns: 1, LogLevel: "silent",
})
require.NoError(t, err)
t.Cleanup(func() { _ = store.Close() })
seedDecisions(t, store)
addBypass(t, store, metadata.BypassTypePackage, "npm/crit")
addBypass(t, store, metadata.BypassTypeCVE, "CVE-2")
mgr, err := New(config.SecurityConfig{Enabled: true, BlockOnSeverity: "high"}, store)
require.NoError(t, err)
decisions, err := mgr.ScanDecisions(context.Background(), nil)
require.NoError(t, err)
got := map[string]ScanDecision{}
for _, d := range decisions {
got[d.Summary.Name] = d
}
require.NotNil(t, got["crit"].Bypass, "package bypass applies")
require.Equal(t, metadata.BypassTypePackage, got["crit"].Bypass.Type)
require.False(t, got["crit"].Blocked)
require.NotNil(t, got["mix"].Bypass, "CVE bypass covers a finding")
require.Equal(t, metadata.BypassTypeCVE, got["mix"].Bypass.Type)
require.Nil(t, got["clean"].Bypass)
require.Nil(t, got["low"].Bypass)
}
+9 -2
View File
@@ -21,6 +21,7 @@ import (
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
"github.com/lukaszraczylo/gohoarder/pkg/scanner/gomodule"
"github.com/lukaszraczylo/gohoarder/pkg/scanner/scanerr"
"github.com/lukaszraczylo/gohoarder/pkg/scanner/scanver"
"github.com/lukaszraczylo/gohoarder/pkg/uuid"
"github.com/rs/zerolog/log"
)
@@ -30,7 +31,8 @@ const ScannerName = "govulncheck"
// Scanner implements the govulncheck vulnerability scanner for Go modules
type Scanner struct {
config config.GovulncheckConfig
version scanver.Cache
config config.GovulncheckConfig
}
// New creates a new govulncheck scanner
@@ -219,9 +221,11 @@ func parseFindings(output []byte, module string) ([]GovulncheckVuln, error) {
// Health checks if govulncheck is available
func (s *Scanner) Health(ctx context.Context) error {
cmd := exec.CommandContext(ctx, "govulncheck", "-version")
if err := cmd.Run(); err != nil {
output, err := cmd.Output()
if err != nil {
return fmt.Errorf("govulncheck not available: %w (install with: go install golang.org/x/vuln/cmd/govulncheck@latest)", err)
}
s.version.Record(string(output))
return nil
}
@@ -355,3 +359,6 @@ type GovulncheckVuln struct {
ModuleVersion string
Summary string
}
// Version returns the version the last successful health check reported.
func (s *Scanner) Version() string { return s.version.Version() }
+9 -2
View File
@@ -14,6 +14,7 @@ import (
"github.com/lukaszraczylo/gohoarder/pkg/config"
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
"github.com/lukaszraczylo/gohoarder/pkg/scanner/gomodule"
"github.com/lukaszraczylo/gohoarder/pkg/scanner/scanver"
"github.com/lukaszraczylo/gohoarder/pkg/uuid"
"github.com/rs/zerolog/log"
)
@@ -23,7 +24,8 @@ const ScannerName = "grype"
// Scanner implements the Grype vulnerability scanner
type Scanner struct {
config config.GrypeConfig
version scanver.Cache
config config.GrypeConfig
}
// New creates a new Grype scanner
@@ -106,9 +108,11 @@ func parse(output []byte) (*GrypeResult, error) {
// Health checks if Grype is available
func (s *Scanner) Health(ctx context.Context) error {
cmd := exec.CommandContext(ctx, "grype", "version")
if err := cmd.Run(); err != nil {
output, err := cmd.Output()
if err != nil {
return fmt.Errorf("grype not available: %w", err)
}
s.version.Record(string(output))
return nil
}
@@ -223,3 +227,6 @@ type GrypeArtifact struct {
Version string `json:"version"`
Type string `json:"type"`
}
// Version returns the version the last successful health check reported.
func (s *Scanner) Version() string { return s.version.Version() }
+37
View File
@@ -66,3 +66,40 @@ func TestHealthDoesNotCacheCancelledProbe(t *testing.T) {
t.Fatalf("scanner health ran %d times, want 2", got)
}
}
type versionedProbe struct {
healthProbe
name string
}
func (s *versionedProbe) Name() string { return s.name }
func (s *versionedProbe) Version() string { return "1.2.3" }
// One broken scanner must not hide the state of the others.
func TestStatusesReportEveryScanner(t *testing.T) {
good := &versionedProbe{name: "trivy"}
bad := &healthProbe{err: errors.New("missing")}
m := &Manager{enabled: true, scanners: []Scanner{bad, good}}
statuses := m.Statuses(context.Background())
if len(statuses) != 2 {
t.Fatalf("Statuses() = %d entries, want 2", len(statuses))
}
if statuses[0].Name != "counting" || statuses[0].Healthy || statuses[0].Version != "" {
t.Fatalf("broken scanner status = %+v", statuses[0])
}
if statuses[1].Name != "trivy" || !statuses[1].Healthy || statuses[1].Version != "1.2.3" {
t.Fatalf("healthy scanner status = %+v", statuses[1])
}
_ = m.Statuses(context.Background())
if got := bad.calls.Load(); got != 1 {
t.Fatalf("scanner health ran %d times, want 1 (cached)", got)
}
}
func TestStatusesEmptyWhenDisabled(t *testing.T) {
m := &Manager{enabled: false, scanners: []Scanner{&healthProbe{}}}
if got := m.Statuses(context.Background()); got != nil {
t.Fatalf("Statuses() = %v, want nil", got)
}
}
+9 -2
View File
@@ -17,6 +17,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/scanner/scanver"
"github.com/lukaszraczylo/gohoarder/pkg/uuid"
"github.com/rs/zerolog/log"
)
@@ -26,7 +27,8 @@ const ScannerName = "npm-audit"
// Scanner implements the npm audit vulnerability scanner
type Scanner struct {
config config.NpmAuditConfig
version scanver.Cache
config config.NpmAuditConfig
}
// New creates a new npm audit scanner
@@ -172,9 +174,11 @@ func writeWrapper(dir, packageName, archive string) error {
// Health checks if npm is available
func (s *Scanner) Health(ctx context.Context) error {
cmd := exec.CommandContext(ctx, "npm", "--version")
if err := cmd.Run(); err != nil {
output, err := cmd.Output()
if err != nil {
return fmt.Errorf("npm not available: %w", err)
}
s.version.Record(string(output))
return nil
}
@@ -313,3 +317,6 @@ type NpmAdvisory struct {
Range string `json:"range"`
Source int `json:"source"`
}
// Version returns the version the last successful health check reported.
func (s *Scanner) Version() string { return s.version.Version() }
+9 -2
View File
@@ -17,6 +17,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/scanner/scanver"
"github.com/lukaszraczylo/gohoarder/pkg/uuid"
"github.com/rs/zerolog/log"
)
@@ -26,7 +27,8 @@ const ScannerName = "pip-audit"
// Scanner implements the pip-audit vulnerability scanner
type Scanner struct {
config config.PipAuditConfig
version scanver.Cache
config config.PipAuditConfig
}
// New creates a new pip-audit scanner
@@ -123,9 +125,11 @@ var (
// Health checks if pip-audit is available
func (s *Scanner) Health(ctx context.Context) error {
cmd := exec.CommandContext(ctx, "pip-audit", "--version")
if err := cmd.Run(); err != nil {
output, err := cmd.Output()
if err != nil {
return fmt.Errorf("pip-audit not available: %w (install with: pip install pip-audit)", err)
}
s.version.Record(string(output))
return nil
}
@@ -228,3 +232,6 @@ type PipVuln struct {
FixVersions []string `json:"fix_versions"`
Aliases []string `json:"aliases"`
}
// Version returns the version the last successful health check reported.
func (s *Scanner) Version() string { return s.version.Version() }
+98 -39
View File
@@ -7,6 +7,7 @@ import (
stderrors "errors"
"fmt"
"os"
"slices"
"strings"
"sync"
"time"
@@ -75,11 +76,22 @@ func (m *Manager) currentFileSource() FileSource {
const healthTTL = 30 * time.Second
type healthCache struct {
at time.Time
err error
mu sync.Mutex
at time.Time
err error
states []ScannerStatus
mu sync.Mutex
}
// ScannerStatus is one scanner's last health probe.
type ScannerStatus struct {
Name string
Version string // empty when the scanner does not report one
Healthy bool
}
// versioned is implemented by scanners that learn their version during a health probe.
type versioned interface{ Version() string }
// Manager manages multiple security scanners
type Manager struct {
health healthCache
@@ -690,6 +702,11 @@ func (m *Manager) missingScanDecision(registry, packageName, version string) (bo
// packageBypassed reports whether an active admin bypass covers the whole package.
func packageBypassed(registry, bypassName, version, releaseKey string, bypasses []*metadata.CVEBypass) bool {
return packageBypass(registry, bypassName, version, releaseKey, bypasses) != nil
}
// packageBypass returns the active admin bypass that covers the whole package, or nil.
func packageBypass(registry, bypassName, version, releaseKey string, bypasses []*metadata.CVEBypass) *metadata.CVEBypass {
packageKey := fmt.Sprintf("%s/%s@%s", registry, bypassName, version)
packageKeyNoVersion := fmt.Sprintf("%s/%s", registry, bypassName)
for _, bypass := range bypasses {
@@ -701,11 +718,28 @@ func packageBypassed(registry, bypassName, version, releaseKey string, bypasses
Str("reason", bypass.Reason).
Time("expires_at", bypass.ExpiresAt).
Msg("Package bypassed by admin")
return true
return bypass
}
}
}
return false
return nil
}
// cveBypasses maps upper-cased CVE ids to the active bypass that applies to this package.
func cveBypasses(registry, bypassName, version, releaseKey string, bypasses []*metadata.CVEBypass) map[string]*metadata.CVEBypass {
packageKey := fmt.Sprintf("%s/%s@%s", registry, bypassName, version)
packageKeyNoVersion := fmt.Sprintf("%s/%s", registry, bypassName)
out := make(map[string]*metadata.CVEBypass)
for _, bypass := range bypasses {
if bypass.Type != metadata.BypassTypeCVE || !bypass.Active {
continue
}
if bypass.AppliesTo != "" && bypass.AppliesTo != packageKey && bypass.AppliesTo != packageKeyNoVersion && (releaseKey == "" || bypass.AppliesTo != releaseKey) {
continue
}
out[strings.ToUpper(bypass.Target)] = bypass
}
return out
}
// scanFacts is what the blocking policy needs to know about one scan.
@@ -731,21 +765,7 @@ func (m *Manager) evaluateScan(registry, packageName, version, releaseKey string
return true, "scan failed - fail closed", nil
}
bypassName := normalizeBypassPackageName(registry, packageName)
packageKey := fmt.Sprintf("%s/%s@%s", registry, bypassName, version)
packageKeyNoVersion := fmt.Sprintf("%s/%s", registry, bypassName)
// Build set of bypassed CVEs for fast lookup
bypassedCVEs := make(map[string]*metadata.CVEBypass)
for _, bypass := range bypasses {
if bypass.Type == metadata.BypassTypeCVE && bypass.Active {
// Check if bypass applies to this package (if AppliesTo is set)
if bypass.AppliesTo != "" && bypass.AppliesTo != packageKey && bypass.AppliesTo != packageKeyNoVersion && (releaseKey == "" || bypass.AppliesTo != releaseKey) {
continue // This bypass doesn't apply to this package
}
bypassedCVEs[strings.ToUpper(bypass.Target)] = bypass
}
}
bypassedCVEs := cveBypasses(registry, normalizeBypassPackageName(registry, packageName), version, releaseKey, bypasses)
// Count vulnerabilities by severity, excluding bypassed CVEs
severityCounts := f.counts
@@ -830,6 +850,8 @@ func (m *Manager) evaluateScan(registry, packageName, version, releaseKey string
// ScanDecision pairs a package's latest scan with the blocking verdict.
type ScanDecision struct {
Summary *metadata.ScanSummary
// Bypass is the active admin bypass that applied to this package, if any.
Bypass *metadata.CVEBypass
Reason string
Blocked bool
}
@@ -862,25 +884,25 @@ func (m *Manager) ScanDecisions(ctx context.Context, packageIDs []string) ([]Sca
for _, sum := range summaries {
d := ScanDecision{Summary: sum}
if m.enabled {
d.Blocked, d.Reason = m.judgeSummary(sum, bypasses, withList)
d.Blocked, d.Reason, d.Bypass = m.judgeSummary(sum, bypasses, withList)
}
decisions = append(decisions, d)
}
return decisions, nil
}
func (m *Manager) judgeSummary(sum *metadata.ScanSummary, bypasses []*metadata.CVEBypass, withList bool) (bool, string) {
func (m *Manager) judgeSummary(sum *metadata.ScanSummary, bypasses []*metadata.CVEBypass, withList bool) (bool, string, *metadata.CVEBypass) {
bypassName := normalizeBypassPackageName(sum.Registry, sum.Name)
releaseKey := ""
if sum.ReleaseVersion != "" {
releaseKey = fmt.Sprintf("%s/%s@%s", sum.Registry, bypassName, sum.ReleaseVersion)
}
if packageBypassed(sum.Registry, bypassName, sum.Version, releaseKey, bypasses) {
return false, ""
if b := packageBypass(sum.Registry, bypassName, sum.Version, releaseKey, bypasses); b != nil {
return false, "", b
}
if !sum.HasScan {
blocked, reason, _ := m.missingScanDecision(sum.Registry, sum.Name, sum.Version)
return blocked, reason
return blocked, reason, nil
}
infra, _ := sum.Details[DetailInfrastructureError].(bool)
facts := scanFacts{status: sum.Status, infra: infra, total: sum.Total, hasList: withList, vulns: sum.Vulnerabilities}
@@ -890,7 +912,17 @@ func (m *Manager) judgeSummary(sum *metadata.ScanSummary, bypasses []*metadata.C
}
}
blocked, reason, _ := m.evaluateScan(sum.Registry, sum.Name, sum.Version, releaseKey, bypasses, facts)
return blocked, reason
var applied *metadata.CVEBypass
if withList {
covered := cveBypasses(sum.Registry, bypassName, sum.Version, releaseKey, bypasses)
for _, v := range sum.Vulnerabilities {
if b, ok := covered[strings.ToUpper(v.ID)]; ok {
applied = b
break
}
}
}
return blocked, reason, applied
}
// UpdateDatabases updates vulnerability databases for all scanners
@@ -925,24 +957,51 @@ func (m *Manager) Health(ctx context.Context) error {
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
m.refreshHealth(ctx)
return m.health.err
}
func (m *Manager) checkScanners(ctx context.Context) error {
// Statuses reports each registered scanner's health from the same 30 s cache as Health.
func (m *Manager) Statuses(ctx context.Context) []ScannerStatus {
if !m.enabled {
return nil
}
m.health.mu.Lock()
defer m.health.mu.Unlock()
m.refreshHealth(ctx)
return slices.Clone(m.health.states)
}
// refreshHealth re-probes the scanners when the cached result is older than healthTTL; the caller holds health.mu.
func (m *Manager) refreshHealth(ctx context.Context) {
if !m.health.at.IsZero() && time.Since(m.health.at) < healthTTL {
return
}
states, err := m.checkScanners(ctx)
if ctx.Err() != nil {
m.health.err, m.health.states = err, states
return
}
m.health.at, m.health.err, m.health.states = time.Now(), err, states
}
// checkScanners probes every scanner and returns the first failure, so one broken scanner does not hide the rest.
func (m *Manager) checkScanners(ctx context.Context) ([]ScannerStatus, error) {
var first error
states := make([]ScannerStatus, 0, len(m.scanners))
for _, scanner := range m.scanners {
if err := scanner.Health(ctx); err != nil {
return fmt.Errorf("scanner %s health check failed: %w", scanner.Name(), err)
err := scanner.Health(ctx)
st := ScannerStatus{Name: scanner.Name(), Healthy: err == nil}
if v, ok := scanner.(versioned); ok {
st.Version = v.Version()
}
states = append(states, st)
if err != nil && first == nil {
first = fmt.Errorf("scanner %s health check failed: %w", scanner.Name(), err)
}
}
return nil
return states, first
}
// shouldRunScanner determines if a scanner should run for a given registry
+29
View File
@@ -0,0 +1,29 @@
// Package scanver remembers the version a scanner's CLI reported at its last health check.
package scanver
import (
"regexp"
"sync/atomic"
)
var versionToken = regexp.MustCompile(`\d+\.\d+(?:\.\d+)?[0-9A-Za-z.+-]*`)
// Cache holds the last version seen; the zero value reports no version.
type Cache struct {
v atomic.Pointer[string]
}
// Record stores the first version-like token in a CLI's version output.
func (c *Cache) Record(output string) {
if tok := versionToken.FindString(output); tok != "" {
c.v.Store(&tok)
}
}
// Version returns the recorded version, or "" when none was seen.
func (c *Cache) Version() string {
if p := c.v.Load(); p != nil {
return *p
}
return ""
}
+35
View File
@@ -0,0 +1,35 @@
package scanver
import "testing"
func TestRecord(t *testing.T) {
tests := []struct {
name string
output string
want string
}{
{name: "trivy", output: "Version: 0.58.1\nVulnerability DB:\n Version: 2\n", want: "0.58.1"},
{name: "grype", output: "Application: grype\nVersion: 0.87.0\n", want: "0.87.0"},
{name: "npm", output: "10.9.2\n", want: "10.9.2"},
{name: "prerelease", output: "pip-audit 2.8.0rc1", want: "2.8.0rc1"},
{name: "no version", output: "command not found", want: ""},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var c Cache
c.Record(tt.output)
if got := c.Version(); got != tt.want {
t.Fatalf("Version() = %q, want %q", got, tt.want)
}
})
}
}
func TestRecordKeepsLastGoodVersion(t *testing.T) {
var c Cache
c.Record("1.2.3")
c.Record("garbage")
if got := c.Version(); got != "1.2.3" {
t.Fatalf("Version() = %q, want 1.2.3", got)
}
}
+7 -1
View File
@@ -14,6 +14,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/scanner/scanver"
"github.com/lukaszraczylo/gohoarder/pkg/uuid"
"github.com/rs/zerolog/log"
)
@@ -23,7 +24,8 @@ const ScannerName = "trivy"
// Scanner implements the Scanner interface using Trivy
type Scanner struct {
config config.TrivyConfig
version scanver.Cache
config config.TrivyConfig
}
// TrivyResult represents Trivy JSON output structure
@@ -247,6 +249,10 @@ func (s *Scanner) Health(ctx context.Context) error {
return fmt.Errorf("trivy not available: %w (output: %s)", err, string(output))
}
s.version.Record(string(output))
log.Debug().Str("version", strings.TrimSpace(string(output))).Msg("Trivy health check passed")
return nil
}
// Version returns the version the last successful health check reported.
func (s *Scanner) Version() string { return s.version.Version() }