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:
2026-11-24 02:49:28 +00:00
parent e80489e55c
commit c685131865
14 changed files with 360 additions and 19 deletions
@@ -8,7 +8,8 @@ import { mountStrict } from '@/test/mountStrict'
vi.mock('axios')
const idle = { enabled: true, running: false, scope: '', queued: 0, done: 0, failed: 0 }
const running = { enabled: true, running: true, scope: 'vulnerable', queued: 10, done: 3, failed: 1 }
const running = { enabled: true, running: true, scope: 'vulnerable', queued: 10, done: 3, failed: 1, elapsed_seconds: 40, eta_seconds: 60 }
let estimate: unknown
const finished = { ...running, running: false, done: 9 }
let restore: (() => void) | undefined
@@ -17,11 +18,12 @@ let statuses: Array<typeof idle | typeof running>
beforeEach(() => {
localStorage.setItem('admin_api_key', 'test-key')
statuses = [idle]
estimate = { vulnerable: { artifacts: 12, seconds: 30 }, all: { artifacts: 1200, seconds: 6000 }, avg_scan_seconds: 10, concurrency: 2 }
vi.mocked(axios.get).mockReset()
vi.mocked(axios.post).mockReset()
vi.mocked(axios.get).mockImplementation(async (url: string) => {
if (url === '/api/admin/rescan/status') return { data: statuses.length > 1 ? statuses.shift() : statuses[0] } as never
if (url === '/api/stats') return { data: { stats: { total_packages: 1200 } } } as never
if (url === '/api/admin/rescan/estimate') return { data: estimate } as never
throw new Error(`unexpected request: ${url}`)
})
})
@@ -71,15 +73,30 @@ describe('RescanPanel', () => {
await flushPromises()
expect(vi.mocked(axios.post)).not.toHaveBeenCalled()
expect(body()).toContain('re-runs all scanners on every cached artifact')
// 1200 artifacts x 10 s / 2 in parallel = 6000 s = 100 minutes
expect(body()).toContain('1,200 artifacts')
expect(body()).toContain('roughly 100 minutes')
expect(body()).toContain('1,200 artifacts, 2 at a time and 10.0 seconds each on recent scans: roughly 100 minutes')
expect(vi.mocked(axios.get)).toHaveBeenCalledWith('/api/admin/rescan/estimate', { headers: { Authorization: 'Bearer test-key' } })
dialogButton('Rescan everything').click()
await flushPromises()
expect(vi.mocked(axios.post)).toHaveBeenCalledWith('/api/admin/rescan', { scope: 'all' }, expect.anything())
})
it('does not invent an estimate before any scan was timed', async () => {
estimate = { vulnerable: { artifacts: 1, seconds: null }, all: { artifacts: 7, seconds: null }, avg_scan_seconds: 0, concurrency: 2 }
const wrapper = await open()
await wrapper.get('[data-testid="rescan-all"]').trigger('click')
await flushPromises()
expect(body()).toContain('No scan has been timed yet, so there is no estimate.')
expect(body()).not.toContain('roughly')
})
it('shows the live rate and the time left while a rescan runs', async () => {
statuses = [running]
const wrapper = await open()
// 4 processed in 40 s is 6 a minute; the server says 60 s remain.
expect(wrapper.get('[data-testid="rescan-live"]').text()).toBe('6.0 artifacts a minute. About 1 minute left.')
})
it('polls until the rescan finishes and then stops', async () => {
vi.useFakeTimers({ shouldAdvanceTime: true })
vi.mocked(axios.post).mockResolvedValue({ data: { queued: 10, scope: 'vulnerable' } })
@@ -126,6 +143,15 @@ describe('RescanPanel', () => {
expect(body()).toContain('Enter your admin API key to start a rescan.')
})
it('asks for the admin key before it sizes a full rescan', async () => {
localStorage.clear()
const wrapper = await open()
await wrapper.get('[data-testid="rescan-all"]').trigger('click')
await flushPromises()
expect(vi.mocked(axios.get)).not.toHaveBeenCalledWith('/api/admin/rescan/estimate', expect.anything())
expect(body()).toContain('Enter your admin API key to start a rescan.')
})
it('forgets a key the server refuses', async () => {
vi.mocked(axios.post).mockRejectedValue({ response: { status: 403 } })
const wrapper = await open()
+44 -12
View File
@@ -21,6 +21,7 @@
{{ status.running ? 'Running.' : 'Finished.' }}
{{ formatNumber(status.done) }} scanned, {{ formatNumber(status.failed) }} failed, of {{ formatNumber(status.queued) }} queued.
</p>
<p v-if="status.running && liveRate" class="m-0 text-sm text-muted-foreground" data-testid="rescan-live">{{ liveRate }}</p>
</div>
</CardContent>
@@ -41,7 +42,7 @@ import axios from 'axios'
import { Button, Card, CardContent, CardDescription, CardHeader, CardTitle, ConfirmDialog, Progress, useToastStore } from '@perfect-design/ui'
import AdminKeyDialog from './AdminKeyDialog.vue'
import { useAdminKey } from '@/lib/adminKey'
import { formatDuration, formatNumber } from '@/lib/format'
import { formatApproxDuration, formatNumber } from '@/lib/format'
import { faRotateRight } from '@/lib/icons'
type Scope = 'vulnerable' | 'all'
@@ -54,13 +55,22 @@ interface RescanStatus {
queued: number
done: number
failed: number
elapsed_seconds?: number
/** Absent until the first artifact is processed. */
eta_seconds?: number
}
/** Response of GET /api/admin/rescan/estimate; seconds is null until a scan has been timed. */
interface RescanEstimate {
vulnerable: { artifacts: number; seconds: number | null }
all: { artifacts: number; seconds: number | null }
avg_scan_seconds: number
concurrency: number
}
const props = defineProps<{ enabled: boolean; concurrency: number }>()
const POLL_MS = 2000
// A guess: one scan of one artifact takes seconds, and the server does not report a measured rate.
const SECONDS_PER_ARTIFACT = 10
const adminKey = useAdminKey()
const toasts = useToastStore()
@@ -69,8 +79,9 @@ const status = ref<RescanStatus | null>(null)
const starting = ref<Scope | null>(null)
const confirmOpen = ref(false)
const showKeyDialog = ref(false)
const cachedArtifacts = ref<number | null>(null)
const estimate = ref<RescanEstimate | null>(null)
let pendingScope: Scope | null = null
let pendingConfirm = false
let timer: ReturnType<typeof setTimeout> | undefined
const running = computed(() => status.value?.running === true)
@@ -81,12 +92,23 @@ const note = computed(() => {
if (running.value) return 'A rescan is running. Another one can start when it finishes.'
return 'Needs the admin API key. The rescan runs in the background.'
})
const liveRate = computed(() => {
const st = status.value
const elapsed = st?.elapsed_seconds ?? 0
if (!st || processed.value === 0 || elapsed <= 0) return ''
const perMinute = (processed.value / elapsed) * 60
const rate = `${perMinute < 10 ? perMinute.toFixed(1) : formatNumber(Math.round(perMinute))} artifacts a minute`
return st.eta_seconds === undefined ? rate : `${rate}. About ${formatApproxDuration(st.eta_seconds)} left.`
})
const everythingWarning = computed(() => {
const base = 'This re-runs all scanners on every cached artifact.'
const count = cachedArtifacts.value
if (count === null) return `${base} It can take a long time and loads the scanners at ${props.concurrency} in parallel.`
const seconds = Math.max(60, Math.ceil(((count * SECONDS_PER_ARTIFACT) / Math.max(props.concurrency, 1)) / 60) * 60)
return `${base} For ${formatNumber(count)} artifacts, ${props.concurrency} at a time and about ${SECONDS_PER_ARTIFACT} seconds each, that takes roughly ${formatDuration(seconds)}.`
const est = estimate.value
const all = est?.all
if (!est || !all) return `${base} It can take a long time.`
const count = `${formatNumber(all.artifacts)} artifacts`
if (all.seconds === null) return `${base} ${count} are cached. No scan has been timed yet, so there is no estimate.`
const { avg_scan_seconds: avg, concurrency } = est
return `${base} ${count}, ${concurrency} at a time and ${avg.toFixed(1)} seconds each on recent scans: roughly ${formatApproxDuration(all.seconds)}.`
})
function errorStatus(err: unknown): number | undefined {
@@ -111,12 +133,17 @@ function schedulePoll() {
}
async function askAll() {
adminKey.load()
if (!adminKey.key.value) {
pendingConfirm = true
showKeyDialog.value = true
return
}
confirmOpen.value = true
try {
const res = await axios.get<{ stats?: { total_packages?: number } }>('/api/stats')
cachedArtifacts.value = res.data.stats?.total_packages ?? null
estimate.value = (await axios.get<RescanEstimate>('/api/admin/rescan/estimate', { headers: adminKey.headers.value })).data
} catch {
cachedArtifacts.value = null
estimate.value = null
}
}
@@ -152,7 +179,12 @@ async function start(scope: Scope) {
function resume() {
const scope = pendingScope
pendingScope = null
if (scope) void start(scope)
if (pendingConfirm) {
pendingConfirm = false
void askAll()
} else if (scope) {
void start(scope)
}
}
onMounted(async () => {
+16 -1
View File
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest'
import { formatDuration } from './format'
import { formatApproxDuration, formatDuration } from './format'
describe('formatDuration', () => {
it.each([
@@ -13,3 +13,18 @@ describe('formatDuration', () => {
expect(formatDuration(seconds)).toBe(expected)
})
})
describe('formatApproxDuration', () => {
it.each([
[0, '1 second'],
[40, '40 seconds'],
[59.4, '59 seconds'],
[60, '1 minute'],
[750, '13 minutes'],
[7199, '120 minutes'],
[7200, '2 hours'],
[36000, '10 hours'],
])('%d seconds reads %s', (seconds, expected) => {
expect(formatApproxDuration(seconds)).toBe(expected)
})
})
+7
View File
@@ -26,6 +26,13 @@ export function formatDuration(seconds: number): string {
return plural(Math.round(seconds / SECONDS_PER_MINUTE), 'minute')
}
/** A span in the largest fitting unit, rounded: "40 seconds", "12 minutes", "3 hours". */
export function formatApproxDuration(seconds: number): string {
if (seconds < SECONDS_PER_MINUTE) return plural(Math.max(1, Math.round(seconds)), 'second')
if (seconds < 2 * SECONDS_PER_HOUR) return plural(Math.round(seconds / SECONDS_PER_MINUTE), 'minute')
return plural(Math.round(seconds / SECONDS_PER_HOUR), 'hour')
}
export function formatDate(date: string): string {
if (!date) return 'N/A'
const parsed = new Date(date)
+1
View File
@@ -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)
+40
View File
@@ -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")
+73
View File
@@ -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")
}
+1
View File
@@ -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")
}
+11
View File
@@ -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
}
+7
View File
@@ -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 {
+38
View File
@@ -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,
+48 -1
View File
@@ -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 }
+2
View File
@@ -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 {