perf(api): serve package lists and stats in constant queries

The dashboard waited seconds for /api/packages and /api/stats. Both
handlers ran queries per package, so the cost grew with the cache.

Baseline, measured live through a port-forward (median of 5):
- /api/packages: 3033 ms, 594 items, limit ignored
- /api/packages?limit=50&offset=0: 2813 ms
- /api/stats: 3813 ms
- /api/stats/timeseries?period=1day: 12 ms

Baseline queries per request, counted on SQLite with 20 and 120 rows:
- /api/packages: 141 and 841 queries (7 per package)
- /api/stats: 103 and 603 queries (5 per package)

Both handlers now run a constant number of queries: 4 for the full list,
6 for a page, 6 for stats. The query-count tests fail on the old code.

- /api/packages pages (registry, name) groups with page, page_size,
  registry, q, sort and order, and returns total_groups. Without page
  and page_size it returns every package, so old clients keep working.
- A batched scan lookup replaces the per-package GetScanResult and
  CheckVulnerabilities calls. ScanDecisions returns the same verdicts as
  CheckVulnerabilities, proven by a policy and bypass matrix test.
- The silent 1000-row cap is gone from the list and the Go delete.
- /api/stats sums per registry with GROUP BY and judges blocked
  packages in one batch.
- Migration 202611240001 adds scan_results (package_id, scanned_at) on
  SQLite, PostgreSQL and MySQL. The existing (registry_id, name, version)
  index already serves the group lookups.
