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)