mirror of
https://github.com/lukaszraczylo/gohoarder.git
synced 2026-11-27 06:46:01 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
13abb140d7 | ||
|
|
378b8731fc | ||
|
|
a83cc20058 | ||
|
|
501bf1aec8 | ||
|
|
527c1759f9 | ||
|
|
933b5a75c0 | ||
|
|
f4cf96e1e8 | ||
|
|
aa8487ad87 | ||
|
|
2ada975065 | ||
|
|
b98e761c90 | ||
|
|
a457e3d2e8 | ||
|
|
ba8bc392ec | ||
|
|
1512230ab3 | ||
|
|
bd9d686383 | ||
|
|
4d31e535ff | ||
|
|
fe2d9f8b3a | ||
|
|
a84f080b79 | ||
|
|
9b4659218c | ||
|
|
1256756057 | ||
|
|
262771d224 | ||
|
|
536f35ab55 |
+6
-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
|
||||
@@ -85,6 +85,8 @@ server {
|
||||
proxy_set_header X-Forwarded-Host $host;
|
||||
proxy_set_header X-Forwarded-Port $server_port;
|
||||
proxy_set_header Connection "";
|
||||
# The backend authenticates by API-key header; browser session cookies only bloat the request.
|
||||
proxy_set_header Cookie "";
|
||||
|
||||
# Timeouts for long-running operations
|
||||
proxy_connect_timeout 60s;
|
||||
@@ -122,6 +124,7 @@ server {
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_set_header Cookie "";
|
||||
|
||||
# WebSocket timeouts
|
||||
proxy_connect_timeout 7d;
|
||||
@@ -144,6 +147,8 @@ server {
|
||||
|
||||
# Frontend SPA - serve index.html for all other routes
|
||||
location / {
|
||||
# index.html names the hashed bundles; a cached copy keeps serving the previous release.
|
||||
add_header Cache-Control "no-cache" always;
|
||||
try_files $uri $uri/ /index.html;
|
||||
}
|
||||
}
|
||||
|
||||
+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,9 @@ 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
|
||||
|
||||
logging:
|
||||
@@ -255,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
|
||||
|
||||
+4
-2
@@ -10,6 +10,7 @@ server:
|
||||
host: "0.0.0.0"
|
||||
port: 8080 # Backend API server port
|
||||
read_timeout: "5m"
|
||||
read_buffer_size: 16384 # Bytes for the request line plus headers; larger requests get 431
|
||||
write_timeout: "5m"
|
||||
idle_timeout: "2m"
|
||||
# Origins allowed to call /api from a browser and to open the WebSocket. Exact
|
||||
@@ -96,11 +97,12 @@ 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:
|
||||
ttl_overrides: # Per-registry metadata freshness; replaces default_ttl for that registry. Keys: npm, pypi, go
|
||||
npm: "24h"
|
||||
pip: "24h"
|
||||
pypi: "24h"
|
||||
go: "24h"
|
||||
|
||||
security:
|
||||
|
||||
@@ -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 },
|
||||
],
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ data:
|
||||
host: {{ .Values.server.host | quote }}
|
||||
port: {{ .Values.server.port }}
|
||||
read_timeout: {{ .Values.server.readTimeout | quote }}
|
||||
read_buffer_size: {{ .Values.server.readBufferSize }}
|
||||
write_timeout: {{ .Values.server.writeTimeout | quote }}
|
||||
idle_timeout: {{ .Values.server.idleTimeout | quote }}
|
||||
allowed_origins: {{ .Values.server.allowedOrigins | default list | toJson }}
|
||||
@@ -75,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:
|
||||
|
||||
@@ -91,6 +91,7 @@ server:
|
||||
host: "0.0.0.0"
|
||||
port: 8080
|
||||
readTimeout: "5m"
|
||||
readBufferSize: 16384 # Bytes for the request line plus headers; larger requests get 431
|
||||
writeTimeout: "5m"
|
||||
idleTimeout: "2m"
|
||||
# Browser origins allowed to use /api and /ws; empty = same-origin only
|
||||
@@ -380,11 +381,12 @@ 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:
|
||||
ttlOverrides: # Per-registry metadata freshness; replaces defaultTTL for that registry. Keys: npm, pypi, go
|
||||
npm: "24h"
|
||||
pip: "24h"
|
||||
pypi: "24h"
|
||||
go: "24h"
|
||||
|
||||
# Security scanning configuration
|
||||
|
||||
+14
-5
@@ -26,6 +26,9 @@ Currency: `sh lean4/scripts/check_currency.sh origin/main`.
|
||||
| GH-19 | SSRF | every redirect hop passes the upstream allowlist, the scheme rule and a non-private address check | security, CWE-918 | medium | `Access.redirect_escapes_allowlist`, `fixed_redirect_stays_allowlisted` / `TestRedirectToDisallowedHostRefused`, `TestRedirectToLoopbackRefused`, `TestRedirectToPrivateLiteralRefused`, `TestRedirectAllowedToAllowedWorks`, `TestRedirectHopsCapped`, `TestSidecarRedirectOffAllowlistRefused` | 787c757 |
|
||||
| GH-20 | stats, sqlite | SQLite upserts hourly and daily rows as PostgreSQL does, one row per bucket | correctness | low (SQLite only) | `Stats.old_sqlite_duplicates_rows`, `fixed_sqlite_package_row_keeps_late_events` / `TestSQLiteHourlyTotalsMatchPostgresSemantics`, `TestPostgresHourlyTotalsMatchSQLite`, `TestSQLiteDailyRollupIsIdempotent`, `TestSQLiteStatsDedupeMigration` | f46e079 |
|
||||
| GH-21 | scan retry | a scan retry on S3 or SMB storage reads the stored blob instead of a removed temp file | correctness | low (file-based scanners on remote storage) | `Security.old_remote_retry_unreadable`, `fixed_retry_always_readable` / `TestScanRetryOnRemoteStorageReadsBlobAgain` | 31db940 |
|
||||
| GH-22 | dashboard API | an OIDC-logged-in browser can call `/api` with a long URL; the proxy hop neither forwards session cookies nor exceeds the read buffer | availability | medium (every `/api` call returned 431 for OIDC users) | not modelled (header size, no decision logic) / `TestLargeRequestHeadersAreAccepted`, `TestReadBufferSizeIsConfigurable`, `scripts/check_frontend_cookie_strip.sh` | 536f35a |
|
||||
| GH-23 | PyPI sidecar | pip's PEP 658 request (`<link>.metadata`, suffix on `original_url`) is served as its wheel's sidecar; another file's sidecar is still refused | correctness (pip install failed with 400) | medium (every pip install through the proxy) | `Access.pip_form_keeps_key_binding`, `pip_sidecar_of_other_file_rejected`, `pip_sidecar_of_same_file_accepted` / `TestPipSidecarFormIsStreamed`, `TestHandlePackageFile_OriginalURLFilenameBound` | 501bf1a |
|
||||
| GH-24 | rescan | with `security.rescan_interval` set, artifacts whose scan never completed are scanned and old results refreshed | correctness (scans lost to a restart stayed unscanned; new CVEs never picked up) | medium | not modelled (worker wiring) / `TestWorkersStartTheRescanWorker` | 378b873 |
|
||||
|
||||
### Exploit paths and reach
|
||||
|
||||
@@ -50,16 +53,22 @@ Currency: `sh lean4/scripts/check_currency.sh origin/main`.
|
||||
|
||||
### Notes on the fixed rows
|
||||
|
||||
- **GH-15.** `cache.ttl_overrides` has no consumer in the Go code (`grep TTLOverrides pkg cmd`: the field and its compiled default
|
||||
only). The per-registry keys are kept and now default to 24h; they change nothing until something reads them.
|
||||
- **GH-15.** `cache.ttl_overrides` now has a consumer: `cache.Config.TTLOverrides` sets the metadata freshness per registry
|
||||
(`npm`, `pypi`, `go`; `pip` is an alias of `pypi`), and a registry without an override keeps `default_ttl`. Artifacts keep no
|
||||
age expiry. Defaults hold no override, so lowering `default_ttl` still applies everywhere. Config load rejects an unknown
|
||||
registry key or a non-positive value. Tests: `TestMetadataTTLOverridesApplyPerRegistry`, `TestMetadataTTLOverridesSkipArtifacts`,
|
||||
`TestNPMMetadataTTLOverrideReachesCache`, `TestTTLOverridesValidation`.
|
||||
- **GH-18.** New keys read `ghk_<id>.<secret>`; the hash covers the secret and one lookup selects the stored key. A miss
|
||||
compares a dummy hash. Keys minted before are accepted through a legacy path capped at 4 concurrent bcrypt compares. They
|
||||
cannot be migrated: the raw key holds no id and the stored hash covers the whole raw key. Re-issue them to leave the
|
||||
legacy path. Production holds none.
|
||||
- **GH-20.** SQLite startup merges old duplicate rows (package rows add up, derived rows keep one) and creates the unique indexes.
|
||||
- **GH-21.** `RescanWorker` still skips remote storage ("No local file path available"); that is a separate, unchanged behaviour.
|
||||
- **GH-17 cleanup.** The per-handler `Access-Control-Allow-Origin: *` lines in `pkg/app/handlers*.go` are now overridden by the
|
||||
guard and are dead; remove them once the API performance work lands.
|
||||
- **GH-21.** `RescanWorker` reads each blob through the cache `ScanFile` source, so periodic rescans cover S3 and SMB as well as
|
||||
local storage. A remote blob is copied to a temp file for the scan and removed after it. Test: `TestRescanWorkerScansRemoteStorage`.
|
||||
- **GH-22.** Frontend nginx dropped the `Cookie` header on `/api/` and `/ws` (the backend reads none; keys travel in `Authorization` / `X-API-Key`).
|
||||
The server read buffer is `server.read_buffer_size`, default 16384 (Fiber's default is 8192): a long Referer or `Authorization` no longer gets 431.
|
||||
- **GH-17 cleanup.** The per-handler `Access-Control-*` lines in `pkg/app/handlers*.go` are removed; `apiOriginGuard` is the only CORS
|
||||
source. `TestHandlersSetNoCORSHeaders` and `TestAPIResponsesNeverCarryWildcardOrigin` guard it.
|
||||
|
||||
## Not fixed
|
||||
|
||||
|
||||
@@ -121,6 +121,30 @@ theorem old_guard_allows_key_poisoning :
|
||||
exact ⟨"requests-2.31.0-py3-none-any.whl", ⟨"files.pythonhosted.org", "evil-9.9.9-py3-none-any.whl"⟩,
|
||||
by decide, by decide⟩
|
||||
|
||||
/-- pip requests the PEP 658 sidecar as `<link>.metadata`, so the suffix lands on `original_url` and the
|
||||
request names the sidecar of the requested file. `handlePackageFile` streams it and never stores it. -/
|
||||
def pipSidecar (requested : String) (f : Fetch) : Bool := decide (f.file = requested ++ ".metadata")
|
||||
|
||||
/-- The guard with the pip form: the requested file, or its own sidecar. -/
|
||||
def acceptsPip (requested : String) (f : Fetch) : Bool :=
|
||||
hostAllowed f.host && (decide (f.file = requested) || pipSidecar requested f)
|
||||
|
||||
/-- What the pip form stores still names the key: only the sidecar escapes, and it is not stored. -/
|
||||
theorem pip_form_keeps_key_binding (requested : String) (f : Fetch)
|
||||
(h : acceptsPip requested f = true) (hs : pipSidecar requested f = false) : f.file = requested := by
|
||||
simp only [acceptsPip, Bool.and_eq_true, Bool.or_eq_true, decide_eq_true_eq] at h
|
||||
rcases h.2 with h2 | h2
|
||||
· exact h2
|
||||
· rw [h2] at hs; exact absurd hs (by simp)
|
||||
|
||||
theorem pip_sidecar_of_other_file_rejected :
|
||||
acceptsPip "example-1.0.0-py3-none-any.whl"
|
||||
⟨"files.pythonhosted.org", "evil-9.9.9-py3-none-any.whl.metadata"⟩ = false := by decide
|
||||
|
||||
theorem pip_sidecar_of_same_file_accepted :
|
||||
acceptsPip "example-1.0.0-py3-none-any.whl"
|
||||
⟨"files.pythonhosted.org", "example-1.0.0-py3-none-any.whl.metadata"⟩ = true := by decide
|
||||
|
||||
theorem internal_hosts_rejected :
|
||||
hostAllowed "169.254.169.254" = false ∧ hostAllowed "localhost" = false ∧
|
||||
hostAllowed "metadata.google.internal" = false := by decide
|
||||
|
||||
@@ -56,6 +56,27 @@ theorem old_default_ttl_exceeded_gate :
|
||||
∃ gate ttl now s t : ℤ, now - s ≤ ttl ∧ s < t ∧ gateAccepts gate now t ∧ ttl = 168 ∧ gate = 72 := by
|
||||
exact ⟨72, 168, 200, 100, 116, by decide, by decide, by unfold gateAccepts; decide, rfl, rfl⟩
|
||||
|
||||
/-! ### Per-registry override (`cache.ttl_overrides`, `Manager.metadataTTL`) -/
|
||||
|
||||
/-- The freshness window of a metadata entry: the registry's override when set, else `default_ttl`. -/
|
||||
def effectiveTtl (override : Option ℤ) (default : ℤ) : ℤ := override.getD default
|
||||
|
||||
/-- The staleness bound holds for a registry exactly when its effective window is within the gate. -/
|
||||
theorem override_within_gate_hides_only_gated (gate default now s t : ℤ) (override : Option ℤ)
|
||||
(hcfg : effectiveTtl override default ≤ gate) (hstale : now - s ≤ effectiveTtl override default)
|
||||
(hnew : s < t) : ¬ gateAccepts gate now t :=
|
||||
stale_hides_only_gated gate _ now s t hstale hcfg hnew
|
||||
|
||||
/-- An override replaces `default_ttl`; it does not add to it, and an absent override keeps it. -/
|
||||
theorem override_replaces_default (default o : ℤ) :
|
||||
effectiveTtl (some o) default = o ∧ effectiveTtl none default = default := ⟨rfl, rfl⟩
|
||||
|
||||
/-- An override above the gate loses the bound: operator choice, not enforced by config load. -/
|
||||
theorem override_above_gate_breaks_bound :
|
||||
∃ gate default now s t : ℤ, effectiveTtl (some 168) default = 168 ∧ now - s ≤ 168 ∧ s < t ∧
|
||||
gateAccepts gate now t ∧ gate = 72 := by
|
||||
exact ⟨72, 24, 200, 100, 116, rfl, by decide, by decide, by unfold gateAccepts; decide, rfl⟩
|
||||
|
||||
/-- Publish times never change, so a version present in a stale snapshot is gated identically to a fresh one. -/
|
||||
theorem listed_versions_gated_identically (gate now t : ℤ) : gateAccepts gate now t ↔ gateAccepts gate now t :=
|
||||
Iff.rfl
|
||||
|
||||
@@ -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
|
||||
|
||||
+24
-10
@@ -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,11 +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,
|
||||
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)
|
||||
@@ -313,7 +319,7 @@ func (a *App) initializeComponents() error {
|
||||
// Initialize rescan worker if enabled
|
||||
if a.config.Security.Enabled && a.config.Security.RescanInterval > 0 {
|
||||
log.Info().Dur("interval", a.config.Security.RescanInterval).Msg("Initializing package rescan worker")
|
||||
a.rescanWorker = scanner.NewRescanWorker(a.scanManager, a.metadata, a.storage, a.config.Security.RescanInterval)
|
||||
a.rescanWorker = scanner.NewRescanWorker(a.scanManager, a.metadata, a.config.Security.RescanInterval)
|
||||
}
|
||||
|
||||
// Initialize WebSocket server
|
||||
@@ -391,10 +397,11 @@ func (a *App) initializeComponents() error {
|
||||
func (a *App) setupServer() error {
|
||||
// Create Fiber app
|
||||
a.app = fiber.New(fiber.Config{
|
||||
ReadTimeout: a.config.Server.ReadTimeout,
|
||||
WriteTimeout: a.config.Server.WriteTimeout,
|
||||
ServerHeader: "GoHoarder",
|
||||
AppName: "GoHoarder v1.0",
|
||||
ReadTimeout: a.config.Server.ReadTimeout,
|
||||
WriteTimeout: a.config.Server.WriteTimeout,
|
||||
ReadBufferSize: a.config.Server.ReadBufferSize,
|
||||
ServerHeader: "GoHoarder",
|
||||
AppName: "GoHoarder v1.0",
|
||||
})
|
||||
|
||||
// Auth middleware factories. Built once, reused on every gated route.
|
||||
@@ -444,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)
|
||||
@@ -458,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)
|
||||
@@ -608,6 +617,11 @@ func (a *App) startWorkers(ctx context.Context) {
|
||||
// Start periodic stats broadcaster (every 30s) so connected WS clients
|
||||
// see live counter updates without polling.
|
||||
go a.startStatsBroadcaster(ctx)
|
||||
|
||||
// Re-scans artifacts whose scan was lost to a restart and refreshes old results.
|
||||
if a.rescanWorker != nil {
|
||||
go a.rescanWorker.Start(ctx)
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) Run() error {
|
||||
|
||||
+1
-1
@@ -58,7 +58,7 @@ func apiOriginGuard(allowed []string) fiber.Handler {
|
||||
|
||||
err := c.Next()
|
||||
|
||||
// Handlers set a wildcard grant; replace it with the allowlist decision.
|
||||
// Drop any grant a handler or upstream set; the allowlist decides.
|
||||
c.Response().Header.Del(headerACAllowOrigin)
|
||||
c.Response().Header.Del(headerACAllowMethods)
|
||||
c.Response().Header.Del(headerACAllowHeaders)
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"go/ast"
|
||||
"go/parser"
|
||||
"go/token"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/config"
|
||||
)
|
||||
|
||||
// Handlers must not set CORS headers themselves: apiOriginGuard owns the decision.
|
||||
func TestHandlersSetNoCORSHeaders(t *testing.T) {
|
||||
files, err := filepath.Glob("*.go")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fset := token.NewFileSet()
|
||||
for _, f := range files {
|
||||
if strings.HasSuffix(f, "_test.go") || f == "cors.go" {
|
||||
continue
|
||||
}
|
||||
parsed, err := parser.ParseFile(fset, f, nil, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("parse %s: %v", f, err)
|
||||
}
|
||||
ast.Inspect(parsed, func(n ast.Node) bool {
|
||||
lit, ok := n.(*ast.BasicLit)
|
||||
if !ok || lit.Kind != token.STRING {
|
||||
return true
|
||||
}
|
||||
if v, err := strconv.Unquote(lit.Value); err == nil && strings.HasPrefix(v, "Access-Control-") {
|
||||
t.Errorf("%s: handler sets %q; apiOriginGuard owns CORS", fset.Position(lit.Pos()), v)
|
||||
}
|
||||
return true
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAPIResponsesNeverCarryWildcardOrigin(t *testing.T) {
|
||||
const dashboard = "https://dash.example.com"
|
||||
a := newTestApp(t, func(c *config.Config) { c.Server.AllowedOrigins = []string{dashboard} })
|
||||
targets := []string{
|
||||
"/api/stats", "/api/info", "/api/config", "/api/packages",
|
||||
"/api/analytics/top", "/api/analytics/trending", "/api/analytics/trends", "/api/analytics/total",
|
||||
"/api/analytics/search?q=x", "/api/stats/timeseries",
|
||||
}
|
||||
for _, origin := range []string{"", dashboard, "https://evil.example.net"} {
|
||||
for _, target := range targets {
|
||||
hdr := map[string]string{}
|
||||
if origin != "" {
|
||||
hdr["Origin"] = origin
|
||||
}
|
||||
code, h, _ := doRequest(t, a, target, hdr)
|
||||
if code == http.StatusNotFound {
|
||||
t.Errorf("GET %s = 404, route missing", target)
|
||||
}
|
||||
if got := h.Get("Access-Control-Allow-Origin"); got == "*" {
|
||||
t.Errorf("GET %s Origin=%q carries Access-Control-Allow-Origin: *", target, origin)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
)
|
||||
|
||||
func doDelete(t *testing.T, a *App, target string) (int, string) {
|
||||
t.Helper()
|
||||
req := httptest.NewRequest(http.MethodDelete, target, nil)
|
||||
resp, err := a.app.Test(req, fiber.TestConfig{Timeout: 40 * time.Second})
|
||||
if err != nil {
|
||||
t.Fatalf("DELETE %s: %v", target, err)
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
t.Fatalf("read body: %v", err)
|
||||
}
|
||||
return resp.StatusCode, string(body)
|
||||
}
|
||||
|
||||
func TestDeleteMissingPackageIs404(t *testing.T) {
|
||||
a := newTestApp(t, nil)
|
||||
for _, target := range []string{
|
||||
"/api/packages/npm/nope/1.0.0",
|
||||
"/api/packages/pypi/nope/1.0.0",
|
||||
"/api/packages/go/example.com/nope/v1.0.0",
|
||||
} {
|
||||
code, body := doDelete(t, a, target)
|
||||
if code != http.StatusNotFound {
|
||||
t.Errorf("DELETE %s = %d %s, want 404", target, code, body)
|
||||
}
|
||||
var out map[string]string
|
||||
if err := json.Unmarshal([]byte(body), &out); err != nil || out["error"] == "" {
|
||||
t.Errorf("DELETE %s body %q is not a JSON error", target, body)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteExistingPackageIs200(t *testing.T) {
|
||||
a := newTestApp(t, nil)
|
||||
ctx := context.Background()
|
||||
err := a.metadata.SavePackage(ctx, &metadata.Package{
|
||||
Registry: "npm", Name: "left-pad", Version: "1.0.0", StorageKey: "npm/left-pad/1.0.0",
|
||||
Size: 10, CachedAt: time.Now(), LastAccessed: time.Now(),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("SavePackage: %v", err)
|
||||
}
|
||||
|
||||
code, body := doDelete(t, a, "/api/packages/npm/left-pad/1.0.0")
|
||||
if code != http.StatusOK || !strings.Contains(body, `"deleted":true`) {
|
||||
t.Fatalf("DELETE existing = %d %s, want 200 deleted", code, body)
|
||||
}
|
||||
if code, body := doDelete(t, a, "/api/packages/npm/left-pad/1.0.0"); code != http.StatusNotFound {
|
||||
t.Errorf("second DELETE = %d %s, want 404", code, body)
|
||||
}
|
||||
}
|
||||
+40
-31
@@ -2,11 +2,15 @@ package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
stderrors "errors"
|
||||
"fmt"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/lukaszraczylo/gohoarder/internal/version"
|
||||
apperrors "github.com/lukaszraczylo/gohoarder/pkg/errors"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/websocket"
|
||||
@@ -16,9 +20,6 @@ import (
|
||||
// handlePackages handles /api/packages endpoint
|
||||
func (a *App) handlePackages(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "application/json")
|
||||
c.Set("Access-Control-Allow-Origin", "*")
|
||||
c.Set("Access-Control-Allow-Methods", "GET, DELETE, OPTIONS")
|
||||
c.Set("Access-Control-Allow-Headers", "Content-Type")
|
||||
|
||||
if c.Method() == "OPTIONS" {
|
||||
return c.SendStatus(fiber.StatusOK)
|
||||
@@ -70,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"),
|
||||
@@ -89,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)
|
||||
@@ -98,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.
|
||||
@@ -146,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 {
|
||||
@@ -291,6 +316,10 @@ func (a *App) handleDeletePackage(c fiber.Ctx) error {
|
||||
} else {
|
||||
// For NPM and PyPI, delete directly
|
||||
if err := a.cache.Delete(ctx, registry, name, version); err != nil {
|
||||
var appErr *apperrors.Error
|
||||
if stderrors.As(err, &appErr) && appErr.Code == apperrors.ErrCodeNotFound {
|
||||
return c.Status(fiber.StatusNotFound).JSON(fiber.Map{"error": "package not found"})
|
||||
}
|
||||
log.Error().
|
||||
Err(err).
|
||||
Str("registry", registry).
|
||||
@@ -330,9 +359,6 @@ func (a *App) handleDeletePackage(c fiber.Ctx) error {
|
||||
// handleStats handles /api/stats endpoint
|
||||
func (a *App) handleStats(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "application/json")
|
||||
c.Set("Access-Control-Allow-Origin", "*")
|
||||
c.Set("Access-Control-Allow-Methods", "GET, OPTIONS")
|
||||
c.Set("Access-Control-Allow-Headers", "Content-Type")
|
||||
|
||||
if c.Method() == "OPTIONS" {
|
||||
return c.SendStatus(fiber.StatusOK)
|
||||
@@ -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
|
||||
@@ -410,9 +428,6 @@ func (a *App) handleStats(c fiber.Ctx) error {
|
||||
// Returns time-series download statistics for charts
|
||||
func (a *App) handleTimeSeriesStats(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "application/json")
|
||||
c.Set("Access-Control-Allow-Origin", "*")
|
||||
c.Set("Access-Control-Allow-Methods", "GET, OPTIONS")
|
||||
c.Set("Access-Control-Allow-Headers", "Content-Type")
|
||||
|
||||
if c.Method() == "OPTIONS" {
|
||||
return c.SendStatus(fiber.StatusOK)
|
||||
@@ -452,9 +467,6 @@ func (a *App) handleTimeSeriesStats(c fiber.Ctx) error {
|
||||
// Returns runtime configuration for the frontend
|
||||
func (a *App) handleConfig(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "application/json")
|
||||
c.Set("Access-Control-Allow-Origin", "*")
|
||||
c.Set("Access-Control-Allow-Methods", "GET, OPTIONS")
|
||||
c.Set("Access-Control-Allow-Headers", "Content-Type")
|
||||
|
||||
if c.Method() == "OPTIONS" {
|
||||
return c.SendStatus(fiber.StatusOK)
|
||||
@@ -486,9 +498,6 @@ func (a *App) handleConfig(c fiber.Ctx) error {
|
||||
// handleInfo handles /api/info endpoint
|
||||
func (a *App) handleInfo(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "application/json")
|
||||
c.Set("Access-Control-Allow-Origin", "*")
|
||||
c.Set("Access-Control-Allow-Methods", "GET, OPTIONS")
|
||||
c.Set("Access-Control-Allow-Headers", "Content-Type")
|
||||
|
||||
if c.Method() == "OPTIONS" {
|
||||
return c.SendStatus(fiber.StatusOK)
|
||||
|
||||
@@ -45,9 +45,6 @@ func (a *App) requireAdmin(c fiber.Ctx) error {
|
||||
// handleAdminBypasses handles /api/admin/bypasses endpoint
|
||||
func (a *App) handleAdminBypasses(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "application/json")
|
||||
c.Set("Access-Control-Allow-Origin", "*")
|
||||
c.Set("Access-Control-Allow-Methods", "GET, POST, PATCH, DELETE, OPTIONS")
|
||||
c.Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
|
||||
|
||||
if c.Method() == "OPTIONS" {
|
||||
return c.SendStatus(fiber.StatusOK)
|
||||
|
||||
@@ -10,7 +10,6 @@ import (
|
||||
// handleAnalyticsTopPackages returns the most downloaded packages
|
||||
func (a *App) handleAnalyticsTopPackages(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "application/json")
|
||||
c.Set("Access-Control-Allow-Origin", "*")
|
||||
|
||||
// Get limit from query params (default: 10)
|
||||
limit := 10
|
||||
@@ -31,7 +30,6 @@ func (a *App) handleAnalyticsTopPackages(c fiber.Ctx) error {
|
||||
// handleAnalyticsTrendingPackages returns trending packages
|
||||
func (a *App) handleAnalyticsTrendingPackages(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "application/json")
|
||||
c.Set("Access-Control-Allow-Origin", "*")
|
||||
|
||||
// Get limit from query params (default: 10)
|
||||
limit := 10
|
||||
@@ -52,7 +50,6 @@ func (a *App) handleAnalyticsTrendingPackages(c fiber.Ctx) error {
|
||||
// handleAnalyticsTrends returns download trends over time
|
||||
func (a *App) handleAnalyticsTrends(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "application/json")
|
||||
c.Set("Access-Control-Allow-Origin", "*")
|
||||
|
||||
trends := a.analyticsEngine.GetTrends()
|
||||
|
||||
@@ -64,7 +61,6 @@ func (a *App) handleAnalyticsTrends(c fiber.Ctx) error {
|
||||
// handleAnalyticsTotalStats returns overall statistics
|
||||
func (a *App) handleAnalyticsTotalStats(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "application/json")
|
||||
c.Set("Access-Control-Allow-Origin", "*")
|
||||
|
||||
stats := a.analyticsEngine.GetTotalStats()
|
||||
|
||||
@@ -74,7 +70,6 @@ func (a *App) handleAnalyticsTotalStats(c fiber.Ctx) error {
|
||||
// handleAnalyticsRegistryStats returns per-registry statistics
|
||||
func (a *App) handleAnalyticsRegistryStats(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "application/json")
|
||||
c.Set("Access-Control-Allow-Origin", "*")
|
||||
|
||||
registry := c.Params("registry")
|
||||
if registry == "" {
|
||||
@@ -91,7 +86,6 @@ func (a *App) handleAnalyticsRegistryStats(c fiber.Ctx) error {
|
||||
// handleAnalyticsPackageStats returns statistics for a specific package
|
||||
func (a *App) handleAnalyticsPackageStats(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "application/json")
|
||||
c.Set("Access-Control-Allow-Origin", "*")
|
||||
|
||||
registry := c.Params("registry")
|
||||
name := c.Params("name")
|
||||
@@ -117,7 +111,6 @@ func (a *App) handleAnalyticsPackageStats(c fiber.Ctx) error {
|
||||
// handleAnalyticsSearch searches for packages matching a query
|
||||
func (a *App) handleAnalyticsSearch(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "application/json")
|
||||
c.Set("Access-Control-Allow-Origin", "*")
|
||||
|
||||
query := c.Query("q")
|
||||
if query == "" {
|
||||
|
||||
@@ -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"
|
||||
@@ -11,9 +12,6 @@ import (
|
||||
// handleVulnerabilities handles /api/packages/{registry}/{name}/{version}/vulnerabilities endpoint
|
||||
func (a *App) handleVulnerabilities(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "application/json")
|
||||
c.Set("Access-Control-Allow-Origin", "*")
|
||||
c.Set("Access-Control-Allow-Methods", "GET, OPTIONS")
|
||||
c.Set("Access-Control-Allow-Headers", "Content-Type")
|
||||
|
||||
if c.Method() == "OPTIONS" {
|
||||
return c.SendStatus(fiber.StatusOK)
|
||||
@@ -45,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"})
|
||||
@@ -172,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
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ package app
|
||||
import (
|
||||
"archive/zip"
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net"
|
||||
@@ -18,6 +19,7 @@ import (
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/config"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
)
|
||||
|
||||
// newTestApp builds a full App on temp storage with the given config tweaks.
|
||||
@@ -284,3 +286,33 @@ func TestPyPI_UVExcludeNewerResolvesThroughProxy(t *testing.T) {
|
||||
t.Fatalf("uv resolved foo although it was uploaded after the cutoff:\n%s", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNPMMetadataTTLOverrideReachesCache(t *testing.T) {
|
||||
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
_, _ = w.Write([]byte(`{"name":"left-pad","versions":{}}`))
|
||||
}))
|
||||
t.Cleanup(upstream.Close)
|
||||
|
||||
a := newTestApp(t, func(c *config.Config) {
|
||||
c.Handlers.NPM.UpstreamRegistry = upstream.URL
|
||||
c.Cache.TTLOverrides = map[string]time.Duration{"npm": 90 * time.Minute}
|
||||
})
|
||||
if code, _, body := doRequest(t, a, "/npm/left-pad", nil); code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body %q", code, body)
|
||||
}
|
||||
|
||||
pkgs, err := a.metadata.ListPackages(context.Background(), &metadata.ListOptions{Registry: "npm"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, p := range pkgs {
|
||||
if p.ExpiresAt == nil {
|
||||
continue
|
||||
}
|
||||
if got := p.ExpiresAt.Sub(p.CachedAt); got < 89*time.Minute || got > 91*time.Minute {
|
||||
t.Errorf("npm metadata freshness = %s, want 90m from cache.ttl_overrides", got)
|
||||
}
|
||||
return
|
||||
}
|
||||
t.Fatalf("no npm metadata entry with an expiry among %d packages", len(pkgs))
|
||||
}
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/config"
|
||||
)
|
||||
|
||||
const recentPackagesURL = "/api/packages?page=1&page_size=10&sort=cached_at&order=desc"
|
||||
|
||||
// Fiber v3 defaults to an 8192-byte read buffer; OIDC session cookies plus a long Referer exceed it.
|
||||
func TestLargeRequestHeadersAreAccepted(t *testing.T) {
|
||||
a := newTestApp(t, nil)
|
||||
headers := map[string]string{
|
||||
"Cookie": "session=" + strings.Repeat("a", 5000),
|
||||
"Referer": "https://dash.example.com/" + strings.Repeat("r", 5000),
|
||||
}
|
||||
code, _, body := doRequest(t, a, recentPackagesURL, headers)
|
||||
if code != http.StatusOK {
|
||||
t.Fatalf("GET with ~10KB of headers = %d %q, want 200", code, body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadBufferSizeIsConfigurable(t *testing.T) {
|
||||
if got := config.Default().Server.ReadBufferSize; got != 16384 {
|
||||
t.Fatalf("default server.read_buffer_size = %d, want 16384", got)
|
||||
}
|
||||
a := newTestApp(t, func(c *config.Config) { c.Server.ReadBufferSize = 4096 })
|
||||
req := httptest.NewRequest(http.MethodGet, recentPackagesURL, nil)
|
||||
req.Header.Set("Cookie", "session="+strings.Repeat("a", 6000))
|
||||
if _, err := a.app.Test(req); err == nil || !strings.Contains(err.Error(), "small read buffer") {
|
||||
t.Errorf("6KB header with a 4096 buffer: err = %v, want a small-read-buffer rejection", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/config"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
)
|
||||
|
||||
// A cached artifact whose scan never completed (lost to a restart) is scanned once the
|
||||
// workers start, when security.rescan_interval is set.
|
||||
func TestWorkersStartTheRescanWorker(t *testing.T) {
|
||||
osv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"vulns":[]}`))
|
||||
}))
|
||||
defer osv.Close()
|
||||
|
||||
a := newTestApp(t, func(c *config.Config) {
|
||||
c.Security.Enabled = true
|
||||
c.Security.RescanInterval = time.Hour
|
||||
c.Security.Scanners.OSV.Enabled = true
|
||||
c.Security.Scanners.OSV.APIURL = osv.URL
|
||||
})
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
const key = "npm/left-pad/1.3.0"
|
||||
if err := a.storage.Put(ctx, key, strings.NewReader("tarball"), nil); err != nil {
|
||||
t.Fatalf("storage.Put: %v", err)
|
||||
}
|
||||
now := time.Now()
|
||||
err := a.metadata.SavePackage(ctx, &metadata.Package{
|
||||
Registry: "npm", Name: "left-pad", Version: "1.3.0", StorageKey: key,
|
||||
Size: 7, CachedAt: now, LastAccessed: now,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("SavePackage: %v", err)
|
||||
}
|
||||
|
||||
a.startWorkers(ctx)
|
||||
|
||||
deadline := time.Now().Add(20 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
if _, err := a.metadata.GetScanResult(ctx, "npm", "left-pad", "1.3.0"); err == nil {
|
||||
return
|
||||
}
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
}
|
||||
t.Fatal("no scan result after the workers started; the rescan worker never ran")
|
||||
}
|
||||
@@ -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,58 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/config"
|
||||
)
|
||||
|
||||
func listTree(t *testing.T, dir string) string {
|
||||
t.Helper()
|
||||
var names []string
|
||||
err := filepath.Walk(dir, func(p string, _ os.FileInfo, err error) error {
|
||||
if err == nil {
|
||||
names = append(names, p)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return strings.Join(names, "\n")
|
||||
}
|
||||
|
||||
// Shutdown must leave nothing running against the data directory: a late SQLite close deletes
|
||||
// its -wal/-shm files after Shutdown returned and breaks the removal of the directory.
|
||||
func TestShutdownLeavesDataDirectoryStable(t *testing.T) {
|
||||
for i := 0; i < 40; i++ {
|
||||
dir := t.TempDir()
|
||||
cfg := config.Default()
|
||||
cfg.Storage.Backend = "filesystem"
|
||||
cfg.Storage.Path = filepath.Join(dir, "store")
|
||||
cfg.Metadata.Backend = "sqlite"
|
||||
cfg.Metadata.SQLite.Path = filepath.Join(dir, "meta", "meta.db")
|
||||
if err := os.MkdirAll(filepath.Dir(cfg.Metadata.SQLite.Path), 0o750); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg.Security.Enabled = false
|
||||
cfg.Prewarming.Enabled = false
|
||||
cfg.Auth.Enabled = false
|
||||
a, err := New(cfg)
|
||||
if err != nil {
|
||||
t.Fatalf("New: %v", err)
|
||||
}
|
||||
doRequest(t, a, "/api/stats", nil)
|
||||
if err := a.Shutdown(); err != nil {
|
||||
t.Fatalf("Shutdown: %v", err)
|
||||
}
|
||||
before := listTree(t, dir)
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
if after := listTree(t, dir); before != after {
|
||||
t.Fatalf("iteration %d: data directory changed after Shutdown:\nbefore:\n%s\nafter:\n%s", i, before, after)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
+14
-6
@@ -16,15 +16,23 @@ func TestWorkersDrainTheBroadcastChannel(t *testing.T) {
|
||||
defer cancel()
|
||||
a.startWorkers(ctx)
|
||||
|
||||
const events = 1000
|
||||
for i := 0; i < events; i++ {
|
||||
a.wsServer.BroadcastEvent("cache_hit", map[string]interface{}{"i": i})
|
||||
if i%200 == 0 {
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
// Bursts stay under the 256-slot channel and wait for the loop to drain between them, so the
|
||||
// result depends on the loop running, not on how fast the scheduler runs it.
|
||||
const (
|
||||
bursts = 10
|
||||
burstLen = 100
|
||||
)
|
||||
for b := 0; b < bursts; b++ {
|
||||
for i := 0; i < burstLen; i++ {
|
||||
a.wsServer.BroadcastEvent("cache_hit", map[string]interface{}{"i": i})
|
||||
}
|
||||
deadline := time.Now().Add(10 * time.Second)
|
||||
for a.wsServer.Pending() > 0 && time.Now().Before(deadline) {
|
||||
time.Sleep(time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
if dropped := a.wsServer.Dropped(); dropped != 0 {
|
||||
t.Fatalf("dropped %d of %d events; the broadcast loop is not draining the channel", dropped, events)
|
||||
t.Fatalf("dropped %d of %d events; the broadcast loop is not draining the channel", dropped, bursts*burstLen)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
+49
-10
@@ -80,15 +80,17 @@ func (m *Manager) emit(eventType string, payload map[string]interface{}) {
|
||||
|
||||
// Config holds cache manager configuration
|
||||
type Config struct {
|
||||
Now func() time.Time // Clock; nil means time.Now
|
||||
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)
|
||||
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)
|
||||
ScanWaitTimeout time.Duration // How long the first download waits for its scan (0 = 30s)
|
||||
FailClosed bool // Refuse a package whose scan did not finish in time
|
||||
Now func() time.Time // Clock; nil means time.Now
|
||||
TTLOverrides map[string]time.Duration // Per-registry metadata freshness TTL; falls back to DefaultTTL
|
||||
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)
|
||||
ScanWaitTimeout time.Duration // How long the first download waits for its scan (0 = 30s)
|
||||
FailClosed bool // Refuse a package whose scan did not finish in time
|
||||
}
|
||||
|
||||
const defaultScanWaitTimeout = 30 * time.Second
|
||||
@@ -96,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
|
||||
|
||||
@@ -586,7 +591,7 @@ func (m *Manager) store(ctx context.Context, registry, name, version, releaseVer
|
||||
// entries must refresh and keep a freshness expiry.
|
||||
var expiresAt *time.Time
|
||||
if isMetadataEntry {
|
||||
exp := now.Add(m.config.DefaultTTL)
|
||||
exp := now.Add(m.metadataTTL(registry))
|
||||
expiresAt = &exp
|
||||
}
|
||||
|
||||
@@ -737,6 +742,14 @@ func (m *Manager) Delete(ctx context.Context, registry, name, version string) er
|
||||
return m.deletePackage(ctx, pkg)
|
||||
}
|
||||
|
||||
// metadataTTL returns the freshness window for a registry's metadata entries.
|
||||
func (m *Manager) metadataTTL(registry string) time.Duration {
|
||||
if ttl, ok := m.config.TTLOverrides[registry]; ok {
|
||||
return ttl
|
||||
}
|
||||
return m.config.DefaultTTL
|
||||
}
|
||||
|
||||
// deletePackage deletes a package from both storage and metadata
|
||||
func (m *Manager) deletePackage(ctx context.Context, pkg *metadata.Package) error {
|
||||
// Delete from storage
|
||||
@@ -908,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")
|
||||
}
|
||||
Vendored
+75
@@ -0,0 +1,75 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/config"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// listingMetadata adds the full listing the rescan worker walks.
|
||||
type listingMetadata struct{ scanMetadata }
|
||||
|
||||
func (m listingMetadata) ListPackages(context.Context, *metadata.ListOptions) ([]*metadata.Package, error) {
|
||||
return m.list(0, func(*metadata.Package) bool { return true }, func(a, b *metadata.Package) bool { return a.Name < b.Name }), nil
|
||||
}
|
||||
|
||||
// bodyScanner reports the bytes it can read at the path it is given.
|
||||
type bodyScanner struct{ seen chan string }
|
||||
|
||||
func (*bodyScanner) Name() string { return "body-scanner" }
|
||||
func (*bodyScanner) Health(context.Context) error { return nil }
|
||||
func (s *bodyScanner) Scan(_ context.Context, registry, name, version, path string) (*metadata.ScanResult, error) {
|
||||
body, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
s.seen <- "unreadable"
|
||||
return nil, err
|
||||
}
|
||||
s.seen <- string(body)
|
||||
return &metadata.ScanResult{Registry: registry, PackageName: name, PackageVersion: version, Scanner: s.Name(), Status: metadata.ScanStatusClean}, nil
|
||||
}
|
||||
|
||||
// A backend with no local path (S3, SMB) must still be rescanned: the worker reads the blob
|
||||
// through the cache's file source instead of skipping the package.
|
||||
func TestRescanWorkerScansRemoteStorage(t *testing.T) {
|
||||
clock := newFakeClock()
|
||||
store := newMemStorage() // no GetLocalPath, like S3 and SMB
|
||||
meta := listingMetadata{scanMetadata{newMemMetadata(clock)}}
|
||||
|
||||
scanMgr, err := scanner.New(config.SecurityConfig{Enabled: true}, meta)
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(scanMgr.Stop)
|
||||
bs := &bodyScanner{seen: make(chan string, 8)}
|
||||
scanMgr.RegisterScanner(bs)
|
||||
|
||||
mgr, err := New(store, meta, scanMgr, nil, Config{Now: clock.Now, CleanupInterval: 24 * time.Hour})
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { _ = mgr.Close() })
|
||||
scanMgr.SetFileSource(mgr.ScanFile)
|
||||
|
||||
ctx := context.Background()
|
||||
require.NoError(t, store.Put(ctx, "npm/left-pad/1.3.0", strings.NewReader("tarball-bytes"), nil))
|
||||
require.NoError(t, meta.SavePackage(ctx, &metadata.Package{
|
||||
Registry: "npm", Name: "left-pad", Version: "1.3.0", StorageKey: "npm/left-pad/1.3.0",
|
||||
CachedAt: clock.Now(), LastAccessed: clock.Now(),
|
||||
}))
|
||||
|
||||
worker := scanner.NewRescanWorker(scanMgr, meta, time.Hour)
|
||||
runCtx, cancel := context.WithCancel(ctx)
|
||||
done := make(chan struct{})
|
||||
go func() { worker.Start(runCtx); close(done) }()
|
||||
t.Cleanup(func() { cancel(); <-done })
|
||||
|
||||
select {
|
||||
case got := <-bs.seen:
|
||||
require.Equal(t, "tarball-bytes", got)
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("rescan never scanned the remote-storage package")
|
||||
}
|
||||
}
|
||||
Vendored
+38
@@ -0,0 +1,38 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func (h *idleHarness) getFrom(t *testing.T, registry, name, version string) *CacheEntry {
|
||||
t.Helper()
|
||||
entry, err := h.mgr.Get(context.Background(), registry, name, version, func(context.Context) (*FetchResult, error) {
|
||||
return &FetchResult{Data: io.NopCloser(strings.NewReader("payload-" + name)), UpstreamURL: "https://upstream/" + name}, nil
|
||||
})
|
||||
require.NoError(t, err)
|
||||
_ = entry.Data.Close()
|
||||
return entry
|
||||
}
|
||||
|
||||
func TestMetadataTTLOverridesApplyPerRegistry(t *testing.T) {
|
||||
h := newIdleHarness(t, Config{
|
||||
DefaultTTL: 6 * time.Hour,
|
||||
TTLOverrides: map[string]time.Duration{"npm": time.Hour, "go": 12 * time.Hour},
|
||||
})
|
||||
|
||||
require.Equal(t, time.Hour, h.getFrom(t, "npm", "left-pad", "metadata").Package.ExpiresAt.Sub(h.clock.Now()))
|
||||
require.Equal(t, 12*time.Hour, h.getFrom(t, "go", "example.com/m/@v/list", "list").Package.ExpiresAt.Sub(h.clock.Now()))
|
||||
require.Equal(t, 6*time.Hour, h.getFrom(t, "pypi", "left-pad", "metadata").Package.ExpiresAt.Sub(h.clock.Now()), "registry without override keeps default_ttl")
|
||||
}
|
||||
|
||||
func TestMetadataTTLOverridesSkipArtifacts(t *testing.T) {
|
||||
h := newIdleHarness(t, Config{TTLOverrides: map[string]time.Duration{"npm": time.Hour}})
|
||||
|
||||
require.Nil(t, h.getFrom(t, "npm", "left-pad", artifactVer).Package.ExpiresAt, "artifacts have no age expiry")
|
||||
}
|
||||
+50
-17
@@ -35,6 +35,7 @@ type ServerConfig struct {
|
||||
ReadTimeout time.Duration `mapstructure:"read_timeout" json:"read_timeout"`
|
||||
WriteTimeout time.Duration `mapstructure:"write_timeout" json:"write_timeout"`
|
||||
IdleTimeout time.Duration `mapstructure:"idle_timeout" json:"idle_timeout"`
|
||||
ReadBufferSize int `mapstructure:"read_buffer_size" json:"read_buffer_size"` // bytes; caps the request line plus headers
|
||||
}
|
||||
|
||||
// TLSConfig contains TLS/HTTPS configuration
|
||||
@@ -137,17 +138,38 @@ type MySQLConfig struct {
|
||||
// release-age gate clients apply, so a cached page never hides the entries the gate reads.
|
||||
const DefaultMetadataTTL = 24 * time.Hour
|
||||
|
||||
// DefaultReadBufferSize is the HTTP server read buffer. Fiber's own 8192 rejects browsers
|
||||
// that send OIDC session cookies plus a long Referer or URL with 431.
|
||||
const DefaultReadBufferSize = 16384
|
||||
|
||||
// ttlOverrideRegistries maps each accepted cache.ttl_overrides key to its registry name.
|
||||
var ttlOverrideRegistries = map[string]string{"npm": "npm", "pypi": "pypi", "pip": "pypi", "go": "go"}
|
||||
|
||||
// MetadataTTLOverrides returns the per-registry metadata freshness TTLs keyed by registry name.
|
||||
func (c CacheConfig) MetadataTTLOverrides() map[string]time.Duration {
|
||||
out := make(map[string]time.Duration, len(c.TTLOverrides))
|
||||
for key, ttl := range c.TTLOverrides {
|
||||
out[ttlOverrideRegistries[key]] = ttl
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// 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
|
||||
@@ -334,11 +356,12 @@ type PyPIHandlerConfig struct {
|
||||
func Default() *Config {
|
||||
return &Config{
|
||||
Server: ServerConfig{
|
||||
Host: "0.0.0.0",
|
||||
Port: 8080,
|
||||
ReadTimeout: 5 * time.Minute,
|
||||
WriteTimeout: 5 * time.Minute,
|
||||
IdleTimeout: 2 * time.Minute,
|
||||
Host: "0.0.0.0",
|
||||
Port: 8080,
|
||||
ReadTimeout: 5 * time.Minute,
|
||||
WriteTimeout: 5 * time.Minute,
|
||||
IdleTimeout: 2 * time.Minute,
|
||||
ReadBufferSize: DefaultReadBufferSize,
|
||||
TLS: TLSConfig{
|
||||
Enabled: false,
|
||||
},
|
||||
@@ -359,16 +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
|
||||
TTLOverrides: map[string]time.Duration{
|
||||
"npm": DefaultMetadataTTL,
|
||||
"pip": DefaultMetadataTTL,
|
||||
"go": DefaultMetadataTTL,
|
||||
},
|
||||
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,
|
||||
@@ -511,12 +530,26 @@ func (c *Config) Validate() error {
|
||||
}
|
||||
|
||||
// Validate cache
|
||||
if c.Server.ReadBufferSize < 0 {
|
||||
return fmt.Errorf("server.read_buffer_size cannot be negative")
|
||||
}
|
||||
if c.Cache.DefaultTTL < 0 {
|
||||
return fmt.Errorf("cache.default_ttl cannot be negative")
|
||||
}
|
||||
if c.Cache.IdleTTL < 0 {
|
||||
return fmt.Errorf("cache.idle_ttl cannot be negative")
|
||||
}
|
||||
for key, ttl := range c.Cache.TTLOverrides {
|
||||
if _, ok := ttlOverrideRegistries[key]; !ok {
|
||||
return fmt.Errorf("cache.ttl_overrides: unknown registry %q (want npm, pypi or go)", key)
|
||||
}
|
||||
if ttl <= 0 {
|
||||
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")
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package config
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -37,3 +38,51 @@ func TestShippedExamplesKeepMetadataTTLWithinGate(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestTTLOverridesValidation(t *testing.T) {
|
||||
for name, tc := range map[string]struct {
|
||||
overrides map[string]time.Duration
|
||||
wantErr string
|
||||
}{
|
||||
"known registries": {map[string]time.Duration{"npm": time.Hour, "pypi": time.Hour, "go": time.Hour}, ""},
|
||||
"pip alias": {map[string]time.Duration{"pip": time.Hour}, ""},
|
||||
"unknown registry": {map[string]time.Duration{"cargo": time.Hour}, "cache.ttl_overrides"},
|
||||
"zero": {map[string]time.Duration{"npm": 0}, "cache.ttl_overrides"},
|
||||
"negative": {map[string]time.Duration{"go": -time.Hour}, "cache.ttl_overrides"},
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
c := Default()
|
||||
c.Cache.TTLOverrides = tc.overrides
|
||||
err := c.Validate()
|
||||
if tc.wantErr == "" {
|
||||
require.NoError(t, err)
|
||||
return
|
||||
}
|
||||
require.ErrorContains(t, err, tc.wantErr)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestMetadataTTLOverridesNormalisesPip(t *testing.T) {
|
||||
c := CacheConfig{TTLOverrides: map[string]time.Duration{"pip": time.Hour, "npm": 2 * time.Hour}}
|
||||
require.Equal(t, map[string]time.Duration{"pypi": time.Hour, "npm": 2 * time.Hour}, c.MetadataTTLOverrides())
|
||||
}
|
||||
|
||||
func TestDefaultsKeepNoTTLOverrides(t *testing.T) {
|
||||
require.Empty(t, Default().Cache.TTLOverrides, "an unset override must not shadow default_ttl")
|
||||
}
|
||||
|
||||
func TestLoadReadsTTLOverridesFromYAML(t *testing.T) {
|
||||
write := func(body string) string {
|
||||
path := filepath.Join(t.TempDir(), "config.yaml")
|
||||
require.NoError(t, os.WriteFile(path, []byte(body), 0o600))
|
||||
return path
|
||||
}
|
||||
|
||||
cfg, err := Load(write("cache:\n ttl_overrides:\n npm: 2h\n pip: 30m\n"))
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, map[string]time.Duration{"npm": 2 * time.Hour, "pypi": 30 * time.Minute}, cfg.Cache.MetadataTTLOverrides())
|
||||
|
||||
_, err = Load(write("cache:\n ttl_overrides:\n cargo: 2h\n"))
|
||||
require.ErrorContains(t, err, "cache.ttl_overrides")
|
||||
}
|
||||
|
||||
@@ -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,8 @@
|
||||
package gormstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/rs/zerolog/log"
|
||||
@@ -17,6 +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
|
||||
@@ -36,6 +42,15 @@ func (w *AggregationWorker) clock() time.Time {
|
||||
return time.Now()
|
||||
}
|
||||
|
||||
// StartAsync runs Start in a goroutine that Stop waits for.
|
||||
func (w *AggregationWorker) StartAsync() {
|
||||
w.wg.Add(1)
|
||||
go func() {
|
||||
defer w.wg.Done()
|
||||
w.Start()
|
||||
}()
|
||||
}
|
||||
|
||||
// Start begins the aggregation worker
|
||||
func (w *AggregationWorker) Start() {
|
||||
log.Info().Msg("Starting aggregation worker")
|
||||
@@ -68,9 +83,10 @@ func (w *AggregationWorker) Start() {
|
||||
}
|
||||
}
|
||||
|
||||
// Stop stops the aggregation worker
|
||||
// Stop stops the aggregation worker and waits for a started one to exit. Safe to call repeatedly.
|
||||
func (w *AggregationWorker) Stop() {
|
||||
close(w.stopChan)
|
||||
w.stopOnce.Do(func() { close(w.stopChan) })
|
||||
w.wg.Wait()
|
||||
}
|
||||
|
||||
// AggregateHourly aggregates download events into hourly stats
|
||||
@@ -276,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 {
|
||||
@@ -371,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
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
package gormstore
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestCloseIsIdempotent(t *testing.T) {
|
||||
store := openFileStore(t, true)
|
||||
if err := store.Close(); err != nil {
|
||||
t.Fatalf("first Close: %v", err)
|
||||
}
|
||||
if err := store.Close(); err != nil {
|
||||
t.Fatalf("second Close: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -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,10 +125,17 @@ 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)
|
||||
go store.aggregationWorker.Start()
|
||||
store.aggregationWorker.StartAsync()
|
||||
} else {
|
||||
// For tests: create worker but don't start it
|
||||
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
|
||||
|
||||
@@ -22,6 +22,9 @@ func TestHandlePackageFile_OriginalURLFilenameBound(t *testing.T) {
|
||||
{"same file", path, "https://files.pythonhosted.org/packages/ab/cd/ef/example-1.0.0-py3-none-any.whl", false},
|
||||
{"same file with query", path, "https://files.pythonhosted.org/packages/ab/cd/ef/example-1.0.0-py3-none-any.whl?x=1", false},
|
||||
{"sidecar of same file", path + ".metadata", "https://files.pythonhosted.org/packages/ab/cd/ef/example-1.0.0-py3-none-any.whl", false},
|
||||
// pip appends ".metadata" to the whole link, so the suffix lands on original_url instead of the path.
|
||||
{"pip sidecar of same file", path, "https://files.pythonhosted.org/packages/ab/cd/ef/example-1.0.0-py3-none-any.whl.metadata", false},
|
||||
{"pip sidecar of another file", path, "https://files.pythonhosted.org/packages/ab/cd/ef/evil-9.9.9-py3-none-any.whl.metadata", true},
|
||||
}
|
||||
|
||||
h := newHandlerForSSRFTest()
|
||||
|
||||
@@ -288,6 +288,11 @@ func (h *Handler) handlePackageFile(ctx context.Context, w http.ResponseWriter,
|
||||
parsed.RawPath = ""
|
||||
originalURL = parsed.String()
|
||||
}
|
||||
// pip appends ".metadata" to the whole link, so the suffix lands on original_url, not the path.
|
||||
if !isSidecar && gopath.Base(parsed.Path) == filename+metadataSuffix {
|
||||
isSidecar = true
|
||||
filename += metadataSuffix
|
||||
}
|
||||
if !isAllowedPyPIHost(parsed.Host, h.allowedHosts) {
|
||||
log.Warn().
|
||||
Str("original_url", originalURL).
|
||||
|
||||
@@ -39,3 +39,31 @@ func TestSidecarRedirectOffAllowlistRefused(t *testing.T) {
|
||||
t.Errorf("redirect target was fetched (hits=%d)", hit.Load())
|
||||
}
|
||||
}
|
||||
|
||||
// pip requests the PEP 658 sidecar as <link>.metadata, which puts the suffix on original_url.
|
||||
// It must be streamed as a sidecar, never cached as the wheel.
|
||||
func TestPipSidecarFormIsStreamed(t *testing.T) {
|
||||
const meta = "Metadata-Version: 2.1\nName: example\n"
|
||||
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if !strings.HasSuffix(r.URL.Path, "/example-1.0.0-py3-none-any.whl.metadata") {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
_, _ = w.Write([]byte(meta))
|
||||
}))
|
||||
defer upstream.Close()
|
||||
|
||||
client := network.NewClient(network.Config{Timeout: 5 * time.Second, MaxRetries: 1, AllowPrivateRedirects: true})
|
||||
// No cache: touching it would panic, so a 200 proves the request never reached the wheel path.
|
||||
h := &Handler{client: client, allowedHosts: []string{"127.0.0.1"}}
|
||||
|
||||
const path = "/example/example-1.0.0-py3-none-any.whl"
|
||||
q := url.Values{"original_url": {upstream.URL + "/files/example-1.0.0-py3-none-any.whl.metadata"}}
|
||||
req := httptest.NewRequest(http.MethodGet, path+"?"+q.Encode(), nil)
|
||||
w := httptest.NewRecorder()
|
||||
h.handlePackageFile(req.Context(), w, req, path)
|
||||
|
||||
if w.Code != http.StatusOK || w.Body.String() != meta {
|
||||
t.Errorf("code=%d body=%q, want 200 with the metadata", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
+17
-29
@@ -6,14 +6,12 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/storage"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
// RescanWorker handles periodic re-scanning of cached packages
|
||||
type RescanWorker struct {
|
||||
metadataStore metadata.MetadataStore
|
||||
storage storage.StorageBackend
|
||||
manager *Manager
|
||||
stopCh chan struct{}
|
||||
stopOnce sync.Once
|
||||
@@ -21,11 +19,10 @@ type RescanWorker struct {
|
||||
}
|
||||
|
||||
// NewRescanWorker creates a new rescan worker
|
||||
func NewRescanWorker(manager *Manager, metadataStore metadata.MetadataStore, storageBackend storage.StorageBackend, interval time.Duration) *RescanWorker {
|
||||
func NewRescanWorker(manager *Manager, metadataStore metadata.MetadataStore, interval time.Duration) *RescanWorker {
|
||||
return &RescanWorker{
|
||||
manager: manager,
|
||||
metadataStore: metadataStore,
|
||||
storage: storageBackend,
|
||||
interval: interval,
|
||||
stopCh: make(chan struct{}),
|
||||
}
|
||||
@@ -123,7 +120,6 @@ func (w *RescanWorker) rescanPackages(ctx context.Context) {
|
||||
Str("version", pkg.Version).
|
||||
Msg("Package needs rescanning")
|
||||
|
||||
// Get file path from storage using the storage key from the package metadata
|
||||
if pkg.StorageKey == "" {
|
||||
log.Warn().
|
||||
Str("registry", pkg.Registry).
|
||||
@@ -134,7 +130,18 @@ func (w *RescanWorker) rescanPackages(ctx context.Context) {
|
||||
continue
|
||||
}
|
||||
|
||||
filePath, err := w.getPackageFilePath(ctx, pkg.StorageKey)
|
||||
source := w.manager.currentFileSource()
|
||||
if source == nil {
|
||||
log.Debug().
|
||||
Str("registry", pkg.Registry).
|
||||
Str("package", pkg.Name).
|
||||
Str("version", pkg.Version).
|
||||
Msg("No file source configured, skipping rescan")
|
||||
skipped++
|
||||
continue
|
||||
}
|
||||
|
||||
filePath, cleanup, err := source(ctx, pkg.Registry, pkg.Name, pkg.Version)
|
||||
if err != nil {
|
||||
log.Warn().
|
||||
Err(err).
|
||||
@@ -142,23 +149,15 @@ func (w *RescanWorker) rescanPackages(ctx context.Context) {
|
||||
Str("package", pkg.Name).
|
||||
Str("version", pkg.Version).
|
||||
Str("storage_key", pkg.StorageKey).
|
||||
Msg("Failed to get package file path, skipping rescan")
|
||||
Msg("Failed to read package file, skipping rescan")
|
||||
failed++
|
||||
continue
|
||||
}
|
||||
|
||||
if filePath == "" {
|
||||
log.Debug().
|
||||
Str("registry", pkg.Registry).
|
||||
Str("package", pkg.Name).
|
||||
Str("version", pkg.Version).
|
||||
Msg("No local file path available, skipping rescan")
|
||||
skipped++
|
||||
continue
|
||||
}
|
||||
|
||||
// Perform the actual scan
|
||||
if err := w.manager.ScanPackage(ctx, pkg.Registry, pkg.Name, pkg.Version, filePath); err != nil {
|
||||
err = w.manager.ScanPackage(ctx, pkg.Registry, pkg.Name, pkg.Version, filePath)
|
||||
cleanup()
|
||||
if err != nil {
|
||||
log.Error().
|
||||
Err(err).
|
||||
Str("registry", pkg.Registry).
|
||||
@@ -210,14 +209,3 @@ func (w *RescanWorker) needsRescan(ctx context.Context, pkg *metadata.Package) (
|
||||
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// getPackageFilePath retrieves the local file path for a package from storage
|
||||
func (w *RescanWorker) getPackageFilePath(ctx context.Context, storageKey string) (string, error) {
|
||||
// Check if storage backend supports local paths
|
||||
if localProvider, ok := w.storage.(storage.LocalPathProvider); ok {
|
||||
return localProvider.GetLocalPath(ctx, storageKey)
|
||||
}
|
||||
|
||||
// If storage doesn't support local paths (S3, SMB), we can't rescan
|
||||
return "", nil
|
||||
}
|
||||
|
||||
@@ -65,6 +65,12 @@ func (m *Manager) SetFileSource(fs FileSource) {
|
||||
m.stateMu.Unlock()
|
||||
}
|
||||
|
||||
func (m *Manager) currentFileSource() FileSource {
|
||||
m.stateMu.Lock()
|
||||
defer m.stateMu.Unlock()
|
||||
return m.fileSource
|
||||
}
|
||||
|
||||
// Manager manages multiple security scanners
|
||||
type Manager struct {
|
||||
metadataStore metadata.MetadataStore
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -251,6 +251,11 @@ func (s *Server) Dropped() uint64 {
|
||||
return s.dropped.Load()
|
||||
}
|
||||
|
||||
// Pending returns how many events wait in the broadcast channel.
|
||||
func (s *Server) Pending() int {
|
||||
return len(s.broadcast)
|
||||
}
|
||||
|
||||
// BroadcastEvent satisfies the events.Broadcaster contract used by
|
||||
// cache/scanner sub-systems. It accepts a string event type and an
|
||||
// arbitrary payload (typically map[string]any) and forwards to the
|
||||
|
||||
Executable
+57
@@ -0,0 +1,57 @@
|
||||
#!/bin/sh
|
||||
# Builds the frontend image from a Dockerfile and checks that /api and /ws do not forward the
|
||||
# browser's Cookie header to the backend. Usage: scripts/check_frontend_cookie_strip.sh [Dockerfile]
|
||||
set -eu
|
||||
|
||||
dockerfile="${1:-Dockerfile.frontend}"
|
||||
root="$(git rev-parse --show-toplevel)"
|
||||
work="$(mktemp -d)"
|
||||
tag="gohoarder-frontend-cookie-check:$$"
|
||||
net="gohoarder-cookie-check-$$"
|
||||
stub="$net-backend"
|
||||
front="$net-frontend"
|
||||
|
||||
cleanup() {
|
||||
docker rm -f "$front" "$stub" >/dev/null 2>&1 || true
|
||||
docker network rm "$net" >/dev/null 2>&1 || true
|
||||
docker rmi "$tag" >/dev/null 2>&1 || true
|
||||
rm -rf "$work"
|
||||
}
|
||||
trap cleanup EXIT
|
||||
|
||||
mkdir -p "$work/frontend/dist"
|
||||
echo '<html></html>' >"$work/frontend/dist/index.html"
|
||||
cp "$root/$dockerfile" "$work/Dockerfile"
|
||||
docker build -q --load -t "$tag" "$work" >/dev/null
|
||||
|
||||
cat >"$work/stub.conf" <<'CONF'
|
||||
server {
|
||||
listen 8080;
|
||||
location / { default_type text/plain; return 200 "cookie=[$http_cookie]"; }
|
||||
}
|
||||
CONF
|
||||
|
||||
docker network create "$net" >/dev/null
|
||||
docker run -d --name "$stub" --network "$net" -v "$work/stub.conf:/etc/nginx/conf.d/default.conf:ro" nginx:alpine >/dev/null
|
||||
docker run -d --name "$front" --network "$net" -e BACKEND_HOST="$stub" -e BACKEND_PORT=8080 "$tag" >/dev/null
|
||||
|
||||
cookie="session=$(head -c 8000 /dev/zero | tr '\0' 'a')"
|
||||
status=0
|
||||
for path in /api/packages /ws; do
|
||||
ok=no
|
||||
for _ in 1 2 3 4 5 6 7 8 9 10; do
|
||||
body="$(docker exec "$front" wget -qO- --header "Cookie: $cookie" "http://127.0.0.1$path" 2>/dev/null || true)"
|
||||
[ -n "$body" ] && ok=yes && break
|
||||
sleep 1
|
||||
done
|
||||
if [ "$ok" = no ]; then
|
||||
echo "FAIL: $path returned no body"
|
||||
status=1
|
||||
elif [ "$body" = "cookie=[]" ]; then
|
||||
echo "ok: $path forwards no Cookie"
|
||||
else
|
||||
echo "FAIL: $path forwarded a Cookie header ($(printf '%s' "$body" | wc -c) bytes)"
|
||||
status=1
|
||||
fi
|
||||
done
|
||||
exit "$status"
|
||||
Executable
+48
@@ -0,0 +1,48 @@
|
||||
#!/bin/sh
|
||||
# Builds the frontend image from a Dockerfile and checks that the SPA HTML is revalidated on every
|
||||
# load while hashed assets stay immutable. A cached index.html keeps old bundles after a deploy.
|
||||
# Usage: scripts/check_frontend_html_cache.sh [Dockerfile]
|
||||
set -eu
|
||||
|
||||
dockerfile="${1:-Dockerfile.frontend}"
|
||||
root="$(git rev-parse --show-toplevel)"
|
||||
work="$(mktemp -d)"
|
||||
tag="gohoarder-frontend-cache-check:$$"
|
||||
front="gohoarder-cache-check-$$"
|
||||
|
||||
cleanup() {
|
||||
docker rm -f "$front" >/dev/null 2>&1 || true
|
||||
docker rmi "$tag" >/dev/null 2>&1 || true
|
||||
rm -rf "$work"
|
||||
}
|
||||
trap cleanup EXIT
|
||||
|
||||
mkdir -p "$work/frontend/dist/assets"
|
||||
echo '<html></html>' >"$work/frontend/dist/index.html"
|
||||
echo 'console.log(1)' >"$work/frontend/dist/assets/index-abc123.js"
|
||||
cp "$root/$dockerfile" "$work/Dockerfile"
|
||||
docker build -q --load -t "$tag" "$work" >/dev/null
|
||||
docker run -d --name "$front" -e BACKEND_HOST=127.0.0.1 -e BACKEND_PORT=8080 "$tag" >/dev/null
|
||||
|
||||
headers() {
|
||||
for _ in 1 2 3 4 5 6 7 8 9 10; do
|
||||
out="$(docker exec "$front" wget -S -qO /dev/null "http://127.0.0.1$1" 2>&1 || true)"
|
||||
case "$out" in *"HTTP/"*) printf '%s' "$out" | grep -i 'cache-control' || true; return ;; esac
|
||||
sleep 1
|
||||
done
|
||||
}
|
||||
|
||||
status=0
|
||||
for path in / /index.html /packages /package/go/example.com/mod/v1.0.0; do
|
||||
cc="$(headers "$path")"
|
||||
case "$cc" in
|
||||
*no-cache*) echo "ok: $path is revalidated" ;;
|
||||
*) echo "FAIL: $path Cache-Control [$cc], want no-cache"; status=1 ;;
|
||||
esac
|
||||
done
|
||||
cc="$(headers /assets/index-abc123.js)"
|
||||
case "$cc" in
|
||||
*immutable*) echo "ok: hashed asset is immutable" ;;
|
||||
*) echo "FAIL: asset Cache-Control [$cc], want immutable"; status=1 ;;
|
||||
esac
|
||||
exit "$status"
|
||||
Reference in New Issue
Block a user