mirror of
https://github.com/lukaszraczylo/gohoarder.git
synced 2026-11-26 06:37:07 +00:00
feat(security): size the rescan from measured scan times
The confirmation for a full rescan used a fixed guess of 10 seconds per artifact. Scans now record their wall time in scan_results. The new GET /api/admin/rescan/estimate returns the artifact count of each scope and the time at the configured concurrency, from the average of recent scans. While a rescan runs, the status reports elapsed time and an ETA, and the panel shows the live rate.
This commit is contained in:
@@ -502,6 +502,7 @@ func (a *App) setupServer() error {
|
||||
// Admin endpoints (forced rescan)
|
||||
a.app.Post("/api/admin/rescan", a.requireAdmin, a.handleRescanTrigger)
|
||||
a.app.Get("/api/admin/rescan/status", a.requireAdmin, a.handleRescanStatus)
|
||||
a.app.Get("/api/admin/rescan/estimate", a.requireAdmin, a.handleRescanEstimate)
|
||||
|
||||
// Admin endpoints (API key management)
|
||||
a.app.Post("/api/admin/keys", a.requireAdmin, a.handleGenerateAPIKey)
|
||||
|
||||
@@ -3,6 +3,7 @@ package app
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"math"
|
||||
"time"
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
@@ -30,6 +31,11 @@ func rescanStatusBody(a *App) fiber.Map {
|
||||
st := a.rescanWorker.Status()
|
||||
body["running"], body["scope"] = st.Running, string(st.Scope)
|
||||
body["queued"], body["done"], body["failed"] = st.Queued, st.Done, st.Failed
|
||||
body["elapsed_seconds"] = int64(st.Elapsed.Seconds())
|
||||
// The rate so far predicts the rest; nothing is known before the first artifact finishes.
|
||||
if processed := st.Done + st.Failed; st.Running && processed > 0 {
|
||||
body["eta_seconds"] = int64(st.Elapsed.Seconds() * float64(st.Queued-processed) / float64(processed))
|
||||
}
|
||||
if !st.StartedAt.IsZero() {
|
||||
body["started_at"] = st.StartedAt.UTC().Format(time.RFC3339)
|
||||
}
|
||||
@@ -66,6 +72,40 @@ func (a *App) handleRescanTrigger(c fiber.Ctx) error {
|
||||
return c.Status(fiber.StatusAccepted).JSON(fiber.Map{"queued": queued, "scope": req.Scope})
|
||||
}
|
||||
|
||||
type rescanScopeEstimate struct {
|
||||
// Seconds is null until the store has recorded a scan duration.
|
||||
Seconds *int64 `json:"seconds"`
|
||||
Artifacts int `json:"artifacts"`
|
||||
}
|
||||
|
||||
// handleRescanEstimate sizes each scope from the artifact counts, the average of recent scan
|
||||
// durations and the configured concurrency.
|
||||
func (a *App) handleRescanEstimate(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "application/json")
|
||||
if a.rescanWorker == nil {
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": scanner.ErrRescanDisabled.Error()})
|
||||
}
|
||||
est, err := a.rescanWorker.Estimate(a.jobContext())
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Failed to estimate rescan")
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": "failed to estimate rescan"})
|
||||
}
|
||||
sized := func(artifacts int) rescanScopeEstimate {
|
||||
out := rescanScopeEstimate{Artifacts: artifacts}
|
||||
if est.AvgScan > 0 {
|
||||
secs := int64(math.Ceil(est.AvgScan.Seconds() * float64(artifacts) / float64(max(est.Concurrency, 1))))
|
||||
out.Seconds = &secs
|
||||
}
|
||||
return out
|
||||
}
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"vulnerable": sized(est.Vulnerable),
|
||||
"all": sized(est.All),
|
||||
"avg_scan_seconds": est.AvgScan.Seconds(),
|
||||
"concurrency": est.Concurrency,
|
||||
})
|
||||
}
|
||||
|
||||
// handleRescanStatus reports the progress of the latest admin-triggered rescan.
|
||||
func (a *App) handleRescanStatus(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "application/json")
|
||||
|
||||
@@ -139,3 +139,76 @@ func TestRescanRoutesNeedAdmin(t *testing.T) {
|
||||
require.Equal(t, http.StatusUnauthorized, resp.StatusCode, tc.path)
|
||||
}
|
||||
}
|
||||
|
||||
type fixedScanner struct{}
|
||||
|
||||
func (fixedScanner) Name() string { return "fixed" }
|
||||
func (fixedScanner) Scan(_ context.Context, registry, name, version, _ string) (*metadata.ScanResult, error) {
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
return &metadata.ScanResult{Registry: registry, PackageName: name, PackageVersion: version, Scanner: "fixed", ScannedAt: time.Now(), Status: metadata.ScanStatusClean}, nil
|
||||
}
|
||||
func (fixedScanner) Health(context.Context) error { return nil }
|
||||
|
||||
func getRescan(t *testing.T, f *fiber.App, path string) map[string]any {
|
||||
t.Helper()
|
||||
resp, err := f.Test(httptest.NewRequest(http.MethodGet, path, nil))
|
||||
require.NoError(t, err)
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
require.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
return decodeBody(t, resp)
|
||||
}
|
||||
|
||||
func TestRescanEstimateUsesMeasuredScanTimeAndConcurrency(t *testing.T) {
|
||||
a, f := rescanApp(t)
|
||||
f.Get("/api/admin/rescan/estimate", a.handleRescanEstimate)
|
||||
a.scanManager.RegisterScanner(fixedScanner{})
|
||||
a.scanManager.SetFileSource(func(context.Context, string, string, string) (string, func(), error) {
|
||||
return "/tmp/dummy", func() {}, nil
|
||||
})
|
||||
for _, v := range []string{"1.0.0", "1.1.0", "1.2.0", "1.3.0"} {
|
||||
saveRescanPackage(t, a, "left-pad", v)
|
||||
}
|
||||
|
||||
before := getRescan(t, f, "/api/admin/rescan/estimate")
|
||||
require.EqualValues(t, 4, jsonAt(before, "all", "artifacts"))
|
||||
require.Nil(t, jsonAt(before, "all", "seconds"), "no scan was timed yet")
|
||||
|
||||
code, _ := postRescan(t, f, `{"scope":"all"}`)
|
||||
require.Equal(t, http.StatusAccepted, code)
|
||||
require.Eventually(t, func() bool { return rescanStatus(t, f)["running"] == false }, 10*time.Second, 10*time.Millisecond)
|
||||
|
||||
after := getRescan(t, f, "/api/admin/rescan/estimate")
|
||||
avg := after["avg_scan_seconds"].(float64)
|
||||
require.Greater(t, avg, 0.019, "the 20 ms scanner was measured")
|
||||
concurrency := after["concurrency"].(float64)
|
||||
require.EqualValues(t, 4, jsonAt(after, "all", "artifacts"))
|
||||
require.InDelta(t, avg*4/concurrency, jsonAt(after, "all", "seconds"), 1, "ceil of artifacts x average / concurrency")
|
||||
require.EqualValues(t, 0, jsonAt(after, "vulnerable", "artifacts"))
|
||||
}
|
||||
|
||||
func TestRescanStatusReportsEtaWhileRunning(t *testing.T) {
|
||||
a, f := rescanApp(t)
|
||||
a.scanManager.RegisterScanner(fixedScanner{})
|
||||
saveRescanPackage(t, a, "a", "1.0.0")
|
||||
saveRescanPackage(t, a, "b", "1.0.0")
|
||||
release, calls := make(chan struct{}), make(chan struct{}, 2)
|
||||
a.scanManager.SetFileSource(func(context.Context, string, string, string) (string, func(), error) {
|
||||
calls <- struct{}{}
|
||||
if len(calls) > 1 {
|
||||
<-release
|
||||
}
|
||||
return "/tmp/dummy", func() {}, nil
|
||||
})
|
||||
|
||||
code, _ := postRescan(t, f, `{"scope":"all"}`)
|
||||
require.Equal(t, http.StatusAccepted, code)
|
||||
require.Eventually(t, func() bool { return len(calls) == 2 && rescanStatus(t, f)["done"].(float64) == 1 }, 5*time.Second, 5*time.Millisecond)
|
||||
|
||||
st := rescanStatus(t, f)
|
||||
require.Equal(t, true, st["running"])
|
||||
require.Contains(t, st, "eta_seconds", "one of two is done, so the rate predicts the rest")
|
||||
require.Contains(t, st, "elapsed_seconds")
|
||||
close(release)
|
||||
require.Eventually(t, func() bool { return rescanStatus(t, f)["running"] == false }, 5*time.Second, 10*time.Millisecond)
|
||||
require.NotContains(t, rescanStatus(t, f), "eta_seconds")
|
||||
}
|
||||
|
||||
@@ -913,6 +913,7 @@ func (s *GORMStoreV2) SaveScanResult(ctx context.Context, result *metadata.ScanR
|
||||
HighCount: highCount,
|
||||
MediumCount: mediumCount,
|
||||
LowCount: lowCount,
|
||||
ScanDuration: result.DurationMs,
|
||||
Details: JSONBField(details),
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
package gormstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func saveScan(t *testing.T, store *GORMStoreV2, name string, at time.Time, ms int) {
|
||||
t.Helper()
|
||||
trendingPackage(t, store, "npm", name, "1.0.0")
|
||||
require.NoError(t, store.SaveScanResult(context.Background(), &metadata.ScanResult{
|
||||
Registry: "npm", PackageName: name, PackageVersion: "1.0.0", Scanner: "test",
|
||||
ScannedAt: at, Status: metadata.ScanStatusClean, DurationMs: ms,
|
||||
}))
|
||||
}
|
||||
|
||||
func TestAverageScanDurationUsesTheLatestRecordedScans(t *testing.T) {
|
||||
store := trendingStore(t)
|
||||
ctx := context.Background()
|
||||
|
||||
avg, err := store.AverageScanDuration(ctx, 10)
|
||||
require.NoError(t, err)
|
||||
require.Zero(t, avg, "no scans yet")
|
||||
|
||||
saveScan(t, store, "old", trendingNow.Add(-3*time.Hour), 9000)
|
||||
saveScan(t, store, "a", trendingNow.Add(-2*time.Hour), 1000)
|
||||
saveScan(t, store, "b", trendingNow.Add(-time.Hour), 3000)
|
||||
saveScan(t, store, "unrecorded", trendingNow, 0)
|
||||
|
||||
avg, err = store.AverageScanDuration(ctx, 2)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 2*time.Second, avg, "the two latest recorded scans, the zero ignored")
|
||||
|
||||
avg, err = store.AverageScanDuration(ctx, 10)
|
||||
require.NoError(t, err)
|
||||
require.InDelta(t, float64(13000)/3, float64(avg.Milliseconds()), 1, "mean of 9000, 1000 and 3000")
|
||||
}
|
||||
@@ -136,3 +136,14 @@ func (s *GORMStoreV2) packageDownloads(ctx context.Context, table, sum, cond str
|
||||
}
|
||||
return rows, nil
|
||||
}
|
||||
|
||||
// AverageScanDuration averages the latest sample scans that recorded a duration.
|
||||
func (s *GORMStoreV2) AverageScanDuration(ctx context.Context, sample int) (time.Duration, error) {
|
||||
recent := s.db.WithContext(ctx).Model(&ScanResultModel{}).
|
||||
Select("scan_duration").Where("scan_duration > 0").Order("scanned_at DESC").Limit(sample)
|
||||
var avgMs float64
|
||||
if err := s.db.WithContext(ctx).Table("(?) AS r", recent).Select("COALESCE(AVG(scan_duration), 0)").Scan(&avgMs).Error; err != nil {
|
||||
return 0, errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to average scan durations")
|
||||
}
|
||||
return time.Duration(avgMs * float64(time.Millisecond)), nil
|
||||
}
|
||||
|
||||
@@ -211,6 +211,7 @@ type ScanResult struct {
|
||||
Status ScanStatus `json:"status"`
|
||||
Vulnerabilities []Vulnerability `json:"vulnerabilities"`
|
||||
VulnerabilityCount int `json:"vulnerability_count"`
|
||||
DurationMs int `json:"duration_ms"` // wall time of the scan that produced it
|
||||
}
|
||||
|
||||
// Vulnerability represents a security vulnerability
|
||||
@@ -452,6 +453,12 @@ type TrendingPackage struct {
|
||||
Previous int64 `json:"previous"`
|
||||
}
|
||||
|
||||
// ScanDurationSource reports how long recent scans took, for backends that keep it.
|
||||
type ScanDurationSource interface {
|
||||
// AverageScanDuration averages the latest sample scans that recorded a duration; zero means none did.
|
||||
AverageScanDuration(ctx context.Context, sample int) (time.Duration, error)
|
||||
}
|
||||
|
||||
// TrendingSource ranks packages from persisted download history. Backends without
|
||||
// persisted downloads do not implement it.
|
||||
type TrendingSource interface {
|
||||
|
||||
@@ -329,6 +329,7 @@ type RescanStatus struct {
|
||||
Queued int64
|
||||
Done int64
|
||||
Failed int64
|
||||
Elapsed time.Duration
|
||||
Running bool
|
||||
}
|
||||
|
||||
@@ -436,6 +437,38 @@ dispatch:
|
||||
Msg("Forced rescan completed")
|
||||
}
|
||||
|
||||
// scanDurationSample is how many recent scans the estimate averages.
|
||||
const scanDurationSample = 200
|
||||
|
||||
// RescanEstimate sizes a forced rescan before it starts.
|
||||
type RescanEstimate struct {
|
||||
// AvgScan is the mean wall time of recent scans; zero when none was recorded.
|
||||
AvgScan time.Duration
|
||||
Vulnerable int
|
||||
All int
|
||||
Concurrency int
|
||||
}
|
||||
|
||||
// Estimate counts the artifacts each scope would queue and averages recent scan durations.
|
||||
func (w *RescanWorker) Estimate(ctx context.Context) (RescanEstimate, error) {
|
||||
est := RescanEstimate{Concurrency: w.concurrency}
|
||||
all, err := w.forcedPackages(ctx, RescanAll)
|
||||
if err != nil {
|
||||
return est, err
|
||||
}
|
||||
vulnerable, err := w.forcedPackages(ctx, RescanVulnerable)
|
||||
if err != nil {
|
||||
return est, err
|
||||
}
|
||||
est.All, est.Vulnerable = len(all), len(vulnerable)
|
||||
if src, ok := w.metadataStore.(metadata.ScanDurationSource); ok {
|
||||
if est.AvgScan, err = src.AverageScanDuration(ctx, scanDurationSample); err != nil {
|
||||
return est, fmt.Errorf("average scan duration: %w", err)
|
||||
}
|
||||
}
|
||||
return est, nil
|
||||
}
|
||||
|
||||
// Status reports the latest forced rescan; the zero value means none ran yet.
|
||||
func (w *RescanWorker) Status() RescanStatus {
|
||||
w.runMu.Lock()
|
||||
@@ -444,7 +477,12 @@ func (w *RescanWorker) Status() RescanStatus {
|
||||
if run == nil {
|
||||
return RescanStatus{}
|
||||
}
|
||||
elapsed := run.finished.Sub(run.started)
|
||||
if run.running {
|
||||
elapsed = time.Since(run.started)
|
||||
}
|
||||
return RescanStatus{
|
||||
Elapsed: elapsed,
|
||||
StartedAt: run.started,
|
||||
FinishedAt: run.finished,
|
||||
Scope: run.scope,
|
||||
|
||||
@@ -208,7 +208,7 @@ func TestRescanNowIgnoresActiveWindowAndFreshness(t *testing.T) {
|
||||
scanKey("npm", "cold", "1.0.0"): 1,
|
||||
scanKey("go", "example.com/m/@v/v1.0.0.zip", "v1.0.0"): 1,
|
||||
}, cs.snapshot())
|
||||
assert.Equal(t, RescanStatus{StartedAt: st.StartedAt, FinishedAt: st.FinishedAt, Scope: RescanAll, Queued: 2, Done: 2}, st)
|
||||
assert.Equal(t, RescanStatus{StartedAt: st.StartedAt, FinishedAt: st.FinishedAt, Elapsed: st.FinishedAt.Sub(st.StartedAt), Scope: RescanAll, Queued: 2, Done: 2}, st)
|
||||
assert.False(t, st.FinishedAt.IsZero())
|
||||
}
|
||||
|
||||
@@ -263,3 +263,50 @@ func TestRescanNowCountsFailures(t *testing.T) {
|
||||
assert.Equal(t, int64(1), st.Done)
|
||||
assert.Equal(t, int64(1), st.Failed)
|
||||
}
|
||||
|
||||
// durationStore adds the recorded-duration average a gorm store provides.
|
||||
type durationStore struct {
|
||||
*rescanStore
|
||||
avg time.Duration
|
||||
}
|
||||
|
||||
func (d durationStore) AverageScanDuration(context.Context, int) (time.Duration, error) {
|
||||
return d.avg, nil
|
||||
}
|
||||
|
||||
func TestEstimateCountsScopesAndAveragesRecordedScans(t *testing.T) {
|
||||
now := time.Now()
|
||||
a, b := pkgRow("npm", "a", "1.0.0", now), pkgRow("npm", "b", "1.0.0", now)
|
||||
a.ID, b.ID = "id-a", "id-b"
|
||||
meta := pkgRow("npm", "a", "list", now)
|
||||
store := &rescanStore{
|
||||
results: map[string]*metadata.ScanResult{}, packages: []*metadata.Package{a, b, meta},
|
||||
summaries: []*metadata.ScanSummary{{PackageID: "id-a", Total: 1}},
|
||||
}
|
||||
mgr := newTestManager(t, store)
|
||||
w := NewRescanWorker(mgr, durationStore{store, 1500 * time.Millisecond}, time.Hour, WithConcurrency(3))
|
||||
|
||||
est, err := w.Estimate(context.Background())
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, RescanEstimate{AvgScan: 1500 * time.Millisecond, Vulnerable: 1, All: 2, Concurrency: 3}, est)
|
||||
}
|
||||
|
||||
func TestScanRecordsItsDuration(t *testing.T) {
|
||||
store := &rescanStore{results: map[string]*metadata.ScanResult{}}
|
||||
mgr := newTestManager(t, store)
|
||||
mgr.RegisterScanner(&slowScanner{delay: 30 * time.Millisecond})
|
||||
|
||||
require.NoError(t, mgr.ScanPackage(context.Background(), "npm", "a", "1.0.0", "/tmp/dummy"))
|
||||
saved := store.results[scanKey("npm", "a", "1.0.0")]
|
||||
require.NotNil(t, saved)
|
||||
assert.GreaterOrEqual(t, saved.DurationMs, 30)
|
||||
}
|
||||
|
||||
type slowScanner struct{ delay time.Duration }
|
||||
|
||||
func (s *slowScanner) Name() string { return "slow" }
|
||||
func (s *slowScanner) Scan(_ context.Context, registry, name, version, _ string) (*metadata.ScanResult, error) {
|
||||
time.Sleep(s.delay)
|
||||
return &metadata.ScanResult{Registry: registry, PackageName: name, PackageVersion: version, Scanner: "slow", ScannedAt: time.Now(), Status: metadata.ScanStatusClean}, nil
|
||||
}
|
||||
func (s *slowScanner) Health(context.Context) error { return nil }
|
||||
|
||||
@@ -309,6 +309,7 @@ func (m *Manager) scan(ctx context.Context, registry, packageName, version strin
|
||||
key := scanKey(registry, packageName, version)
|
||||
m.markInflight(key, 1)
|
||||
defer m.markInflight(key, -1)
|
||||
started := time.Now()
|
||||
|
||||
log.Info().
|
||||
Str("registry", registry).
|
||||
@@ -429,6 +430,7 @@ func (m *Manager) scan(ctx context.Context, registry, packageName, version strin
|
||||
mergedResult := m.mergeResults(scanResults, scannerNames)
|
||||
// The store finds the package by its cache version, not the release version.
|
||||
mergedResult.PackageVersion = version
|
||||
mergedResult.DurationMs = int(time.Since(started).Milliseconds())
|
||||
|
||||
// Save consolidated result to metadata store
|
||||
if err := m.metadataStore.SaveScanResult(ctx, mergedResult); err != nil {
|
||||
|
||||
Reference in New Issue
Block a user