mirror of
https://github.com/lukaszraczylo/gohoarder.git
synced 2026-11-25 06:35:21 +00:00
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:
@@ -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 }
|
||||
|
||||
@@ -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";
|
||||
|
||||
+9
-1
@@ -56,6 +56,7 @@ type App struct {
|
||||
networkClient *network.Client
|
||||
scanManager *scanner.Manager
|
||||
rescanWorker *scanner.RescanWorker
|
||||
workerCtx context.Context
|
||||
analyticsEngine *analytics.Engine
|
||||
wsServer *websocket.Server
|
||||
prewarmWorker *prewarming.Worker
|
||||
@@ -323,7 +324,8 @@ func (a *App) initializeComponents() error {
|
||||
a.scanManager.SetFileSource(a.cache.ScanFile)
|
||||
|
||||
// Initialize rescan worker if enabled
|
||||
if a.config.Security.Enabled && a.config.Security.RescanInterval > 0 {
|
||||
// Built whenever scanning is on: an interval of 0 only turns off the periodic cycle, not admin rescans.
|
||||
if a.config.Security.Enabled {
|
||||
log.Info().Dur("interval", a.config.Security.RescanInterval).Msg("Initializing package rescan worker")
|
||||
a.rescanWorker = scanner.NewRescanWorker(a.scanManager, a.metadata, a.config.Security.RescanInterval,
|
||||
scanner.WithActiveWindow(a.config.Security.RescanActiveWindow),
|
||||
@@ -497,6 +499,10 @@ func (a *App) setupServer() error {
|
||||
a.app.Post("/api/admin/prewarming/trigger", a.requireAdmin, a.handlePrewarmingTrigger)
|
||||
a.app.Post("/api/admin/prewarming/package", a.requireAdmin, a.handlePrewarmingPackage)
|
||||
|
||||
// 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)
|
||||
|
||||
// Admin endpoints (API key management)
|
||||
a.app.Post("/api/admin/keys", a.requireAdmin, a.handleGenerateAPIKey)
|
||||
a.app.Get("/api/admin/keys", a.requireAdmin, a.handleListAPIKeys)
|
||||
@@ -625,6 +631,8 @@ func (a *App) setupServer() error {
|
||||
|
||||
// startWorkers starts the background loops that live as long as ctx.
|
||||
func (a *App) startWorkers(ctx context.Context) {
|
||||
a.workerCtx = ctx
|
||||
|
||||
// Without the event loop the broadcast channel fills after 256 events and websocket clients never register.
|
||||
a.wsServer.Start(ctx)
|
||||
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
type rescanRequest struct {
|
||||
Scope scanner.RescanScope `json:"scope"`
|
||||
}
|
||||
|
||||
// jobContext is the context of work that outlives a request: it ends with the server.
|
||||
func (a *App) jobContext() context.Context {
|
||||
if a.workerCtx != nil {
|
||||
return a.workerCtx
|
||||
}
|
||||
return context.Background()
|
||||
}
|
||||
|
||||
func rescanStatusBody(a *App) fiber.Map {
|
||||
body := fiber.Map{"enabled": a.rescanWorker != nil, "running": false, "scope": "", "queued": 0, "done": 0, "failed": 0}
|
||||
if a.rescanWorker == nil {
|
||||
return body
|
||||
}
|
||||
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
|
||||
if !st.StartedAt.IsZero() {
|
||||
body["started_at"] = st.StartedAt.UTC().Format(time.RFC3339)
|
||||
}
|
||||
if !st.FinishedAt.IsZero() {
|
||||
body["finished_at"] = st.FinishedAt.UTC().Format(time.RFC3339)
|
||||
}
|
||||
return body
|
||||
}
|
||||
|
||||
// handleRescanTrigger queues a rescan of cached artifacts and answers 202 with the queued count.
|
||||
func (a *App) handleRescanTrigger(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "application/json")
|
||||
|
||||
var req rescanRequest
|
||||
if err := c.Bind().Body(&req); err != nil || !req.Scope.Valid() {
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": `scope must be "vulnerable" or "all"`})
|
||||
}
|
||||
if a.rescanWorker == nil {
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": scanner.ErrRescanDisabled.Error()})
|
||||
}
|
||||
|
||||
queued, err := a.rescanWorker.RescanNow(a.jobContext(), req.Scope)
|
||||
switch {
|
||||
case errors.Is(err, scanner.ErrRescanRunning):
|
||||
return c.Status(fiber.StatusConflict).JSON(fiber.Map{"error": err.Error(), "status": rescanStatusBody(a)})
|
||||
case errors.Is(err, scanner.ErrRescanDisabled):
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": err.Error()})
|
||||
case err != nil:
|
||||
log.Error().Err(err).Msg("Failed to queue rescan")
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": "failed to queue rescan"})
|
||||
}
|
||||
|
||||
log.Info().Str("scope", string(req.Scope)).Int("queued", queued).Msg("Rescan queued via API")
|
||||
return c.Status(fiber.StatusAccepted).JSON(fiber.Map{"queued": queued, "scope": req.Scope})
|
||||
}
|
||||
|
||||
// handleRescanStatus reports the progress of the latest admin-triggered rescan.
|
||||
func (a *App) handleRescanStatus(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "application/json")
|
||||
return c.Status(fiber.StatusOK).JSON(rescanStatusBody(a))
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/config"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func rescanApp(t *testing.T) (*App, *fiber.App) {
|
||||
t.Helper()
|
||||
a := newTestApp(t, func(c *config.Config) {
|
||||
c.Security.Enabled = true
|
||||
c.Security.UpdateDBOnStartup = false
|
||||
c.Security.RescanInterval = 0
|
||||
disableAllScanners(c)
|
||||
})
|
||||
f := fiber.New()
|
||||
f.Post("/api/admin/rescan", a.handleRescanTrigger)
|
||||
f.Get("/api/admin/rescan/status", a.handleRescanStatus)
|
||||
return a, f
|
||||
}
|
||||
|
||||
func decodeBody(t *testing.T, resp *http.Response) map[string]any {
|
||||
t.Helper()
|
||||
var out map[string]any
|
||||
require.NoError(t, json.NewDecoder(resp.Body).Decode(&out))
|
||||
return out
|
||||
}
|
||||
|
||||
func postRescan(t *testing.T, f *fiber.App, body string) (int, map[string]any) {
|
||||
t.Helper()
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/admin/rescan", strings.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
resp, err := f.Test(req)
|
||||
require.NoError(t, err)
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
return resp.StatusCode, decodeBody(t, resp)
|
||||
}
|
||||
|
||||
func rescanStatus(t *testing.T, f *fiber.App) map[string]any {
|
||||
t.Helper()
|
||||
resp, err := f.Test(httptest.NewRequest(http.MethodGet, "/api/admin/rescan/status", nil))
|
||||
require.NoError(t, err)
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
require.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
return decodeBody(t, resp)
|
||||
}
|
||||
|
||||
func saveRescanPackage(t *testing.T, a *App, name, version string) {
|
||||
t.Helper()
|
||||
now := time.Now()
|
||||
require.NoError(t, a.metadata.SavePackage(context.Background(), &metadata.Package{
|
||||
Registry: "npm", Name: name, Version: version, StorageKey: "npm/" + name + "/" + version, Size: 1, CachedAt: now, LastAccessed: now,
|
||||
}))
|
||||
}
|
||||
|
||||
func TestRescanTriggerQueuesAndReportsProgress(t *testing.T) {
|
||||
a, f := rescanApp(t)
|
||||
saveRescanPackage(t, a, "left-pad", "1.3.0")
|
||||
saveRescanPackage(t, a, "left-pad", "metadata")
|
||||
|
||||
code, body := postRescan(t, f, `{"scope":"all"}`)
|
||||
require.Equal(t, http.StatusAccepted, code)
|
||||
require.EqualValues(t, 1, body["queued"], "the metadata row is not queued")
|
||||
require.Equal(t, "all", body["scope"])
|
||||
|
||||
require.Eventually(t, func() bool { return rescanStatus(t, f)["running"] == false }, 5*time.Second, 10*time.Millisecond)
|
||||
st := rescanStatus(t, f)
|
||||
require.EqualValues(t, 1, st["queued"])
|
||||
require.EqualValues(t, 1, st["done"].(float64)+st["failed"].(float64), "the one artifact is processed")
|
||||
require.NotEmpty(t, st["finished_at"])
|
||||
}
|
||||
|
||||
func TestRescanTriggerRefusesASecondRunWhileActive(t *testing.T) {
|
||||
a, f := rescanApp(t)
|
||||
saveRescanPackage(t, a, "left-pad", "1.3.0")
|
||||
release, entered := make(chan struct{}), make(chan struct{}, 1)
|
||||
a.scanManager.SetFileSource(func(context.Context, string, string, string) (string, func(), error) {
|
||||
select {
|
||||
case entered <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
<-release
|
||||
return "", func() {}, context.Canceled
|
||||
})
|
||||
|
||||
code, _ := postRescan(t, f, `{"scope":"all"}`)
|
||||
require.Equal(t, http.StatusAccepted, code)
|
||||
<-entered
|
||||
require.Equal(t, true, rescanStatus(t, f)["running"])
|
||||
|
||||
code, body := postRescan(t, f, `{"scope":"vulnerable"}`)
|
||||
require.Equal(t, http.StatusConflict, code)
|
||||
require.NotEmpty(t, body["error"])
|
||||
|
||||
close(release)
|
||||
require.Eventually(t, func() bool { return rescanStatus(t, f)["running"] == false }, 5*time.Second, 10*time.Millisecond)
|
||||
}
|
||||
|
||||
func TestRescanTriggerRejectsBadInput(t *testing.T) {
|
||||
_, f := rescanApp(t)
|
||||
for _, body := range []string{``, `{}`, `{"scope":"everything"}`, `not json`} {
|
||||
code, _ := postRescan(t, f, body)
|
||||
require.Equal(t, http.StatusBadRequest, code, body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRescanTriggerNeedsScanningOn(t *testing.T) {
|
||||
a := newTestApp(t, func(c *config.Config) { c.Security.Enabled = false })
|
||||
f := fiber.New()
|
||||
f.Post("/api/admin/rescan", a.handleRescanTrigger)
|
||||
f.Get("/api/admin/rescan/status", a.handleRescanStatus)
|
||||
|
||||
code, _ := postRescan(t, f, `{"scope":"all"}`)
|
||||
require.Equal(t, http.StatusBadRequest, code)
|
||||
require.Equal(t, false, rescanStatus(t, f)["enabled"])
|
||||
}
|
||||
|
||||
func TestRescanRoutesNeedAdmin(t *testing.T) {
|
||||
a, _ := rescanApp(t)
|
||||
for _, tc := range []struct{ method, path string }{
|
||||
{http.MethodPost, "/api/admin/rescan"},
|
||||
{http.MethodGet, "/api/admin/rescan/status"},
|
||||
} {
|
||||
req := httptest.NewRequest(tc.method, tc.path, strings.NewReader(`{"scope":"all"}`))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
resp, err := a.app.Test(req)
|
||||
require.NoError(t, err)
|
||||
_ = resp.Body.Close()
|
||||
require.Equal(t, http.StatusUnauthorized, resp.StatusCode, tc.path)
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,8 @@ package scanner
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
@@ -15,7 +17,9 @@ type RescanWorker struct {
|
||||
metadataStore metadata.MetadataStore
|
||||
manager *Manager
|
||||
stopCh chan struct{}
|
||||
run *forcedRun
|
||||
stopOnce sync.Once
|
||||
runMu sync.Mutex
|
||||
interval time.Duration
|
||||
activeWindow time.Duration
|
||||
concurrency int
|
||||
@@ -195,6 +199,11 @@ func (w *RescanWorker) rescanOne(ctx context.Context, pkg *metadata.Package, cou
|
||||
return
|
||||
}
|
||||
|
||||
w.scanOne(ctx, pkg, counts)
|
||||
}
|
||||
|
||||
// scanOne scans a package from its stored file without asking whether it is due.
|
||||
func (w *RescanWorker) scanOne(ctx context.Context, pkg *metadata.Package, counts *rescanCounts) {
|
||||
log.Info().
|
||||
Str("registry", pkg.Registry).
|
||||
Str("package", pkg.Name).
|
||||
@@ -281,3 +290,167 @@ func (w *RescanWorker) needsRescan(ctx context.Context, pkg *metadata.Package) (
|
||||
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// RescanScope selects the artifacts of a forced rescan.
|
||||
type RescanScope string
|
||||
|
||||
// Scopes of a forced rescan.
|
||||
const (
|
||||
// RescanVulnerable rescans artifacts whose latest scan holds findings.
|
||||
RescanVulnerable RescanScope = "vulnerable"
|
||||
// RescanAll rescans every cached artifact.
|
||||
RescanAll RescanScope = "all"
|
||||
)
|
||||
|
||||
// Valid reports whether s names a known scope.
|
||||
func (s RescanScope) Valid() bool { return s == RescanVulnerable || s == RescanAll }
|
||||
|
||||
// Errors of a forced rescan.
|
||||
var (
|
||||
ErrRescanRunning = errors.New("a rescan is already running")
|
||||
ErrRescanDisabled = errors.New("security scanning is disabled")
|
||||
)
|
||||
|
||||
// forcedRun is the state of one forced rescan; counts update while it runs.
|
||||
type forcedRun struct {
|
||||
started time.Time
|
||||
finished time.Time
|
||||
scope RescanScope
|
||||
counts rescanCounts
|
||||
queued int
|
||||
running bool
|
||||
}
|
||||
|
||||
// RescanStatus is a snapshot of the latest forced rescan.
|
||||
type RescanStatus struct {
|
||||
StartedAt time.Time
|
||||
FinishedAt time.Time
|
||||
Scope RescanScope
|
||||
Queued int64
|
||||
Done int64
|
||||
Failed int64
|
||||
Running bool
|
||||
}
|
||||
|
||||
// RescanNow queues a background rescan of the cached artifacts in scope, whatever the active
|
||||
// window or the age of their last scan, and returns how many it queued. ctx must outlive the caller.
|
||||
func (w *RescanWorker) RescanNow(ctx context.Context, scope RescanScope) (int, error) {
|
||||
if !w.manager.enabled {
|
||||
return 0, ErrRescanDisabled
|
||||
}
|
||||
run := &forcedRun{scope: scope, started: time.Now(), running: true}
|
||||
w.runMu.Lock()
|
||||
if w.run != nil && w.run.running {
|
||||
w.runMu.Unlock()
|
||||
return 0, ErrRescanRunning
|
||||
}
|
||||
w.run = run
|
||||
w.runMu.Unlock()
|
||||
|
||||
packages, err := w.forcedPackages(ctx, scope)
|
||||
if err != nil {
|
||||
w.finish(run)
|
||||
return 0, err
|
||||
}
|
||||
w.runMu.Lock()
|
||||
run.queued = len(packages)
|
||||
w.runMu.Unlock()
|
||||
if len(packages) == 0 {
|
||||
w.finish(run)
|
||||
return 0, nil
|
||||
}
|
||||
go w.runForced(ctx, run, packages)
|
||||
return len(packages), nil
|
||||
}
|
||||
|
||||
func (w *RescanWorker) finish(run *forcedRun) {
|
||||
w.runMu.Lock()
|
||||
run.running = false
|
||||
run.finished = time.Now()
|
||||
w.runMu.Unlock()
|
||||
}
|
||||
|
||||
func (w *RescanWorker) forcedPackages(ctx context.Context, scope RescanScope) ([]*metadata.Package, error) {
|
||||
all, err := w.metadataStore.ListPackages(ctx, &metadata.ListOptions{})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list packages for rescan: %w", err)
|
||||
}
|
||||
var vulnerable map[string]struct{}
|
||||
if scope == RescanVulnerable {
|
||||
summaries, err := w.metadataStore.GetScanSummaries(ctx, nil, false)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read scan summaries for rescan: %w", err)
|
||||
}
|
||||
vulnerable = make(map[string]struct{}, len(summaries))
|
||||
for _, sum := range summaries {
|
||||
if sum.Total > 0 {
|
||||
vulnerable[sum.PackageID] = struct{}{}
|
||||
}
|
||||
}
|
||||
}
|
||||
out := make([]*metadata.Package, 0, len(all))
|
||||
for _, pkg := range all {
|
||||
if metadata.IsMetadataEntry(pkg.Registry, pkg.Name, pkg.Version) {
|
||||
continue
|
||||
}
|
||||
if vulnerable != nil {
|
||||
if _, ok := vulnerable[pkg.ID]; !ok {
|
||||
continue
|
||||
}
|
||||
}
|
||||
out = append(out, pkg)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (w *RescanWorker) runForced(ctx context.Context, run *forcedRun, packages []*metadata.Package) {
|
||||
defer w.finish(run)
|
||||
jobs := make(chan *metadata.Package)
|
||||
var wg sync.WaitGroup
|
||||
for i := 0; i < w.concurrency; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for pkg := range jobs {
|
||||
w.scanOne(ctx, pkg, &run.counts)
|
||||
}
|
||||
}()
|
||||
}
|
||||
dispatch:
|
||||
for _, pkg := range packages {
|
||||
select {
|
||||
case jobs <- pkg:
|
||||
case <-ctx.Done():
|
||||
break dispatch
|
||||
case <-w.stopCh:
|
||||
break dispatch
|
||||
}
|
||||
}
|
||||
close(jobs)
|
||||
wg.Wait()
|
||||
log.Info().
|
||||
Str("scope", string(run.scope)).
|
||||
Int("queued", run.queued).
|
||||
Int64("scanned", run.counts.scanned.Load()).
|
||||
Int64("failed", run.counts.failed.Load()+run.counts.skipNoSource.Load()).
|
||||
Msg("Forced rescan completed")
|
||||
}
|
||||
|
||||
// Status reports the latest forced rescan; the zero value means none ran yet.
|
||||
func (w *RescanWorker) Status() RescanStatus {
|
||||
w.runMu.Lock()
|
||||
defer w.runMu.Unlock()
|
||||
run := w.run
|
||||
if run == nil {
|
||||
return RescanStatus{}
|
||||
}
|
||||
return RescanStatus{
|
||||
StartedAt: run.started,
|
||||
FinishedAt: run.finished,
|
||||
Scope: run.scope,
|
||||
Queued: int64(run.queued),
|
||||
Done: run.counts.scanned.Load(),
|
||||
Failed: run.counts.failed.Load() + run.counts.skipNoSource.Load(),
|
||||
Running: run.running,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,8 +14,9 @@ import (
|
||||
|
||||
// rescanStore serves a fixed package list and keeps saved scan results.
|
||||
type rescanStore struct {
|
||||
results map[string]*metadata.ScanResult
|
||||
packages []*metadata.Package
|
||||
results map[string]*metadata.ScanResult
|
||||
packages []*metadata.Package
|
||||
summaries []*metadata.ScanSummary
|
||||
stubMetadataStore
|
||||
rmu sync.Mutex
|
||||
}
|
||||
@@ -24,6 +25,10 @@ func (s *rescanStore) ListPackages(context.Context, *metadata.ListOptions) ([]*m
|
||||
return s.packages, nil
|
||||
}
|
||||
|
||||
func (s *rescanStore) GetScanSummaries(context.Context, []string, bool) ([]*metadata.ScanSummary, error) {
|
||||
return s.summaries, nil
|
||||
}
|
||||
|
||||
func (s *rescanStore) GetScanResult(_ context.Context, registry, name, version string) (*metadata.ScanResult, error) {
|
||||
s.rmu.Lock()
|
||||
defer s.rmu.Unlock()
|
||||
@@ -159,3 +164,102 @@ func TestRescanConcurrencyFloor(t *testing.T) {
|
||||
}
|
||||
assert.Equal(t, 1, NewRescanWorker(nil, nil, time.Hour).concurrency)
|
||||
}
|
||||
|
||||
// forcedFixture builds a worker over pkgs whose file source calls gate before each scan.
|
||||
func forcedFixture(t *testing.T, pkgs []*metadata.Package, summaries []*metadata.ScanSummary, gate func(), opts ...RescanOption) (*RescanWorker, *countingScanner) {
|
||||
t.Helper()
|
||||
store := &rescanStore{results: map[string]*metadata.ScanResult{}, packages: pkgs, summaries: summaries}
|
||||
mgr := newTestManager(t, store)
|
||||
cs := &countingScanner{calls: map[string]int{}}
|
||||
mgr.RegisterScanner(cs)
|
||||
mgr.SetFileSource(func(context.Context, string, string, string) (string, func(), error) {
|
||||
if gate != nil {
|
||||
gate()
|
||||
}
|
||||
return "/tmp/dummy", func() {}, nil
|
||||
})
|
||||
return NewRescanWorker(mgr, store, time.Hour, opts...), cs
|
||||
}
|
||||
|
||||
func waitIdle(t *testing.T, w *RescanWorker) RescanStatus {
|
||||
t.Helper()
|
||||
require.Eventually(t, func() bool { return !w.Status().Running }, 5*time.Second, 5*time.Millisecond)
|
||||
return w.Status()
|
||||
}
|
||||
|
||||
func TestRescanNowIgnoresActiveWindowAndFreshness(t *testing.T) {
|
||||
now := time.Now()
|
||||
pkgs := []*metadata.Package{
|
||||
pkgRow("npm", "cold", "1.0.0", now.Add(-90*24*time.Hour)),
|
||||
pkgRow("go", "example.com/m/@v/v1.0.0.zip", "v1.0.0", now),
|
||||
pkgRow("go", "example.com/m/@v/v1.0.0.mod", "v1.0.0", now),
|
||||
}
|
||||
w, cs := forcedFixture(t, pkgs, nil, nil, WithActiveWindow(time.Hour), WithConcurrency(2))
|
||||
// A fresh result would make the periodic cycle skip this package.
|
||||
w.metadataStore.(*rescanStore).results[scanKey("npm", "cold", "1.0.0")] = &metadata.ScanResult{ScannedAt: now}
|
||||
pkgs[0].SecurityScanned = true
|
||||
|
||||
queued, err := w.RescanNow(context.Background(), RescanAll)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, 2, queued)
|
||||
st := waitIdle(t, w)
|
||||
|
||||
assert.Equal(t, map[string]int{
|
||||
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.False(t, st.FinishedAt.IsZero())
|
||||
}
|
||||
|
||||
func TestRescanNowVulnerableScopeOnlyTakesPackagesWithFindings(t *testing.T) {
|
||||
now := time.Now()
|
||||
a, b, c := pkgRow("npm", "a", "1.0.0", now), pkgRow("npm", "b", "1.0.0", now), pkgRow("npm", "c", "1.0.0", now)
|
||||
a.ID, b.ID, c.ID = "id-a", "id-b", "id-c"
|
||||
summaries := []*metadata.ScanSummary{{PackageID: "id-a", Total: 3}, {PackageID: "id-b", Total: 0}}
|
||||
w, cs := forcedFixture(t, []*metadata.Package{a, b, c}, summaries, nil)
|
||||
|
||||
queued, err := w.RescanNow(context.Background(), RescanVulnerable)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, 1, queued)
|
||||
waitIdle(t, w)
|
||||
assert.Equal(t, map[string]int{scanKey("npm", "a", "1.0.0"): 1}, cs.snapshot())
|
||||
}
|
||||
|
||||
func TestRescanNowRefusesASecondRunWhileActive(t *testing.T) {
|
||||
release := make(chan struct{})
|
||||
entered := make(chan struct{}, 1)
|
||||
w, _ := forcedFixture(t, []*metadata.Package{pkgRow("npm", "a", "1.0.0", time.Now())}, nil, func() {
|
||||
select {
|
||||
case entered <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
<-release
|
||||
})
|
||||
|
||||
_, err := w.RescanNow(context.Background(), RescanAll)
|
||||
require.NoError(t, err)
|
||||
<-entered
|
||||
assert.True(t, w.Status().Running)
|
||||
_, err = w.RescanNow(context.Background(), RescanAll)
|
||||
assert.ErrorIs(t, err, ErrRescanRunning)
|
||||
|
||||
close(release)
|
||||
waitIdle(t, w)
|
||||
_, err = w.RescanNow(context.Background(), RescanAll)
|
||||
assert.NoError(t, err, "a finished run frees the slot")
|
||||
waitIdle(t, w)
|
||||
}
|
||||
|
||||
func TestRescanNowCountsFailures(t *testing.T) {
|
||||
pkgs := []*metadata.Package{pkgRow("npm", "ok", "1.0.0", time.Now()), pkgRow("npm", "nokey", "1.0.0", time.Now())}
|
||||
pkgs[1].StorageKey = ""
|
||||
w, _ := forcedFixture(t, pkgs, nil, nil)
|
||||
|
||||
_, err := w.RescanNow(context.Background(), RescanAll)
|
||||
require.NoError(t, err)
|
||||
st := waitIdle(t, w)
|
||||
assert.Equal(t, int64(2), st.Queued)
|
||||
assert.Equal(t, int64(1), st.Done)
|
||||
assert.Equal(t, int64(1), st.Failed)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user