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")
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user