feat(security): add an admin-triggered rescan

POST /api/admin/rescan queues a background rescan of the cached
artifacts with scope vulnerable or all. It ignores the active window and
the age of the last scan, runs on the server context and uses the rescan
worker concurrency. A second request while a run is active gets 409.
GET /api/admin/rescan/status reports queued, done, failed and running.
The System page gets a Rescan section with progress and a confirmation
for the full rescan.
This commit is contained in:
2026-11-24 02:38:24 +00:00
parent 3bfc367898
commit 9ff6de2414
10 changed files with 812 additions and 3 deletions
+3
View File
@@ -48,6 +48,8 @@
</Card>
</div>
<RescanPanel :enabled="info.security.enabled" :concurrency="info.security.rescan.concurrency" />
<Card>
<CardHeader>
<CardTitle as="h2">Inspectors</CardTitle>
@@ -130,6 +132,7 @@ import {
type DataTableColumn,
} from '@perfect-design/ui'
import AdminKeyDialog from './parts/AdminKeyDialog.vue'
import RescanPanel from './parts/RescanPanel.vue'
import { useAdminKey } from '@/lib/adminKey'
import { formatBytes, formatDuration } from '@/lib/format'
import { faRotateRight } from '@/lib/icons'
@@ -0,0 +1,136 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { createPinia, setActivePinia } from 'pinia'
import axios from 'axios'
import { flushPromises } from '@vue/test-utils'
import RescanPanel from './RescanPanel.vue'
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 finished = { ...running, running: false, done: 9 }
let restore: (() => void) | undefined
let statuses: Array<typeof idle | typeof running>
beforeEach(() => {
localStorage.setItem('admin_api_key', 'test-key')
statuses = [idle]
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
throw new Error(`unexpected request: ${url}`)
})
})
afterEach(() => {
restore?.()
restore = undefined
localStorage.clear()
vi.useRealTimers()
})
async function open(props = { enabled: true, concurrency: 2 }) {
const pinia = createPinia()
setActivePinia(pinia)
const mounted = await mountStrict(RescanPanel, { props, global: { plugins: [pinia] } })
restore = mounted.restore
await flushPromises()
return mounted.wrapper
}
const body = () => document.body.textContent ?? ''
function dialogButton(label: string): HTMLButtonElement {
const btn = [...document.body.querySelectorAll('[role="alertdialog"] button, [role="dialog"] button')].find((b) => b.textContent?.trim() === label)
if (!btn) throw new Error(`no button "${label}"`)
return btn as HTMLButtonElement
}
describe('RescanPanel', () => {
it('starts a vulnerable rescan with the admin key and shows progress', async () => {
vi.mocked(axios.post).mockResolvedValue({ data: { queued: 10, scope: 'vulnerable' } })
statuses = [idle, running]
const wrapper = await open()
await wrapper.get('[data-testid="rescan-vulnerable"]').trigger('click')
await flushPromises()
expect(vi.mocked(axios.post)).toHaveBeenCalledWith('/api/admin/rescan', { scope: 'vulnerable' }, { headers: { Authorization: 'Bearer test-key' } })
expect(wrapper.get('[data-testid="rescan-counts"]').text()).toContain('3 scanned, 1 failed, of 10 queued')
expect(wrapper.get('[data-testid="rescan-vulnerable"]').attributes('disabled')).toBeDefined()
expect(wrapper.get('[data-testid="rescan-note"]').text()).toContain('A rescan is running')
})
it('asks before rescanning everything and says how long it takes', async () => {
vi.mocked(axios.post).mockResolvedValue({ data: { queued: 1200, scope: 'all' } })
const wrapper = await open()
await wrapper.get('[data-testid="rescan-all"]').trigger('click')
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')
dialogButton('Rescan everything').click()
await flushPromises()
expect(vi.mocked(axios.post)).toHaveBeenCalledWith('/api/admin/rescan', { scope: 'all' }, expect.anything())
})
it('polls until the rescan finishes and then stops', async () => {
vi.useFakeTimers({ shouldAdvanceTime: true })
vi.mocked(axios.post).mockResolvedValue({ data: { queued: 10, scope: 'vulnerable' } })
statuses = [idle, running, running, finished]
const wrapper = await open()
await wrapper.get('[data-testid="rescan-vulnerable"]').trigger('click')
await flushPromises()
const statusCalls = () => vi.mocked(axios.get).mock.calls.filter(([url]) => url === '/api/admin/rescan/status').length
await vi.advanceTimersByTimeAsync(2100)
await vi.advanceTimersByTimeAsync(2100)
await flushPromises()
expect(wrapper.get('[data-testid="rescan-counts"]').text()).toContain('Finished.')
const settled = statusCalls()
await vi.advanceTimersByTimeAsync(10000)
expect(statusCalls()).toBe(settled)
})
it('shows the running rescan when the server answers 409', async () => {
vi.mocked(axios.post).mockRejectedValue({ response: { status: 409 } })
statuses = [idle, running]
const wrapper = await open()
await wrapper.get('[data-testid="rescan-vulnerable"]').trigger('click')
await flushPromises()
expect(wrapper.get('[data-testid="rescan-counts"]').text()).toContain('3 scanned')
})
it('is disabled and explains why when scanning is off', async () => {
const wrapper = await open({ enabled: false, concurrency: 2 })
expect(wrapper.get('[data-testid="rescan-vulnerable"]').attributes('disabled')).toBeDefined()
expect(wrapper.get('[data-testid="rescan-all"]').attributes('disabled')).toBeDefined()
expect(wrapper.get('[data-testid="rescan-note"]').text()).toContain('Security scanning is off')
expect(vi.mocked(axios.get)).not.toHaveBeenCalled()
})
it('asks for the admin key before it posts anything', async () => {
localStorage.clear()
const wrapper = await open()
await wrapper.get('[data-testid="rescan-vulnerable"]').trigger('click')
await flushPromises()
expect(vi.mocked(axios.post)).not.toHaveBeenCalled()
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()
await wrapper.get('[data-testid="rescan-vulnerable"]').trigger('click')
await flushPromises()
expect(localStorage.getItem('admin_api_key')).toBeNull()
})
})
@@ -0,0 +1,169 @@
<template>
<Card data-testid="rescan-panel">
<CardHeader>
<CardTitle as="h2">Rescan</CardTitle>
<CardDescription>Scan cached packages again now, without waiting for the interval. Stored findings are refreshed with the current scanners.</CardDescription>
</CardHeader>
<CardContent class="flex flex-col gap-4">
<div class="flex flex-col gap-2 sm:flex-row sm:items-center">
<Button :icon-start="faRotateRight" :loading="starting === 'vulnerable'" :disabled="blocked" data-testid="rescan-vulnerable" @click="start('vulnerable')">
Rescan vulnerable packages
</Button>
<Button variant="outline" :icon-start="faRotateRight" :loading="starting === 'all'" :disabled="blocked" data-testid="rescan-all" @click="askAll">
Rescan everything
</Button>
</div>
<p class="m-0 text-sm text-muted-foreground" data-testid="rescan-note">{{ note }}</p>
<div v-if="status && status.queued > 0" class="flex flex-col gap-2" data-testid="rescan-progress">
<Progress :model-value="processed" :max="status.queued" label="Rescan progress" show-value />
<p class="m-0 text-sm" data-testid="rescan-counts">
{{ status.running ? 'Running.' : 'Finished.' }}
{{ formatNumber(status.done) }} scanned, {{ formatNumber(status.failed) }} failed, of {{ formatNumber(status.queued) }} queued.
</p>
</div>
</CardContent>
<ConfirmDialog
v-model:open="confirmOpen"
title="Rescan every cached package?"
:description="everythingWarning"
confirm-label="Rescan everything"
@confirm="start('all')"
/>
<AdminKeyDialog v-model:open="showKeyDialog" description="Enter your admin API key to start a rescan." @saved="resume" />
</Card>
</template>
<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref } from 'vue'
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 { faRotateRight } from '@/lib/icons'
type Scope = 'vulnerable' | 'all'
/** Response of GET /api/admin/rescan/status. */
interface RescanStatus {
enabled: boolean
running: boolean
scope: string
queued: number
done: number
failed: 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()
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)
let pendingScope: Scope | null = null
let timer: ReturnType<typeof setTimeout> | undefined
const running = computed(() => status.value?.running === true)
const blocked = computed(() => !props.enabled || running.value || starting.value !== null)
const processed = computed(() => (status.value ? status.value.done + status.value.failed : 0))
const note = computed(() => {
if (!props.enabled) return 'Security scanning is off in the configuration.'
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 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)}.`
})
function errorStatus(err: unknown): number | undefined {
return (err as { response?: { status?: number } }).response?.status
}
async function refresh() {
const res = await axios.get<RescanStatus>('/api/admin/rescan/status', { headers: adminKey.headers.value })
status.value = res.data
return res.data
}
function schedulePoll() {
clearTimeout(timer)
timer = setTimeout(async () => {
try {
if ((await refresh()).running) schedulePoll()
} catch {
// The next click shows the error; a failed poll must not toast every two seconds.
}
}, POLL_MS)
}
async function askAll() {
confirmOpen.value = true
try {
const res = await axios.get<{ stats?: { total_packages?: number } }>('/api/stats')
cachedArtifacts.value = res.data.stats?.total_packages ?? null
} catch {
cachedArtifacts.value = null
}
}
async function start(scope: Scope) {
adminKey.load()
if (!adminKey.key.value) {
pendingScope = scope
showKeyDialog.value = true
return
}
starting.value = scope
try {
const res = await axios.post<{ queued: number }>('/api/admin/rescan', { scope }, { headers: adminKey.headers.value })
toasts.success('Rescan started', `${formatNumber(res.data.queued)} artifacts queued.`)
await refresh()
if (status.value?.running) schedulePoll()
} catch (err) {
const code = errorStatus(err)
if (code === 409) {
toasts.info('A rescan is already running', 'Wait for it to finish.')
await refresh().then(schedulePoll, () => undefined)
} else if (code === 401 || code === 403) {
adminKey.clear()
toasts.error('Admin key refused', 'Enter a key with the admin role.')
} else {
toasts.error('Could not start the rescan', err instanceof Error ? err.message : 'Request failed')
}
} finally {
starting.value = null
}
}
function resume() {
const scope = pendingScope
pendingScope = null
if (scope) void start(scope)
}
onMounted(async () => {
adminKey.load()
if (!props.enabled || !adminKey.key.value) return
try {
if ((await refresh()).running) schedulePoll()
} catch {
// Progress is optional here; a stale or missing key surfaces when the admin starts a rescan.
}
})
onUnmounted(() => clearTimeout(timer))
</script>
@@ -35,6 +35,7 @@ const API_KEY_STORAGE = 'admin_api_key'
function respond(url: string) {
if (url.startsWith('/api/system')) return { data: SYSTEM }
if (url.startsWith('/api/admin/rescan/status')) return { data: { enabled: true, running: false, scope: '', queued: 0, done: 0, failed: 0 } }
if (url.startsWith('/api/analytics/package/')) return { data: PACKAGE_ANALYTICS }
if (url.startsWith('/api/analytics/')) return { data: TOP_PACKAGES }
if (url.startsWith('/api/stats/timeseries')) return { data: TIMESERIES }
+1
View File
@@ -66,6 +66,7 @@
@source "../../node_modules/@perfect-design/ui/dist/components/primitives/Icon/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/primitives/IconButton/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/primitives/Link/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/primitives/Progress/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/primitives/ScrollArea/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/primitives/Spinner/*.js";
@source "../../node_modules/@perfect-design/ui/dist/components/primitives/StatusBadge/*.js";