mirror of
https://github.com/lukaszraczylo/gohoarder.git
synced 2026-11-27 06:46:01 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
933b5a75c0 | ||
|
|
f4cf96e1e8 | ||
|
|
aa8487ad87 | ||
|
|
2ada975065 | ||
|
|
b98e761c90 | ||
|
|
a457e3d2e8 | ||
|
|
ba8bc392ec | ||
|
|
1512230ab3 | ||
|
|
bd9d686383 |
+1
-1
@@ -2,7 +2,7 @@
|
||||
# Combines frontend serving and backend proxy (previously separate gateway)
|
||||
# EXPECTS: Pre-built frontend files in frontend/dist/ directory
|
||||
|
||||
FROM nginx:alpine
|
||||
FROM mirror.gcr.io/library/nginx:1.31.9-alpine@sha256:fb4658584bd9a916ffb6f6e365f97c25cfdb2923801f551ea08356e695f14ff7
|
||||
|
||||
# Install envsubst for runtime configuration
|
||||
RUN apk add --no-cache gettext
|
||||
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
# This Dockerfile expects a PRE-BUILT binary from GoReleaser (no compilation)
|
||||
# GoReleaser injects the platform-specific binary automatically
|
||||
|
||||
FROM --platform=$TARGETPLATFORM alpine:latest
|
||||
FROM --platform=$TARGETPLATFORM mirror.gcr.io/library/alpine:3.24.4@sha256:f59abe656b692d901e184be3445e084786602108599d2a51d229c0f5a48c71bf
|
||||
|
||||
ARG TARGETARCH
|
||||
|
||||
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
# This Dockerfile expects a PRE-BUILT binary from GoReleaser (no compilation)
|
||||
# GoReleaser injects the platform-specific binary automatically
|
||||
|
||||
FROM --platform=$TARGETPLATFORM alpine:latest
|
||||
FROM --platform=$TARGETPLATFORM mirror.gcr.io/library/alpine:3.24.4@sha256:f59abe656b692d901e184be3445e084786602108599d2a51d229c0f5a48c71bf
|
||||
|
||||
ARG TARGETARCH
|
||||
|
||||
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
# This Dockerfile expects a PRE-BUILT binary from GoReleaser (no compilation)
|
||||
# GoReleaser injects the platform-specific binary automatically
|
||||
|
||||
FROM --platform=$TARGETPLATFORM alpine:latest
|
||||
FROM --platform=$TARGETPLATFORM mirror.gcr.io/library/alpine:3.24.4@sha256:f59abe656b692d901e184be3445e084786602108599d2a51d229c0f5a48c71bf
|
||||
|
||||
ARG TARGETARCH
|
||||
|
||||
|
||||
@@ -236,6 +236,7 @@ security:
|
||||
cache:
|
||||
default_ttl: 24h # Freshness window for metadata pages (version lists, package documents)
|
||||
idle_ttl: 168h # Remove cached items not requested for 7 days; 0 disables
|
||||
deleted_retention: 720h # Purge deleted package rows after 30 days; 0 keeps them
|
||||
ttl_overrides: # Per-registry metadata freshness (npm, pypi, go); replaces default_ttl, never applies to artifacts
|
||||
pypi: 12h
|
||||
cleanup_interval: 1h
|
||||
@@ -257,6 +258,8 @@ Every `cleanup_interval` the cleanup run removes:
|
||||
- **Idle items.** Any cached item, artifact or metadata page, whose last request is older than `idle_ttl` (default `168h`, seven days). Each request, hit or miss, resets the clock. Set `idle_ttl: 0` to turn idle eviction off.
|
||||
- **Stale metadata.** Version lists, package documents and Go `.mod`/`.info` files past `default_ttl` (default `24h`, below the 72h release-age gate clients apply). They refresh on the next request.
|
||||
|
||||
- **Deleted rows.** Evicting or deleting a package marks its database row deleted. Rows deleted longer ago than `deleted_retention` (default `720h`, 30 days) are removed for good, in batches of 500. Download history and the daily trend snapshots are kept. Set `deleted_retention: 0` to keep every row.
|
||||
|
||||
Artifacts (tarballs, wheels, module zips) never expire by age, so a package that clients keep requesting stays cached. Size-based LRU eviction at `max_size_bytes` is unchanged. Removed items keep their download history in the statistics.
|
||||
|
||||
### Environment Variables
|
||||
|
||||
@@ -97,6 +97,7 @@ cache:
|
||||
default_ttl: "24h" # Freshness window for metadata pages (version lists, packuments, .mod/.info); artifacts never expire by age
|
||||
cleanup_interval: "1h"
|
||||
idle_ttl: "168h" # Remove cached items not requested for this long; "0" disables
|
||||
deleted_retention: "720h" # Purge deleted package rows after this long; "0" keeps them forever
|
||||
max_size_bytes: 536870912000 # 500GB
|
||||
per_project_quota: 53687091200 # 50GB
|
||||
ttl_overrides: # Per-registry metadata freshness; replaces default_ttl for that registry. Keys: npm, pypi, go
|
||||
|
||||
@@ -1,12 +1,17 @@
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest'
|
||||
import { mount } from '@vue/test-utils'
|
||||
import { mount as mountWith } from '@vue/test-utils'
|
||||
import { createPinia, setActivePinia } from 'pinia'
|
||||
import Dashboard from './Dashboard.vue'
|
||||
import { usePackageStore } from '../stores/packages'
|
||||
import { useRealtimeStore, __resetRealtimeSingleton } from '../stores/realtime'
|
||||
import { createTestRouter } from '@/test/router'
|
||||
|
||||
describe('Dashboard.vue', () => {
|
||||
beforeEach(() => {
|
||||
let router: Awaited<ReturnType<typeof createTestRouter>>
|
||||
const mount = (component: typeof Dashboard) => mountWith(component, { global: { plugins: [router] } })
|
||||
|
||||
beforeEach(async () => {
|
||||
router = await createTestRouter('/')
|
||||
setActivePinia(createPinia())
|
||||
__resetRealtimeSingleton()
|
||||
// Mock the fetch functions to prevent actual API calls
|
||||
|
||||
@@ -39,35 +39,38 @@
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">Download activity</CardTitle>
|
||||
<CardAction>
|
||||
<SegmentedControl v-model="selectedPeriod" :options="chartPeriods" aria-label="Period" />
|
||||
</CardAction>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<LoadingState
|
||||
v-if="chartLoading && chartData.length === 0"
|
||||
layout="inline"
|
||||
label="Loading chart data..."
|
||||
/>
|
||||
<ErrorState
|
||||
v-else-if="chartError"
|
||||
variant="inline"
|
||||
title="Could not load download activity"
|
||||
:message="chartError"
|
||||
@retry="fetchTimeSeriesData"
|
||||
/>
|
||||
<BarChart
|
||||
v-else
|
||||
:labels="chartLabels"
|
||||
:series="[{ name: 'Downloads', data: chartData }]"
|
||||
label="Downloads over the selected period"
|
||||
empty-text="No download activity in this period"
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<div class="grid gap-6 lg:grid-cols-2">
|
||||
<Card class="min-w-0">
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">Download activity</CardTitle>
|
||||
<CardAction>
|
||||
<SegmentedControl v-model="selectedPeriod" :options="chartPeriods" aria-label="Period" />
|
||||
</CardAction>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<LoadingState
|
||||
v-if="chartLoading && chartData.length === 0"
|
||||
layout="inline"
|
||||
label="Loading chart data..."
|
||||
/>
|
||||
<ErrorState
|
||||
v-else-if="chartError"
|
||||
variant="inline"
|
||||
title="Could not load download activity"
|
||||
:message="chartError"
|
||||
@retry="fetchTimeSeriesData"
|
||||
/>
|
||||
<BarChart
|
||||
v-else
|
||||
:labels="chartLabels"
|
||||
:series="[{ name: 'Downloads', data: chartData }]"
|
||||
label="Downloads over the selected period"
|
||||
empty-text="No download activity in this period"
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<TrendChart compact class="min-w-0" />
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
@@ -124,6 +127,7 @@ import {
|
||||
type DataTableColumn,
|
||||
} from '@perfect-design/ui'
|
||||
import type { IconDefinition } from '@perfect-design/ui/lib/icons-tools'
|
||||
import TrendChart from './TrendChart.vue'
|
||||
import { usePackageStore, type Package } from '../stores/packages'
|
||||
import { useRealtimeStore } from '../stores/realtime'
|
||||
import type { EventType, RealtimeEvent } from '@/lib/ws'
|
||||
|
||||
@@ -1,18 +1,65 @@
|
||||
<template>
|
||||
<StatGroup :columns="4" :aria-label="label">
|
||||
<KpiTile v-for="level in SEVERITY_LEVELS" :key="level" :label="formatSeverityName(level)" :value="counts[level]">
|
||||
<template #icon><StatusDot :tone="SEVERITY_TONES[level]" /></template>
|
||||
</KpiTile>
|
||||
<template v-if="selectable">
|
||||
<KpiTile
|
||||
v-for="level in SEVERITY_LEVELS"
|
||||
:key="level"
|
||||
as="button"
|
||||
type="button"
|
||||
variant="interactive"
|
||||
:label="formatSeverityName(level)"
|
||||
:value="counts[level]"
|
||||
:aria-pressed="isSelected(level)"
|
||||
:class="isSelected(level) && 'ring-2 ring-primary'"
|
||||
:data-severity="level"
|
||||
@click="toggle(level)"
|
||||
>
|
||||
<template #icon><StatusDot :tone="SEVERITY_TONES[level]" /></template>
|
||||
<template #hint>
|
||||
<span v-if="packageCounts">{{ formatPackageCount(packageCounts[level]) }}</span>
|
||||
<span v-if="isSelected(level)" class="font-medium text-foreground" data-testid="severity-filter-on">
|
||||
{{ packageCounts ? ' · ' : '' }}Filter on
|
||||
</span>
|
||||
</template>
|
||||
</KpiTile>
|
||||
</template>
|
||||
<template v-else>
|
||||
<KpiTile v-for="level in SEVERITY_LEVELS" :key="level" :label="formatSeverityName(level)" :value="counts[level]">
|
||||
<template #icon><StatusDot :tone="SEVERITY_TONES[level]" /></template>
|
||||
</KpiTile>
|
||||
</template>
|
||||
</StatGroup>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { KpiTile, StatGroup, StatusDot } from '@perfect-design/ui'
|
||||
import type { VulnerabilityCounts } from '../stores/packages'
|
||||
import { SEVERITY_LEVELS, SEVERITY_TONES, formatSeverityName } from '@/lib/severity'
|
||||
import { SEVERITY_LEVELS, SEVERITY_TONES, formatSeverityName, type SeverityLevel } from '@/lib/severity'
|
||||
|
||||
defineProps<{
|
||||
const props = defineProps<{
|
||||
counts: VulnerabilityCounts
|
||||
label: string
|
||||
/** Tiles become toggle buttons that edit `modelValue`. */
|
||||
selectable?: boolean
|
||||
/** Selected severities; several are allowed. */
|
||||
modelValue?: readonly SeverityLevel[]
|
||||
/** Packages per severity, shown on each tile in selectable mode. */
|
||||
packageCounts?: VulnerabilityCounts
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{ 'update:modelValue': [value: SeverityLevel[]] }>()
|
||||
|
||||
function isSelected(level: SeverityLevel): boolean {
|
||||
return props.modelValue?.includes(level) ?? false
|
||||
}
|
||||
|
||||
function toggle(level: SeverityLevel) {
|
||||
const current = props.modelValue ?? []
|
||||
const next = current.includes(level) ? current.filter((l) => l !== level) : [...current, level]
|
||||
emit('update:modelValue', SEVERITY_LEVELS.filter((l) => next.includes(l)))
|
||||
}
|
||||
|
||||
function formatPackageCount(n: number): string {
|
||||
return `${n} package${n === 1 ? '' : 's'}`
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -70,6 +70,8 @@
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<TrendChart />
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">Registry breakdown</CardTitle>
|
||||
@@ -109,6 +111,7 @@ import {
|
||||
StatGroup,
|
||||
type DataTableColumn,
|
||||
} from '@perfect-design/ui'
|
||||
import TrendChart from './TrendChart.vue'
|
||||
import { formatBytes, formatDuration, formatNumber } from '@/lib/format'
|
||||
import { faBan, faDownload, faHardDrive, faBoxesStacked, faCircleCheck, faTriangleExclamation } from '@/lib/icons'
|
||||
|
||||
|
||||
@@ -0,0 +1,213 @@
|
||||
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 TrendChart from './TrendChart.vue'
|
||||
import { TREND } from '@/test/fixtures'
|
||||
import { mountStrict } from '@/test/mountStrict'
|
||||
import { createTestRouter } from '@/test/router'
|
||||
import { formatTrendDate, trendValues } from '@/lib/trend'
|
||||
|
||||
vi.mock('axios')
|
||||
|
||||
let restore: (() => void) | undefined
|
||||
|
||||
beforeEach(() => {
|
||||
setActivePinia(createPinia())
|
||||
vi.mocked(axios.get).mockReset()
|
||||
vi.mocked(axios.get).mockResolvedValue({ data: TREND })
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
restore?.()
|
||||
restore = undefined
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
async function open(props: Record<string, unknown> = {}) {
|
||||
const router = await createTestRouter('/stats')
|
||||
const mounted = await mountStrict(TrendChart, { props, global: { plugins: [router] } })
|
||||
restore = mounted.restore
|
||||
await flushPromises()
|
||||
return mounted
|
||||
}
|
||||
|
||||
type Wrapper = Awaited<ReturnType<typeof open>>['wrapper']
|
||||
const charts = (w: Wrapper) => w.findAll('svg[role="img"]')
|
||||
const requested = () => vi.mocked(axios.get).mock.calls.map((c) => c[0])
|
||||
|
||||
describe('TrendChart', () => {
|
||||
it('requests the 30 day trend and draws both charts with accessible names', async () => {
|
||||
const { wrapper, problems } = await open()
|
||||
|
||||
expect(problems).toEqual([])
|
||||
expect(requested()).toEqual(['/api/stats/trend?period=30day'])
|
||||
const labels = charts(wrapper).map((c) => c.attributes('aria-label'))
|
||||
expect(labels).toHaveLength(2)
|
||||
expect(labels[0]).toContain('Cached packages per day, from 3 on 2 Jan 2026 to 4 on 4 Jan 2026')
|
||||
expect(labels[1]).toContain('Vulnerable packages per day, from 1 on 3 Jan 2026 to 2 on 4 Jan 2026')
|
||||
})
|
||||
|
||||
it('offers every value as text through the chart data table', async () => {
|
||||
const { wrapper } = await open()
|
||||
const tables = wrapper.findAll('table')
|
||||
|
||||
expect(tables.length).toBeGreaterThanOrEqual(2)
|
||||
expect(tables[0]!.text()).toContain('Cached packages')
|
||||
expect(tables[0]!.text()).toContain('4')
|
||||
})
|
||||
|
||||
it('refetches when the period changes', async () => {
|
||||
const { wrapper } = await open()
|
||||
const ninety = wrapper.findAll('[role="radio"]').find((r) => r.text() === '90 days')!
|
||||
|
||||
await ninety.trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
expect(requested()).toEqual(['/api/stats/trend?period=30day', '/api/stats/trend?period=90day'])
|
||||
})
|
||||
|
||||
it('draws the vulnerable total first and adds a line for each severity that is switched on', async () => {
|
||||
const { wrapper } = await open()
|
||||
const vulnerable = () => charts(wrapper)[1]!.attributes('aria-label')
|
||||
expect(vulnerable()).not.toContain('lines for')
|
||||
|
||||
const critical = wrapper.findAll('button[aria-pressed]').find((b) => b.text() === 'Critical')!
|
||||
expect(critical.attributes('aria-pressed')).toBe('false')
|
||||
await critical.trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
expect(critical.attributes('aria-pressed')).toBe('true')
|
||||
expect(vulnerable()).toContain('with lines for critical')
|
||||
expect(wrapper.text()).toContain('Packages with critical vulnerabilities')
|
||||
|
||||
await critical.trigger('click')
|
||||
await flushPromises()
|
||||
expect(vulnerable()).not.toContain('lines for')
|
||||
})
|
||||
|
||||
it('offers all four severities as toggle buttons', async () => {
|
||||
const { wrapper } = await open()
|
||||
const names = wrapper.findAll('button[aria-pressed]').map((b) => b.text())
|
||||
expect(names).toEqual(['Critical', 'High', 'Moderate', 'Low'])
|
||||
})
|
||||
|
||||
it('says plainly when vulnerability history starts after the first day', async () => {
|
||||
const { wrapper } = await open()
|
||||
expect(wrapper.get('[data-testid="trend-vulnerability-note"]').text()).toBe('Vulnerability history starts 3 Jan 2026.')
|
||||
})
|
||||
|
||||
it('shows no note when every day has vulnerability data', async () => {
|
||||
const full = { ...TREND, vulnerability_history_start: TREND.points[0]!.date }
|
||||
vi.mocked(axios.get).mockResolvedValue({ data: full })
|
||||
const { wrapper } = await open()
|
||||
expect(wrapper.find('[data-testid="trend-vulnerability-note"]').exists()).toBe(false)
|
||||
})
|
||||
|
||||
it('shows an empty state instead of the vulnerable chart while no scan data exists', async () => {
|
||||
const noScans = {
|
||||
...TREND,
|
||||
vulnerability_history_start: null,
|
||||
points: TREND.points.map((p) => ({ ...p, vulnerable_packages: null, critical: null, high: null, moderate: null, low: null })),
|
||||
}
|
||||
vi.mocked(axios.get).mockResolvedValue({ data: noScans })
|
||||
const { wrapper, problems } = await open()
|
||||
|
||||
expect(problems).toEqual([])
|
||||
expect(charts(wrapper)).toHaveLength(1)
|
||||
expect(wrapper.get('[data-slot="empty-state"]').text()).toContain('Vulnerability history has not started')
|
||||
expect(wrapper.get('[data-testid="trend-vulnerability-note"]').text()).toContain('has not started in this period')
|
||||
})
|
||||
|
||||
it('shows an empty state when the server holds no snapshots', async () => {
|
||||
vi.mocked(axios.get).mockResolvedValue({ data: { ...TREND, vulnerability_history_start: null, points: [] } })
|
||||
const { wrapper } = await open()
|
||||
|
||||
expect(wrapper.get('[data-slot="empty-state"]').text()).toContain('No history yet')
|
||||
expect(charts(wrapper)).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('shows a loading state until the first answer arrives', async () => {
|
||||
let resolve!: (value: unknown) => void
|
||||
vi.mocked(axios.get).mockReturnValue(new Promise((r) => (resolve = r)) as never)
|
||||
const { wrapper } = await open()
|
||||
|
||||
expect(wrapper.text()).toContain('Loading package history...')
|
||||
resolve({ data: TREND })
|
||||
await flushPromises()
|
||||
expect(wrapper.text()).not.toContain('Loading package history...')
|
||||
expect(charts(wrapper)).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('shows the error with a retry that fetches again', async () => {
|
||||
vi.mocked(axios.get).mockRejectedValueOnce(new Error('Request failed with status code 502'))
|
||||
const { wrapper, problems } = await open()
|
||||
|
||||
expect(problems).toEqual([])
|
||||
const state = wrapper.get('[data-slot="error-state"]')
|
||||
expect(state.text()).toContain('502')
|
||||
expect(charts(wrapper)).toHaveLength(0)
|
||||
|
||||
await state.get('button').trigger('click')
|
||||
await flushPromises()
|
||||
expect(wrapper.find('[data-slot="error-state"]').exists()).toBe(false)
|
||||
expect(charts(wrapper)).toHaveLength(2)
|
||||
expect(requested()).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('rejects a body without points as an error, not an empty chart', async () => {
|
||||
vi.mocked(axios.get).mockResolvedValue({ data: { stats: {} } })
|
||||
const { wrapper } = await open()
|
||||
expect(wrapper.get('[data-slot="error-state"]').text()).toContain('Unexpected response format')
|
||||
})
|
||||
|
||||
it('ignores an answer that a newer request has replaced', async () => {
|
||||
const answers: Array<(v: unknown) => void> = []
|
||||
vi.mocked(axios.get).mockImplementation(() => new Promise((r) => answers.push(r)) as never)
|
||||
const { wrapper } = await open()
|
||||
await wrapper.findAll('[role="radio"]').find((r) => r.text() === '1 year')!.trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
answers[1]!({ data: { ...TREND, period: '1year', points: [TREND.points[2]] } })
|
||||
await flushPromises()
|
||||
answers[0]!({ data: TREND })
|
||||
await flushPromises()
|
||||
|
||||
expect(wrapper.get('svg[role="img"]').attributes('aria-label')).toContain('from 4 on 4 Jan 2026 to 4 on 4 Jan 2026')
|
||||
})
|
||||
|
||||
describe('compact', () => {
|
||||
it('always asks for 30 days, draws one chart and links to the full history', async () => {
|
||||
const { wrapper, problems } = await open({ compact: true })
|
||||
|
||||
expect(problems).toEqual([])
|
||||
expect(requested()).toEqual(['/api/stats/trend?period=30day'])
|
||||
expect(charts(wrapper)).toHaveLength(1)
|
||||
expect(wrapper.find('[role="radiogroup"]').exists()).toBe(false)
|
||||
expect(wrapper.find('button[aria-pressed]').exists()).toBe(false)
|
||||
expect(wrapper.get('a[href="/stats"]').text()).toBe('Open the full history')
|
||||
expect(wrapper.get('[data-testid="trend-compact-vulnerable"]').text()).toBe('2 vulnerable packages on 4 Jan 2026.')
|
||||
})
|
||||
|
||||
it('says so when the latest day has no vulnerability data', async () => {
|
||||
const last = { ...TREND.points[2]!, vulnerable_packages: null }
|
||||
vi.mocked(axios.get).mockResolvedValue({ data: { ...TREND, points: [TREND.points[0]!, last] } })
|
||||
const { wrapper } = await open({ compact: true })
|
||||
expect(wrapper.get('[data-testid="trend-compact-vulnerable"]').text()).toBe('Vulnerability history has not started yet.')
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('trend helpers', () => {
|
||||
it('formats a UTC date without shifting it with the viewer zone', () => {
|
||||
expect(formatTrendDate('2026-11-23')).toBe('23 Nov')
|
||||
expect(formatTrendDate('2026-01-01', true)).toBe('1 Jan 2026')
|
||||
expect(formatTrendDate('not-a-date')).toBe('not-a-date')
|
||||
})
|
||||
|
||||
it('turns unknown counts into gaps, never zeros', () => {
|
||||
const values = trendValues(TREND.points, 'vulnerable_packages')
|
||||
expect(values[0]).toBeNaN()
|
||||
expect(values.slice(1)).toEqual([1, 2])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,196 @@
|
||||
<template>
|
||||
<Card data-testid="trend-card">
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">{{ compact ? 'Cached packages' : 'Packages over time' }}</CardTitle>
|
||||
<CardDescription>
|
||||
{{ compact ? 'Daily total, last 30 days.' : 'The cache at the end of each UTC day.' }}
|
||||
</CardDescription>
|
||||
<CardAction>
|
||||
<SegmentedControl v-if="!compact" v-model="period" :options="TREND_PERIODS" aria-label="Trend period" />
|
||||
<Button v-else as-child variant="link" size="sm">
|
||||
<RouterLink to="/stats">Open the full history</RouterLink>
|
||||
</Button>
|
||||
</CardAction>
|
||||
</CardHeader>
|
||||
<CardContent class="flex flex-col gap-8">
|
||||
<LoadingState v-if="loading && !data" layout="inline" label="Loading package history..." />
|
||||
<ErrorState
|
||||
v-else-if="error"
|
||||
variant="inline"
|
||||
title="Could not load the package history"
|
||||
:message="error"
|
||||
@retry="load"
|
||||
/>
|
||||
<EmptyState
|
||||
v-else-if="points.length === 0"
|
||||
title="No history yet"
|
||||
description="The server records the first daily snapshot when it starts, then one more each day."
|
||||
/>
|
||||
<template v-else>
|
||||
<section class="flex flex-col gap-3" aria-labelledby="trend-packages-heading">
|
||||
<h3 id="trend-packages-heading" class="text-sm font-medium">Cached packages</h3>
|
||||
<LineChart
|
||||
variant="area"
|
||||
:size="compact ? 'sm' : 'md'"
|
||||
:y-min="0"
|
||||
:labels="labels"
|
||||
:series="[{ name: 'Cached packages', data: values('total_packages'), tone: 'primary' }]"
|
||||
:label="packagesLabel"
|
||||
/>
|
||||
</section>
|
||||
|
||||
<p v-if="compact" class="text-sm text-muted-foreground" data-testid="trend-compact-vulnerable">
|
||||
{{ compactVulnerable }}
|
||||
</p>
|
||||
|
||||
<section v-else class="flex flex-col gap-3" aria-labelledby="trend-vulnerable-heading">
|
||||
<div class="flex flex-wrap items-center justify-between gap-3">
|
||||
<h3 id="trend-vulnerable-heading" class="text-sm font-medium">Vulnerable packages</h3>
|
||||
<ToggleGroup
|
||||
v-model="severities"
|
||||
type="multiple"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
aria-label="Add a line per severity"
|
||||
>
|
||||
<ToggleGroupItem v-for="level in SEVERITY_LEVELS" :key="level" :value="level">
|
||||
{{ formatSeverityName(level) }}
|
||||
</ToggleGroupItem>
|
||||
</ToggleGroup>
|
||||
</div>
|
||||
<p v-if="vulnerabilityNote" class="text-sm text-muted-foreground" data-testid="trend-vulnerability-note">
|
||||
{{ vulnerabilityNote }}
|
||||
</p>
|
||||
<LineChart
|
||||
v-if="data?.vulnerability_history_start"
|
||||
:y-min="0"
|
||||
:labels="labels"
|
||||
:series="vulnerableSeries"
|
||||
:label="vulnerableLabel"
|
||||
/>
|
||||
<EmptyState
|
||||
v-else
|
||||
size="sm"
|
||||
title="Vulnerability history has not started"
|
||||
description="Scan results are counted from the first daily snapshot that includes them."
|
||||
/>
|
||||
</section>
|
||||
</template>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import axios from 'axios'
|
||||
import { RouterLink } from 'vue-router'
|
||||
import {
|
||||
Button,
|
||||
Card,
|
||||
CardAction,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
EmptyState,
|
||||
ErrorState,
|
||||
LineChart,
|
||||
LoadingState,
|
||||
SegmentedControl,
|
||||
ToggleGroup,
|
||||
ToggleGroupItem,
|
||||
} from '@perfect-design/ui'
|
||||
import { SEVERITY_LEVELS, formatSeverityName, type SeverityLevel } from '@/lib/severity'
|
||||
import {
|
||||
DEFAULT_TREND_PERIOD,
|
||||
SEVERITY_LINE_TONES,
|
||||
TREND_PERIODS,
|
||||
formatTrendDate,
|
||||
trendValues,
|
||||
type TrendPeriod,
|
||||
type TrendPoint,
|
||||
type TrendResponse,
|
||||
} from '@/lib/trend'
|
||||
|
||||
const props = defineProps<{
|
||||
/** Dashboard card: 30 days, cached packages only, a link to the full history. */
|
||||
compact?: boolean
|
||||
}>()
|
||||
|
||||
const period = ref<TrendPeriod>(DEFAULT_TREND_PERIOD)
|
||||
const severities = ref<SeverityLevel[]>([])
|
||||
const data = ref<TrendResponse | null>(null)
|
||||
const loading = ref(false)
|
||||
const error = ref<string | null>(null)
|
||||
|
||||
let request = 0
|
||||
|
||||
async function load() {
|
||||
const current = ++request
|
||||
loading.value = true
|
||||
error.value = null
|
||||
try {
|
||||
const response = await axios.get(`/api/stats/trend?period=${props.compact ? DEFAULT_TREND_PERIOD : period.value}`)
|
||||
if (current !== request) return
|
||||
const body = response.data as TrendResponse | undefined
|
||||
if (!body || !Array.isArray(body.points)) {
|
||||
data.value = null
|
||||
error.value = 'Unexpected response format from server'
|
||||
return
|
||||
}
|
||||
data.value = body
|
||||
} catch (err) {
|
||||
if (current !== request) return
|
||||
data.value = null
|
||||
error.value = err instanceof Error ? err.message : 'Failed to load the package history'
|
||||
} finally {
|
||||
if (current === request) loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(load)
|
||||
watch(period, load)
|
||||
|
||||
const points = computed<TrendPoint[]>(() => data.value?.points ?? [])
|
||||
const labels = computed(() => points.value.map((p) => formatTrendDate(p.date, period.value === '1year')))
|
||||
const values = (key: keyof Omit<TrendPoint, 'date'>) => trendValues(points.value, key)
|
||||
|
||||
function span(key: keyof Omit<TrendPoint, 'date'>): string {
|
||||
const known = points.value.filter((p) => p[key] !== null)
|
||||
const first = known[0]
|
||||
const last = known[known.length - 1]
|
||||
if (!first || !last) return ''
|
||||
return `from ${first[key]} on ${formatTrendDate(first.date, true)} to ${last[key]} on ${formatTrendDate(last.date, true)}`
|
||||
}
|
||||
|
||||
const packagesLabel = computed(() => `Cached packages per day, ${span('total_packages')}`)
|
||||
const vulnerableLabel = computed(() => {
|
||||
const extra = severities.value.length ? `, with lines for ${severities.value.join(', ')}` : ''
|
||||
return `Vulnerable packages per day, ${span('vulnerable_packages')}${extra}`
|
||||
})
|
||||
|
||||
const vulnerableSeries = computed(() => [
|
||||
{ name: 'Vulnerable packages', data: values('vulnerable_packages'), tone: 'primary' as const },
|
||||
...SEVERITY_LEVELS.filter((level) => severities.value.includes(level)).map((level) => ({
|
||||
name: `Packages with ${level} vulnerabilities`,
|
||||
data: values(level),
|
||||
tone: SEVERITY_LINE_TONES[level],
|
||||
})),
|
||||
])
|
||||
|
||||
// Earlier days were never scanned, so their counts are unknown and drawn as a gap.
|
||||
const vulnerabilityNote = computed(() => {
|
||||
const start = data.value?.vulnerability_history_start
|
||||
const first = points.value[0]
|
||||
if (!start) return 'Vulnerability history has not started in this period.'
|
||||
if (first && start > first.date) return `Vulnerability history starts ${formatTrendDate(start, true)}.`
|
||||
return ''
|
||||
})
|
||||
|
||||
const compactVulnerable = computed(() => {
|
||||
const last = points.value[points.value.length - 1]
|
||||
const n = last?.vulnerable_packages
|
||||
if (n === null || n === undefined) return 'Vulnerability history has not started yet.'
|
||||
return `${n} vulnerable package${n === 1 ? '' : 's'} on ${formatTrendDate(last!.date, true)}.`
|
||||
})
|
||||
</script>
|
||||
@@ -0,0 +1,226 @@
|
||||
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 VulnerablePackages from './VulnerablePackages.vue'
|
||||
import type { Package, VulnerabilityCounts } from '@/stores/packages'
|
||||
import { mountStrict } from '@/test/mountStrict'
|
||||
import { createTestRouter } from '@/test/router'
|
||||
|
||||
vi.mock('axios')
|
||||
|
||||
function vulnerable(name: string, counts: Partial<VulnerabilityCounts>): Package {
|
||||
const full = { critical: 0, high: 0, moderate: 0, low: 0, ...counts }
|
||||
return {
|
||||
id: name,
|
||||
registry: 'npm',
|
||||
name,
|
||||
version: '1.0.0',
|
||||
size: 1024,
|
||||
cached_at: '2026-01-03T10:00:00Z',
|
||||
last_accessed: '2026-01-03T10:00:00Z',
|
||||
download_count: 1,
|
||||
vulnerabilities: {
|
||||
scanned: true,
|
||||
status: 'vulnerable',
|
||||
counts: full,
|
||||
total: full.critical + full.high + full.moderate + full.low,
|
||||
scannedAt: '2026-01-03T10:05:00Z',
|
||||
isBlocked: false,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
const ALL_SEVERITIES = 'critical,high,moderate,low'
|
||||
const FIXTURE: Package[] = [
|
||||
vulnerable('alpha-critical', { critical: 1 }),
|
||||
vulnerable('bravo-high', { high: 2 }),
|
||||
vulnerable('charlie-moderate', { moderate: 1 }),
|
||||
vulnerable('delta-mixed', { critical: 1, moderate: 3 }),
|
||||
]
|
||||
const NAMES = FIXTURE.map((p) => p.name)
|
||||
|
||||
let restore: (() => void) | undefined
|
||||
|
||||
beforeEach(() => {
|
||||
setActivePinia(createPinia())
|
||||
vi.mocked(axios.get).mockResolvedValue({ data: { packages: FIXTURE } })
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
restore?.()
|
||||
restore = undefined
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
async function open(path = '/vulnerable-packages') {
|
||||
const router = await createTestRouter(path)
|
||||
const pinia = createPinia()
|
||||
setActivePinia(pinia)
|
||||
const mounted = await mountStrict(VulnerablePackages, { global: { plugins: [pinia, router] } })
|
||||
restore = mounted.restore
|
||||
await flushPromises()
|
||||
return { ...mounted, router }
|
||||
}
|
||||
|
||||
type Wrapper = Awaited<ReturnType<typeof open>>['wrapper']
|
||||
|
||||
const tile = (wrapper: Wrapper, severity: string) => wrapper.get(`button[data-severity="${severity}"]`)
|
||||
const shown = (wrapper: Wrapper) => NAMES.filter((name) => wrapper.text().includes(name))
|
||||
const pressed = (wrapper: Wrapper) =>
|
||||
wrapper.findAll('button[data-severity]').map((b) => b.attributes('aria-pressed'))
|
||||
const clearButtons = (wrapper: Wrapper) => wrapper.findAll('button').filter((b) => b.text() === 'Clear filters')
|
||||
|
||||
describe('VulnerablePackages severity filter', () => {
|
||||
it('starts unfiltered: every vulnerable package, no tile pressed, no clear control', async () => {
|
||||
const { wrapper, problems, router } = await open()
|
||||
|
||||
expect(problems).toEqual([])
|
||||
expect(shown(wrapper)).toEqual(NAMES)
|
||||
expect(pressed(wrapper)).toEqual(['false', 'false', 'false', 'false'])
|
||||
expect(wrapper.text()).not.toContain('Filter on')
|
||||
expect(clearButtons(wrapper)).toHaveLength(0)
|
||||
expect(router.currentRoute.value.query.severity).toBeUndefined()
|
||||
})
|
||||
|
||||
it('asks the server for vulnerable packages only', async () => {
|
||||
await open()
|
||||
expect(axios.get).toHaveBeenCalledWith(`/api/packages?severity=${ALL_SEVERITIES}`)
|
||||
})
|
||||
|
||||
it('renders the four tiles as keyboard-operable buttons in severity order', async () => {
|
||||
const { wrapper } = await open()
|
||||
const tiles = wrapper.findAll('button[data-severity]')
|
||||
|
||||
expect(tiles.map((t) => t.attributes('data-severity'))).toEqual(['critical', 'high', 'moderate', 'low'])
|
||||
for (const t of tiles) {
|
||||
expect(t.element.tagName).toBe('BUTTON')
|
||||
expect(t.attributes('type')).toBe('button')
|
||||
expect(t.attributes('tabindex')).not.toBe('-1')
|
||||
expect(t.attributes('aria-pressed')).toBeDefined()
|
||||
}
|
||||
})
|
||||
|
||||
it('one click filters to that severity and shows the state in text, not colour alone', async () => {
|
||||
const { wrapper, router } = await open()
|
||||
|
||||
await tile(wrapper, 'high').trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
expect(shown(wrapper)).toEqual(['bravo-high'])
|
||||
expect(pressed(wrapper)).toEqual(['false', 'true', 'false', 'false'])
|
||||
expect(tile(wrapper, 'high').text()).toContain('Filter on')
|
||||
expect(tile(wrapper, 'critical').text()).not.toContain('Filter on')
|
||||
expect(wrapper.get('[data-testid="filter-bar"]').text()).toContain('Showing packages with high vulnerabilities.')
|
||||
expect(clearButtons(wrapper)).toHaveLength(1)
|
||||
expect(router.currentRoute.value.query.severity).toBe('high')
|
||||
})
|
||||
|
||||
it('keeps the tile counts of the whole list while a filter is on', async () => {
|
||||
const { wrapper } = await open()
|
||||
const before = tile(wrapper, 'critical').text()
|
||||
|
||||
await tile(wrapper, 'high').trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
expect(tile(wrapper, 'critical').text()).toBe(before)
|
||||
expect(tile(wrapper, 'critical').text()).toContain('2 packages')
|
||||
})
|
||||
|
||||
it('selects several severities with OR semantics', async () => {
|
||||
const { wrapper, router } = await open()
|
||||
|
||||
await tile(wrapper, 'critical').trigger('click')
|
||||
await flushPromises()
|
||||
expect(shown(wrapper)).toEqual(['alpha-critical', 'delta-mixed'])
|
||||
|
||||
await tile(wrapper, 'high').trigger('click')
|
||||
await flushPromises()
|
||||
expect(shown(wrapper)).toEqual(['alpha-critical', 'bravo-high', 'delta-mixed'])
|
||||
expect(pressed(wrapper)).toEqual(['true', 'true', 'false', 'false'])
|
||||
expect(router.currentRoute.value.query.severity).toBe('critical,high')
|
||||
expect(wrapper.get('[data-testid="filter-bar"]').text()).toContain('critical or high')
|
||||
})
|
||||
|
||||
it('a second click toggles the filter off and removes the query', async () => {
|
||||
const { wrapper, router } = await open()
|
||||
|
||||
await tile(wrapper, 'moderate').trigger('click')
|
||||
await flushPromises()
|
||||
expect(shown(wrapper)).toEqual(['charlie-moderate', 'delta-mixed'])
|
||||
|
||||
await tile(wrapper, 'moderate').trigger('click')
|
||||
await flushPromises()
|
||||
expect(shown(wrapper)).toEqual(NAMES)
|
||||
expect(pressed(wrapper)).toEqual(['false', 'false', 'false', 'false'])
|
||||
expect(clearButtons(wrapper)).toHaveLength(0)
|
||||
expect(router.currentRoute.value.query.severity).toBeUndefined()
|
||||
})
|
||||
|
||||
it('Clear filters resets every selected severity at once', async () => {
|
||||
const { wrapper, router } = await open()
|
||||
await tile(wrapper, 'critical').trigger('click')
|
||||
await tile(wrapper, 'high').trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
await clearButtons(wrapper)[0]!.trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
expect(shown(wrapper)).toEqual(NAMES)
|
||||
expect(pressed(wrapper)).toEqual(['false', 'false', 'false', 'false'])
|
||||
expect(router.currentRoute.value.query.severity).toBeUndefined()
|
||||
})
|
||||
|
||||
it('restores the filter from the URL, as after a reload or a shared link', async () => {
|
||||
const { wrapper } = await open('/vulnerable-packages?severity=high,critical')
|
||||
|
||||
expect(shown(wrapper)).toEqual(['alpha-critical', 'bravo-high', 'delta-mixed'])
|
||||
expect(pressed(wrapper)).toEqual(['true', 'true', 'false', 'false'])
|
||||
expect(clearButtons(wrapper)).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('ignores unknown severities in the URL and keeps the other query parameters', async () => {
|
||||
const { wrapper, router } = await open('/vulnerable-packages?severity=bogus&ref=mail')
|
||||
expect(shown(wrapper)).toEqual(NAMES)
|
||||
expect(clearButtons(wrapper)).toHaveLength(0)
|
||||
|
||||
await tile(wrapper, 'low').trigger('click')
|
||||
await flushPromises()
|
||||
expect(router.currentRoute.value.query).toEqual({ ref: 'mail', severity: 'low' })
|
||||
})
|
||||
|
||||
it('shows a library empty state with a clear control when no package matches', async () => {
|
||||
const { wrapper, router } = await open('/vulnerable-packages?severity=low')
|
||||
|
||||
const empty = wrapper.get('[data-slot="empty-state"]')
|
||||
expect(empty.text()).toContain('No packages match the filter')
|
||||
expect(shown(wrapper)).toEqual([])
|
||||
// The tiles stay so the filter can be changed without leaving the page.
|
||||
expect(pressed(wrapper)).toEqual(['false', 'false', 'false', 'true'])
|
||||
|
||||
await empty.findAll('button').find((b) => b.text() === 'Clear filters')!.trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
expect(shown(wrapper)).toEqual(NAMES)
|
||||
expect(wrapper.find('[data-slot="empty-state"]').exists()).toBe(false)
|
||||
expect(router.currentRoute.value.query.severity).toBeUndefined()
|
||||
})
|
||||
|
||||
it('keeps the success state when nothing is vulnerable, filter or not', async () => {
|
||||
vi.mocked(axios.get).mockResolvedValue({ data: { packages: [] } })
|
||||
const { wrapper } = await open('/vulnerable-packages?severity=critical')
|
||||
|
||||
expect(wrapper.text()).toContain('No vulnerable packages')
|
||||
expect(wrapper.find('button[data-severity]').exists()).toBe(false)
|
||||
})
|
||||
|
||||
it('still narrows to blocked packages on the blocked route', async () => {
|
||||
const blocked = vulnerable('echo-blocked', { critical: 1 })
|
||||
blocked.vulnerabilities!.isBlocked = true
|
||||
vi.mocked(axios.get).mockResolvedValue({ data: { packages: [...FIXTURE, blocked] } })
|
||||
const { wrapper } = await open('/blocked-packages?severity=critical')
|
||||
|
||||
expect(wrapper.text()).toContain('echo-blocked')
|
||||
expect(wrapper.text()).not.toContain('alpha-critical')
|
||||
})
|
||||
})
|
||||
@@ -23,7 +23,7 @@
|
||||
@retry="fetchVulnerablePackages"
|
||||
/>
|
||||
|
||||
<Card v-else-if="sortedVulnerablePackages.length === 0">
|
||||
<Card v-else-if="vulnerablePackages.length === 0">
|
||||
<CardContent>
|
||||
<EmptyState
|
||||
tone="success"
|
||||
@@ -35,9 +35,34 @@
|
||||
</Card>
|
||||
|
||||
<template v-else>
|
||||
<SeveritySummary :counts="totalCounts" label="Vulnerabilities by severity" />
|
||||
<SeveritySummary
|
||||
v-model="selectedSeverities"
|
||||
selectable
|
||||
:counts="totalCounts"
|
||||
:package-counts="packageCounts"
|
||||
label="Vulnerabilities by severity. Select a severity to filter the packages."
|
||||
/>
|
||||
|
||||
<Card>
|
||||
<div v-if="hasFilter" class="flex flex-wrap items-center justify-between gap-3" data-testid="filter-bar">
|
||||
<p class="text-sm text-muted-foreground" role="status">Showing packages with {{ filterSummary }} vulnerabilities.</p>
|
||||
<Button variant="outline" size="sm" @click="clearFilters">Clear filters</Button>
|
||||
</div>
|
||||
|
||||
<Card v-if="sortedVulnerablePackages.length === 0">
|
||||
<CardContent>
|
||||
<EmptyState
|
||||
:icon="faCircleCheck"
|
||||
title="No packages match the filter"
|
||||
:description="`No ${showOnlyBlocked ? 'blocked' : 'vulnerable'} package has a ${filterSummary} vulnerability.`"
|
||||
>
|
||||
<template #action>
|
||||
<Button variant="outline" @click="clearFilters">Clear filters</Button>
|
||||
</template>
|
||||
</EmptyState>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card v-else>
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">
|
||||
{{ showOnlyBlocked ? 'Blocked' : 'Vulnerable' }} packages ({{ sortedVulnerablePackages.length }})
|
||||
@@ -104,7 +129,7 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { useRouter, useRoute } from 'vue-router'
|
||||
import { usePackageStore, type Package } from '../stores/packages'
|
||||
import { usePackageStore, type Package, type VulnerabilityCounts } from '../stores/packages'
|
||||
import {
|
||||
Accordion,
|
||||
AccordionContent,
|
||||
@@ -128,12 +153,38 @@ import VulnerabilityBadge from './VulnerabilityBadge.vue'
|
||||
import SeveritySummary from './SeveritySummary.vue'
|
||||
import { formatBytes, formatDate, formatNumber, displayVersion, withVersionPrefix } from '@/lib/format'
|
||||
import { faArrowLeft, faCircleCheck } from '@/lib/icons'
|
||||
import { NO_VULNERABILITIES } from '@/lib/severity'
|
||||
import { NO_VULNERABILITIES, SEVERITY_LEVELS, formatSeverityName, type SeverityLevel } from '@/lib/severity'
|
||||
|
||||
const store = usePackageStore()
|
||||
const router = useRouter()
|
||||
const route = useRoute()
|
||||
|
||||
const SEVERITY_QUERY = 'severity'
|
||||
|
||||
/** Reads `?severity=critical,high`: known levels only, in severity order, each once. */
|
||||
function parseSeverityQuery(raw: unknown): SeverityLevel[] {
|
||||
const text = Array.isArray(raw) ? raw.join(',') : typeof raw === 'string' ? raw : ''
|
||||
const wanted = text.split(',').map((part) => part.trim().toLowerCase())
|
||||
return SEVERITY_LEVELS.filter((level) => wanted.includes(level))
|
||||
}
|
||||
|
||||
// The URL is the source of truth, so a reload or a shared link restores the filter.
|
||||
const selectedSeverities = computed<SeverityLevel[]>({
|
||||
get: () => parseSeverityQuery(route.query[SEVERITY_QUERY]),
|
||||
set: (levels) => {
|
||||
const { [SEVERITY_QUERY]: _previous, ...rest } = route.query
|
||||
void router.replace({ query: levels.length > 0 ? { ...rest, [SEVERITY_QUERY]: levels.join(',') } : rest })
|
||||
},
|
||||
})
|
||||
const hasFilter = computed(() => selectedSeverities.value.length > 0)
|
||||
const filterSummary = computed(() =>
|
||||
selectedSeverities.value.map((level) => formatSeverityName(level).toLowerCase()).join(' or '),
|
||||
)
|
||||
|
||||
function clearFilters() {
|
||||
selectedSeverities.value = []
|
||||
}
|
||||
|
||||
const loading = ref(false)
|
||||
const error = ref<string | null>(null)
|
||||
const vulnerablePackages = ref<Package[]>([])
|
||||
@@ -150,7 +201,8 @@ async function fetchVulnerablePackages() {
|
||||
error.value = null
|
||||
|
||||
try {
|
||||
await store.fetchPackages()
|
||||
// The server drops clean packages; the toggles below narrow the rest without another request.
|
||||
await store.fetchPackages({ severity: SEVERITY_LEVELS })
|
||||
// The store records a failed request in store.error and resolves; surface it instead of an empty list.
|
||||
if (store.error) {
|
||||
error.value = store.error
|
||||
@@ -171,9 +223,17 @@ async function fetchVulnerablePackages() {
|
||||
}
|
||||
}
|
||||
|
||||
// A package passes when it has at least one vulnerability of any selected severity.
|
||||
const filteredPackages = computed(() => {
|
||||
if (!hasFilter.value) return vulnerablePackages.value
|
||||
return vulnerablePackages.value.filter((pkg) =>
|
||||
selectedSeverities.value.some((level) => (pkg.vulnerabilities?.counts?.[level] ?? 0) > 0),
|
||||
)
|
||||
})
|
||||
|
||||
// Sort packages by risk: Critical count DESC, High count DESC, Moderate count DESC, Low count DESC
|
||||
const sortedVulnerablePackages = computed(() => {
|
||||
return [...vulnerablePackages.value].sort((a, b) => {
|
||||
return [...filteredPackages.value].sort((a, b) => {
|
||||
const aVulns = a.vulnerabilities?.counts || { critical: 0, high: 0, moderate: 0, low: 0 }
|
||||
const bVulns = b.vulnerabilities?.counts || { critical: 0, high: 0, moderate: 0, low: 0 }
|
||||
|
||||
@@ -227,7 +287,18 @@ const groupedPackages = computed(() => {
|
||||
return Array.from(groups.values())
|
||||
})
|
||||
|
||||
// Calculate total counts across all packages
|
||||
// Packages holding at least one vulnerability of each severity, before any filter.
|
||||
const packageCounts = computed<VulnerabilityCounts>(() => {
|
||||
const counts = { ...NO_VULNERABILITIES }
|
||||
for (const pkg of vulnerablePackages.value) {
|
||||
for (const level of SEVERITY_LEVELS) {
|
||||
if ((pkg.vulnerabilities?.counts?.[level] ?? 0) > 0) counts[level]++
|
||||
}
|
||||
}
|
||||
return counts
|
||||
})
|
||||
|
||||
// Calculate total counts across all packages, before any filter
|
||||
const totalCounts = computed(() =>
|
||||
vulnerablePackages.value.reduce(
|
||||
(sum, pkg) => {
|
||||
|
||||
@@ -12,7 +12,7 @@ import Stats from './Stats.vue'
|
||||
import VulnerabilityBadge from './VulnerabilityBadge.vue'
|
||||
import { __resetRealtimeSingleton, useRealtimeStore } from '@/stores/realtime'
|
||||
import { usePackageStore } from '@/stores/packages'
|
||||
import { BYPASSES, PACKAGES, REGISTRIES, STATS, TIMESERIES, VULNERABILITY_REPORT } from '@/test/fixtures'
|
||||
import { BYPASSES, PACKAGES, REGISTRIES, STATS, TIMESERIES, TREND, VULNERABILITY_REPORT } from '@/test/fixtures'
|
||||
import { mountStrict } from '@/test/mountStrict'
|
||||
import { createTestRouter } from '@/test/router'
|
||||
|
||||
@@ -22,6 +22,7 @@ const API_KEY_STORAGE = 'admin_api_key'
|
||||
|
||||
function respond(url: string) {
|
||||
if (url.startsWith('/api/stats/timeseries')) return { data: TIMESERIES }
|
||||
if (url.startsWith('/api/stats/trend')) return { data: TREND }
|
||||
if (url.startsWith('/api/stats')) return { data: { stats: STATS, registries: REGISTRIES } }
|
||||
if (url.endsWith('/vulnerabilities')) return { data: VULNERABILITY_REPORT }
|
||||
if (url.startsWith('/api/admin/bypasses')) return { data: { bypasses: BYPASSES } }
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
import type { SeverityLevel } from '@/lib/severity'
|
||||
|
||||
export type TrendPeriod = '30day' | '90day' | '1year'
|
||||
|
||||
export const TREND_PERIODS: { value: TrendPeriod; label: string }[] = [
|
||||
{ value: '30day', label: '30 days' },
|
||||
{ value: '90day', label: '90 days' },
|
||||
{ value: '1year', label: '1 year' },
|
||||
]
|
||||
|
||||
export const DEFAULT_TREND_PERIOD: TrendPeriod = '30day'
|
||||
|
||||
/** One UTC day. A null count is unknown (no scan history yet), not zero. */
|
||||
export interface TrendPoint {
|
||||
date: string
|
||||
total_packages: number
|
||||
total_size: number
|
||||
vulnerable_packages: number | null
|
||||
critical: number | null
|
||||
high: number | null
|
||||
moderate: number | null
|
||||
low: number | null
|
||||
blocked: number | null
|
||||
}
|
||||
|
||||
export interface TrendResponse {
|
||||
period: TrendPeriod
|
||||
from: string
|
||||
to: string
|
||||
/** First day in the window with vulnerability data; null when the window has none. */
|
||||
vulnerability_history_start: string | null
|
||||
points: TrendPoint[]
|
||||
}
|
||||
|
||||
/** Chart tone of each severity line, from the LineChart tone set. */
|
||||
export const SEVERITY_LINE_TONES: Record<SeverityLevel, 'danger' | 'warning' | 'info' | 'muted'> = {
|
||||
critical: 'danger',
|
||||
high: 'warning',
|
||||
moderate: 'info',
|
||||
low: 'muted',
|
||||
}
|
||||
|
||||
/** "2026-11-23" as "23 Nov", read in UTC so the label never shifts a day with the viewer's zone. */
|
||||
export function formatTrendDate(iso: string, withYear = false): string {
|
||||
const date = new Date(`${iso}T00:00:00Z`)
|
||||
if (Number.isNaN(date.getTime())) return iso
|
||||
return date.toLocaleDateString('en-GB', {
|
||||
day: 'numeric',
|
||||
month: 'short',
|
||||
year: withYear ? 'numeric' : undefined,
|
||||
timeZone: 'UTC',
|
||||
})
|
||||
}
|
||||
|
||||
/** Chart values of one count; unknown days become NaN, which breaks the line instead of drawing zero. */
|
||||
export function trendValues(points: readonly TrendPoint[], key: keyof Omit<TrendPoint, 'date'>): number[] {
|
||||
return points.map((p) => p[key] ?? Number.NaN)
|
||||
}
|
||||
|
||||
/** True when some day in the window has no vulnerability data. */
|
||||
export function hasUnknownVulnerabilityDays(points: readonly TrendPoint[]): boolean {
|
||||
return points.some((p) => p.vulnerable_packages === null)
|
||||
}
|
||||
@@ -39,6 +39,21 @@ describe('package store paging', () => {
|
||||
])
|
||||
})
|
||||
|
||||
it('fetchPackages asks for the listed severities only, and for everything without them', async () => {
|
||||
vi.mocked(axios.get).mockResolvedValue({ data: { packages: [] } })
|
||||
const store = usePackageStore()
|
||||
|
||||
await store.fetchPackages()
|
||||
await store.fetchPackages({ severity: [] })
|
||||
await store.fetchPackages({ severity: ['critical', 'high'] })
|
||||
|
||||
expect(vi.mocked(axios.get).mock.calls.map((c) => c[0])).toEqual([
|
||||
'/api/packages',
|
||||
'/api/packages',
|
||||
'/api/packages?severity=critical,high',
|
||||
])
|
||||
})
|
||||
|
||||
it('keeps the server group count, and counts groups itself when the server sends none', async () => {
|
||||
const store = usePackageStore()
|
||||
vi.mocked(axios.get).mockResolvedValueOnce({ data: { packages: [pkg(1, '2026-01-01T00:00:00Z')], total_groups: 80 } })
|
||||
|
||||
@@ -95,11 +95,15 @@ export const usePackageStore = defineStore('packages', () => {
|
||||
}
|
||||
let pageRequest = 0
|
||||
|
||||
/** Every package, unpaginated. Only views that filter on scan results need it. */
|
||||
async function fetchPackages() {
|
||||
/**
|
||||
* Every package, unpaginated. Only views that filter on scan results need it.
|
||||
* `severity` keeps the packages whose latest scan has a vulnerability of any listed severity.
|
||||
*/
|
||||
async function fetchPackages(options: { severity?: readonly string[] } = {}) {
|
||||
begin()
|
||||
try {
|
||||
const response = await axios.get('/api/packages')
|
||||
const query = options.severity?.length ? `?severity=${options.severity.join(',')}` : ''
|
||||
const response = await axios.get(`/api/packages${query}`)
|
||||
// Only update packages if we got valid data
|
||||
if (response.data && Array.isArray(response.data.packages)) {
|
||||
packages.value = response.data.packages
|
||||
|
||||
@@ -53,6 +53,22 @@ describe('useRealtimeStore', () => {
|
||||
expect(store.lastStats).toMatchObject({ total_packages: 42, total_size: 1024 })
|
||||
})
|
||||
|
||||
it('unwraps the server stats_update shape {stats, timestamp}', () => {
|
||||
const store = useRealtimeStore()
|
||||
store.ingest(
|
||||
makeEvent('stats_update', {
|
||||
stats: { total_packages: 1454, total_size: 980870617, total_downloads: 5376, scanned_packages: 1451 },
|
||||
timestamp: '2026-11-23T16:00:00Z',
|
||||
}),
|
||||
)
|
||||
expect(store.lastStats).toMatchObject({
|
||||
total_packages: 1454,
|
||||
total_size: 980870617,
|
||||
total_downloads: 5376,
|
||||
scanned_packages: 1451,
|
||||
})
|
||||
})
|
||||
|
||||
it('exposes filtered computed slices', () => {
|
||||
const store = useRealtimeStore()
|
||||
store.ingest(makeEvent('package_cached'))
|
||||
|
||||
@@ -55,7 +55,9 @@ export const useRealtimeStore = defineStore('realtime', () => {
|
||||
events.value.splice(0, events.value.length - EVENTS_CAP)
|
||||
}
|
||||
if (event.type === 'stats_update') {
|
||||
lastStats.value = event.payload as RealtimeStats
|
||||
// The server nests the counters under `stats`; reading the payload flat shows zeros.
|
||||
const nested = event.payload.stats
|
||||
lastStats.value = (nested && typeof nested === 'object' ? nested : event.payload) as RealtimeStats
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/DataTable/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/DescriptionList/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/KpiTile/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/LineChart/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/Sparkline/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/StatGroup/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/Table/*.js";
|
||||
@@ -59,6 +60,8 @@
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/primitives/Spinner/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/primitives/StatusBadge/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/primitives/StatusDot/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/primitives/Toggle/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/primitives/ToggleGroup/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/typography/Markdown/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/typography/Markdown/parse/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/typography/RelativeTime/*.js";
|
||||
|
||||
@@ -158,3 +158,19 @@ export const BYPASSES = [
|
||||
active: false,
|
||||
},
|
||||
]
|
||||
|
||||
function trendDay(offset: number): string {
|
||||
return new Date(Date.UTC(2026, 0, 4 + offset)).toISOString().slice(0, 10)
|
||||
}
|
||||
|
||||
export const TREND = {
|
||||
period: '30day',
|
||||
from: trendDay(-2),
|
||||
to: trendDay(0),
|
||||
vulnerability_history_start: trendDay(-1),
|
||||
points: [
|
||||
{ date: trendDay(-2), total_packages: 3, total_size: 3072, vulnerable_packages: null, critical: null, high: null, moderate: null, low: null, blocked: null },
|
||||
{ date: trendDay(-1), total_packages: 4, total_size: 7168, vulnerable_packages: 1, critical: 0, high: 1, moderate: 0, low: 0, blocked: null },
|
||||
{ date: trendDay(0), total_packages: 4, total_size: 7168, vulnerable_packages: 2, critical: 1, high: 1, moderate: 0, low: 0, blocked: 1 },
|
||||
],
|
||||
}
|
||||
|
||||
@@ -76,6 +76,7 @@ data:
|
||||
default_ttl: {{ .Values.cache.defaultTTL | quote }}
|
||||
cleanup_interval: {{ .Values.cache.cleanupInterval | quote }}
|
||||
idle_ttl: {{ .Values.cache.idleTTL | quote }}
|
||||
deleted_retention: {{ .Values.cache.deletedRetention | default "720h" | quote }}
|
||||
max_size_bytes: {{ .Values.cache.maxSizeBytes }}
|
||||
per_project_quota: {{ .Values.cache.perProjectQuota }}
|
||||
ttl_overrides:
|
||||
|
||||
@@ -381,6 +381,7 @@ cache:
|
||||
defaultTTL: "24h" # Freshness window for metadata pages; keep below the 72h client release-age gate
|
||||
cleanupInterval: "1h"
|
||||
idleTTL: "168h" # Remove cached items not requested for this long; "0" disables
|
||||
deletedRetention: "720h" # Purge deleted package rows after this long; "0" keeps them forever
|
||||
maxSizeBytes: 536870912000 # 500GB
|
||||
perProjectQuota: 53687091200 # 50GB
|
||||
ttlOverrides: # Per-registry metadata freshness; replaces defaultTTL for that registry. Keys: npm, pypi, go
|
||||
|
||||
@@ -6,6 +6,10 @@ import Mathlib
|
||||
Models `pkg/metadata/gormstore/aggregation_worker.go` (`AggregateHourly`, `AggregateDaily`) and
|
||||
`pkg/metadata/gormstore/gormstore_v2.go` `GetTimeSeriesStats`. Time is in whole minutes since the
|
||||
epoch; an hour is 60 minutes and a day 24 hours. Omits: unique IPs, packages, registries.
|
||||
|
||||
The last three sections model the trend snapshots and backfill in `pkg/metadata/gormstore/snapshots.go`,
|
||||
the soft-delete purge in `pkg/metadata/gormstore/purge.go` and `pkg/cache/cache.go` `purgeDeleted`,
|
||||
and the severity filter in `pkg/metadata/gormstore/dashboard.go`.
|
||||
-/
|
||||
|
||||
namespace Gohoarder.Stats
|
||||
@@ -107,4 +111,112 @@ theorem fixed_sqlite_registry_row_idempotent (old new : ℕ) :
|
||||
theorem fixed_sqlite_package_row_keeps_late_events (old new : ℕ) :
|
||||
chartTotal (upsertAdditive old new) = old + new := by simp [chartTotal, upsertAdditive]
|
||||
|
||||
/-! ### Daily snapshots and backfill (`snapshots.go`) -/
|
||||
|
||||
/-- Minutes in a UTC day. -/
|
||||
def dayLen : ℕ := 1440
|
||||
|
||||
/-- `stateAtDayEnd`: a package cached at `cached` and deleted at `x` (`none` = still cached) counts in
|
||||
the snapshot of day `d` iff it was cached before the day ended and not deleted before it ended. -/
|
||||
def aliveAtEnd (cached : ℕ) (deleted : Option ℕ) (d : ℕ) : Prop :=
|
||||
cached < dayLen * (d + 1) ∧ ∀ x, deleted = some x → dayLen * (d + 1) ≤ x
|
||||
|
||||
/-- A package cached and deleted inside one day is in no snapshot. -/
|
||||
theorem same_day_package_never_counted (cached x d : ℕ) (hx : x < dayLen * (d + 1)) :
|
||||
¬ aliveAtEnd cached (some x) d := by
|
||||
rintro ⟨_, h⟩
|
||||
exact absurd (h x rfl) (by omega)
|
||||
|
||||
theorem undeleted_package_counts_from_its_day (cached d : ℕ) :
|
||||
aliveAtEnd cached none d ↔ cached < dayLen * (d + 1) := by
|
||||
simp [aliveAtEnd]
|
||||
|
||||
/-- The backfill adds only each day's change to a running total (`deltas`, then the cumulative loop). -/
|
||||
def delta (s : ℕ → ℤ) (d : ℕ) : ℤ := s d - (if d = 0 then 0 else s (d - 1))
|
||||
|
||||
/-- The running total of the daily changes equals the end-of-day state: the sweep loses nothing. -/
|
||||
theorem sweep_telescopes (s : ℕ → ℤ) (n : ℕ) :
|
||||
∑ d ∈ Finset.range (n + 1), delta s d = s n := by
|
||||
induction n with
|
||||
| zero => simp [delta]
|
||||
| succ n ih =>
|
||||
rw [Finset.sum_range_succ, ih]
|
||||
simp [delta]
|
||||
|
||||
/-- One snapshot row per day, `none` = no row. `upsertSnapshot` (`SnapshotStats`) replaces the day's row. -/
|
||||
def upsertSnapshot (rows : ℕ → Option ℕ) (day v : ℕ) : ℕ → Option ℕ := Function.update rows day (some v)
|
||||
|
||||
/-- Running the snapshot twice in a day leaves the last write only. -/
|
||||
theorem snapshot_last_write_wins (rows : ℕ → Option ℕ) (day a b : ℕ) :
|
||||
upsertSnapshot (upsertSnapshot rows day a) day b = upsertSnapshot rows day b :=
|
||||
Function.update_idem _ _ _
|
||||
|
||||
theorem snapshot_leaves_other_days (rows : ℕ → Option ℕ) (day other v : ℕ) (h : other ≠ day) :
|
||||
upsertSnapshot rows day v other = rows other :=
|
||||
Function.update_of_ne h _ _
|
||||
|
||||
/-- The backfill insert (`ON CONFLICT DO NOTHING`) never replaces an existing row. -/
|
||||
def insertMissing (rows : ℕ → Option ℕ) (day v : ℕ) : ℕ → Option ℕ :=
|
||||
fun d => if d = day then (rows d).or (some v) else rows d
|
||||
|
||||
theorem backfill_keeps_existing (rows : ℕ → Option ℕ) (day a v : ℕ) (h : rows day = some a) :
|
||||
insertMissing rows day v day = some a := by
|
||||
simp [insertMissing, h]
|
||||
|
||||
/-- The backfill runs only while no past-day snapshot exists, so it cannot rewrite history. -/
|
||||
def backfillRuns (pastRows : ℕ) : Bool := pastRows == 0
|
||||
|
||||
theorem backfill_idle_once_history_exists (n : ℕ) : backfillRuns (n + 1) = false := by
|
||||
simp [backfillRuns]
|
||||
|
||||
/-! ### Soft-delete purge (`purge.go`, `cache.go` `purgeDeleted`) -/
|
||||
|
||||
/-- Cutoff = now - retention; a row is purged iff it was deleted before the cutoff. A row that is
|
||||
not deleted (`none`) is never purged. -/
|
||||
def purgeable (now retention : ℕ) (deleted : Option ℕ) : Prop :=
|
||||
∃ x, deleted = some x ∧ x + retention < now
|
||||
|
||||
theorem active_row_never_purged (now retention : ℕ) : ¬ purgeable now retention none := by
|
||||
rintro ⟨x, h, _⟩
|
||||
cases h
|
||||
|
||||
theorem recent_delete_kept (now retention x : ℕ) (h : now ≤ x + retention) :
|
||||
¬ purgeable now retention (some x) := by
|
||||
rintro ⟨y, hy, hlt⟩
|
||||
cases hy
|
||||
omega
|
||||
|
||||
/-- The purge touches package rows only; the snapshot rows come out as they went in. -/
|
||||
def purgeStep {P : Type} (pkgs : List P) (keep : P → Bool) (snaps : ℕ → Option ℕ) :
|
||||
List P × (ℕ → Option ℕ) := (pkgs.filter keep, snaps)
|
||||
|
||||
theorem purge_keeps_snapshots {P : Type} (pkgs : List P) (keep : P → Bool) (snaps : ℕ → Option ℕ) :
|
||||
(purgeStep pkgs keep snaps).2 = snaps := rfl
|
||||
|
||||
/-- One pass purges at most `maxPurgeBatches` batches of `limit` rows. -/
|
||||
def maxPurgeBatches : ℕ := 100
|
||||
|
||||
theorem purge_pass_bounded (batches limit : ℕ) (h : batches ≤ maxPurgeBatches) :
|
||||
batches * limit ≤ maxPurgeBatches * limit :=
|
||||
Nat.mul_le_mul_right limit h
|
||||
|
||||
/-! ### Severity filter (`dashboard.go` `severityFilter`, `latestScanWith`) -/
|
||||
|
||||
/-- A package passes when no severity is selected, or its latest scan counts one of them. -/
|
||||
def passes (selected : List ℕ) (counts : ℕ → ℕ) : Prop := selected = [] ∨ ∃ s ∈ selected, 0 < counts s
|
||||
|
||||
/-- OR semantics: selecting one more severity never hides a package. -/
|
||||
theorem passes_monotone (sel sel' : List ℕ) (counts : ℕ → ℕ) (h : ∀ s ∈ sel, s ∈ sel')
|
||||
(hne : sel ≠ []) (hp : passes sel counts) : passes sel' counts := by
|
||||
right
|
||||
rcases hp with hp | ⟨s, hs, hc⟩
|
||||
· exact absurd hp hne
|
||||
· exact ⟨s, h s hs, hc⟩
|
||||
|
||||
/-- A package with no finding of any selected severity is filtered out. -/
|
||||
theorem clean_package_filtered (sel : List ℕ) (hne : sel ≠ []) : ¬ passes sel (fun _ => 0) := by
|
||||
rintro (h | ⟨s, _, hc⟩)
|
||||
· exact hne h
|
||||
· exact absurd hc (by simp)
|
||||
|
||||
end Gohoarder.Stats
|
||||
|
||||
+13
-6
@@ -215,6 +215,10 @@ func (a *App) initializeComponents() error {
|
||||
return fmt.Errorf("failed to initialize scanner: %w", err)
|
||||
}
|
||||
|
||||
if setter, ok := a.metadata.(blockedCounterSetter); ok {
|
||||
setter.SetBlockedCounter(a.countBlocked)
|
||||
}
|
||||
|
||||
// Initialize analytics engine first (needed by cache)
|
||||
log.Info().Msg("Initializing analytics engine")
|
||||
a.analyticsEngine = analytics.NewEngine(analytics.Config{
|
||||
@@ -231,12 +235,13 @@ func (a *App) initializeComponents() error {
|
||||
cleanupInterval = 5 * time.Minute
|
||||
}
|
||||
a.cache, err = cache.New(a.storage, a.metadata, a.scanManager, a.analyticsEngine, cache.Config{
|
||||
DefaultTTL: a.config.Cache.DefaultTTL,
|
||||
TTLOverrides: a.config.Cache.MetadataTTLOverrides(),
|
||||
CleanupInterval: cleanupInterval,
|
||||
IdleTTL: a.config.Cache.IdleTTL,
|
||||
MaxPackageSize: a.config.Security.Scanners.Static.MaxPackageSize,
|
||||
FailClosed: a.config.Security.FailClosed,
|
||||
DefaultTTL: a.config.Cache.DefaultTTL,
|
||||
TTLOverrides: a.config.Cache.MetadataTTLOverrides(),
|
||||
CleanupInterval: cleanupInterval,
|
||||
IdleTTL: a.config.Cache.IdleTTL,
|
||||
DeletedRetention: a.config.Cache.DeletedRetention,
|
||||
MaxPackageSize: a.config.Security.Scanners.Static.MaxPackageSize,
|
||||
FailClosed: a.config.Security.FailClosed,
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to initialize cache: %w", err)
|
||||
@@ -446,6 +451,7 @@ func (a *App) setupServer() error {
|
||||
a.app.All("/api/packages/*", mwAuth, a.handlePackages) // OPTIONS, preflight, vulnerabilities
|
||||
a.app.Get("/api/stats", mwAuth, a.handleStats)
|
||||
a.app.Get("/api/stats/timeseries", mwAuth, a.handleTimeSeriesStats)
|
||||
a.app.Get("/api/stats/trend", mwAuth, a.handleStatsTrend)
|
||||
a.app.Get("/api/info", mwAuth, a.handleInfo)
|
||||
|
||||
a.app.Get("/api/analytics/top", mwAuth, a.handleAnalyticsTopPackages)
|
||||
@@ -460,6 +466,7 @@ func (a *App) setupServer() error {
|
||||
a.app.All("/api/packages/*", a.handlePackages)
|
||||
a.app.Get("/api/stats", a.handleStats)
|
||||
a.app.Get("/api/stats/timeseries", a.handleTimeSeriesStats)
|
||||
a.app.Get("/api/stats/trend", a.handleStatsTrend)
|
||||
a.app.Get("/api/info", a.handleInfo)
|
||||
|
||||
a.app.Get("/api/analytics/top", a.handleAnalyticsTopPackages)
|
||||
|
||||
+34
-16
@@ -3,6 +3,8 @@ package app
|
||||
import (
|
||||
"context"
|
||||
stderrors "errors"
|
||||
"fmt"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -69,9 +71,25 @@ type listParams struct {
|
||||
paged bool
|
||||
}
|
||||
|
||||
// parseListParams reads page, page_size, registry, q, sort and order. Without
|
||||
// page or page_size the list is unpaginated, as it was before paging existed.
|
||||
func parseListParams(c fiber.Ctx) listParams {
|
||||
// parseSeverities reads a comma-separated severity filter such as "critical,high".
|
||||
func parseSeverities(raw string) ([]string, error) {
|
||||
var out []string
|
||||
for _, part := range strings.Split(raw, ",") {
|
||||
sev := strings.ToLower(strings.TrimSpace(part))
|
||||
if sev == "" || slices.Contains(out, sev) {
|
||||
continue
|
||||
}
|
||||
if !slices.Contains(metadata.Severities, sev) {
|
||||
return nil, fmt.Errorf("invalid severity %q, must be one of: %s", sev, strings.Join(metadata.Severities, ", "))
|
||||
}
|
||||
out = append(out, sev)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// parseListParams reads page, page_size, registry, q, sort, order and severity.
|
||||
// Without page or page_size the list is unpaginated, as it was before paging existed.
|
||||
func parseListParams(c fiber.Ctx) (listParams, error) {
|
||||
p := listParams{opts: metadata.GroupListOptions{
|
||||
Registry: c.Query("registry"),
|
||||
Query: c.Query("q"),
|
||||
@@ -88,6 +106,11 @@ func parseListParams(c fiber.Ctx) listParams {
|
||||
case "desc":
|
||||
p.opts.SortDesc = true
|
||||
}
|
||||
severities, err := parseSeverities(c.Query("severity"))
|
||||
if err != nil {
|
||||
return p, err
|
||||
}
|
||||
p.opts.Severities = severities
|
||||
if c.Query("page") != "" || c.Query("page_size") != "" {
|
||||
p.paged = true
|
||||
p.opts.Page = max(fiber.Query[int](c, "page", 1), 1)
|
||||
@@ -97,7 +120,7 @@ func parseListParams(c fiber.Ctx) listParams {
|
||||
}
|
||||
p.opts.PageSize = min(p.opts.PageSize, maxPageSize)
|
||||
}
|
||||
return p
|
||||
return p, nil
|
||||
}
|
||||
|
||||
// scanDecisions judges scanned packages, falling back to plain summaries without a scan manager.
|
||||
@@ -145,7 +168,10 @@ func vulnerabilityInfo(pkg *metadata.Package, decisions map[string]scanner.ScanD
|
||||
// page_size is given and every group otherwise.
|
||||
func (a *App) handleListPackages(c fiber.Ctx) error {
|
||||
ctx := c.Context()
|
||||
params := parseListParams(c)
|
||||
params, err := parseListParams(c)
|
||||
if err != nil {
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": err.Error()})
|
||||
}
|
||||
|
||||
page, err := a.metadata.ListPackageGroups(ctx, params.opts)
|
||||
if err != nil {
|
||||
@@ -365,17 +391,9 @@ func (a *App) handleStats(c fiber.Ctx) error {
|
||||
}
|
||||
|
||||
// Blocked packages need the blocking policy, so judge every scanned package in one batch.
|
||||
blockedCount := int64(0)
|
||||
if a.config.Security.Enabled && a.scanManager != nil {
|
||||
decisions, err := a.scanManager.ScanDecisions(ctx, nil)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Failed to judge scanned packages")
|
||||
}
|
||||
for _, d := range decisions {
|
||||
if d.Blocked && !metadata.IsMetadataVersion(d.Summary.Version) {
|
||||
blockedCount++
|
||||
}
|
||||
}
|
||||
blockedCount, err := a.countBlocked(ctx)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Failed to judge scanned packages")
|
||||
}
|
||||
|
||||
// Combine statistics using database stats for accuracy
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
// trendPeriods maps the period query value of /api/stats/trend to days of history.
|
||||
var trendPeriods = map[string]int{"30day": 30, "90day": 90, "1year": 365}
|
||||
|
||||
const defaultTrendPeriod = "30day"
|
||||
|
||||
// handleStatsTrend returns one snapshot per day for the period, oldest first.
|
||||
// Vulnerability fields are null for days before vulnerability history starts.
|
||||
func (a *App) handleStatsTrend(c fiber.Ctx) error {
|
||||
period := c.Query("period", defaultTrendPeriod)
|
||||
days, ok := trendPeriods[period]
|
||||
if !ok {
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"error": "invalid period, must be one of: 30day, 90day, 1year",
|
||||
})
|
||||
}
|
||||
|
||||
today := time.Now().UTC().Truncate(24 * time.Hour)
|
||||
from := today.AddDate(0, 0, -(days - 1))
|
||||
points, err := a.metadata.GetStatsTrend(c.Context(), from)
|
||||
if err != nil && !errors.Is(err, metadata.ErrNotImplemented) {
|
||||
log.Error().Err(err).Str("period", period).Msg("Failed to get stats trend")
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": "failed to get stats trend"})
|
||||
}
|
||||
if points == nil {
|
||||
points = []*metadata.StatsSnapshot{}
|
||||
}
|
||||
|
||||
var vulnStart *string
|
||||
for _, p := range points {
|
||||
if p.VulnerablePackages != nil {
|
||||
vulnStart = &p.Date
|
||||
break
|
||||
}
|
||||
}
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"period": period,
|
||||
"from": from.Format(metadata.StatsSnapshotDateLayout),
|
||||
"to": today.Format(metadata.StatsSnapshotDateLayout),
|
||||
"vulnerability_history_start": vulnStart,
|
||||
"points": points,
|
||||
})
|
||||
}
|
||||
|
||||
// countBlocked counts scanned artifacts the blocking policy refuses.
|
||||
func (a *App) countBlocked(ctx context.Context) (int64, error) {
|
||||
if !a.config.Security.Enabled || a.scanManager == nil {
|
||||
return 0, nil
|
||||
}
|
||||
decisions, err := a.scanManager.ScanDecisions(ctx, nil)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
var blocked int64
|
||||
for _, d := range decisions {
|
||||
if d.Blocked && !metadata.IsMetadataVersion(d.Summary.Version) {
|
||||
blocked++
|
||||
}
|
||||
}
|
||||
return blocked, nil
|
||||
}
|
||||
|
||||
// blockedCounterSetter is implemented by stores that snapshot blocked packages.
|
||||
type blockedCounterSetter interface {
|
||||
SetBlockedCounter(func(context.Context) (int64, error))
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
@@ -42,14 +43,14 @@ func (a *App) handleVulnerabilities(c fiber.Ctx) error {
|
||||
Str("version", version).
|
||||
Msg("Getting vulnerabilities for package")
|
||||
|
||||
pkg, pkgErr := a.metadata.GetPackage(ctx, registry, name, version)
|
||||
key, pkg, pkgErr := a.resolvePackageKey(ctx, registry, name, version)
|
||||
releaseVersion := ""
|
||||
if pkgErr == nil && pkg != nil {
|
||||
releaseVersion = pkg.ReleaseVersion
|
||||
}
|
||||
|
||||
// Get scan result from metadata store
|
||||
scanResult, err := a.metadata.GetScanResult(ctx, registry, name, version)
|
||||
scanResult, err := a.metadata.GetScanResult(ctx, registry, key, version)
|
||||
if err != nil {
|
||||
if pkgErr != nil {
|
||||
return c.Status(fiber.StatusNotFound).JSON(fiber.Map{"error": "package not found"})
|
||||
@@ -169,3 +170,23 @@ func (a *App) handleVulnerabilities(c fiber.Ctx) error {
|
||||
|
||||
return c.Status(fiber.StatusOK).JSON(response)
|
||||
}
|
||||
|
||||
// goCacheKeyExts orders the Go cache files a module version is stored under; the
|
||||
// .zip carries the scan result.
|
||||
var goCacheKeyExts = []string{"zip", "mod", "info"}
|
||||
|
||||
// resolvePackageKey maps the name the dashboard shows to the stored row name.
|
||||
// Go rows are stored under cache keys (module/@v/version.ext), not the module path.
|
||||
func (a *App) resolvePackageKey(ctx context.Context, registry, name, version string) (string, *metadata.Package, error) {
|
||||
pkg, err := a.metadata.GetPackage(ctx, registry, name, version)
|
||||
if err == nil || registry != "go" || strings.Contains(name, "/@v/") {
|
||||
return name, pkg, err
|
||||
}
|
||||
for _, ext := range goCacheKeyExts {
|
||||
key := name + "/@v/" + version + "." + ext
|
||||
if p, kerr := a.metadata.GetPackage(ctx, registry, key, version); kerr == nil {
|
||||
return key, p, nil
|
||||
}
|
||||
}
|
||||
return name, nil, err
|
||||
}
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestSeverityFilterOnPackagesList(t *testing.T) {
|
||||
a, _ := newScanningApp(t)
|
||||
seedScanned(t, a, 0, 60) // every fifth package carries one critical finding
|
||||
|
||||
cases := []struct {
|
||||
query string
|
||||
want int
|
||||
}{
|
||||
{"", 60},
|
||||
{"?severity=", 60},
|
||||
{"?severity=critical", 12},
|
||||
{"?severity=Critical,high", 12},
|
||||
{"?severity=high", 0},
|
||||
{"?severity=high,moderate,low", 0},
|
||||
{"?severity=critical&q=pkg-005", 1},
|
||||
{"?severity=critical&q=pkg-006", 0},
|
||||
}
|
||||
for _, c := range cases {
|
||||
if got := getList(t, a, "/api/packages"+c.query); len(got.Packages) != c.want {
|
||||
t.Errorf("%q returned %d packages, want %d", c.query, len(got.Packages), c.want)
|
||||
}
|
||||
}
|
||||
|
||||
paged := getList(t, a, "/api/packages?severity=critical&page=1&page_size=5")
|
||||
if paged.TotalGroups != 12 || len(paged.Packages) != 5 {
|
||||
t.Errorf("paged severity list = %d groups, %d rows; want 12 groups, 5 rows", paged.TotalGroups, len(paged.Packages))
|
||||
}
|
||||
for _, p := range getList(t, a, "/api/packages?severity=critical").Packages {
|
||||
if p.Vulnerabilities.Counts.Critical == 0 {
|
||||
t.Errorf("%s has no critical finding but passed the critical filter", p.Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSeverityFilterRejectsUnknownValue(t *testing.T) {
|
||||
a, _ := newScanningApp(t)
|
||||
for _, q := range []string{"?severity=urgent", "?severity=critical,nope"} {
|
||||
if code, _, body := doRequest(t, a, "/api/packages"+q, nil); code != http.StatusBadRequest {
|
||||
t.Errorf("%q = %d %s, want 400", q, code, body)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata/gormstore"
|
||||
)
|
||||
|
||||
type trendResponse struct {
|
||||
VulnerabilityHistoryStart *string `json:"vulnerability_history_start"`
|
||||
Period string `json:"period"`
|
||||
From string `json:"from"`
|
||||
To string `json:"to"`
|
||||
Points []struct {
|
||||
VulnerablePackages *int64 `json:"vulnerable_packages"`
|
||||
Blocked *int64 `json:"blocked"`
|
||||
Date string `json:"date"`
|
||||
TotalPackages int64 `json:"total_packages"`
|
||||
} `json:"points"`
|
||||
}
|
||||
|
||||
func trendDay(daysAgo int) string {
|
||||
return time.Now().UTC().AddDate(0, 0, -daysAgo).Format("2006-01-02")
|
||||
}
|
||||
|
||||
func getTrend(t *testing.T, a *App, target string) trendResponse {
|
||||
t.Helper()
|
||||
code, _, body := doRequest(t, a, target, nil)
|
||||
if code != http.StatusOK {
|
||||
t.Fatalf("GET %s = %d %s", target, code, body)
|
||||
}
|
||||
var out trendResponse
|
||||
if err := json.Unmarshal([]byte(body), &out); err != nil {
|
||||
t.Fatalf("decode %s: %v", body, err)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func TestSeverityAndTrendQueryCountIsConstant(t *testing.T) {
|
||||
a, counter := newScanningApp(t)
|
||||
targets := []string{
|
||||
"/api/packages?severity=critical,high",
|
||||
"/api/packages?severity=low&page=1&page_size=25",
|
||||
"/api/stats/trend?period=90day",
|
||||
}
|
||||
seedScanned(t, a, 0, 20)
|
||||
small := map[string]int{}
|
||||
for _, target := range targets {
|
||||
small[target] = queriesFor(t, a, counter, target)
|
||||
}
|
||||
seedScanned(t, a, 20, 100)
|
||||
for _, target := range targets {
|
||||
large := queriesFor(t, a, counter, target)
|
||||
t.Logf("%-50s 20 rows: %2d queries, 120 rows: %2d queries", target, small[target], large)
|
||||
if large != small[target] {
|
||||
t.Errorf("%s: %d queries for 20 rows but %d for 120 rows", target, small[target], large)
|
||||
}
|
||||
}
|
||||
if n := small["/api/stats/trend?period=90day"]; n != 1 {
|
||||
t.Errorf("trend costs %d statements, want 1", n)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStatsTrendEndpoint(t *testing.T) {
|
||||
a := newTestApp(t, nil)
|
||||
|
||||
empty := getTrend(t, a, "/api/stats/trend")
|
||||
if empty.Period != "30day" || empty.Points == nil || len(empty.Points) != 0 || empty.VulnerabilityHistoryStart != nil {
|
||||
t.Fatalf("empty trend = %+v, want the default period, no points and no vulnerability start", empty)
|
||||
}
|
||||
|
||||
store := a.metadata.(*gormstore.GORMStoreV2)
|
||||
one, two := int64(1), int64(2)
|
||||
for _, row := range []gormstore.StatsSnapshotModel{
|
||||
{Day: trendDay(100), TotalPackages: 5},
|
||||
{Day: trendDay(40), TotalPackages: 6},
|
||||
{Day: trendDay(2), TotalPackages: 7},
|
||||
{Day: trendDay(1), TotalPackages: 8, VulnerablePackages: &two, Blocked: &one},
|
||||
} {
|
||||
if err := store.DB().Create(&row).Error; err != nil {
|
||||
t.Fatalf("seed snapshot: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
cases := []struct {
|
||||
target string
|
||||
period string
|
||||
points int
|
||||
}{
|
||||
{"/api/stats/trend", "30day", 2},
|
||||
{"/api/stats/trend?period=30day", "30day", 2},
|
||||
{"/api/stats/trend?period=90day", "90day", 3},
|
||||
{"/api/stats/trend?period=1year", "1year", 4},
|
||||
}
|
||||
for _, c := range cases {
|
||||
got := getTrend(t, a, c.target)
|
||||
if got.Period != c.period || len(got.Points) != c.points {
|
||||
t.Errorf("%s = period %q, %d points; want %q, %d", c.target, got.Period, len(got.Points), c.period, c.points)
|
||||
}
|
||||
}
|
||||
|
||||
got := getTrend(t, a, "/api/stats/trend")
|
||||
if got.To != trendDay(0) || got.From != trendDay(29) {
|
||||
t.Errorf("window = %s..%s, want %s..%s", got.From, got.To, trendDay(29), trendDay(0))
|
||||
}
|
||||
if got.Points[0].Date != trendDay(2) || got.Points[1].Date != trendDay(1) {
|
||||
t.Errorf("points not oldest first: %+v", got.Points)
|
||||
}
|
||||
if got.Points[0].VulnerablePackages != nil || got.Points[0].Blocked != nil {
|
||||
t.Errorf("a day without vulnerability data must carry null, got %+v", got.Points[0])
|
||||
}
|
||||
if v := got.Points[1].VulnerablePackages; v == nil || *v != 2 {
|
||||
t.Errorf("vulnerable_packages = %v, want 2", v)
|
||||
}
|
||||
if got.VulnerabilityHistoryStart == nil || *got.VulnerabilityHistoryStart != trendDay(1) {
|
||||
t.Errorf("vulnerability_history_start = %v, want %s", got.VulnerabilityHistoryStart, trendDay(1))
|
||||
}
|
||||
}
|
||||
|
||||
func TestStatsTrendRejectsUnknownPeriod(t *testing.T) {
|
||||
a := newTestApp(t, nil)
|
||||
for _, p := range []string{"7day", "1day", "bogus", "1YEAR"} {
|
||||
if code, _, body := doRequest(t, a, "/api/stats/trend?period="+p, nil); code != http.StatusBadRequest {
|
||||
t.Errorf("period=%s = %d %s, want 400", p, code, body)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
)
|
||||
|
||||
// The list shows Go modules by module path, but rows are stored under cache keys.
|
||||
func TestGoVulnerabilityDetailsResolveCacheKeyNames(t *testing.T) {
|
||||
a := newTestApp(t, nil)
|
||||
ctx := context.Background()
|
||||
const module, version = "github.com/go-git/go-git/v5", "v5.3.0"
|
||||
for _, ext := range []string{"info", "mod", "zip"} {
|
||||
name := module + "/@v/" + version + "." + ext
|
||||
err := a.metadata.SavePackage(ctx, &metadata.Package{
|
||||
Registry: "go", Name: name, Version: version, StorageKey: "go/" + name,
|
||||
Size: 10, CachedAt: time.Now(), LastAccessed: time.Now(),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("SavePackage %s: %v", name, err)
|
||||
}
|
||||
}
|
||||
err := a.metadata.SaveScanResult(ctx, &metadata.ScanResult{
|
||||
Registry: "go", PackageName: module + "/@v/" + version + ".zip", PackageVersion: version,
|
||||
Scanner: "osv", Status: metadata.ScanStatusVulnerable, ScannedAt: time.Now(),
|
||||
Vulnerabilities: []metadata.Vulnerability{{ID: "GHSA-test", Severity: "critical"}},
|
||||
VulnerabilityCount: 1,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("SaveScanResult: %v", err)
|
||||
}
|
||||
|
||||
code, _, body := doRequest(t, a, "/api/packages/go/"+module+"/"+version+"/vulnerabilities", nil)
|
||||
if code != http.StatusOK {
|
||||
t.Fatalf("GET details = %d %s, want 200", code, body)
|
||||
}
|
||||
var out struct {
|
||||
Scanned bool `json:"scanned"`
|
||||
Count int `json:"vulnerability_count"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(body), &out); err != nil {
|
||||
t.Fatalf("decode %q: %v", body, err)
|
||||
}
|
||||
if !out.Scanned || out.Count != 1 {
|
||||
t.Errorf("details = %s, want the .zip scan with 1 vulnerability", body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGoVulnerabilityDetailsMissingModuleIs404(t *testing.T) {
|
||||
a := newTestApp(t, nil)
|
||||
code, _, body := doRequest(t, a, "/api/packages/go/example.com/nope/v1.0.0/vulnerabilities", nil)
|
||||
if code != http.StatusNotFound {
|
||||
t.Errorf("GET missing = %d %s, want 404", code, body)
|
||||
}
|
||||
}
|
||||
@@ -165,6 +165,12 @@ func (f *fakeStore) ListExpiredPackages(context.Context, time.Time, int) ([]*met
|
||||
func (f *fakeStore) ClearArtifactExpiry(context.Context) (int64, error) {
|
||||
return 0, metadata.ErrNotImplemented
|
||||
}
|
||||
func (f *fakeStore) PurgeDeletedPackages(context.Context, time.Time, int) (int64, error) {
|
||||
return 0, metadata.ErrNotImplemented
|
||||
}
|
||||
func (f *fakeStore) GetStatsTrend(context.Context, time.Time) ([]*metadata.StatsSnapshot, error) {
|
||||
return nil, metadata.ErrNotImplemented
|
||||
}
|
||||
func (f *fakeStore) Close() error { return nil }
|
||||
|
||||
// fastCfg uses bcrypt.MinCost so tests that hash multiple keys stay snappy.
|
||||
|
||||
Vendored
+30
@@ -85,6 +85,7 @@ type Config struct {
|
||||
DefaultTTL time.Duration // Freshness TTL for metadata entries
|
||||
CleanupInterval time.Duration // How often to run cleanup
|
||||
IdleTTL time.Duration // Remove entries not requested for this long (0 = off)
|
||||
DeletedRetention time.Duration // Hard-delete soft-deleted rows older than this (0 = keep forever)
|
||||
EvictionThreshold float64 // Trigger eviction when usage > threshold (0.0-1.0)
|
||||
MaxConcurrent int // Max concurrent upstream fetches
|
||||
MaxPackageSize int64 // Maximum package size in bytes (0 = default 2GB)
|
||||
@@ -97,6 +98,9 @@ const defaultScanWaitTimeout = 30 * time.Second
|
||||
// cleanupBatchSize bounds how many rows one cleanup query reads.
|
||||
const cleanupBatchSize = metadata.DefaultBatchSize
|
||||
|
||||
// maxPurgeBatches bounds the soft-delete purge of one cleanup pass; the next pass continues.
|
||||
const maxPurgeBatches = 100
|
||||
|
||||
// getAttempts bounds how often Get re-resolves an entry whose blob vanished.
|
||||
const getAttempts = 2
|
||||
|
||||
@@ -917,14 +921,40 @@ func (m *Manager) cleanup(ctx context.Context) {
|
||||
func(p *metadata.Package) bool { return p.LastAccessed.Before(cutoff) })
|
||||
}
|
||||
|
||||
purged := m.purgeDeleted(ctx, start)
|
||||
|
||||
log.Info().
|
||||
Int("expired", expired.count).
|
||||
Int("idle", idle.count).
|
||||
Int64("bytes_freed", expired.bytes+idle.bytes).
|
||||
Dur("idle_ttl", m.config.IdleTTL).
|
||||
Int64("purged_deleted", purged).
|
||||
Dur("deleted_retention", m.config.DeletedRetention).
|
||||
Msg("Cleanup completed")
|
||||
}
|
||||
|
||||
// purgeDeleted hard-deletes soft-deleted rows past DeletedRetention in bounded
|
||||
// batches and returns how many it removed.
|
||||
func (m *Manager) purgeDeleted(ctx context.Context, now time.Time) int64 {
|
||||
if m.config.DeletedRetention <= 0 {
|
||||
return 0
|
||||
}
|
||||
cutoff := now.Add(-m.config.DeletedRetention)
|
||||
var total int64
|
||||
for i := 0; i < maxPurgeBatches && ctx.Err() == nil; i++ {
|
||||
n, err := m.metadata.PurgeDeletedPackages(ctx, cutoff, cleanupBatchSize)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Failed to purge soft-deleted packages")
|
||||
break
|
||||
}
|
||||
total += n
|
||||
if n < cleanupBatchSize {
|
||||
break
|
||||
}
|
||||
}
|
||||
return total
|
||||
}
|
||||
|
||||
// generateStorageKey generates a storage key for a package
|
||||
func (m *Manager) generateStorageKey(registry, name, version string) string {
|
||||
return fmt.Sprintf("%s/%s/%s", registry, name, version)
|
||||
|
||||
Vendored
+8
@@ -265,6 +265,14 @@ func (m *MockMetadataStore) ListExpiredPackages(context.Context, time.Time, int)
|
||||
|
||||
func (m *MockMetadataStore) ClearArtifactExpiry(context.Context) (int64, error) { return 0, nil }
|
||||
|
||||
func (m *MockMetadataStore) PurgeDeletedPackages(context.Context, time.Time, int) (int64, error) {
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
func (m *MockMetadataStore) GetStatsTrend(context.Context, time.Time) ([]*metadata.StatsSnapshot, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// API key methods are not used by the cache package; stub them out so the
|
||||
// mock continues to satisfy metadata.MetadataStore after the interface gained
|
||||
// API key persistence methods.
|
||||
|
||||
Vendored
+90
@@ -0,0 +1,90 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// purgeRecorder plays a store holding `pending` soft-deleted rows.
|
||||
type purgeRecorder struct {
|
||||
*memMetadata
|
||||
err error
|
||||
cutoffs []time.Time
|
||||
limits []int
|
||||
pending int64
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
func (p *purgeRecorder) PurgeDeletedPackages(_ context.Context, before time.Time, limit int) (int64, error) {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
p.cutoffs = append(p.cutoffs, before)
|
||||
p.limits = append(p.limits, limit)
|
||||
if p.err != nil {
|
||||
return 0, p.err
|
||||
}
|
||||
n := min(p.pending, int64(limit))
|
||||
p.pending -= n
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func newPurgeHarness(t *testing.T, retention time.Duration, pending int64) (*idleHarness, *purgeRecorder) {
|
||||
t.Helper()
|
||||
h := &idleHarness{clock: newFakeClock(), store: newMemStorage()}
|
||||
rec := &purgeRecorder{memMetadata: newMemMetadata(h.clock), pending: pending}
|
||||
h.meta = rec.memMetadata
|
||||
mgr, err := New(h.store, rec, nil, nil, Config{Now: h.clock.Now, CleanupInterval: 24 * time.Hour, DeletedRetention: retention})
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { _ = mgr.Close() })
|
||||
h.mgr = mgr
|
||||
return h, rec
|
||||
}
|
||||
|
||||
func TestCleanupPurgesDeletedRowsPastRetention(t *testing.T) {
|
||||
h, rec := newPurgeHarness(t, 30*day, 3*int64(cleanupBatchSize)+7)
|
||||
|
||||
h.mgr.cleanup(context.Background())
|
||||
|
||||
require.Zero(t, rec.pending, "batches continue until the store runs dry")
|
||||
require.Len(t, rec.limits, 4, "three full batches and a short one")
|
||||
for _, limit := range rec.limits {
|
||||
require.Equal(t, cleanupBatchSize, limit, "every batch is bounded")
|
||||
}
|
||||
require.Equal(t, h.clock.Now().Add(-30*day), rec.cutoffs[0], "the cutoff is now minus the retention")
|
||||
}
|
||||
|
||||
func TestCleanupPurgeIsBoundedPerPass(t *testing.T) {
|
||||
_, rec := newPurgeHarness(t, 30*day, int64(maxPurgeBatches+50)*int64(cleanupBatchSize))
|
||||
h := &Manager{config: Config{DeletedRetention: day, Now: time.Now}, metadata: rec}
|
||||
|
||||
got := h.purgeDeleted(context.Background(), time.Now())
|
||||
|
||||
require.EqualValues(t, maxPurgeBatches*cleanupBatchSize, got)
|
||||
require.EqualValues(t, 50*cleanupBatchSize, rec.pending, "the next pass continues where this one stopped")
|
||||
}
|
||||
|
||||
func TestCleanupSkipsPurgeWhenRetentionIsZero(t *testing.T) {
|
||||
h, rec := newPurgeHarness(t, 0, 10)
|
||||
|
||||
h.mgr.cleanup(context.Background())
|
||||
|
||||
require.Empty(t, rec.limits, "zero keeps every row")
|
||||
require.EqualValues(t, 10, rec.pending)
|
||||
}
|
||||
|
||||
func TestCleanupPurgeFailureDoesNotStopCleanup(t *testing.T) {
|
||||
h, rec := newPurgeHarness(t, 30*day, 10)
|
||||
rec.err = errors.New("db down")
|
||||
h.get(t, "lodash", "metadata")
|
||||
h.clock.Advance(2 * day)
|
||||
|
||||
h.mgr.cleanup(context.Background())
|
||||
|
||||
require.Len(t, rec.limits, 1, "one failed attempt, no retry loop")
|
||||
require.False(t, h.exists("lodash", "metadata"), "expired metadata is still removed")
|
||||
}
|
||||
+16
-7
@@ -157,14 +157,19 @@ func (c CacheConfig) MetadataTTLOverrides() map[string]time.Duration {
|
||||
// DefaultIdleTTL is how long a cached item can go unrequested before cleanup removes it.
|
||||
const DefaultIdleTTL = 7 * 24 * time.Hour
|
||||
|
||||
// DefaultDeletedRetention is how long a soft-deleted package row is kept before cleanup purges it.
|
||||
const DefaultDeletedRetention = 30 * 24 * time.Hour
|
||||
|
||||
// CacheConfig contains cache management configuration
|
||||
type CacheConfig struct {
|
||||
TTLOverrides map[string]time.Duration `mapstructure:"ttl_overrides" json:"ttl_overrides"`
|
||||
DefaultTTL time.Duration `mapstructure:"default_ttl" json:"default_ttl"`
|
||||
CleanupInterval time.Duration `mapstructure:"cleanup_interval" json:"cleanup_interval"`
|
||||
IdleTTL time.Duration `mapstructure:"idle_ttl" json:"idle_ttl"` // 0 disables idle eviction
|
||||
MaxSizeBytes int64 `mapstructure:"max_size_bytes" json:"max_size_bytes"`
|
||||
PerProjectQuota int64 `mapstructure:"per_project_quota" json:"per_project_quota"`
|
||||
// DeletedRetention is how long soft-deleted package rows stay before cleanup purges them; 0 keeps them forever.
|
||||
DeletedRetention time.Duration `mapstructure:"deleted_retention" json:"deleted_retention"`
|
||||
MaxSizeBytes int64 `mapstructure:"max_size_bytes" json:"max_size_bytes"`
|
||||
PerProjectQuota int64 `mapstructure:"per_project_quota" json:"per_project_quota"`
|
||||
}
|
||||
|
||||
// SecurityConfig contains security scanning configuration
|
||||
@@ -377,11 +382,12 @@ func Default() *Config {
|
||||
},
|
||||
},
|
||||
Cache: CacheConfig{
|
||||
DefaultTTL: DefaultMetadataTTL,
|
||||
CleanupInterval: 1 * time.Hour,
|
||||
IdleTTL: DefaultIdleTTL,
|
||||
MaxSizeBytes: 500 * 1024 * 1024 * 1024, // 500GB
|
||||
PerProjectQuota: 50 * 1024 * 1024 * 1024, // 50GB
|
||||
DefaultTTL: DefaultMetadataTTL,
|
||||
CleanupInterval: 1 * time.Hour,
|
||||
IdleTTL: DefaultIdleTTL,
|
||||
DeletedRetention: DefaultDeletedRetention,
|
||||
MaxSizeBytes: 500 * 1024 * 1024 * 1024, // 500GB
|
||||
PerProjectQuota: 50 * 1024 * 1024 * 1024, // 50GB
|
||||
},
|
||||
Security: SecurityConfig{
|
||||
Enabled: false,
|
||||
@@ -541,6 +547,9 @@ func (c *Config) Validate() error {
|
||||
return fmt.Errorf("cache.ttl_overrides.%s must be positive, got %s", key, ttl)
|
||||
}
|
||||
}
|
||||
if c.Cache.DeletedRetention < 0 {
|
||||
return fmt.Errorf("cache.deleted_retention cannot be negative")
|
||||
}
|
||||
if c.Cache.MaxSizeBytes < 0 {
|
||||
return fmt.Errorf("cache.max_size_bytes cannot be negative")
|
||||
}
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestDeletedRetentionDefaultsToThirtyDays(t *testing.T) {
|
||||
require.Equal(t, 30*24*time.Hour, Default().Cache.DeletedRetention)
|
||||
|
||||
cfg, err := loadCacheYAML(t, "cache:\n default_ttl: 24h\n")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 30*24*time.Hour, cfg.Cache.DeletedRetention, "an unset key keeps the default")
|
||||
}
|
||||
|
||||
func TestDeletedRetentionParse(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
yaml string
|
||||
want time.Duration
|
||||
wantErr bool
|
||||
}{
|
||||
{name: "duration string", yaml: "cache:\n deleted_retention: 48h\n", want: 48 * time.Hour},
|
||||
{name: "zero keeps rows", yaml: "cache:\n deleted_retention: 0\n", want: 0},
|
||||
{name: "quoted duration", yaml: "cache:\n deleted_retention: \"720h\"\n", want: 720 * time.Hour},
|
||||
{name: "negative rejected", yaml: "cache:\n deleted_retention: -1h\n", wantErr: true},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
cfg, err := loadCacheYAML(t, tt.yaml)
|
||||
if tt.wantErr {
|
||||
require.ErrorContains(t, err, "cache.deleted_retention")
|
||||
return
|
||||
}
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, tt.want, cfg.Cache.DeletedRetention)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -37,9 +37,39 @@ func (s *Store) ListPackageGroups(ctx context.Context, opts metadata.GroupListOp
|
||||
p.ID = packageKey(p)
|
||||
}
|
||||
}
|
||||
if len(opts.Severities) > 0 {
|
||||
if all, err = s.withSeverity(ctx, all, opts.Severities); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return metadata.PageGroups(all, opts), nil
|
||||
}
|
||||
|
||||
// withSeverity keeps the packages whose scan holds a vulnerability of one of the severities.
|
||||
func (s *Store) withSeverity(ctx context.Context, all []*metadata.Package, severities []string) ([]*metadata.Package, error) {
|
||||
sums, err := s.GetScanSummaries(ctx, nil, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
hit := make(map[string]struct{}, len(sums))
|
||||
for _, sum := range sums {
|
||||
for _, sev := range severities {
|
||||
if (sev == metadata.SeverityCritical && sum.Critical > 0) || (sev == metadata.SeverityHigh && sum.High > 0) ||
|
||||
(sev == metadata.SeverityModerate && sum.Moderate > 0) || (sev == metadata.SeverityLow && sum.Low > 0) {
|
||||
hit[sum.PackageID] = struct{}{}
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
out := all[:0]
|
||||
for _, p := range all {
|
||||
if _, ok := hit[p.ID]; ok {
|
||||
out = append(out, p)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// GetScanSummaries reads each scanned package's latest scan file.
|
||||
func (s *Store) GetScanSummaries(ctx context.Context, packageIDs []string, withDetails bool) ([]*metadata.ScanSummary, error) {
|
||||
all, err := s.listRecords(ctx)
|
||||
|
||||
@@ -195,6 +195,16 @@ func (s *Store) ListExpiredPackages(ctx context.Context, expiredBefore time.Time
|
||||
func(p *metadata.Package) time.Time { return *p.ExpiresAt })
|
||||
}
|
||||
|
||||
// PurgeDeletedPackages is a no-op: the file store deletes packages outright.
|
||||
func (s *Store) PurgeDeletedPackages(context.Context, time.Time, int) (int64, error) {
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
// GetStatsTrend returns no history: the file store keeps no daily snapshots.
|
||||
func (s *Store) GetStatsTrend(context.Context, time.Time) ([]*metadata.StatsSnapshot, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// ClearArtifactExpiry removes ExpiresAt from every non-metadata package.
|
||||
func (s *Store) ClearArtifactExpiry(ctx context.Context) (int64, error) {
|
||||
all, err := s.ListPackages(ctx, nil)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package gormstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
@@ -18,8 +19,10 @@ type AggregationWorker struct {
|
||||
stopChan chan struct{}
|
||||
ticker *time.Ticker
|
||||
now func() time.Time // nil means time.Now
|
||||
blocked func(context.Context) (int64, error)
|
||||
wg sync.WaitGroup
|
||||
stopOnce sync.Once
|
||||
mu sync.Mutex // guards blocked
|
||||
}
|
||||
|
||||
// NewAggregationWorker creates a new aggregation worker
|
||||
@@ -289,7 +292,7 @@ func (w *AggregationWorker) AggregateDaily() error {
|
||||
dayEnd := w.clock().UTC().Truncate(24 * time.Hour)
|
||||
firstDay := dayEnd.Add(-rollupDays * 24 * time.Hour)
|
||||
|
||||
return w.db.Transaction(func(tx *gorm.DB) error {
|
||||
err := w.db.Transaction(func(tx *gorm.DB) error {
|
||||
var aggregateSQL string
|
||||
|
||||
switch dialectName {
|
||||
@@ -384,6 +387,15 @@ func (w *AggregationWorker) AggregateDaily() error {
|
||||
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// The snapshot is not part of the rollup: a failure here must not undo it.
|
||||
if err := w.SnapshotStats(context.Background()); err != nil {
|
||||
log.Error().Err(err).Msg("Failed to record stats snapshot")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// UpdatePackageAccessCounts synchronizes package access_count from download stats
|
||||
|
||||
@@ -63,6 +63,10 @@ func (s *GORMStoreV2) groupFilter(opts metadata.GroupListOptions) (clause string
|
||||
clause += " AND registry_id = ?"
|
||||
args = append(args, id)
|
||||
}
|
||||
if sev := severityFilter(opts.Severities); sev != "" {
|
||||
clause += " AND security_scanned = ? AND id IN (" + latestScanWith(sev) + ")"
|
||||
args = append(args, true)
|
||||
}
|
||||
if q := strings.TrimSpace(opts.Query); q != "" {
|
||||
like := escapeLike(q)
|
||||
clause += " AND (LOWER(name) LIKE ? ESCAPE '" + likeEscape + "'" +
|
||||
@@ -73,6 +77,38 @@ func (s *GORMStoreV2) groupFilter(opts metadata.GroupListOptions) (clause string
|
||||
return clause, args, false, nil
|
||||
}
|
||||
|
||||
// severityColumns maps a severity filter value to its scan_results count column.
|
||||
var severityColumns = map[string]string{
|
||||
metadata.SeverityCritical: "critical_count",
|
||||
metadata.SeverityHigh: "high_count",
|
||||
metadata.SeverityModerate: "medium_count",
|
||||
metadata.SeverityLow: "low_count",
|
||||
}
|
||||
|
||||
// severityFilter ORs the count columns of the known severities; unknown values are ignored.
|
||||
func severityFilter(severities []string) string {
|
||||
var conds []string
|
||||
seen := map[string]bool{}
|
||||
for _, sev := range severities {
|
||||
col, ok := severityColumns[sev]
|
||||
if !ok || seen[sev] {
|
||||
continue
|
||||
}
|
||||
seen[sev] = true
|
||||
conds = append(conds, col+" > 0")
|
||||
}
|
||||
return strings.Join(conds, " OR ")
|
||||
}
|
||||
|
||||
// latestScanWith selects the packages whose newest scan satisfies cond. A tie on
|
||||
// scanned_at goes to the higher id, as GetScanSummaries decides it.
|
||||
func latestScanWith(cond string) string {
|
||||
return `SELECT package_id FROM scan_results WHERE deleted_at IS NULL AND (` + cond + `)
|
||||
AND scanned_at = (SELECT MAX(x.scanned_at) FROM scan_results x WHERE x.package_id = scan_results.package_id AND x.deleted_at IS NULL)
|
||||
AND NOT EXISTS (SELECT 1 FROM scan_results y WHERE y.package_id = scan_results.package_id AND y.deleted_at IS NULL
|
||||
AND y.scanned_at = scan_results.scanned_at AND y.id > scan_results.id)`
|
||||
}
|
||||
|
||||
// groupOrder is the ORDER BY of the group page query.
|
||||
// It reads the aliases of the grouped subquery, which MySQL's only_full_group_by requires.
|
||||
func groupOrder(opts metadata.GroupListOptions) string {
|
||||
|
||||
@@ -125,6 +125,13 @@ func NewV2(cfg Config) (*GORMStoreV2, error) {
|
||||
}
|
||||
}
|
||||
|
||||
// History must exist before the worker writes today's snapshot.
|
||||
if days, err := BackfillStatsSnapshots(context.Background(), db, time.Now()); err != nil {
|
||||
log.Warn().Err(err).Msg("Failed to backfill stats snapshots")
|
||||
} else if days > 0 {
|
||||
log.Info().Int("days", days).Msg("Backfilled stats snapshots")
|
||||
}
|
||||
|
||||
// Start aggregation worker (skip for in-memory databases used in tests)
|
||||
if !strings.Contains(cfg.DSN, ":memory:") {
|
||||
store.aggregationWorker = NewAggregationWorker(db)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package gormstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
@@ -98,6 +99,20 @@ func GetMigrations() []*gormigrate.Migration {
|
||||
return tx.Migrator().DropIndex(&ScanResultModel{}, scanPackageScannedAtIndex)
|
||||
},
|
||||
},
|
||||
{
|
||||
// Daily stats snapshots for the trend chart, seeded from package and scan history.
|
||||
ID: "202611250001",
|
||||
Migrate: func(tx *gorm.DB) error {
|
||||
if err := tx.AutoMigrate(&StatsSnapshotModel{}); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := BackfillStatsSnapshots(context.Background(), tx, time.Now())
|
||||
return err
|
||||
},
|
||||
Rollback: func(tx *gorm.DB) error {
|
||||
return tx.Migrator().DropTable(&StatsSnapshotModel{})
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -292,6 +307,7 @@ func createMySQLOptimizations(tx *gorm.DB) error {
|
||||
func rollbackFromV2(tx *gorm.DB) error {
|
||||
// Drop in reverse order to respect foreign keys
|
||||
tables := []string{
|
||||
"stats_snapshots",
|
||||
"api_keys",
|
||||
"audit_log",
|
||||
"download_stats_daily",
|
||||
|
||||
@@ -351,6 +351,27 @@ func (a *PostgresArray) Scan(value interface{}) error {
|
||||
return json.Unmarshal(bytes, a)
|
||||
}
|
||||
|
||||
// StatsSnapshotModel is the cache state at the end of one UTC day. It has no
|
||||
// foreign key to packages, so purging package rows never touches history. A nil
|
||||
// count is unknown, not zero.
|
||||
type StatsSnapshotModel struct {
|
||||
CreatedAt time.Time `gorm:"not null"`
|
||||
UpdatedAt time.Time `gorm:"not null"`
|
||||
VulnerablePackages *int64
|
||||
Critical *int64 // packages whose highest severity is critical
|
||||
High *int64
|
||||
Moderate *int64
|
||||
Low *int64
|
||||
Blocked *int64
|
||||
Day string `gorm:"primaryKey;size:10"` // YYYY-MM-DD, UTC
|
||||
TotalPackages int64 `gorm:"not null;default:0"`
|
||||
TotalSize int64 `gorm:"not null;default:0"`
|
||||
}
|
||||
|
||||
func (StatsSnapshotModel) TableName() string {
|
||||
return "stats_snapshots"
|
||||
}
|
||||
|
||||
// GetAllModels returns all models for GORM auto-migration
|
||||
func GetAllModels() []interface{} {
|
||||
return []interface{}{
|
||||
@@ -366,5 +387,6 @@ func GetAllModels() []interface{} {
|
||||
&DownloadStatsDailyModel{},
|
||||
&AuditLogModel{},
|
||||
&APIKeyModel{},
|
||||
&StatsSnapshotModel{},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
package gormstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/errors"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// PurgeDeletedPackages hard-deletes up to limit soft-deleted packages deleted
|
||||
// before deletedBefore, oldest id first, with the rows that reference them.
|
||||
// Download history and stats snapshots hold no reference and stay.
|
||||
func (s *GORMStoreV2) PurgeDeletedPackages(ctx context.Context, deletedBefore time.Time, limit int) (int64, error) {
|
||||
if limit <= 0 {
|
||||
limit = metadata.DefaultBatchSize
|
||||
}
|
||||
var purged int64
|
||||
err := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
var ids []int64
|
||||
if err := tx.Unscoped().Model(&PackageModel{}).
|
||||
Where("deleted_at IS NOT NULL AND deleted_at < ?", deletedBefore).
|
||||
Order("id").Limit(limit).Pluck("id", &ids).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if len(ids) == 0 {
|
||||
return nil
|
||||
}
|
||||
// The foreign keys cascade on PostgreSQL and MySQL; SQLite enforces them only when asked.
|
||||
for _, child := range []interface{}{&PackageVulnerabilityModel{}, &ScanResultModel{}, &PackageMetadataModel{}} {
|
||||
if err := tx.Unscoped().Where("package_id IN ?", ids).Delete(child).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
res := tx.Unscoped().Where("id IN ?", ids).Delete(&PackageModel{})
|
||||
purged = res.RowsAffected
|
||||
return res.Error
|
||||
})
|
||||
if err != nil {
|
||||
return 0, errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to purge deleted packages")
|
||||
}
|
||||
return purged, nil
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
//go:build pgintegration
|
||||
|
||||
package gormstore
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestPostgresPurgeDeletedPackages(t *testing.T) {
|
||||
store, _ := newPostgresStore(t)
|
||||
require.NoError(t, store.db.Exec("TRUNCATE packages, stats_snapshots, download_stats_daily RESTART IDENTITY CASCADE").Error)
|
||||
|
||||
checkPurgeDeletedPackages(t, store)
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package gormstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func checkPurgeDeletedPackages(t *testing.T, store *GORMStoreV2) {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
for i := 0; i < 5; i++ {
|
||||
name := fmt.Sprintf("gone-%d", i)
|
||||
seedAt(t, store, name, "1.0.0", 10, daysAgo(60))
|
||||
scanAt(t, store, name, "1.0.0", daysAgo(59), "high")
|
||||
require.NoError(t, store.db.Create(&PackageMetadataModel{PackageID: packageID(t, store, name)}).Error)
|
||||
}
|
||||
seedAt(t, store, "live", "1.0.0", 10, daysAgo(60))
|
||||
scanAt(t, store, "live", "1.0.0", daysAgo(59), "high")
|
||||
seedAt(t, store, "recent", "1.0.0", 10, daysAgo(60))
|
||||
softDeleteAt(t, store, "recent", "1.0.0", daysAgo(5))
|
||||
for i := 0; i < 5; i++ {
|
||||
softDeleteAt(t, store, fmt.Sprintf("gone-%d", i), "1.0.0", daysAgo(40-i))
|
||||
}
|
||||
|
||||
// History survives the purge: snapshots and download rows hold their own counts.
|
||||
days, err := BackfillStatsSnapshots(ctx, store.db, time.Now())
|
||||
require.NoError(t, err)
|
||||
require.Positive(t, days)
|
||||
snapshotsBefore := trendByDay(t, store, daysAgo(100))
|
||||
require.NoError(t, store.db.Create(&DownloadStatsDailyModel{
|
||||
TimeBucket: daysAgo(45), RegistryID: 1, PackageID: ptr(packageIDUnscoped(t, store, "gone-0")), DownloadCount: 9,
|
||||
}).Error)
|
||||
|
||||
cutoff := today().AddDate(0, 0, -30)
|
||||
n, err := store.PurgeDeletedPackages(ctx, cutoff, 2)
|
||||
require.NoError(t, err)
|
||||
require.EqualValues(t, 2, n, "bounded by the batch limit")
|
||||
require.EqualValues(t, 3, countRows(t, store, "gone-%", true), "oldest deletions go first")
|
||||
|
||||
n, err = store.PurgeDeletedPackages(ctx, cutoff, 100)
|
||||
require.NoError(t, err)
|
||||
require.EqualValues(t, 3, n)
|
||||
n, err = store.PurgeDeletedPackages(ctx, cutoff, 100)
|
||||
require.NoError(t, err)
|
||||
require.Zero(t, n, "nothing left past the retention")
|
||||
|
||||
require.Zero(t, countRows(t, store, "gone-%", true))
|
||||
require.EqualValues(t, 1, countRows(t, store, "recent", true), "a deletion inside the retention stays")
|
||||
require.EqualValues(t, 1, countRows(t, store, "live", false), "an active package is never purged")
|
||||
|
||||
var children int64
|
||||
for _, table := range []string{"scan_results", "package_vulnerabilities", "package_metadata"} {
|
||||
var rows int64
|
||||
require.NoError(t, store.db.Table(table).Count(&rows).Error)
|
||||
children += rows
|
||||
}
|
||||
require.EqualValues(t, 1, children, "only the live package keeps its scan row; vulnerability and metadata rows left with their packages")
|
||||
|
||||
var scans int64
|
||||
require.NoError(t, store.db.Model(&ScanResultModel{}).Count(&scans).Error)
|
||||
require.EqualValues(t, 1, scans)
|
||||
|
||||
require.Equal(t, snapshotsBefore, trendByDay(t, store, daysAgo(100)), "snapshots are untouched")
|
||||
var daily int64
|
||||
require.NoError(t, store.db.Model(&DownloadStatsDailyModel{}).Count(&daily).Error)
|
||||
require.EqualValues(t, 1, daily, "download history is untouched")
|
||||
|
||||
again, err := BackfillStatsSnapshots(ctx, store.db, time.Now())
|
||||
require.NoError(t, err)
|
||||
require.Zero(t, again, "the backfill never rewrites history after a purge")
|
||||
}
|
||||
|
||||
func packageID(t *testing.T, store *GORMStoreV2, name string) int64 {
|
||||
t.Helper()
|
||||
var id int64
|
||||
require.NoError(t, store.db.Model(&PackageModel{}).Where("name = ?", name).Pluck("id", &id).Error)
|
||||
return id
|
||||
}
|
||||
|
||||
func packageIDUnscoped(t *testing.T, store *GORMStoreV2, name string) int64 {
|
||||
t.Helper()
|
||||
var id int64
|
||||
require.NoError(t, store.db.Unscoped().Model(&PackageModel{}).Where("name = ?", name).Pluck("id", &id).Error)
|
||||
return id
|
||||
}
|
||||
|
||||
func countRows(t *testing.T, store *GORMStoreV2, namePattern string, deleted bool) int64 {
|
||||
t.Helper()
|
||||
q := store.db.Unscoped().Model(&PackageModel{}).Where("name LIKE ?", namePattern)
|
||||
if deleted {
|
||||
q = q.Where("deleted_at IS NOT NULL")
|
||||
} else {
|
||||
q = q.Where("deleted_at IS NULL")
|
||||
}
|
||||
var n int64
|
||||
require.NoError(t, q.Count(&n).Error)
|
||||
return n
|
||||
}
|
||||
|
||||
func TestBackfillStatsSnapshots(t *testing.T) { checkBackfillStatsSnapshots(t, newTimeSeriesStore(t)) }
|
||||
func TestBackfillWithoutScans(t *testing.T) { checkBackfillWithoutScans(t, newTimeSeriesStore(t)) }
|
||||
func TestSnapshotStats(t *testing.T) { checkSnapshotStats(t, newTimeSeriesStore(t)) }
|
||||
func TestTrendWindow(t *testing.T) { checkTrendWindow(t, newTimeSeriesStore(t)) }
|
||||
func TestTrendStatementsAreConstant(t *testing.T) {
|
||||
checkTrendStatementsAreConstant(t, newTimeSeriesStore(t))
|
||||
}
|
||||
func TestPurgeDeletedPackages(t *testing.T) { checkPurgeDeletedPackages(t, newTimeSeriesStore(t)) }
|
||||
@@ -0,0 +1,23 @@
|
||||
//go:build pgintegration
|
||||
|
||||
package gormstore
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestPostgresSeverityFilter(t *testing.T) {
|
||||
store, _ := newPostgresStore(t)
|
||||
|
||||
for name, check := range map[string]func(*testing.T, *GORMStoreV2){
|
||||
"severity filter": checkSeverityFilter,
|
||||
"severity statements constant": checkSeverityFilterStatementsAreConstant,
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
require.NoError(t, store.db.Exec("TRUNCATE packages RESTART IDENTITY CASCADE").Error)
|
||||
check(t, store)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
package gormstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func checkSeverityFilter(t *testing.T, store *GORMStoreV2) {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
for _, n := range []string{"crit", "high", "mod", "low", "clean", "fixed", "multi", "unscanned"} {
|
||||
seedAt(t, store, n, "1.0.0", 1, daysAgo(3))
|
||||
}
|
||||
scanAt(t, store, "crit", "1.0.0", daysAgo(2), "critical")
|
||||
scanAt(t, store, "high", "1.0.0", daysAgo(2), "high")
|
||||
scanAt(t, store, "mod", "1.0.0", daysAgo(2), "moderate")
|
||||
scanAt(t, store, "low", "1.0.0", daysAgo(2), "low")
|
||||
scanAt(t, store, "clean", "1.0.0", daysAgo(2))
|
||||
scanAt(t, store, "fixed", "1.0.0", daysAgo(2), "critical")
|
||||
scanAt(t, store, "fixed", "1.0.0", daysAgo(1)) // the newest scan decides
|
||||
scanAt(t, store, "multi", "1.0.0", daysAgo(2), "high", "low")
|
||||
|
||||
pick := func(opts metadata.GroupListOptions) []string {
|
||||
page, err := store.ListPackageGroups(ctx, opts)
|
||||
require.NoError(t, err)
|
||||
out := names(page.Packages)
|
||||
for i := range out {
|
||||
for j := i + 1; j < len(out); j++ {
|
||||
if out[j] < out[i] {
|
||||
out[i], out[j] = out[j], out[i]
|
||||
}
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
require.Equal(t, []string{"crit"}, pick(metadata.GroupListOptions{Severities: []string{"critical"}}))
|
||||
require.Equal(t, []string{"high", "multi"}, pick(metadata.GroupListOptions{Severities: []string{"high"}}))
|
||||
require.Equal(t, []string{"crit", "mod"}, pick(metadata.GroupListOptions{Severities: []string{"critical", "moderate"}}), "OR across severities")
|
||||
require.Equal(t, []string{"low", "multi"}, pick(metadata.GroupListOptions{Severities: []string{"low"}}))
|
||||
require.Equal(t, []string{"crit", "high", "low", "mod", "multi"},
|
||||
pick(metadata.GroupListOptions{Severities: metadata.Severities}), "every severity = every vulnerable package")
|
||||
require.Len(t, pick(metadata.GroupListOptions{}), 8, "no filter keeps everything")
|
||||
|
||||
paged, err := store.ListPackageGroups(ctx, metadata.GroupListOptions{Severities: []string{"high", "low"}, Page: 1, PageSize: 2})
|
||||
require.NoError(t, err)
|
||||
require.EqualValues(t, 3, paged.TotalGroups, "paging counts the filtered groups")
|
||||
require.Len(t, paged.Packages, 2)
|
||||
|
||||
require.Equal(t, []string{"crit"}, pick(metadata.GroupListOptions{Severities: []string{"critical"}, Query: "cr"}), "composes with search")
|
||||
require.Empty(t, pick(metadata.GroupListOptions{Severities: []string{"critical"}, Query: "high"}))
|
||||
|
||||
// The trend snapshot counts a package under every severity it holds, exactly as the filter selects it.
|
||||
snap, err := liveSnapshot(ctx, store.db, time.Now(), nil)
|
||||
require.NoError(t, err)
|
||||
for sev, got := range map[string]*int64{
|
||||
metadata.SeverityCritical: snap.Critical, metadata.SeverityHigh: snap.High,
|
||||
metadata.SeverityModerate: snap.Moderate, metadata.SeverityLow: snap.Low,
|
||||
} {
|
||||
require.EqualValues(t, len(pick(metadata.GroupListOptions{Severities: []string{sev}})), *got, sev)
|
||||
}
|
||||
require.EqualValues(t, 5, *snap.VulnerablePackages)
|
||||
require.EqualValues(t, len(pick(metadata.GroupListOptions{Severities: metadata.Severities})), *snap.VulnerablePackages)
|
||||
require.EqualValues(t, [4]int64{1, 2, 1, 2}, [4]int64{*snap.Critical, *snap.High, *snap.Moderate, *snap.Low}, "multi counts under high and low")
|
||||
}
|
||||
|
||||
func checkSeverityFilterStatementsAreConstant(t *testing.T, store *GORMStoreV2) {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
counter := attachCounter(store)
|
||||
measure := func() [2]int {
|
||||
var out [2]int
|
||||
counter.Reset()
|
||||
_, err := store.ListPackageGroups(ctx, metadata.GroupListOptions{Severities: []string{"critical", "high"}})
|
||||
require.NoError(t, err)
|
||||
out[0] = counter.Count()
|
||||
counter.Reset()
|
||||
_, err = store.ListPackageGroups(ctx, metadata.GroupListOptions{Severities: []string{"low"}, Page: 1, PageSize: 25})
|
||||
require.NoError(t, err)
|
||||
out[1] = counter.Count()
|
||||
return out
|
||||
}
|
||||
seedScanned(t, store, 0, 10)
|
||||
small := measure()
|
||||
seedScanned(t, store, 10, 90)
|
||||
large := measure()
|
||||
t.Logf("statements for 10 rows %v, for 100 rows %v", small, large)
|
||||
require.Equal(t, small, large)
|
||||
require.LessOrEqual(t, large[0], 1, "the filter is a subquery of the one list read")
|
||||
require.LessOrEqual(t, large[1], 3)
|
||||
}
|
||||
|
||||
func TestSeverityFilter(t *testing.T) { checkSeverityFilter(t, newTimeSeriesStore(t)) }
|
||||
func TestSeverityFilterStatementsAreConstant(t *testing.T) {
|
||||
checkSeverityFilterStatementsAreConstant(t, newTimeSeriesStore(t))
|
||||
}
|
||||
@@ -0,0 +1,389 @@
|
||||
package gormstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sort"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/errors"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/rs/zerolog/log"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
const (
|
||||
day = 24 * time.Hour
|
||||
snapshotBatch = 500
|
||||
)
|
||||
|
||||
// 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")
|
||||
}
|
||||
|
||||
func dayString(t time.Time) string { return t.UTC().Format(metadata.StatsSnapshotDateLayout) }
|
||||
|
||||
func ptr(v int64) *int64 { return &v }
|
||||
|
||||
// liveSnapshot reads the current cache state in one statement. blocked may be nil.
|
||||
func liveSnapshot(ctx context.Context, db *gorm.DB, at time.Time, blocked *int64) (*StatsSnapshotModel, error) {
|
||||
var r struct {
|
||||
Total int64
|
||||
Size int64
|
||||
Vulnerable int64
|
||||
Critical int64
|
||||
High int64
|
||||
Moderate int64
|
||||
Low int64
|
||||
}
|
||||
// A package counts under every severity its latest scan holds, as the severity filter selects it.
|
||||
scanned := func(col string) string {
|
||||
return "COALESCE(SUM(CASE WHEN security_scanned = ? AND id IN (" + latestScanWith(col+" > 0") + ") THEN 1 ELSE 0 END), 0)"
|
||||
}
|
||||
err := artifactPackages(db.WithContext(ctx).Model(&PackageModel{})).Select(`
|
||||
COUNT(*) AS total,
|
||||
COALESCE(SUM(size), 0) AS size,
|
||||
`+scanned("vuln_count")+` AS vulnerable,
|
||||
`+scanned(severityColumns[metadata.SeverityCritical])+` AS critical,
|
||||
`+scanned(severityColumns[metadata.SeverityHigh])+` AS high,
|
||||
`+scanned(severityColumns[metadata.SeverityModerate])+` AS moderate,
|
||||
`+scanned(severityColumns[metadata.SeverityLow])+` AS low`, true, true, true, true, true).
|
||||
Scan(&r).Error
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to read stats for snapshot")
|
||||
}
|
||||
return &StatsSnapshotModel{
|
||||
Day: dayString(at),
|
||||
TotalPackages: r.Total,
|
||||
TotalSize: r.Size,
|
||||
VulnerablePackages: ptr(r.Vulnerable),
|
||||
Critical: ptr(r.Critical),
|
||||
High: ptr(r.High),
|
||||
Moderate: ptr(r.Moderate),
|
||||
Low: ptr(r.Low),
|
||||
Blocked: blocked,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// snapshotColumns are overwritten when a day's snapshot is written again.
|
||||
var snapshotColumns = []string{
|
||||
"total_packages", "total_size", "vulnerable_packages", "critical", "high", "moderate", "low", "blocked", "updated_at",
|
||||
}
|
||||
|
||||
// upsertSnapshot writes the day's row, replacing an earlier write of the same day.
|
||||
// A nil blocked keeps the stored value so a run without a blocking policy never erases it.
|
||||
func upsertSnapshot(ctx context.Context, db *gorm.DB, snap *StatsSnapshotModel) error {
|
||||
cols := snapshotColumns
|
||||
if snap.Blocked == nil {
|
||||
cols = make([]string, 0, len(snapshotColumns))
|
||||
for _, c := range snapshotColumns {
|
||||
if c != "blocked" {
|
||||
cols = append(cols, c)
|
||||
}
|
||||
}
|
||||
}
|
||||
err := db.WithContext(ctx).Clauses(clause.OnConflict{
|
||||
Columns: []clause.Column{{Name: "day"}},
|
||||
DoUpdates: clause.AssignmentColumns(cols),
|
||||
}).Create(snap).Error
|
||||
if err != nil {
|
||||
return errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to save stats snapshot")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// SnapshotStats records today's (UTC) cache state. Running it again the same
|
||||
// day overwrites that day's row, so the last run of a day is its closing state.
|
||||
func (w *AggregationWorker) SnapshotStats(ctx context.Context) error {
|
||||
now := w.clock()
|
||||
var blocked *int64
|
||||
if count := w.blockedCounter(); count != nil {
|
||||
n, err := count(ctx)
|
||||
if err != nil {
|
||||
log.Warn().Err(err).Msg("Failed to count blocked packages for the stats snapshot")
|
||||
} else {
|
||||
blocked = ptr(n)
|
||||
}
|
||||
}
|
||||
snap, err := liveSnapshot(ctx, w.db, now, blocked)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := upsertSnapshot(ctx, w.db, snap); err != nil {
|
||||
return err
|
||||
}
|
||||
log.Info().Str("day", snap.Day).Int64("packages", snap.TotalPackages).Msg("Recorded stats snapshot")
|
||||
return nil
|
||||
}
|
||||
|
||||
// SetBlockedCounter sets how the snapshot counts blocked packages, which needs the scan policy the store lacks.
|
||||
func (w *AggregationWorker) SetBlockedCounter(count func(context.Context) (int64, error)) {
|
||||
w.mu.Lock()
|
||||
w.blocked = count
|
||||
w.mu.Unlock()
|
||||
}
|
||||
|
||||
func (w *AggregationWorker) blockedCounter() func(context.Context) (int64, error) {
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
return w.blocked
|
||||
}
|
||||
|
||||
// SetBlockedCounter sets how daily snapshots count blocked packages.
|
||||
func (s *GORMStoreV2) SetBlockedCounter(count func(context.Context) (int64, error)) {
|
||||
if s.aggregationWorker != nil {
|
||||
s.aggregationWorker.SetBlockedCounter(count)
|
||||
}
|
||||
}
|
||||
|
||||
// GetStatsTrend returns the daily snapshots from the UTC day of since, oldest first, in one statement.
|
||||
func (s *GORMStoreV2) GetStatsTrend(ctx context.Context, since time.Time) ([]*metadata.StatsSnapshot, error) {
|
||||
var rows []StatsSnapshotModel
|
||||
if err := s.db.WithContext(ctx).Where("day >= ?", dayString(since)).Order("day").Find(&rows).Error; err != nil {
|
||||
return nil, errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to read stats snapshots")
|
||||
}
|
||||
out := make([]*metadata.StatsSnapshot, len(rows))
|
||||
for i, r := range rows {
|
||||
out[i] = &metadata.StatsSnapshot{
|
||||
Date: r.Day,
|
||||
TotalPackages: r.TotalPackages,
|
||||
TotalSize: r.TotalSize,
|
||||
VulnerablePackages: r.VulnerablePackages,
|
||||
Critical: r.Critical,
|
||||
High: r.High,
|
||||
Moderate: r.Moderate,
|
||||
Low: r.Low,
|
||||
Blocked: r.Blocked,
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// dayState is one package's contribution to a day's totals.
|
||||
type dayState struct {
|
||||
size, vulnerable, critical, high, moderate, low int64
|
||||
alive int64
|
||||
}
|
||||
|
||||
func (a dayState) minus(b dayState) dayState {
|
||||
return dayState{
|
||||
alive: a.alive - b.alive, size: a.size - b.size, vulnerable: a.vulnerable - b.vulnerable,
|
||||
critical: a.critical - b.critical, high: a.high - b.high, moderate: a.moderate - b.moderate, low: a.low - b.low,
|
||||
}
|
||||
}
|
||||
|
||||
func (a *dayState) add(b dayState) {
|
||||
a.alive += b.alive
|
||||
a.size += b.size
|
||||
a.vulnerable += b.vulnerable
|
||||
a.critical += b.critical
|
||||
a.high += b.high
|
||||
a.moderate += b.moderate
|
||||
a.low += b.low
|
||||
}
|
||||
|
||||
// backfillScan is one scan result reduced to what the history needs.
|
||||
type backfillScan struct {
|
||||
at time.Time
|
||||
vulns, critical, high, moderate, lowCounts int
|
||||
id int64
|
||||
}
|
||||
|
||||
// backfillPackage is one package's lifetime: alive from cachedAt up to deletedAt.
|
||||
type backfillPackage struct {
|
||||
cachedAt time.Time
|
||||
deletedAt *time.Time
|
||||
size int64
|
||||
}
|
||||
|
||||
// stateAtDayEnd is the package's contribution at the end of the UTC day whose
|
||||
// midnight-after is end. withScans is false for days before any scan exists.
|
||||
func (p backfillPackage) stateAtDayEnd(end time.Time, scans []backfillScan, withScans bool) dayState {
|
||||
if !p.cachedAt.Before(end) || (p.deletedAt != nil && p.deletedAt.Before(end)) {
|
||||
return dayState{}
|
||||
}
|
||||
st := dayState{alive: 1, size: p.size}
|
||||
if !withScans {
|
||||
return st
|
||||
}
|
||||
// scans is sorted by (at, id); the last one before end is the latest.
|
||||
i := sort.Search(len(scans), func(i int) bool { return !scans[i].at.Before(end) })
|
||||
if i == 0 {
|
||||
return st
|
||||
}
|
||||
sc := scans[i-1]
|
||||
if sc.vulns > 0 {
|
||||
st.vulnerable = 1
|
||||
}
|
||||
// Every severity the scan holds counts, as in liveSnapshot.
|
||||
if sc.critical > 0 {
|
||||
st.critical = 1
|
||||
}
|
||||
if sc.high > 0 {
|
||||
st.high = 1
|
||||
}
|
||||
if sc.moderate > 0 {
|
||||
st.moderate = 1
|
||||
}
|
||||
if sc.lowCounts > 0 {
|
||||
st.low = 1
|
||||
}
|
||||
return st
|
||||
}
|
||||
|
||||
// BackfillStatsSnapshots writes one snapshot per past UTC day, from the first
|
||||
// package to the day before today, when no snapshot of a past day exists yet. Package counts
|
||||
// come from cached_at and deleted_at. Vulnerability counts come from the
|
||||
// append-only scan results and start at the first scan; earlier days leave
|
||||
// them nil, as blocked is always nil (the policy at the time is not stored).
|
||||
// It returns the number of days written.
|
||||
func BackfillStatsSnapshots(ctx context.Context, db *gorm.DB, now time.Time) (int, error) {
|
||||
today := now.UTC().Truncate(day)
|
||||
var existing int64
|
||||
if err := db.WithContext(ctx).Model(&StatsSnapshotModel{}).Where("day < ?", dayString(today)).Count(&existing).Error; err != nil {
|
||||
return 0, errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to count stats snapshots")
|
||||
}
|
||||
if existing > 0 {
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
pkgs, err := loadBackfillPackages(ctx, db)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if len(pkgs) == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
scans, firstScan, err := loadBackfillScans(ctx, db, pkgs)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
deltas := map[int64]dayState{}
|
||||
first := today
|
||||
for id, p := range pkgs {
|
||||
if d := p.cachedAt.UTC().Truncate(day); d.Before(first) {
|
||||
first = d
|
||||
}
|
||||
prev := dayState{}
|
||||
for _, d := range candidateDays(p, scans[id], today) {
|
||||
cur := p.stateAtDayEnd(d.Add(day), scans[id], !firstScan.IsZero() && !d.Before(firstScan))
|
||||
if delta := cur.minus(prev); delta != (dayState{}) {
|
||||
acc := deltas[d.Unix()]
|
||||
acc.add(delta)
|
||||
deltas[d.Unix()] = acc
|
||||
}
|
||||
prev = cur
|
||||
}
|
||||
}
|
||||
|
||||
var rows []StatsSnapshotModel
|
||||
var total dayState
|
||||
for d := first; d.Before(today); d = d.Add(day) {
|
||||
total.add(deltas[d.Unix()])
|
||||
row := StatsSnapshotModel{Day: dayString(d), TotalPackages: total.alive, TotalSize: total.size}
|
||||
if !firstScan.IsZero() && !d.Before(firstScan) {
|
||||
row.VulnerablePackages, row.Critical, row.High = ptr(total.vulnerable), ptr(total.critical), ptr(total.high)
|
||||
row.Moderate, row.Low = ptr(total.moderate), ptr(total.low)
|
||||
}
|
||||
rows = append(rows, row)
|
||||
}
|
||||
if len(rows) == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
err = db.WithContext(ctx).Clauses(clause.OnConflict{DoNothing: true}).CreateInBatches(rows, snapshotBatch).Error
|
||||
if err != nil {
|
||||
return 0, errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to backfill stats snapshots")
|
||||
}
|
||||
return len(rows), nil
|
||||
}
|
||||
|
||||
// candidateDays lists, sorted, the days before today on which a package's
|
||||
// end-of-day state can change: when it was cached, deleted or scanned.
|
||||
func candidateDays(p backfillPackage, scans []backfillScan, today time.Time) []time.Time {
|
||||
set := map[int64]struct{}{}
|
||||
mark := func(t time.Time) {
|
||||
if d := t.UTC().Truncate(day); d.Before(today) {
|
||||
set[d.Unix()] = struct{}{}
|
||||
}
|
||||
}
|
||||
mark(p.cachedAt)
|
||||
if p.deletedAt != nil {
|
||||
mark(*p.deletedAt)
|
||||
}
|
||||
for _, s := range scans {
|
||||
mark(s.at)
|
||||
}
|
||||
days := make([]time.Time, 0, len(set))
|
||||
for unix := range set {
|
||||
days = append(days, time.Unix(unix, 0).UTC())
|
||||
}
|
||||
sort.Slice(days, func(i, j int) bool { return days[i].Before(days[j]) })
|
||||
return days
|
||||
}
|
||||
|
||||
func loadBackfillPackages(ctx context.Context, db *gorm.DB) (map[int64]backfillPackage, error) {
|
||||
var rows []struct {
|
||||
CachedAt time.Time
|
||||
DeletedAt *time.Time
|
||||
ID int64
|
||||
Size int64
|
||||
}
|
||||
err := artifactPackages(db.WithContext(ctx).Unscoped().Model(&PackageModel{})).
|
||||
Select("id, cached_at, deleted_at, size").Scan(&rows).Error
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to read packages for backfill")
|
||||
}
|
||||
pkgs := make(map[int64]backfillPackage, len(rows))
|
||||
for _, r := range rows {
|
||||
pkgs[r.ID] = backfillPackage{cachedAt: r.CachedAt, deletedAt: r.DeletedAt, size: r.Size}
|
||||
}
|
||||
return pkgs, nil
|
||||
}
|
||||
|
||||
// loadBackfillScans groups the scan results of the given packages and returns
|
||||
// the UTC day of the first scan (zero when there is none).
|
||||
func loadBackfillScans(ctx context.Context, db *gorm.DB, pkgs map[int64]backfillPackage) (map[int64][]backfillScan, time.Time, error) {
|
||||
var rows []struct {
|
||||
ScannedAt time.Time
|
||||
ID int64
|
||||
PackageID int64
|
||||
VulnCount int
|
||||
CriticalCount int
|
||||
HighCount int
|
||||
MediumCount int
|
||||
LowCount int
|
||||
}
|
||||
err := db.WithContext(ctx).Model(&ScanResultModel{}).
|
||||
Select("id, package_id, scanned_at, vuln_count, critical_count, high_count, medium_count, low_count").
|
||||
Scan(&rows).Error
|
||||
if err != nil {
|
||||
return nil, time.Time{}, errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to read scans for backfill")
|
||||
}
|
||||
scans := map[int64][]backfillScan{}
|
||||
var firstScan time.Time
|
||||
for _, r := range rows {
|
||||
if _, ok := pkgs[r.PackageID]; !ok {
|
||||
continue
|
||||
}
|
||||
scans[r.PackageID] = append(scans[r.PackageID], backfillScan{
|
||||
id: r.ID, at: r.ScannedAt, vulns: r.VulnCount,
|
||||
critical: r.CriticalCount, high: r.HighCount, moderate: r.MediumCount, lowCounts: r.LowCount,
|
||||
})
|
||||
if d := r.ScannedAt.UTC().Truncate(day); firstScan.IsZero() || d.Before(firstScan) {
|
||||
firstScan = d
|
||||
}
|
||||
}
|
||||
for _, list := range scans {
|
||||
sort.Slice(list, func(i, j int) bool {
|
||||
if list[i].at.Equal(list[j].at) {
|
||||
return list[i].id < list[j].id
|
||||
}
|
||||
return list[i].at.Before(list[j].at)
|
||||
})
|
||||
}
|
||||
return scans, firstScan, nil
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
//go:build pgintegration
|
||||
|
||||
package gormstore
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestPostgresTrendSeverityAndPurge(t *testing.T) {
|
||||
store, _ := newPostgresStore(t)
|
||||
|
||||
reset := func(t *testing.T) {
|
||||
t.Helper()
|
||||
require.NoError(t, store.db.Exec(
|
||||
"TRUNCATE packages, stats_snapshots, download_stats_daily RESTART IDENTITY CASCADE").Error)
|
||||
}
|
||||
for name, check := range map[string]func(*testing.T, *GORMStoreV2){
|
||||
"backfill": checkBackfillStatsSnapshots,
|
||||
"backfill without scans": checkBackfillWithoutScans,
|
||||
"snapshot": checkSnapshotStats,
|
||||
"trend window": checkTrendWindow,
|
||||
"trend statements constant": checkTrendStatementsAreConstant,
|
||||
"severity filter": checkSeverityFilter,
|
||||
"severity statements constant": checkSeverityFilterStatementsAreConstant,
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
reset(t)
|
||||
check(t, store)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPostgresStatsSnapshotsHaveNoPackageForeignKey(t *testing.T) {
|
||||
store, _ := newPostgresStore(t)
|
||||
|
||||
var referencing []string
|
||||
require.NoError(t, store.db.Raw(
|
||||
"SELECT conrelid::regclass::text FROM pg_constraint WHERE contype = 'f' AND confrelid = 'packages'::regclass",
|
||||
).Scan(&referencing).Error)
|
||||
require.NotContains(t, referencing, "stats_snapshots", "a package purge must not cascade over history")
|
||||
}
|
||||
@@ -0,0 +1,257 @@
|
||||
package gormstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/internal/dbcount"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func today() time.Time { return time.Now().UTC().Truncate(day) }
|
||||
|
||||
// daysAgo is noon UTC, n days before today.
|
||||
func daysAgo(n int) time.Time { return today().AddDate(0, 0, -n).Add(12 * time.Hour) }
|
||||
|
||||
func seedAt(t *testing.T, store *GORMStoreV2, name, version string, size int64, cachedAt time.Time) {
|
||||
t.Helper()
|
||||
require.NoError(t, store.SavePackage(context.Background(), &metadata.Package{
|
||||
Registry: "npm", Name: name, Version: version, StorageKey: fmt.Sprintf("npm/%s/%s", name, version),
|
||||
Size: size, CachedAt: cachedAt, LastAccessed: cachedAt,
|
||||
}))
|
||||
}
|
||||
|
||||
func scanAt(t *testing.T, store *GORMStoreV2, name, version string, at time.Time, severities ...string) {
|
||||
t.Helper()
|
||||
res := &metadata.ScanResult{
|
||||
Registry: "npm", PackageName: name, PackageVersion: version, Scanner: "test", ScannedAt: at,
|
||||
Status: metadata.ScanStatusClean,
|
||||
}
|
||||
for i, sev := range severities {
|
||||
res.Status = metadata.ScanStatusVulnerable
|
||||
res.Vulnerabilities = append(res.Vulnerabilities, metadata.Vulnerability{ID: fmt.Sprintf("CVE-%d", i), Severity: sev})
|
||||
}
|
||||
res.VulnerabilityCount = len(severities)
|
||||
require.NoError(t, store.SaveScanResult(context.Background(), res))
|
||||
}
|
||||
|
||||
// softDeleteAt deletes the package and backdates the deletion.
|
||||
func softDeleteAt(t *testing.T, store *GORMStoreV2, name, version string, at time.Time) {
|
||||
t.Helper()
|
||||
require.NoError(t, store.DeletePackage(context.Background(), "npm", name, version))
|
||||
require.NoError(t, store.db.Unscoped().Model(&PackageModel{}).
|
||||
Where("name = ? AND version = ?", name, version).Update("deleted_at", at).Error)
|
||||
}
|
||||
|
||||
func trendByDay(t *testing.T, store *GORMStoreV2, since time.Time) map[string]*metadata.StatsSnapshot {
|
||||
t.Helper()
|
||||
pts, err := store.GetStatsTrend(context.Background(), since)
|
||||
require.NoError(t, err)
|
||||
out := map[string]*metadata.StatsSnapshot{}
|
||||
for _, p := range pts {
|
||||
out[p.Date] = p
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func vulns(p *metadata.StatsSnapshot) [5]int64 {
|
||||
get := func(v *int64) int64 {
|
||||
if v == nil {
|
||||
return -1
|
||||
}
|
||||
return *v
|
||||
}
|
||||
return [5]int64{get(p.VulnerablePackages), get(p.Critical), get(p.High), get(p.Moderate), get(p.Low)}
|
||||
}
|
||||
|
||||
// checkBackfillStatsSnapshots seeds a five-day history and proves the reconstruction day by day.
|
||||
func checkBackfillStatsSnapshots(t *testing.T, store *GORMStoreV2) {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
|
||||
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, "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
|
||||
scanAt(t, store, "a", "1.0.0", daysAgo(1)) // clean rescan
|
||||
softDeleteAt(t, store, "b", "1.0.0", daysAgo(2))
|
||||
softDeleteAt(t, store, "early", "1.0.0", daysAgo(2).Add(time.Hour))
|
||||
|
||||
days, err := BackfillStatsSnapshots(ctx, store.db, time.Now())
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 5, days, "day -5 to day -1; today belongs to the live snapshot")
|
||||
|
||||
got := trendByDay(t, store, daysAgo(10))
|
||||
require.Len(t, got, 5)
|
||||
day := func(n int) *metadata.StatsSnapshot {
|
||||
p, ok := got[dayString(daysAgo(n))]
|
||||
require.True(t, ok, "day -%d", n)
|
||||
return p
|
||||
}
|
||||
|
||||
require.EqualValues(t, 1, day(5).TotalPackages)
|
||||
require.EqualValues(t, 10, day(5).TotalSize)
|
||||
require.Equal(t, [5]int64{-1, -1, -1, -1, -1}, vulns(day(5)), "no scan existed yet: unknown, not zero")
|
||||
|
||||
require.EqualValues(t, 2, day(4).TotalPackages)
|
||||
require.EqualValues(t, 30, day(4).TotalSize)
|
||||
require.Equal(t, [5]int64{1, 0, 1, 0, 0}, vulns(day(4)))
|
||||
|
||||
require.EqualValues(t, 2, day(3).TotalPackages)
|
||||
require.Equal(t, [5]int64{2, 1, 1, 0, 1}, vulns(day(3)), "a counts under critical and low")
|
||||
|
||||
require.EqualValues(t, 1, day(2).TotalPackages, "b was deleted on day -2; early lived and died within it")
|
||||
require.EqualValues(t, 10, day(2).TotalSize)
|
||||
require.Equal(t, [5]int64{1, 1, 0, 0, 1}, vulns(day(2)))
|
||||
|
||||
require.EqualValues(t, 1, day(1).TotalPackages)
|
||||
require.Equal(t, [5]int64{0, 0, 0, 0, 0}, vulns(day(1)), "the clean rescan clears the vulnerability")
|
||||
require.Nil(t, day(1).Blocked, "the policy of a past day is not reconstructable")
|
||||
|
||||
again, err := BackfillStatsSnapshots(ctx, store.db, time.Now())
|
||||
require.NoError(t, err)
|
||||
require.Zero(t, again, "a second run is a no-op")
|
||||
require.Len(t, trendByDay(t, store, daysAgo(10)), 5)
|
||||
}
|
||||
|
||||
// checkBackfillWithoutScans proves that without scan history only package counts are written.
|
||||
func checkBackfillWithoutScans(t *testing.T, store *GORMStoreV2) {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
days, err := BackfillStatsSnapshots(ctx, store.db, time.Now())
|
||||
require.NoError(t, err)
|
||||
require.Zero(t, days, "no packages, no history")
|
||||
|
||||
seedAt(t, store, "a", "1.0.0", 10, daysAgo(2))
|
||||
days, err = BackfillStatsSnapshots(ctx, store.db, time.Now())
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 2, days)
|
||||
for _, p := range trendByDay(t, store, daysAgo(10)) {
|
||||
require.EqualValues(t, 1, p.TotalPackages)
|
||||
require.Equal(t, [5]int64{-1, -1, -1, -1, -1}, vulns(p))
|
||||
}
|
||||
}
|
||||
|
||||
func checkSnapshotStats(t *testing.T, store *GORMStoreV2) {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
seedAt(t, store, "a", "1.0.0", 10, daysAgo(1))
|
||||
seedAt(t, store, "b", "1.0.0", 20, daysAgo(1))
|
||||
seedAt(t, store, "c", "1.0.0", 30, daysAgo(1))
|
||||
scanAt(t, store, "a", "1.0.0", daysAgo(1), "critical")
|
||||
scanAt(t, store, "b", "1.0.0", daysAgo(1), "moderate")
|
||||
|
||||
// An in-memory database has no running worker; this one is the test's own.
|
||||
worker := store.aggregationWorker
|
||||
store.SetBlockedCounter(func(context.Context) (int64, error) { return 1, nil })
|
||||
require.NoError(t, worker.SnapshotStats(ctx))
|
||||
require.NoError(t, worker.SnapshotStats(ctx), "the same day twice writes one row")
|
||||
|
||||
rows := trendByDay(t, store, today())
|
||||
require.Len(t, rows, 1)
|
||||
snap := rows[dayString(time.Now())]
|
||||
require.NotNil(t, snap)
|
||||
require.EqualValues(t, 3, snap.TotalPackages)
|
||||
require.EqualValues(t, 60, snap.TotalSize)
|
||||
require.Equal(t, [5]int64{2, 1, 0, 1, 0}, vulns(snap))
|
||||
require.EqualValues(t, 1, *snap.Blocked)
|
||||
|
||||
// The next run of the day replaces the counts.
|
||||
scanAt(t, store, "a", "1.0.0", daysAgo(0).Add(-time.Hour), "high")
|
||||
store.SetBlockedCounter(nil)
|
||||
require.NoError(t, worker.SnapshotStats(ctx))
|
||||
snap = trendByDay(t, store, today())[dayString(time.Now())]
|
||||
require.Equal(t, [5]int64{2, 0, 1, 1, 0}, vulns(snap))
|
||||
require.EqualValues(t, 1, *snap.Blocked, "a run without a blocking policy keeps the earlier count")
|
||||
|
||||
store.SetBlockedCounter(func(context.Context) (int64, error) { return 0, errors.New("scanner down") })
|
||||
require.NoError(t, worker.SnapshotStats(ctx), "a failed blocked count must not lose the snapshot")
|
||||
}
|
||||
|
||||
func checkTrendWindow(t *testing.T, store *GORMStoreV2) {
|
||||
t.Helper()
|
||||
for i := 0; i < 5; i++ {
|
||||
require.NoError(t, store.db.Create(&StatsSnapshotModel{Day: dayString(daysAgo(i)), TotalPackages: int64(i)}).Error)
|
||||
}
|
||||
pts, err := store.GetStatsTrend(context.Background(), daysAgo(2))
|
||||
require.NoError(t, err)
|
||||
require.Len(t, pts, 3)
|
||||
require.Equal(t, dayString(daysAgo(2)), pts[0].Date, "oldest first, from the since day inclusive")
|
||||
require.Equal(t, dayString(daysAgo(0)), pts[2].Date)
|
||||
require.Nil(t, pts[0].VulnerablePackages)
|
||||
|
||||
none, err := store.GetStatsTrend(context.Background(), today().AddDate(0, 0, 1))
|
||||
require.NoError(t, err)
|
||||
require.Empty(t, none)
|
||||
}
|
||||
|
||||
// attachCounter counts the statements of the store and of its worker, which holds its own handle.
|
||||
func attachCounter(store *GORMStoreV2) *dbcount.Counter {
|
||||
var counter *dbcount.Counter
|
||||
store.aggregationWorker.Stop() // its handle is swapped below; a running loop would race
|
||||
store.WrapDB(func(db *gorm.DB) *gorm.DB {
|
||||
counted, c := dbcount.Attach(db)
|
||||
counter = c
|
||||
return counted
|
||||
})
|
||||
store.aggregationWorker.db = store.db
|
||||
return counter
|
||||
}
|
||||
|
||||
func checkTrendStatementsAreConstant(t *testing.T, store *GORMStoreV2) {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
counter := attachCounter(store)
|
||||
|
||||
measure := func() map[string]int {
|
||||
out := map[string]int{}
|
||||
counter.Reset()
|
||||
_, err := store.GetStatsTrend(ctx, daysAgo(365))
|
||||
require.NoError(t, err)
|
||||
out["trend"] = counter.Count()
|
||||
counter.Reset()
|
||||
require.NoError(t, store.aggregationWorker.SnapshotStats(ctx))
|
||||
out["snapshot"] = counter.Count()
|
||||
require.NoError(t, store.db.Exec("DELETE FROM stats_snapshots").Error)
|
||||
counter.Reset()
|
||||
_, err = BackfillStatsSnapshots(ctx, store.db, time.Now().AddDate(0, 0, 400))
|
||||
require.NoError(t, err)
|
||||
out["backfill"] = counter.Count()
|
||||
return out
|
||||
}
|
||||
|
||||
seedScanned(t, store, 0, 10)
|
||||
small := measure()
|
||||
seedScanned(t, store, 10, 90)
|
||||
large := measure()
|
||||
t.Logf("statements for 10 packages %v, for 100 packages %v", small, large)
|
||||
require.Equal(t, small, large)
|
||||
require.Equal(t, 1, large["trend"])
|
||||
require.Equal(t, 2, large["snapshot"], "one aggregate read, one upsert")
|
||||
require.LessOrEqual(t, large["backfill"], 4, "count, packages, scans, one insert batch")
|
||||
require.Positive(t, large["backfill"])
|
||||
}
|
||||
|
||||
func TestStatsSnapshotMigration(t *testing.T) {
|
||||
store := newTimeSeriesStore(t)
|
||||
seedAt(t, store, "a", "1.0.0", 10, daysAgo(2))
|
||||
require.NoError(t, store.db.Migrator().DropTable(&StatsSnapshotModel{}))
|
||||
for _, migration := range GetMigrations() {
|
||||
if migration.ID != "202611250001" {
|
||||
continue
|
||||
}
|
||||
require.NoError(t, migration.Migrate(store.db))
|
||||
require.NoError(t, migration.Migrate(store.db), "rerun must be a no-op")
|
||||
require.Len(t, trendByDay(t, store, daysAgo(10)), 2, "the migration seeds the history")
|
||||
return
|
||||
}
|
||||
t.Fatal("migration 202611250001 is not registered")
|
||||
}
|
||||
@@ -86,6 +86,15 @@ type MetadataStore interface {
|
||||
// the given time, oldest first. A limit <= 0 means DefaultBatchSize.
|
||||
ListExpiredPackages(ctx context.Context, expiredBefore time.Time, limit int) ([]*Package, error)
|
||||
|
||||
// PurgeDeletedPackages hard-deletes up to limit soft-deleted packages whose
|
||||
// deletion is older than deletedBefore, with their scan and vulnerability
|
||||
// rows, and returns the number removed. A limit <= 0 means DefaultBatchSize.
|
||||
PurgeDeletedPackages(ctx context.Context, deletedBefore time.Time, limit int) (int64, error)
|
||||
|
||||
// GetStatsTrend returns the daily stats snapshots from the UTC day of since
|
||||
// on, oldest first. Backends without history return none.
|
||||
GetStatsTrend(ctx context.Context, since time.Time) ([]*StatsSnapshot, error)
|
||||
|
||||
// ClearArtifactExpiry removes ExpiresAt from every non-metadata entry and
|
||||
// returns the number of rows changed. It is idempotent.
|
||||
ClearArtifactExpiry(ctx context.Context) (int64, error)
|
||||
@@ -332,11 +341,42 @@ type GroupListOptions struct {
|
||||
Registry string // empty = every registry
|
||||
Query string // case-insensitive substring of name, version or release version
|
||||
SortBy string // one of the GroupSort* keys; empty = name
|
||||
SortDesc bool
|
||||
Page int // 1-based
|
||||
PageSize int // 0 = every group, unpaginated
|
||||
// Severities keeps rows whose latest scan holds a vulnerability of any listed
|
||||
// severity (SeverityCritical and the like); empty = no severity filter.
|
||||
Severities []string
|
||||
Page int // 1-based
|
||||
PageSize int // 0 = every group, unpaginated
|
||||
SortDesc bool
|
||||
}
|
||||
|
||||
// Severity filter values of GroupListOptions.
|
||||
const (
|
||||
SeverityCritical = "critical"
|
||||
SeverityHigh = "high"
|
||||
SeverityModerate = "moderate"
|
||||
SeverityLow = "low"
|
||||
)
|
||||
|
||||
// Severities lists the severity filter values, most severe first.
|
||||
var Severities = []string{SeverityCritical, SeverityHigh, SeverityModerate, SeverityLow}
|
||||
|
||||
// StatsSnapshot is the cache state at the end of one UTC day. The pointer
|
||||
// fields are nil for days whose value cannot be reconstructed.
|
||||
type StatsSnapshot struct {
|
||||
VulnerablePackages *int64 `json:"vulnerable_packages"`
|
||||
Critical *int64 `json:"critical"`
|
||||
High *int64 `json:"high"`
|
||||
Moderate *int64 `json:"moderate"`
|
||||
Low *int64 `json:"low"`
|
||||
Blocked *int64 `json:"blocked"`
|
||||
Date string `json:"date"` // YYYY-MM-DD, UTC
|
||||
TotalPackages int64 `json:"total_packages"`
|
||||
TotalSize int64 `json:"total_size"`
|
||||
}
|
||||
|
||||
// StatsSnapshotDateLayout is the layout of StatsSnapshot.Date.
|
||||
const StatsSnapshotDateLayout = "2006-01-02"
|
||||
|
||||
// GroupPage is one page of groups, flattened to rows.
|
||||
type GroupPage struct {
|
||||
// Packages holds every version row of each group on the page, in group
|
||||
|
||||
@@ -134,6 +134,12 @@ func (m *stubMetadataStore) ListExpiredPackages(context.Context, time.Time, int)
|
||||
return nil, nil
|
||||
}
|
||||
func (m *stubMetadataStore) ClearArtifactExpiry(context.Context) (int64, error) { return 0, nil }
|
||||
func (m *stubMetadataStore) PurgeDeletedPackages(context.Context, time.Time, int) (int64, error) {
|
||||
return 0, nil
|
||||
}
|
||||
func (m *stubMetadataStore) GetStatsTrend(context.Context, time.Time) ([]*metadata.StatsSnapshot, error) {
|
||||
return nil, nil
|
||||
}
|
||||
func (m *stubMetadataStore) SaveAPIKey(context.Context, *metadata.APIKey) error {
|
||||
return metadata.ErrNotImplemented
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user