This commit is contained in:
2026-11-23 13:26:50 +00:00
parent a7b9917696
commit db5ca2539f
24 changed files with 2049 additions and 244 deletions
+171
View File
@@ -0,0 +1,171 @@
package scanner
import (
"context"
"fmt"
"testing"
"time"
"github.com/lukaszraczylo/gohoarder/pkg/config"
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
"github.com/lukaszraczylo/gohoarder/pkg/metadata/gormstore"
"github.com/stretchr/testify/require"
)
type decisionFixture struct {
scan *metadata.ScanResult
name, registry, pkg, version, release string
scannedWithoutRow bool
}
func vuln(id, severity string) metadata.Vulnerability {
return metadata.Vulnerability{ID: id, Severity: severity}
}
func decisionFixtures() []decisionFixture {
scan := func(status metadata.ScanStatus, details map[string]interface{}, vulns ...metadata.Vulnerability) *metadata.ScanResult {
return &metadata.ScanResult{Scanner: "t", Status: status, ScannedAt: time.Now(), Details: details, Vulnerabilities: vulns, VulnerabilityCount: len(vulns)}
}
return []decisionFixture{
{name: "clean", registry: "npm", pkg: "clean", version: "1.0.0", scan: scan(metadata.ScanStatusClean, nil)},
{name: "critical", registry: "npm", pkg: "crit", version: "1.0.0", scan: scan(metadata.ScanStatusVulnerable, nil, vuln("CVE-1", "critical"))},
{name: "high+moderate", registry: "npm", pkg: "mix", version: "1.0.0", scan: scan(metadata.ScanStatusVulnerable, nil, vuln("CVE-2", "high"), vuln("CVE-3", "medium"))},
{name: "low only", registry: "npm", pkg: "low", version: "1.0.0", scan: scan(metadata.ScanStatusVulnerable, nil, vuln("CVE-4", "low"), vuln("CVE-5", "weird"))},
{name: "infra error", registry: "npm", pkg: "infra", version: "1.0.0", scan: scan(metadata.ScanStatusError, map[string]interface{}{DetailInfrastructureError: true})},
{name: "scan error", registry: "npm", pkg: "err", version: "1.0.0", scan: scan(metadata.ScanStatusError, nil)},
{name: "scanned without row", registry: "npm", pkg: "lost", version: "1.0.0", scannedWithoutRow: true},
{name: "go zip", registry: "go", pkg: "github.com/a/b/@v/v1.0.0.zip", version: "v1.0.0", scan: scan(metadata.ScanStatusVulnerable, nil, vuln("CVE-6", "high"))},
{name: "pypi release", registry: "pypi", pkg: "six", version: "six-1.0.tar.gz", release: "1.0", scan: scan(metadata.ScanStatusVulnerable, nil, vuln("CVE-7", "critical"))},
}
}
func seedDecisions(t *testing.T, store *gormstore.GORMStoreV2) map[string]string {
t.Helper()
ctx := context.Background()
ids := map[string]string{}
for _, f := range decisionFixtures() {
now := time.Now()
require.NoError(t, store.SavePackage(ctx, &metadata.Package{
Registry: f.registry, Name: f.pkg, Version: f.version, ReleaseVersion: f.release,
StorageKey: fmt.Sprintf("%s/%s/%s", f.registry, f.pkg, f.version), Size: 1, CachedAt: now, LastAccessed: now,
}))
if f.scan != nil {
res := *f.scan
res.Registry, res.PackageName, res.PackageVersion = f.registry, f.pkg, f.version
require.NoError(t, store.SaveScanResult(ctx, &res))
}
if f.scannedWithoutRow {
require.NoError(t, store.DB().Exec("UPDATE packages SET security_scanned = ? WHERE name = ?", true, f.pkg).Error)
}
}
return ids
}
func addBypass(t *testing.T, store *gormstore.GORMStoreV2, kind metadata.BypassType, target string) {
t.Helper()
require.NoError(t, store.SaveCVEBypass(context.Background(), &metadata.CVEBypass{
Type: kind, Target: target, Reason: "test", CreatedBy: "test", Active: true, ExpiresAt: time.Now().Add(time.Hour),
}))
}
// ScanDecisions must reach the same verdict as CheckVulnerabilities for every policy and bypass combination.
func TestScanDecisionsMatchCheckVulnerabilities(t *testing.T) {
policies := map[string]config.SecurityConfig{
"block on high": {Enabled: true, BlockOnSeverity: "high", BlockThresholds: config.VulnerabilityThresholds{Critical: -1, High: -1, Medium: -1, Low: -1}},
"block on critical": {Enabled: true, BlockOnSeverity: "critical", BlockThresholds: config.VulnerabilityThresholds{Critical: -1, High: -1, Medium: -1, Low: -1}},
"block on moderate": {Enabled: true, BlockOnSeverity: "moderate", BlockThresholds: config.VulnerabilityThresholds{Critical: -1, High: -1, Medium: -1, Low: -1}},
"block on low": {Enabled: true, BlockOnSeverity: "low", BlockThresholds: config.VulnerabilityThresholds{Critical: -1, High: -1, Medium: -1, Low: -1}},
"thresholds": {Enabled: true, BlockOnSeverity: "none", BlockThresholds: config.VulnerabilityThresholds{Critical: 0, High: 1, Medium: 0, Low: 1}},
"fail closed": {Enabled: true, FailClosed: true, BlockOnSeverity: "none", BlockThresholds: config.VulnerabilityThresholds{Critical: -1, High: -1, Medium: -1, Low: -1}},
"block on low, closed": {Enabled: true, FailClosed: true, BlockOnSeverity: "low", BlockThresholds: config.VulnerabilityThresholds{Critical: -1, High: -1, Medium: -1, Low: -1}},
"disabled scanner mgr": {Enabled: false, BlockOnSeverity: "low"},
"thresholds, high only": {Enabled: true, BlockOnSeverity: "none", BlockThresholds: config.VulnerabilityThresholds{Critical: -1, High: 0, Medium: -1, Low: -1}},
}
bypassSets := map[string]func(*testing.T, *gormstore.GORMStoreV2){
"no bypass": func(*testing.T, *gormstore.GORMStoreV2) {},
"cve bypass": func(t *testing.T, s *gormstore.GORMStoreV2) { addBypass(t, s, metadata.BypassTypeCVE, "cve-1") },
"cve high": func(t *testing.T, s *gormstore.GORMStoreV2) { addBypass(t, s, metadata.BypassTypeCVE, "CVE-2") },
"package bypass": func(t *testing.T, s *gormstore.GORMStoreV2) { addBypass(t, s, metadata.BypassTypePackage, "npm/crit") },
"go bypass": func(t *testing.T, s *gormstore.GORMStoreV2) {
addBypass(t, s, metadata.BypassTypePackage, "go/github.com/a/[email protected]")
},
"release bypass": func(t *testing.T, s *gormstore.GORMStoreV2) {
addBypass(t, s, metadata.BypassTypePackage, "pypi/[email protected]")
},
"both kinds": func(t *testing.T, s *gormstore.GORMStoreV2) {
addBypass(t, s, metadata.BypassTypeCVE, "CVE-3")
addBypass(t, s, metadata.BypassTypePackage, "npm/mix")
},
}
for bypassName, setBypasses := range bypassSets {
store, err := gormstore.NewV2(gormstore.Config{
Driver: "sqlite", DSN: fmt.Sprintf("file:dec_%d?mode=memory&cache=shared", time.Now().UnixNano()),
MaxOpenConns: 1, MaxIdleConns: 1, LogLevel: "silent",
})
require.NoError(t, err)
seedDecisions(t, store)
setBypasses(t, store)
for policyName, cfg := range policies {
t.Run(bypassName+"/"+policyName, func(t *testing.T) {
mgr, err := New(cfg, store)
require.NoError(t, err)
ctx := context.Background()
decisions, err := mgr.ScanDecisions(ctx, nil)
require.NoError(t, err)
require.Len(t, decisions, len(decisionFixtures()))
for _, d := range decisions {
s := d.Summary
wantBlocked, wantReason, checkErr := mgr.CheckVulnerabilities(ctx, s.Registry, s.Name, s.Version)
require.NoError(t, checkErr)
require.Equal(t, wantBlocked, d.Blocked, "%s/%s@%s", s.Registry, s.Name, s.Version)
if wantBlocked && len(wantReason) > 0 && wantReason[0] != 'P' {
// Count-based reasons carry numbers that differ only under CVE bypasses; the
// fixed fail-closed reasons must match exactly.
require.Equal(t, wantReason, d.Reason)
}
}
ids := make([]string, 0, 3)
for _, d := range decisions[:3] {
ids = append(ids, d.Summary.PackageID)
}
subset, err := mgr.ScanDecisions(ctx, ids)
require.NoError(t, err)
require.Len(t, subset, 3)
})
}
require.NoError(t, store.Close())
}
}
func TestScanDecisionsVerdicts(t *testing.T) {
store, err := gormstore.NewV2(gormstore.Config{
Driver: "sqlite", DSN: fmt.Sprintf("file:decv_%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.BypassTypeCVE, "CVE-3")
mgr, err := New(config.SecurityConfig{
Enabled: true, BlockOnSeverity: "high",
BlockThresholds: config.VulnerabilityThresholds{Critical: -1, High: -1, Medium: -1, Low: -1},
}, store)
require.NoError(t, err)
decisions, err := mgr.ScanDecisions(context.Background(), nil)
require.NoError(t, err)
blocked := map[string]bool{}
for _, d := range decisions {
blocked[d.Summary.Name] = d.Blocked
}
require.Equal(t, map[string]bool{
"clean": false, "crit": true, "mix": true, "low": false,
"infra": false, // infrastructure failure serves the package unless fail_closed
"err": true, "lost": true,
"github.com/a/b/@v/v1.0.0.zip": true, "six": true,
}, blocked)
}
+143 -37
View File
@@ -564,24 +564,10 @@ func (m *Manager) CheckVulnerabilities(ctx context.Context, registry, packageNam
bypasses = []*metadata.CVEBypass{} // Continue without bypasses
}
// Check if entire package is bypassed
bypassName := normalizeBypassPackageName(registry, packageName)
packageKey := fmt.Sprintf("%s/%s@%s", registry, bypassName, version)
packageKeyNoVersion := fmt.Sprintf("%s/%s", registry, bypassName)
releaseKey := m.releaseVersionKey(ctx, registry, packageName, version, bypassName)
for _, bypass := range bypasses {
if bypass.Type == metadata.BypassTypePackage && bypass.Active {
if bypass.Target == packageKey || bypass.Target == packageKeyNoVersion || (releaseKey != "" && bypass.Target == releaseKey) {
log.Info().
Str("package", packageKey).
Str("bypass_id", bypass.ID).
Str("reason", bypass.Reason).
Time("expires_at", bypass.ExpiresAt).
Msg("Package bypassed by admin")
return false, "", nil
}
}
if packageBypassed(registry, bypassName, version, releaseKey, bypasses) {
return false, "", nil
}
// Get latest scan result.
@@ -596,10 +582,7 @@ 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
return m.missingScanDecision(registry, packageName, version)
}
// Real backend error (DB transient, etc.) — also block.
log.Warn().
@@ -613,17 +596,70 @@ func (m *Manager) CheckVulnerabilities(ctx context.Context, registry, packageNam
return true, "no scan available - fail closed", nil
}
infra, _ := result.Details[DetailInfrastructureError].(bool)
return m.evaluateScan(registry, packageName, version, releaseKey, bypasses, scanFacts{
status: result.Status,
infra: infra,
vulns: result.Vulnerabilities,
hasList: true,
})
}
// missingScanDecision is the verdict for a package flagged scanned that has no scan record.
func (m *Manager) missingScanDecision(registry, packageName, version string) (bool, string, error) {
if !m.config.FailClosed && m.isInflight(scanKey(registry, packageName, version)) {
return false, "", nil
}
return true, "no scan available - fail closed", nil
}
// packageBypassed reports whether an active admin bypass covers the whole package.
func packageBypassed(registry, bypassName, version, releaseKey string, bypasses []*metadata.CVEBypass) bool {
packageKey := fmt.Sprintf("%s/%s@%s", registry, bypassName, version)
packageKeyNoVersion := fmt.Sprintf("%s/%s", registry, bypassName)
for _, bypass := range bypasses {
if bypass.Type == metadata.BypassTypePackage && bypass.Active {
if bypass.Target == packageKey || bypass.Target == packageKeyNoVersion || (releaseKey != "" && bypass.Target == releaseKey) {
log.Info().
Str("package", packageKey).
Str("bypass_id", bypass.ID).
Str("reason", bypass.Reason).
Time("expires_at", bypass.ExpiresAt).
Msg("Package bypassed by admin")
return true
}
}
}
return false
}
// scanFacts is what the blocking policy needs to know about one scan.
type scanFacts struct {
counts map[string]int // per-severity counts, used when hasList is false
status metadata.ScanStatus
vulns []metadata.Vulnerability
total int // findings when the list is not loaded
infra bool // the scan failed on infrastructure, not on the package
hasList bool // vulns is the full list, so CVE bypasses can be applied
}
// evaluateScan applies bypasses and thresholds to one scan.
func (m *Manager) evaluateScan(registry, packageName, version, releaseKey string, bypasses []*metadata.CVEBypass, f scanFacts) (bool, string, error) {
// If the scan itself errored (all scanners failed for this package),
// 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 {
if f.status == metadata.ScanStatusError {
if f.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
}
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 {
@@ -637,22 +673,26 @@ func (m *Manager) CheckVulnerabilities(ctx context.Context, registry, packageNam
}
// Count vulnerabilities by severity, excluding bypassed CVEs
severityCounts := make(map[string]int)
remaining := 0
for _, vuln := range result.Vulnerabilities {
// Check if this CVE is bypassed
if bypass, ok := bypassedCVEs[strings.ToUpper(vuln.ID)]; ok {
log.Debug().
Str("cve", vuln.ID).
Str("package", packageName).
Str("bypass_id", bypass.ID).
Str("reason", bypass.Reason).
Time("expires_at", bypass.ExpiresAt).
Msg("CVE bypassed by admin")
continue
severityCounts := f.counts
remaining := f.total
if f.hasList {
severityCounts = make(map[string]int)
remaining = 0
for _, vuln := range f.vulns {
// Check if this CVE is bypassed
if bypass, ok := bypassedCVEs[strings.ToUpper(vuln.ID)]; ok {
log.Debug().
Str("cve", vuln.ID).
Str("package", packageName).
Str("bypass_id", bypass.ID).
Str("reason", bypass.Reason).
Time("expires_at", bypass.ExpiresAt).
Msg("CVE bypassed by admin")
continue
}
severityCounts[metadata.NormalizeSeverity(vuln.Severity)]++
remaining++
}
severityCounts[metadata.NormalizeSeverity(vuln.Severity)]++
remaining++
}
// Check against thresholds
@@ -712,6 +752,72 @@ func (m *Manager) CheckVulnerabilities(ctx context.Context, registry, packageNam
return false, "", nil
}
// ScanDecision pairs a package's latest scan with the blocking verdict.
type ScanDecision struct {
Summary *metadata.ScanSummary
Reason string
Blocked bool
}
// ScanDecisions judges scanned packages in a constant number of statements. A nil
// packageIDs judges every scanned package. The verdicts equal CheckVulnerabilities.
func (m *Manager) ScanDecisions(ctx context.Context, packageIDs []string) ([]ScanDecision, error) {
var bypasses []*metadata.CVEBypass
if m.enabled {
var err error
if bypasses, err = m.metadataStore.GetActiveCVEBypasses(ctx); err != nil {
log.Warn().Err(err).Msg("Failed to get CVE bypasses, continuing without bypasses")
bypasses = nil
}
}
// Per-CVE bypasses need the vulnerability ids; counts alone decide otherwise.
withList := false
for _, b := range bypasses {
if b.Type == metadata.BypassTypeCVE && b.Active {
withList = true
break
}
}
summaries, err := m.metadataStore.GetScanSummaries(ctx, packageIDs, withList)
if err != nil {
return nil, err
}
decisions := make([]ScanDecision, 0, len(summaries))
for _, sum := range summaries {
d := ScanDecision{Summary: sum}
if m.enabled {
d.Blocked, d.Reason = 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) {
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 !sum.HasScan {
blocked, reason, _ := m.missingScanDecision(sum.Registry, sum.Name, sum.Version)
return blocked, reason
}
infra, _ := sum.Details[DetailInfrastructureError].(bool)
facts := scanFacts{status: sum.Status, infra: infra, total: sum.Total, hasList: withList, vulns: sum.Vulnerabilities}
if !withList {
facts.counts = map[string]int{
"CRITICAL": sum.Critical, "HIGH": sum.High, "MODERATE": sum.Moderate, "LOW": sum.Low,
}
}
blocked, reason, _ := m.evaluateScan(sum.Registry, sum.Name, sum.Version, releaseKey, bypasses, facts)
return blocked, reason
}
// UpdateDatabases updates vulnerability databases for all scanners
func (m *Manager) UpdateDatabases(ctx context.Context) error {
if !m.enabled {
+9
View File
@@ -89,6 +89,15 @@ func (m *stubMetadataStore) DeletePackage(context.Context, string, string, strin
func (m *stubMetadataStore) ListPackages(context.Context, *metadata.ListOptions) ([]*metadata.Package, error) {
return nil, nil
}
func (m *stubMetadataStore) ListPackageGroups(context.Context, metadata.GroupListOptions) (*metadata.GroupPage, error) {
return nil, nil
}
func (m *stubMetadataStore) GetScanSummaries(context.Context, []string, bool) ([]*metadata.ScanSummary, error) {
return nil, nil
}
func (m *stubMetadataStore) GetRegistryStats(context.Context) ([]metadata.RegistryStat, error) {
return nil, nil
}
func (m *stubMetadataStore) UpdateDownloadCount(context.Context, string, string, string) error {
return nil
}