Compare commits

..
12 Commits
Author SHA1 Message Date
github-actions[bot]andGitHub 1432c7176b chore(deps): update dependencies
Automated dependency update. All tests passed.
2026-11-27 03:16:49 +00:00
github-actions[bot]andGitHub 426225bd14 chore(deps): update module github.com/valyala/fasthttp to v1.80.0
Automated dependency update. All tests passed.
2026-11-26 03:16:45 +00:00
github-actions[bot]andGitHub 518d836c7b chore(deps): update dependency @testing-library/jest-dom to v8
Automated dependency update. All tests passed.
2026-11-24 03:18:45 +00:00
lukaszraczylo 1e99b53d51 fix(auth): accept the bootstrap admin key on the boot that creates it
The server loaded the API key cache before it created the admin key
from GOHOARDER_BOOTSTRAP_ADMIN_KEY. The new key was therefore refused
until the next restart. Bootstrap now runs before the cache loads.
2026-11-24 02:55:37 +00:00
lukaszraczylo 9c0420161e fix(metadata): leave Go metadata files out of the registry stats
GetRegistryStats counted Go .mod and .info rows while GetStats and the
package rows left them out. The overview registry table therefore
showed more Go packages than the totals. Both stores now use the
artifact filter.
2026-11-24 02:51:18 +00:00
lukaszraczylo c685131865 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.
2026-11-24 02:49:28 +00:00
lukaszraczylo e80489e55c fix(analytics): make the trending windows contiguous
Hourly rows are kept for 7 days, so the previous week came from daily
rollups that ended at a day boundary. Downloads between that boundary and
the start of the recent week counted in neither. The boundary day is now
its rollup minus the hourly rows after the boundary.
2026-11-24 02:44:09 +00:00
lukaszraczylo 5f4bdbed80 fix(metadata): treat .mod and .info names as metadata for Go only
GetStats, the package list and the stats snapshots dropped any registry's
names that end in .mod or .info. An npm or PyPI package with such a name
vanished from the counts. The filter now matches IsMetadataEntry.
2026-11-24 02:43:17 +00:00
lukaszraczylo 1b00236749 test(gormstore): stop the background aggregator in time-series stores
Rollup tests set the worker clock while the background aggregation loop
read it, so the race detector failed about one run in ten. These stores
now stop the loop, and the tests drive aggregation by hand.
2026-11-24 02:42:11 +00:00
lukaszraczylo 9ff6de2414 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.
2026-11-24 02:38:24 +00:00
lukaszraczylo 3bfc367898 feat(analytics): serve trending packages from persisted downloads
Trending read the in-memory analytics engine, which restarts empty. The
endpoint now ranks packages by the last 7 days of stored downloads and
reports the previous 7 days for the change. It counts a Go module once
and skips metadata entries. A daily time_bucket index serves the range
read. The Overview panel shows the change and no longer says the data
resets on restart.
2026-11-24 02:33:21 +00:00
lukaszraczylo 6715cefd25 fix(packages): list only cache artifacts in the package rows
The rows layout listed Go .mod and .info files. They are never scanned,
so they showed as pending and made the page total larger than /api/stats.
The group query now applies the same artifact filter as GetStats.
2026-11-24 02:32:58 +00:00
38 changed files with 1816 additions and 65 deletions
+2 -2
View File
@@ -15,7 +15,7 @@
"@fontsource/ibm-plex-mono": "5.3.0",
"@fontsource/ibm-plex-sans": "5.3.0",
"@fortawesome/free-solid-svg-icons": "7.3.1",
"@perfect-design/ui": "0.3.10",
"@perfect-design/ui": "0.3.11",
"axios": "^1.20.0",
"pinia": "^4.0.0",
"vue": "^3.5.26",
@@ -23,7 +23,7 @@
},
"devDependencies": {
"@tailwindcss/vite": "^4.3.3",
"@testing-library/jest-dom": "^7.0.0",
"@testing-library/jest-dom": "^8.0.0",
"@testing-library/vue": "^8.1.0",
"@vitejs/plugin-vue": "^6.0.3",
"@vue/test-utils": "^2.4.6",
+12 -12
View File
@@ -23,8 +23,8 @@ importers:
specifier: 7.3.1
version: 7.3.1
'@perfect-design/ui':
specifier: 0.3.10
version: 0.3.10([email protected](@vue/[email protected])([email protected])([email protected]([email protected])))([email protected])([email protected]([email protected]))
specifier: 0.3.11
version: 0.3.11([email protected](@vue/[email protected])([email protected])([email protected]([email protected])))([email protected])([email protected]([email protected]))
axios:
specifier: ^1.20.0
version: 1.21.1([email protected]([email protected]))([email protected])
@@ -42,8 +42,8 @@ importers:
specifier: ^4.3.3
version: 4.3.5([email protected]([email protected])([email protected]))
'@testing-library/jest-dom':
specifier: ^7.0.0
version: 7.0.1(@testing-library/[email protected])([email protected]([email protected])([email protected]([email protected])([email protected])))
specifier: ^8.0.0
version: 8.0.0(@testing-library/[email protected])([email protected]([email protected])([email protected]([email protected])([email protected])))
'@testing-library/vue':
specifier: ^8.1.0
version: 8.1.0(@vue/[email protected])(@vue/[email protected])(@vue/[email protected])([email protected]([email protected]))
@@ -353,8 +353,8 @@ packages:
'@oxc-project/[email protected]':
resolution: {integrity: sha512-1Duyg48TdJNdyhEB8Xn1L36bT9Pv6GUtlKjHxOys8xkaF/rQq3XJE+bAurSK/AgIz5mGFsb77cn9Pb20+WCScw==}
'@perfect-design/[email protected]0':
resolution: {integrity: sha512-nFpY8dK6braHsRPVdX3bUCrkPNfwiUj2KfvUfLdFRFlfBRaqrkNGx2QkmNu/L0rdNe6JQj6Mvdrb+LnC/sFg8Q==}
'@perfect-design/[email protected]1':
resolution: {integrity: sha512-vu7liBjd6ZndJWio3gt1EHmOVi1VAcPQ/v+8xQRLvrIH9Bd43ZYsgsh+JITpBRmagYyAxPjo1zFU7ma/I6lVmg==}
peerDependencies:
pinia: ^3.0.0 || ^4.0.0
tailwindcss: ^4.1.0
@@ -561,12 +561,12 @@ packages:
resolution: {integrity: sha512-FlS4ZWlp97iiNWig0Muq8p+3rVDjRiYE+YKGbAqXOu9nwJFFOdL00kFpz42M+4huzYi86vAK1sOOfyOG45muIQ==}
engines: {node: '>=14'}
'@testing-library/jest-dom@7.0.1':
resolution: {integrity: sha512-oMDTC3oA+6CXSO2JZnvOI7CA6oVub6kij5ggk9ohwye5slmkwxYDXcPOVxgMw/RQlticjtO0C1RZkR97HgrWMw==}
'@testing-library/jest-dom@8.0.0':
resolution: {integrity: sha512-Nu45KEeFgP/ydCMipnisMblq6YHViqEFi3fKN0a40s+zdKDDD7vEPCEavS0i7i4RxmclcEIL8q2o42pu+WgNgg==}
engines: {node: '>=22', npm: '>=6', yarn: '>=1'}
peerDependencies:
'@testing-library/dom': '>=10 <11'
vitest: '>= 0.32'
vitest: '>=5 <6'
peerDependenciesMeta:
vitest:
optional: true
@@ -1967,7 +1967,7 @@ snapshots:
'@oxc-project/[email protected]': {}
'@perfect-design/[email protected]0([email protected](@vue/[email protected])([email protected])([email protected]([email protected])))([email protected])([email protected]([email protected]))':
'@perfect-design/[email protected]1([email protected](@vue/[email protected])([email protected])([email protected]([email protected])))([email protected])([email protected]([email protected]))':
dependencies:
pinia: 4.1.0(@vue/[email protected])([email protected])([email protected]([email protected]))
reka-ui: 2.11.0([email protected]([email protected]))
@@ -2123,11 +2123,11 @@ snapshots:
lz-string: 1.5.0
pretty-format: 27.5.1
'@testing-library/jest-dom@7.0.1(@testing-library/[email protected])([email protected]([email protected])([email protected]([email protected])([email protected])))':
'@testing-library/jest-dom@8.0.0(@testing-library/[email protected])([email protected]([email protected])([email protected]([email protected])([email protected])))':
dependencies:
'@adobe/css-tools': 4.4.4
'@testing-library/dom': 10.4.2
aria-query: 5.1.3
aria-query: 5.3.0
css.escape: 1.5.1
dom-accessibility-api: 0.6.3
picocolors: 1.1.1
+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,162 @@
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, elapsed_seconds: 40, eta_seconds: 60 }
let estimate: unknown
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]
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/admin/rescan/estimate') return { data: estimate } 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')
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' } })
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('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()
await wrapper.get('[data-testid="rescan-vulnerable"]').trigger('click')
await flushPromises()
expect(localStorage.getItem('admin_api_key')).toBeNull()
})
})
@@ -0,0 +1,201 @@
<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>
<p v-if="status.running && liveRate" class="m-0 text-sm text-muted-foreground" data-testid="rescan-live">{{ liveRate }}</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 { formatApproxDuration, 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
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
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 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)
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 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 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 {
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() {
adminKey.load()
if (!adminKey.key.value) {
pendingConfirm = true
showKeyDialog.value = true
return
}
confirmOpen.value = true
try {
estimate.value = (await axios.get<RescanEstimate>('/api/admin/rescan/estimate', { headers: adminKey.headers.value })).data
} catch {
estimate.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 (pendingConfirm) {
pendingConfirm = false
void askAll()
} else 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>
@@ -74,11 +74,25 @@ describe('TopPackages', () => {
expect(wrapper.get('[data-testid="top-packages"]').text()).toContain('No downloads yet')
})
it('shows the change against the previous 7 days for trending packages', async () => {
serve([], [
{ Registry: 'npm', Name: 'left-pad', Downloads: 9, RecentDownloads: 9, PreviousDownloads: 4 },
{ Registry: 'npm', Name: 'six', Downloads: 3, RecentDownloads: 3, PreviousDownloads: 8 },
])
const wrapper = await open()
const rows = wrapper.findAll('[data-testid="top-packages"] li').map((li) => li.text())
const pad = rows.find((r) => r.includes('left-pad'))
const six = rows.find((r) => r.includes('six'))
expect(pad).toMatch(/\+5/)
expect(six).toMatch(/[-−]5/)
})
it('names where each ranking comes from', async () => {
serve([row('npm', 'left-pad', 3)])
const wrapper = await open()
const text = wrapper.get('[data-testid="top-packages"]').text()
expect(text).toContain('The counts survive restarts.')
expect(text).toContain('Counted in memory, so it restarts with the server.')
expect(text).toContain('the change from the 7 days before')
expect(text).not.toContain('restarts with the server')
})
})
+17 -6
View File
@@ -15,7 +15,7 @@
<Card class="min-w-0">
<CardHeader>
<CardTitle as="h2">Trending</CardTitle>
<CardDescription>Downloads in the last 7 days. Counted in memory, so it restarts with the server.</CardDescription>
<CardDescription>Downloads in the last 7 days, and the change from the 7 days before. The counts survive restarts.</CardDescription>
</CardHeader>
<CardContent>
<LoadingState v-if="loading" layout="inline" label="Loading trending packages..." />
@@ -44,12 +44,13 @@ import {
} from '@perfect-design/ui'
import { modulePath } from '@/lib/format'
/** The analytics engine serialises Go field names. */
/** The trending endpoint serialises Go field names. */
interface PopularPackage {
Registry: string
Name: string
Downloads: number
RecentDownloads: number
PreviousDownloads?: number
}
/** One stored version row; its count is kept in the database. */
@@ -69,13 +70,17 @@ const loading = ref(false)
const error = ref<string | null>(null)
// Rows with equal registry and module path (a Go module's .zip, .mod and .info) are one package.
function entries(rows: PopularPackage[], pick: (p: PopularPackage) => number): LeaderboardEntry[] {
function entries(rows: PopularPackage[], pick: (p: PopularPackage) => number, change?: (p: PopularPackage) => number): LeaderboardEntry[] {
const totals = new Map<string, LeaderboardEntry>()
for (const row of rows) {
const id = `${row.Registry}/${modulePath(row.Name)}`
const existing = totals.get(id)
if (existing) existing.value += pick(row)
else totals.set(id, { id, label: `${row.Registry} · ${modulePath(row.Name)}`, value: pick(row) })
if (existing) {
existing.value += pick(row)
if (change) existing.delta = (existing.delta ?? 0) + change(row)
} else {
totals.set(id, { id, label: `${row.Registry} · ${modulePath(row.Name)}`, value: pick(row), ...(change ? { delta: change(row) } : {}) })
}
}
return [...totals.values()].filter((e) => e.value > 0).sort((a, b) => b.value - a.value).slice(0, LIMIT)
}
@@ -88,7 +93,13 @@ const top = computed(() =>
(p) => p.Downloads,
),
)
const trending = computed(() => entries(recent.value, (p) => p.RecentDownloads))
const trending = computed(() =>
entries(
recent.value,
(p) => p.RecentDownloads,
(p) => p.RecentDownloads - (p.PreviousDownloads ?? 0),
),
)
async function load() {
loading.value = true
@@ -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 }
+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
@@ -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";
+4 -4
View File
@@ -50,7 +50,7 @@ require (
github.com/aws/aws-sdk-go-v2/service/sso v1.39.5 // indirect
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.44.5 // indirect
github.com/aws/aws-sdk-go-v2/service/sts v1.53.0 // indirect
github.com/aws/smithy-go v1.28.9 // indirect
github.com/aws/smithy-go v1.28.10 // indirect
github.com/beorn7/perks v1.0.1 // indirect
github.com/cenkalti/backoff/v4 v4.3.0 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
@@ -71,7 +71,7 @@ require (
github.com/go-logr/stdr v1.2.2 // indirect
github.com/go-ole/go-ole v1.3.0 // indirect
github.com/go-viper/mapstructure/v2 v2.5.0 // indirect
github.com/gofiber/schema v1.10.0 // indirect
github.com/gofiber/schema v1.10.2 // indirect
github.com/gofiber/utils/v2 v2.6.5 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/hashicorp/go-uuid v1.0.4 // indirect
@@ -100,7 +100,7 @@ require (
github.com/moby/moby/client v0.6.3 // indirect
github.com/moby/patternmatcher v0.6.1 // indirect
github.com/moby/sys/sequential v0.7.0 // indirect
github.com/moby/sys/user v0.5.0 // indirect
github.com/moby/sys/user v0.5.1 // indirect
github.com/moby/sys/userns v0.2.1 // indirect
github.com/moby/term v0.5.2 // indirect
github.com/molecule-man/go-brrr v1.3.1 // indirect
@@ -125,7 +125,7 @@ require (
github.com/tklauser/go-sysconf v0.4.0 // indirect
github.com/tklauser/numcpus v0.12.0 // indirect
github.com/valyala/bytebufferpool v1.0.0 // indirect
github.com/valyala/fasthttp v1.79.0 // indirect
github.com/valyala/fasthttp v1.80.0 // indirect
github.com/yusufpapurcu/wmi v1.2.4 // indirect
go.opentelemetry.io/auto/sdk v1.2.2 // indirect
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.72.0 // indirect
+8 -8
View File
@@ -42,8 +42,8 @@ github.com/aws/aws-sdk-go-v2/service/ssooidc v1.44.5 h1:uIOBLMhef4N16WguadoHKuBy
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.44.5/go.mod h1:NwWmkFLtsTVyXQpbzPOlYLwEoANkdCFjJRtrNcbg/vY=
github.com/aws/aws-sdk-go-v2/service/sts v1.53.0 h1:my9Y6lxcqvPV5k4OTqnxr8XbiTDDRos1leEh050Z93U=
github.com/aws/aws-sdk-go-v2/service/sts v1.53.0/go.mod h1:MG6N8U9+lY4LqchrlHPqCOSr7hyxw70XU0Et2YR3eNA=
github.com/aws/smithy-go v1.28.9 h1:zkZ058OpNX0iGTK24b+ZUEQSMc11CBA6oO7xtKZfzkY=
github.com/aws/smithy-go v1.28.9/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc=
github.com/aws/smithy-go v1.28.10 h1:SfPnj8fGCVAI/P5YC4/1JjuMsucbPp2dROnSTYNo2PE=
github.com/aws/smithy-go v1.28.10/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc=
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
github.com/cenkalti/backoff/v4 v4.3.0 h1:MyRJ/UdXutAwSAT+s3wNd7MfTIcy71VQueUuFK343L8=
@@ -105,8 +105,8 @@ github.com/goccy/go-json v0.12.0 h1:pD+oWouAiz4yruwXIt/iT+lOMeyhr1aTtxzaMP/RgVI=
github.com/goccy/go-json v0.12.0/go.mod h1:3NdmfEkZlB7YI5UFw/qdFKq8XN1aiWR0YyRPWZNQltY=
github.com/gofiber/fiber/v3 v3.7.0 h1:aF+GfB7nP9Dd0wVsv6wmr8675v66OGfjSyoDhPmvKEo=
github.com/gofiber/fiber/v3 v3.7.0/go.mod h1:7dlbpUZ789TJg4q/VfdS1UWDtB6Fl/Smk6ZYZusMpAQ=
github.com/gofiber/schema v1.10.0 h1:d/2/NpHOVD0f29aNvM3KSPmaEDLJZvxW5edtN4Ymd8U=
github.com/gofiber/schema v1.10.0/go.mod h1:scfpXbReJ8y9xKlNnrwlewJ8nIGVZZmzoHZ4i5yGxG0=
github.com/gofiber/schema v1.10.2 h1:mjqtglIvi/+NK3gJTra6wKOaBLZYx+tdNu7xtaCVPOg=
github.com/gofiber/schema v1.10.2/go.mod h1:scfpXbReJ8y9xKlNnrwlewJ8nIGVZZmzoHZ4i5yGxG0=
github.com/gofiber/utils/v2 v2.6.5 h1:rU+8ao6LKi3fKOA3sEjfLv1T+2C2IwomeVmEKaqkr4A=
github.com/gofiber/utils/v2 v2.6.5/go.mod h1:OqPxdhDW7fPz0dupDanqf4e5O15IyFKy724y/EY9RI4=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
@@ -187,8 +187,8 @@ github.com/moby/sys/mountinfo v0.7.2 h1:1shs6aH5s4o5H2zQLn796ADW1wMrIwHsyJ2v9Kou
github.com/moby/sys/mountinfo v0.7.2/go.mod h1:1YOa8w8Ih7uW0wALDUgT1dTTSBrZ+HiBLGws92L2RU4=
github.com/moby/sys/sequential v0.7.0 h1:ASQNGNROJSuOO6LL6bPHbKvuZu6NU8P4ldPWk31zj/8=
github.com/moby/sys/sequential v0.7.0/go.mod h1:NfSTAp6V3fw4tmkD62PEcOKeZKquXT8VKCkf7aVR79o=
github.com/moby/sys/user v0.5.0 h1:5+S4lyoavGyX1DGs68NW8xpx48T9+a7ogSUc0KjZg8Y=
github.com/moby/sys/user v0.5.0/go.mod h1:4mQzP5aTmaLjDLp/dc870oNkik6E9vjRtWYwI05gvow=
github.com/moby/sys/user v0.5.1 h1:IMM/21OvpU2icUZczWBwLMf8iBEx1bOoiCQqcy1eKu0=
github.com/moby/sys/user v0.5.1/go.mod h1:4mQzP5aTmaLjDLp/dc870oNkik6E9vjRtWYwI05gvow=
github.com/moby/sys/userns v0.2.1 h1:4OvdM7BcPkASbuouHsbW3aeMJSFlYDldBRnXVZhaRk8=
github.com/moby/sys/userns v0.2.1/go.mod h1:IHUYgu/kao6N8YZlp9Cf444ySSvCmDlmzUcYfDHOl28=
github.com/moby/term v0.5.2 h1:6qk3FJAFDs6i/q3W/pQ97SX192qKfZgGjCQqfCJkgzQ=
@@ -271,8 +271,8 @@ github.com/tklauser/numcpus v0.12.0 h1:NR85qdvHA9pFse3x3weVZ0r0ST8R6l5RHbZrlRaqo
github.com/tklauser/numcpus v0.12.0/go.mod h1:ABHeXzJnr/qqwguhClkZKT1/8VABcYrsyUiUGobwWJg=
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
github.com/valyala/fasthttp v1.79.0 h1:32ur91W4kWG+1s6x3oDlP8/KNmjlZZlUzSSC4p9LSWE=
github.com/valyala/fasthttp v1.79.0/go.mod h1:NQN+PlgP93+JRPnCiApN5XwnI24oMQf8kuzrxtsTy9A=
github.com/valyala/fasthttp v1.80.0 h1:10pVr/QLFGbSX8ikDS0i+wOi2AGY2Sy0TACVpoiG+7U=
github.com/valyala/fasthttp v1.80.0/go.mod h1:oulvtxx5dQeORu6sKWaJItcnWXRqiGmrTFQ4gmZjLFM=
github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM=
github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg=
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
+16 -6
View File
@@ -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
@@ -308,22 +309,24 @@ func (a *App) initializeComponents() error {
log.Info().Msg("Initializing authentication manager")
authCfg := auth.Config{BcryptCost: a.config.Auth.BcryptCost}
a.authManager = auth.NewWithStore(authCfg, a.metadata)
// Bootstrap before Load: a key saved after the cache is hydrated stays invalid until the next restart.
bootCtx, bootCancel := context.WithTimeout(context.Background(), 30*time.Second)
if err := auth.BootstrapAdminFromEnv(bootCtx, a.metadata, authCfg); err != nil {
log.Warn().Err(err).Msg("Failed to bootstrap admin API key from environment")
}
bootCancel()
loadCtx, loadCancel := context.WithTimeout(context.Background(), 30*time.Second)
if err := a.authManager.Load(loadCtx); err != nil {
// Empty key set is recoverable: log and continue rather than fail boot.
log.Warn().Err(err).Msg("Failed to load API keys from metadata store; starting with empty key set")
}
loadCancel()
bootCtx, bootCancel := context.WithTimeout(context.Background(), 30*time.Second)
if err := auth.BootstrapAdminFromEnv(bootCtx, a.metadata, authCfg); err != nil {
log.Warn().Err(err).Msg("Failed to bootstrap admin API key from environment")
}
bootCancel()
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 +500,11 @@ 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)
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)
a.app.Get("/api/admin/keys", a.requireAdmin, a.handleListAPIKeys)
@@ -625,6 +633,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)
+29
View File
@@ -0,0 +1,29 @@
package app
import (
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/gofiber/fiber/v3"
"github.com/lukaszraczylo/gohoarder/pkg/auth"
)
// The env-bootstrapped admin key must work on the boot that creates it, not only after a restart.
func TestBootstrapAdminKeyWorksOnFirstBoot(t *testing.T) {
const key = "bootstrap-admin-key-for-test"
t.Setenv(auth.BootstrapAdminEnvVar, key)
a := newTestApp(t, nil)
req := httptest.NewRequest(http.MethodGet, "/api/admin/prewarming/status", nil)
req.Header.Set("X-API-Key", key)
resp, err := a.app.Test(req, fiber.TestConfig{Timeout: 10 * time.Second})
if err != nil {
t.Fatal(err)
}
_ = resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Fatalf("admin route with the bootstrap key = %d, want 200", resp.StatusCode)
}
}
+42 -1
View File
@@ -4,6 +4,7 @@ import (
"strconv"
"github.com/gofiber/fiber/v3"
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
"github.com/rs/zerolog/log"
)
@@ -27,7 +28,18 @@ func (a *App) handleAnalyticsTopPackages(c fiber.Ctx) error {
})
}
// handleAnalyticsTrendingPackages returns trending packages
// trendingPackage keeps the Go field names the dashboard reads from the analytics engine.
type trendingPackage struct {
Registry string
Name string
Downloads int64
RecentDownloads int64
PreviousDownloads int64
Trend float64
}
// handleAnalyticsTrendingPackages ranks packages by downloads in the last 7 days. Persisted
// history serves it so a restart keeps the ranking; the in-memory engine covers stores without it.
func (a *App) handleAnalyticsTrendingPackages(c fiber.Ctx) error {
c.Set("Content-Type", "application/json")
@@ -39,6 +51,35 @@ func (a *App) handleAnalyticsTrendingPackages(c fiber.Ctx) error {
}
}
if source, ok := a.metadata.(metadata.TrendingSource); ok {
stored, err := source.GetTrendingPackages(c.Context(), limit)
if err != nil {
log.Error().Err(err).Msg("Failed to read trending packages")
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
"error": "failed to read trending packages",
})
}
packages := make([]trendingPackage, 0, len(stored))
for _, p := range stored {
trend := 0.0
if p.Previous > 0 {
trend = float64(p.Recent-p.Previous) / float64(p.Previous) * 100
}
packages = append(packages, trendingPackage{
Registry: p.Registry,
Name: p.Name,
Downloads: p.Recent,
RecentDownloads: p.Recent,
PreviousDownloads: p.Previous,
Trend: trend,
})
}
return c.Status(fiber.StatusOK).JSON(fiber.Map{
"packages": packages,
"total": len(packages),
})
}
packages := a.analyticsEngine.GetTrendingPackages(limit)
return c.Status(fiber.StatusOK).JSON(fiber.Map{
+29
View File
@@ -148,3 +148,32 @@ func TestRowsLayoutSortsByRisk(t *testing.T) {
t.Errorf("risk desc names = %v, want the clean package last", got)
}
}
func TestRowsLayoutExcludesGoMetadataFiles(t *testing.T) {
a := newVerdictApp(t)
before, _ := getJSON(t, a, "/api/packages?layout=rows")
now := time.Now()
for _, name := range []string{"example.com/m/@v/v1.0.0.mod", "example.com/m/@v/v1.0.0.info", "example.com/m/@v/v1.0.0.zip", "example.com/only/@v/v0.1.0.mod"} {
if err := a.metadata.SavePackage(context.Background(), &metadata.Package{
Registry: "go", Name: name, Version: "v1.0.0", StorageKey: "go/" + name, Size: 1, CachedAt: now, LastAccessed: now,
}); err != nil {
t.Fatal(err)
}
}
out, _ := getJSON(t, a, "/api/packages?layout=rows&registry=go")
if got := rowNames(out); !slices.Equal(got, []string{"example.com/m"}) {
t.Errorf("go rows = %v, want only the .zip", got)
}
if out["total"].(float64) != 1 {
t.Errorf("total = %v, want 1", out["total"])
}
if pending := out["counts"].(map[string]any)["verdicts"].(map[string]any)["pending"].(float64); pending != 1 {
t.Errorf("pending count = %v, want 1", pending)
}
after, _ := getJSON(t, a, "/api/packages?layout=rows")
if after["total"].(float64) != before["total"].(float64)+1 {
t.Errorf("total = %v, want %v", after["total"], before["total"].(float64)+1)
}
}
+113
View File
@@ -0,0 +1,113 @@
package app
import (
"context"
"errors"
"math"
"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
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)
}
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})
}
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")
return c.Status(fiber.StatusOK).JSON(rescanStatusBody(a))
}
+214
View File
@@ -0,0 +1,214 @@
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)
}
}
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")
}
+84
View File
@@ -0,0 +1,84 @@
package app
import (
"context"
"encoding/json"
"fmt"
"net/http/httptest"
"testing"
"time"
"github.com/gofiber/fiber/v3"
"github.com/lukaszraczylo/gohoarder/pkg/analytics"
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
"github.com/lukaszraczylo/gohoarder/pkg/metadata/gormstore"
"github.com/stretchr/testify/require"
)
type trendingResponse struct {
Packages []trendingPackage `json:"packages"`
Total int `json:"total"`
}
func getTrending(t *testing.T, a *App, query string) trendingResponse {
t.Helper()
f := fiber.New()
f.Get("/api/analytics/trending", a.handleAnalyticsTrendingPackages)
resp, err := f.Test(httptest.NewRequest("GET", "/api/analytics/trending"+query, nil))
require.NoError(t, err)
require.Equal(t, 200, resp.StatusCode)
var out trendingResponse
require.NoError(t, json.NewDecoder(resp.Body).Decode(&out))
return out
}
func seedDownloads(t *testing.T, store metadata.Store, registry, name, version string, n int) {
t.Helper()
ctx := context.Background()
now := time.Now()
require.NoError(t, store.SavePackage(ctx, &metadata.Package{
Registry: registry, Name: name, Version: version, StorageKey: registry + "/" + name + "/" + version,
Size: 1, CachedAt: now, LastAccessed: now,
}))
for i := 0; i < n; i++ {
require.NoError(t, store.UpdateDownloadCount(ctx, registry, name, version))
}
}
func TestTrendingServedFromPersistedDownloads(t *testing.T) {
store, err := gormstore.NewV2(gormstore.Config{
Driver: "sqlite", DSN: fmt.Sprintf("file:trend_%d?mode=memory&cache=shared", time.Now().UnixNano()),
MaxOpenConns: 1, MaxIdleConns: 1, LogLevel: "silent",
})
require.NoError(t, err)
t.Cleanup(func() { _ = store.Close() })
seedDownloads(t, store, "npm", "left-pad", "1.3.0", 3)
seedDownloads(t, store, "go", "github.com/google/uuid/@v/v1.6.0.zip", "v1.6.0", 2)
seedDownloads(t, store, "go", "github.com/google/uuid/@v/v1.6.0.mod", "v1.6.0", 2)
// A fresh engine is what a restarted server has: it must not decide the ranking.
engine := analytics.NewEngine(analytics.Config{MaxEvents: 10, FlushInterval: time.Minute})
t.Cleanup(engine.Close)
got := getTrending(t, &App{metadata: store, analyticsEngine: engine}, "")
require.Equal(t, 2, got.Total)
require.Equal(t, "npm", got.Packages[0].Registry)
require.Equal(t, "left-pad", got.Packages[0].Name)
require.Equal(t, int64(3), got.Packages[0].RecentDownloads)
require.Equal(t, int64(0), got.Packages[0].PreviousDownloads)
require.Equal(t, "github.com/google/uuid", got.Packages[1].Name)
require.Equal(t, int64(2), got.Packages[1].RecentDownloads)
limited := getTrending(t, &App{metadata: store, analyticsEngine: engine}, "?limit=1")
require.Len(t, limited.Packages, 1)
}
func TestTrendingFallsBackToEngineWithoutPersistedHistory(t *testing.T) {
engine := analytics.NewEngine(analytics.Config{MaxEvents: 10, FlushInterval: time.Minute})
t.Cleanup(engine.Close)
engine.TrackDownload(analytics.PackageDownload{Registry: "npm", Name: "lodash", Version: "4", Timestamp: time.Now()})
got := getTrending(t, &App{analyticsEngine: engine}, "")
require.Equal(t, 1, got.Total)
require.Equal(t, "lodash", got.Packages[0].Name)
}
+1 -1
View File
@@ -132,7 +132,7 @@ func (s *Store) GetRegistryStats(ctx context.Context) ([]metadata.RegistryStat,
byRegistry := map[string]*metadata.RegistryStat{}
var order []string
for _, p := range all {
if metadata.IsMetadataVersion(p.Version) {
if metadata.IsMetadataEntry(p.Registry, p.Name, p.Version) {
continue
}
st, ok := byRegistry[p.Registry]
+5 -4
View File
@@ -49,8 +49,10 @@ func (s *GORMStoreV2) registryNames() map[int32]string {
// groupFilter builds the WHERE clause shared by the group count, the group page and the row fetch.
func (s *GORMStoreV2) groupFilter(opts metadata.GroupListOptions) (clause string, args []interface{}, empty bool, err error) {
clause = "version NOT IN ?"
args = []interface{}{metadata.MetadataVersions}
// The artifact filter GetStats applies, so list totals and /api/stats agree.
nameCond, nameArgs := notGoMetadataName()
clause = "version NOT IN ? AND " + nameCond
args = append([]interface{}{metadata.MetadataVersions}, nameArgs...)
if opts.Registry != "" {
id, idErr := s.getRegistryID(opts.Registry)
if idErr != nil {
@@ -351,9 +353,8 @@ func (s *GORMStoreV2) GetRegistryStats(ctx context.Context) ([]metadata.Registry
Size int64
Downloads int64
}
if err := s.db.WithContext(ctx).Model(&PackageModel{}).
if err := artifactPackages(s.db.WithContext(ctx).Model(&PackageModel{})).
Select("registry_id, COUNT(*) AS count, COALESCE(SUM(size), 0) AS size, COALESCE(SUM(access_count), 0) AS downloads").
Where("version NOT IN ?", metadata.MetadataVersions).
Group("registry_id").Order("registry_id").
Scan(&rows).Error; err != nil {
return nil, errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to aggregate registry stats")
+1 -1
View File
@@ -296,7 +296,7 @@ func checkRegistryStats(t *testing.T, store *GORMStoreV2) {
got[s.Registry] = s
}
require.Equal(t, metadata.RegistryStat{Registry: "npm", Count: 6, Size: 100 + 110 + 300 + 900 + 10 + 20, Downloads: 3 + 1 + 7}, got["npm"], "the list page is excluded")
require.Equal(t, metadata.RegistryStat{Registry: "go", Count: 5, Size: 500 + 10 + 5 + 520 + 40, Downloads: 3}, got["go"])
require.Equal(t, metadata.RegistryStat{Registry: "go", Count: 3, Size: 500 + 520 + 40, Downloads: 3}, got["go"], "the .mod and .info files are excluded, as in GetStats")
require.Equal(t, metadata.RegistryStat{Registry: "pypi", Count: 2, Size: 80, Downloads: 4}, got["pypi"])
}
+5 -9
View File
@@ -554,14 +554,8 @@ func (s *GORMStoreV2) ClearArtifactExpiry(ctx context.Context) (int64, error) {
query := s.db.WithContext(ctx).Model(&PackageModel{}).
Where("expires_at IS NOT NULL").
Where("version NOT IN ?", metadata.MetadataVersions)
// The name suffixes mark metadata for Go modules only.
suffixConds := make([]string, 0, len(metadata.MetadataNameSuffixes))
args := []interface{}{metadata.GoRegistry}
for _, suffix := range metadata.MetadataNameSuffixes {
suffixConds = append(suffixConds, "name LIKE ?")
args = append(args, "%"+suffix)
}
query = query.Where("NOT (registry_id IN (SELECT id FROM registries WHERE name = ?) AND ("+strings.Join(suffixConds, " OR ")+"))", args...)
cond, args := notGoMetadataName()
query = query.Where(cond, args...)
result := query.UpdateColumn("expires_at", nil)
if result.Error != nil {
return 0, errors.Wrap(result.Error, errors.ErrCodeStorageFailure, "failed to clear artifact expiry")
@@ -629,7 +623,8 @@ func (s *GORMStoreV2) GetStats(ctx context.Context, registry string) (*metadata.
query = query.Where("version NOT IN (?)", []string{"list", "latest", "metadata", "page"})
// Filter out Go module metadata files (.mod, .info) - only count actual packages (.zip)
query = query.Where("name NOT LIKE ?", "%.mod").Where("name NOT LIKE ?", "%.info")
cond, condArgs := notGoMetadataName()
query = query.Where(cond, condArgs...)
// Filter by registry if specified
if registry != "" {
@@ -918,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"
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
"github.com/stretchr/testify/require"
)
func TestGroupListSkipsGoMetadataFiles(t *testing.T) {
store := trendingStore(t)
for _, name := range []string{"example.com/m/@v/v1.0.0.mod", "example.com/m/@v/v1.0.0.info", "example.com/m/@v/v1.0.0.zip"} {
trendingPackage(t, store, "go", name, "v1.0.0")
}
for _, size := range []int{0, 10} {
page, err := store.ListPackageGroups(context.Background(), metadata.GroupListOptions{PageSize: size, Page: 1})
require.NoError(t, err)
require.Len(t, page.Packages, 1, "page size %d", size)
require.Equal(t, "example.com/m", page.Packages[0].Name)
}
}
func TestMetadataSuffixesAreGoOnly(t *testing.T) {
store := trendingStore(t)
ctx := context.Background()
trendingPackage(t, store, "npm", "left.mod", "1.0.0")
trendingPackage(t, store, "npm", "right.info", "1.0.0")
trendingPackage(t, store, "pypi", "foo.mod", "foo.mod-1.0.tar.gz")
trendingPackage(t, store, "go", "example.com/m/@v/v1.0.0.zip", "v1.0.0")
trendingPackage(t, store, "go", "example.com/m/@v/v1.0.0.mod", "v1.0.0")
trendingPackage(t, store, "go", "example.com/m/@v/v1.0.0.info", "v1.0.0")
stats, err := store.GetStats(ctx, "")
require.NoError(t, err)
require.EqualValues(t, 4, stats.TotalPackages)
page, err := store.ListPackageGroups(ctx, metadata.GroupListOptions{})
require.NoError(t, err)
require.Len(t, page.Packages, 4)
}
+13
View File
@@ -113,9 +113,22 @@ func GetMigrations() []*gormigrate.Migration {
return tx.Migrator().DropTable(&StatsSnapshotModel{})
},
},
{
// Serves the previous-week range read behind trending packages.
ID: "202611250002",
Migrate: func(tx *gorm.DB) error {
return createIndexIfMissing(tx, &DownloadStatsDailyModel{}, dailyTimeIndex)
},
Rollback: func(tx *gorm.DB) error {
return tx.Migrator().DropIndex(&DownloadStatsDailyModel{}, dailyTimeIndex)
},
},
}
}
// dailyTimeIndex is download_stats_daily (time_bucket).
const dailyTimeIndex = "idx_stats_daily_time"
// scanPackageScannedAtIndex is scan_results (package_id, scanned_at).
const scanPackageScannedAtIndex = "idx_scan_package_scanned_at"
+2 -2
View File
@@ -238,8 +238,8 @@ func (DownloadStatsHourlyModel) TableName() string {
// DownloadStatsDailyModel represents pre-aggregated daily statistics
type DownloadStatsDailyModel struct {
TimeBucket time.Time `gorm:"not null;index:idx_stats_daily_composite,priority:2"` // Truncated to day
PackageID *int64 `gorm:"index:idx_stats_daily_package"` // NULL = all packages in registry
TimeBucket time.Time `gorm:"not null;index:idx_stats_daily_composite,priority:2;index:idx_stats_daily_time"` // Truncated to day
PackageID *int64 `gorm:"index:idx_stats_daily_package"` // NULL = all packages in registry
TopUserAgents JSONBField // Top 10 user agents
BaseModel
@@ -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")
}
+15 -2
View File
@@ -3,6 +3,7 @@ package gormstore
import (
"context"
"sort"
"strings"
"time"
"github.com/lukaszraczylo/gohoarder/pkg/errors"
@@ -20,8 +21,20 @@ const (
// artifactPackages limits a query on packages to cache artifacts: no metadata
// pages and no Go .mod/.info files, as GetStats counts them.
func artifactPackages(db *gorm.DB) *gorm.DB {
return db.Where("version NOT IN ?", metadata.MetadataVersions).
Where("name NOT LIKE ?", "%.mod").Where("name NOT LIKE ?", "%.info")
cond, args := notGoMetadataName()
return db.Where("version NOT IN ?", metadata.MetadataVersions).Where(cond, args...)
}
// notGoMetadataName is the condition that drops Go .mod/.info rows; the suffixes mean
// metadata for Go only, as metadata.IsMetadataEntry has it.
func notGoMetadataName() (string, []interface{}) {
conds := make([]string, 0, len(metadata.MetadataNameSuffixes))
args := []interface{}{metadata.GoRegistry}
for _, suffix := range metadata.MetadataNameSuffixes {
conds = append(conds, "name LIKE ?")
args = append(args, "%"+suffix)
}
return "NOT (registry_id IN (SELECT id FROM registries WHERE name = ?) AND (" + strings.Join(conds, " OR ") + "))", args
}
func dayString(t time.Time) string { return t.UTC().Format(metadata.StatsSnapshotDateLayout) }
+5 -2
View File
@@ -76,8 +76,11 @@ func checkBackfillStatsSnapshots(t *testing.T, store *GORMStoreV2) {
seedAt(t, store, "a", "1.0.0", 10, daysAgo(5))
seedAt(t, store, "b", "1.0.0", 20, daysAgo(4))
seedAt(t, store, "a", "list", 5, daysAgo(5)) // metadata page: never counted
seedAt(t, store, "mod/@v/v1.mod", "v1", 7, daysAgo(5)) // Go .mod file: never counted
seedAt(t, store, "a", "list", 5, daysAgo(5)) // metadata page: never counted
require.NoError(t, store.SavePackage(ctx, &metadata.Package{ // Go .mod file: never counted
Registry: "go", Name: "mod/@v/v1.mod", Version: "v1", StorageKey: "go/mod/@v/v1.mod",
Size: 7, CachedAt: daysAgo(5), LastAccessed: daysAgo(5),
}))
seedAt(t, store, "early", "1.0.0", 40, daysAgo(2)) // cached and deleted the same day
scanAt(t, store, "b", "1.0.0", daysAgo(4), "high") // first scan: vulnerability history starts here
scanAt(t, store, "a", "1.0.0", daysAgo(3), "critical", "low") // critical wins over low
@@ -28,6 +28,8 @@ func newTimeSeriesStore(t *testing.T) *GORMStoreV2 {
LogLevel: "silent",
})
require.NoError(t, err)
// Tests drive aggregation by hand and set the worker clock; the background loop would race that write.
store.aggregationWorker.Stop()
return store
}
+149
View File
@@ -0,0 +1,149 @@
package gormstore
import (
"context"
"sort"
"strings"
"time"
"github.com/lukaszraczylo/gohoarder/pkg/errors"
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
)
const trendingWindow = 7 * 24 * time.Hour
type trendingKey struct{ registry, name string }
type trendingRow struct {
Registry string
Name string
Version string
Count int64
}
// GetTrendingPackages ranks packages by downloads in the last 7 days, with the 7 days before
// for the change. Downloads sit in raw events (current hour), hourly rows (kept 7 days) and
// daily rollups (older), the same layering GetTimeSeriesStats merges. The previous window ends
// exactly where the recent one starts: whole days come from the rollups, and the day that
// holds the boundary is its rollup minus the hourly rows after the boundary.
func (s *GORMStoreV2) GetTrendingPackages(ctx context.Context, limit int) ([]*metadata.TrendingPackage, error) {
now := s.clock().UTC()
since := now.Add(-trendingWindow).Truncate(time.Hour)
boundaryDay := since.Truncate(24 * time.Hour)
// Whole days only: pick the count that keeps the previous window closest to 7 days.
fullDays := 7
if since.Sub(boundaryDay) >= 12*time.Hour {
fullDays = 6
}
// The 12h shift keeps midnight rows on the right side whether the driver stores a date or a timestamp.
shift := 12 * time.Hour
fullFrom, fullTo := boundaryDay.AddDate(0, 0, -fullDays).Add(-shift), boundaryDay.Add(-shift)
hourly, err := s.packageDownloads(ctx, "download_stats_hourly s", "SUM(s.download_count)", "s.time_bucket >= ?", since)
if err != nil {
return nil, err
}
events, err := s.packageDownloads(ctx, "download_events s", "COUNT(*)", "s.downloaded_at >= ?", since)
if err != nil {
return nil, err
}
daily, err := s.packageDownloads(ctx, "download_stats_daily s", "SUM(s.download_count)", "s.time_bucket >= ? AND s.time_bucket < ?", fullFrom, fullTo)
if err != nil {
return nil, err
}
partialDay, err := s.packageDownloads(ctx, "download_stats_daily s", "SUM(s.download_count)", "s.time_bucket >= ? AND s.time_bucket < ?", fullTo, boundaryDay.Add(shift))
if err != nil {
return nil, err
}
afterBoundary, err := s.packageDownloads(ctx, "download_stats_hourly s", "SUM(s.download_count)", "s.time_bucket >= ? AND s.time_bucket < ?", since, boundaryDay.Add(24*time.Hour))
if err != nil {
return nil, err
}
// Hourly rows trail the rollup, so the difference can dip below zero.
after := make(map[trendingRow]int64, len(afterBoundary))
for _, r := range afterBoundary {
after[trendingRow{Registry: r.Registry, Name: r.Name, Version: r.Version}] += r.Count
}
for _, r := range partialDay {
left := r.Count - after[trendingRow{Registry: r.Registry, Name: r.Name, Version: r.Version}]
if left > 0 {
daily = append(daily, trendingRow{Registry: r.Registry, Name: r.Name, Version: r.Version, Count: left})
}
}
totals := make(map[trendingKey]*metadata.TrendingPackage)
add := func(rows []trendingRow, recent bool) {
for _, r := range rows {
if metadata.IsMetadataEntry(r.Registry, r.Name, r.Version) {
continue
}
name := r.Name
if r.Registry == metadata.GoRegistry {
name, _, _ = strings.Cut(name, "/@v/")
}
key := trendingKey{r.Registry, name}
pkg := totals[key]
if pkg == nil {
pkg = &metadata.TrendingPackage{Registry: r.Registry, Name: name}
totals[key] = pkg
}
if recent {
pkg.Recent += r.Count
} else {
pkg.Previous += r.Count
}
}
}
add(hourly, true)
add(events, true)
add(daily, false)
ranked := make([]*metadata.TrendingPackage, 0, len(totals))
for _, pkg := range totals {
if pkg.Recent > 0 {
ranked = append(ranked, pkg)
}
}
sort.Slice(ranked, func(i, j int) bool {
if ranked[i].Recent != ranked[j].Recent {
return ranked[i].Recent > ranked[j].Recent
}
if ranked[i].Registry != ranked[j].Registry {
return ranked[i].Registry < ranked[j].Registry
}
return ranked[i].Name < ranked[j].Name
})
if limit > 0 && limit < len(ranked) {
ranked = ranked[:limit]
}
return ranked, nil
}
// packageDownloads sums one download table per package row; table carries the alias "s".
func (s *GORMStoreV2) packageDownloads(ctx context.Context, table, sum, cond string, args ...interface{}) ([]trendingRow, error) {
var rows []trendingRow
err := s.db.WithContext(ctx).
Table(table).
Select("r.name AS registry, p.name AS name, p.version AS version, "+sum+" AS count").
Joins("JOIN packages p ON p.id = s.package_id").
Joins("JOIN registries r ON r.id = p.registry_id").
Where("s.package_id IS NOT NULL").
Where(cond, args...).
Group("r.name, p.name, p.version").
Scan(&rows).Error
if err != nil {
return nil, errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to read trending downloads")
}
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
}
+172
View File
@@ -0,0 +1,172 @@
package gormstore
import (
"context"
"testing"
"time"
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
"github.com/stretchr/testify/require"
)
var trendingNow = time.Date(2026, 11, 24, 10, 30, 0, 0, time.UTC)
func trendingStore(t *testing.T) *GORMStoreV2 {
t.Helper()
store := newTimeSeriesStore(t)
store.now = func() time.Time { return trendingNow }
return store
}
func trendingPackage(t *testing.T, store *GORMStoreV2, registry, name, version string) int64 {
t.Helper()
ctx := context.Background()
require.NoError(t, store.SavePackage(ctx, &metadata.Package{
Registry: registry, Name: name, Version: version, StorageKey: registry + "/" + name + "/" + version,
Size: 10, CachedAt: trendingNow, LastAccessed: trendingNow,
}))
var pkg PackageModel
require.NoError(t, store.db.Where("name = ? AND version = ?", name, version).First(&pkg).Error)
return pkg.ID
}
func trendingEvents(t *testing.T, store *GORMStoreV2, packageID int64, at time.Time, n int) {
t.Helper()
var pkg PackageModel
require.NoError(t, store.db.First(&pkg, packageID).Error)
for i := 0; i < n; i++ {
require.NoError(t, store.db.Create(&DownloadEventModel{PackageID: packageID, RegistryID: pkg.RegistryID, DownloadedAt: at}).Error)
}
}
func trendingStat(t *testing.T, store *GORMStoreV2, model interface{}, packageID int64, bucket time.Time, n int64) {
t.Helper()
var pkg PackageModel
require.NoError(t, store.db.First(&pkg, packageID).Error)
switch model.(type) {
case *DownloadStatsHourlyModel:
require.NoError(t, store.db.Create(&DownloadStatsHourlyModel{RegistryID: pkg.RegistryID, PackageID: &packageID, TimeBucket: bucket, DownloadCount: n}).Error)
default:
require.NoError(t, store.db.Create(&DownloadStatsDailyModel{RegistryID: pkg.RegistryID, PackageID: &packageID, TimeBucket: bucket, DownloadCount: n}).Error)
}
}
func TestTrendingCombinesEventsHourlyAndPreviousWeek(t *testing.T) {
store := trendingStore(t)
ctx := context.Background()
pad := trendingPackage(t, store, "npm", "left-pad", "1.3.0")
trendingEvents(t, store, pad, trendingNow.Add(-10*time.Minute), 2)
trendingStat(t, store, &DownloadStatsHourlyModel{}, pad, trendingNow.Add(-3*24*time.Hour).Truncate(time.Hour), 5)
trendingStat(t, store, &DownloadStatsDailyModel{}, pad, time.Date(2026, 11, 13, 0, 0, 0, 0, time.UTC), 4)
trendingStat(t, store, &DownloadStatsDailyModel{}, pad, time.Date(2026, 11, 15, 0, 0, 0, 0, time.UTC), 3)
got, err := store.GetTrendingPackages(ctx, 10)
require.NoError(t, err)
require.Equal(t, []*metadata.TrendingPackage{{Registry: "npm", Name: "left-pad", Recent: 7, Previous: 7}}, got)
}
func TestTrendingExcludesDownloadsOutsideBothWindows(t *testing.T) {
store := trendingStore(t)
pad := trendingPackage(t, store, "npm", "left-pad", "1.3.0")
trendingStat(t, store, &DownloadStatsDailyModel{}, pad, time.Date(2026, 11, 5, 0, 0, 0, 0, time.UTC), 50)
trendingStat(t, store, &DownloadStatsDailyModel{}, pad, time.Date(2026, 11, 9, 0, 0, 0, 0, time.UTC), 60)
trendingEvents(t, store, pad, trendingNow.Add(-time.Minute), 1)
got, err := store.GetTrendingPackages(context.Background(), 10)
require.NoError(t, err)
require.Len(t, got, 1)
require.Equal(t, int64(1), got[0].Recent)
require.Equal(t, int64(0), got[0].Previous)
}
func TestTrendingKeepsOnlyPackagesDownloadedThisWeek(t *testing.T) {
store := trendingStore(t)
old := trendingPackage(t, store, "npm", "old", "1.0.0")
trendingStat(t, store, &DownloadStatsDailyModel{}, old, time.Date(2026, 11, 14, 0, 0, 0, 0, time.UTC), 9)
got, err := store.GetTrendingPackages(context.Background(), 10)
require.NoError(t, err)
require.Empty(t, got)
}
func TestTrendingCountsGoModuleOnceAndSkipsMetadata(t *testing.T) {
store := trendingStore(t)
zip := trendingPackage(t, store, "go", "github.com/google/uuid/@v/v1.6.0.zip", "v1.6.0")
mod := trendingPackage(t, store, "go", "github.com/google/uuid/@v/v1.6.0.mod", "v1.6.0")
list := trendingPackage(t, store, "go", "github.com/google/uuid/@v/list", "list")
other := trendingPackage(t, store, "go", "github.com/google/uuid/@v/v1.5.0.zip", "v1.5.0")
meta := trendingPackage(t, store, "npm", "left-pad", "metadata")
for _, id := range []int64{zip, mod, list, meta} {
trendingEvents(t, store, id, trendingNow.Add(-time.Hour), 3)
}
trendingEvents(t, store, other, trendingNow.Add(-time.Hour), 2)
got, err := store.GetTrendingPackages(context.Background(), 10)
require.NoError(t, err)
require.Equal(t, []*metadata.TrendingPackage{{Registry: "go", Name: "github.com/google/uuid", Recent: 5}}, got)
}
func TestTrendingKeysByRegistryAndRanksWithLimit(t *testing.T) {
store := trendingStore(t)
npm := trendingPackage(t, store, "npm", "six", "1.0.0")
pypi := trendingPackage(t, store, "pypi", "six", "six-1.0.tar.gz")
third := trendingPackage(t, store, "npm", "a", "1.0.0")
trendingEvents(t, store, npm, trendingNow.Add(-time.Hour), 4)
trendingEvents(t, store, pypi, trendingNow.Add(-time.Hour), 6)
trendingEvents(t, store, third, trendingNow.Add(-time.Hour), 1)
got, err := store.GetTrendingPackages(context.Background(), 2)
require.NoError(t, err)
require.Equal(t, []*metadata.TrendingPackage{
{Registry: "pypi", Name: "six", Recent: 6},
{Registry: "npm", Name: "six", Recent: 4},
}, got)
}
func TestTrendingSurvivesAggregation(t *testing.T) {
store := newTimeSeriesStore(t)
recordDownloads(t, store, 3)
require.NoError(t, store.db.Exec("UPDATE download_events SET downloaded_at = ?", time.Now().Add(-3*time.Hour)).Error)
require.NoError(t, store.AggregateDownloadData(context.Background()))
var raw int64
require.NoError(t, store.db.Table("download_events").Count(&raw).Error)
require.Zero(t, raw, "events are rolled into hourly rows")
got, err := store.GetTrendingPackages(context.Background(), 10)
require.NoError(t, err)
require.Len(t, got, 1)
require.Equal(t, int64(3), got[0].Recent)
}
func TestDailyTimeIndexExists(t *testing.T) {
store := trendingStore(t)
require.True(t, store.db.Migrator().HasIndex(&DownloadStatsDailyModel{}, dailyTimeIndex))
}
// The day that holds the boundary is split: its rollup minus the hourly rows after the boundary.
func TestTrendingCountsTheBoundaryDayOnce(t *testing.T) {
store := trendingStore(t)
pad := trendingPackage(t, store, "npm", "left-pad", "1.3.0")
// 5 downloads on Nov 17; 2 of them at 12:00, after the boundary at 10:00.
trendingStat(t, store, &DownloadStatsDailyModel{}, pad, time.Date(2026, 11, 17, 0, 0, 0, 0, time.UTC), 5)
trendingStat(t, store, &DownloadStatsHourlyModel{}, pad, time.Date(2026, 11, 17, 12, 0, 0, 0, time.UTC), 2)
got, err := store.GetTrendingPackages(context.Background(), 10)
require.NoError(t, err)
require.Equal(t, []*metadata.TrendingPackage{{Registry: "npm", Name: "left-pad", Recent: 2, Previous: 3}}, got)
}
// Past noon the previous window takes six whole days, so it stays near 7 days long.
func TestTrendingPreviousWindowStaysNearAWeek(t *testing.T) {
store := trendingStore(t)
store.now = func() time.Time { return time.Date(2026, 11, 24, 14, 30, 0, 0, time.UTC) }
pad := trendingPackage(t, store, "npm", "left-pad", "1.3.0")
trendingEvents(t, store, pad, store.now().Add(-time.Minute), 1)
trendingStat(t, store, &DownloadStatsDailyModel{}, pad, time.Date(2026, 11, 10, 0, 0, 0, 0, time.UTC), 40)
trendingStat(t, store, &DownloadStatsDailyModel{}, pad, time.Date(2026, 11, 11, 0, 0, 0, 0, time.UTC), 6)
got, err := store.GetTrendingPackages(context.Background(), 10)
require.NoError(t, err)
require.Equal(t, int64(6), got[0].Previous)
}
+1 -1
View File
@@ -38,7 +38,7 @@ type groupAgg struct {
func PageGroups(all []*Package, opts GroupListOptions) *GroupPage {
groups := map[string]*groupAgg{}
for _, p := range all {
if IsMetadataVersion(p.Version) || (opts.Registry != "" && p.Registry != opts.Registry) || !MatchesQuery(p, opts.Query) {
if IsMetadataEntry(p.Registry, p.Name, p.Version) || (opts.Registry != "" && p.Registry != opts.Registry) || !MatchesQuery(p, opts.Query) {
continue
}
name := CleanName(p.Name)
+21
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
@@ -443,3 +444,23 @@ func DedupeVersions(rows []*Package) []*Package {
}
return out
}
// TrendingPackage is a package's download count over the last 7 days and the 7 days before.
type TrendingPackage struct {
Registry string `json:"registry"`
Name string `json:"name"`
Recent int64 `json:"recent"`
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 {
GetTrendingPackages(ctx context.Context, limit int) ([]*TrendingPackage, error)
}
+211
View File
@@ -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,205 @@ 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
Elapsed time.Duration
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")
}
// 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()
defer w.runMu.Unlock()
run := w.run
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,
Queued: int64(run.queued),
Done: run.counts.scanned.Load(),
Failed: run.counts.failed.Load() + run.counts.skipNoSource.Load(),
Running: run.running,
}
}
+153 -2
View File
@@ -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,149 @@ 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, Elapsed: st.FinishedAt.Sub(st.StartedAt), 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)
}
// 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 {