Compare commits

...
27 Commits
Author SHA1 Message Date
lukaszraczylo e6d8ed0f2e fix(scanner): reuse a recent scanner health result
Each /health request ran the version command of every scanner. Under rescan load one round took about 1.4 seconds, which exceeds the client probes that use /health to choose the cache. The result is now reused for 30 seconds. A probe that ends with a cancelled context is not stored.
2026-11-23 19:47:16 +00:00
lukaszraczylo 40ed8f8213 docs(lean): model rescan skip and on-access freshness as GH-26
The rescan worker skip predicate matches the serve path. A hit whose scan is
older than the interval is judged on a fresh scan, or on the previous result
when the rescan times out.
2026-11-23 19:30:16 +00:00
lukaszraczylo ecf750adbb feat(cache): rescan stale cache hits before serving
With security.rescan_on_access and rescan_interval set, a hit whose scan
result is missing or older than the interval is rescanned before it is
served. Concurrent hits share one scan, and the scan runs under the
manager context so a client disconnect does not abort it. The wait is
bounded by scan_wait_timeout. On a timeout the previous result decides,
or the first-download rule applies when none exists.
2026-11-23 19:27:49 +00:00
lukaszraczylo 41f8369c43 feat(rescan): limit rescans to active packages and run them in parallel
security.rescan_active_window skips packages not requested within the
window. security.rescan_concurrency runs a bounded pool of scans per
cycle. The cycle summary reports skips by reason. Both options default
to the previous behaviour.
2026-11-23 19:26:10 +00:00
lukaszraczylo d6044cdd2e fix(rescan): skip Go .mod and .info rows in the rescan worker
The worker kept its own list of metadata versions and scanned Go module
metadata rows that the serve path never scans. It now uses
metadata.IsMetadataEntry like the cache layer.
2026-11-23 19:25:28 +00:00
lukaszraczylo 1baa6b8e26 docs(lean): model the merge of error results as GH-25
Add the merge model for error-status results and the ledger row. One
error result with one clean result reads clean, all errors read error,
and an error never hides a finding.
2026-11-23 18:07:30 +00:00
lukaszraczylo 3d6bda3a5f fix(pip-audit): audit the release from a pinned requirement
pip-audit takes a project directory as its positional argument and has
no --pyproject option, so every wheel and sdist scan failed. The scanner
now audits name==version from a requirements file with --no-deps and
--disable-pip.

It reads stdout only, lists each advisory once, and treats a skip_reason
as an error because pip-audit exits 0 for a package it could not audit.
2026-11-23 18:07:27 +00:00
lukaszraczylo e37c797602 fix(govulncheck): scan the module as a dependency and read the stream
govulncheck prints indented JSON objects. The line parser read none of
them, so every module read clean.

govulncheck also never reports advisories against the main module of the
tree it scans. A scan of the x/text 0.3.5 source found nothing. The
module is now a dependency of a wrapper module that imports its
packages, and the scan runs at module level.
2026-11-23 18:07:21 +00:00
lukaszraczylo 157814cf08 fix(npm-audit): audit the package through a wrapper project
npm 11 prints via as an array and metadata.dependencies as an object, so
the parser failed on every report. It now reads both shapes of via and
lists each advisory once.

The lockfile step resolved devDependencies, which took 28 seconds for
dayjs and reported 142 findings in its development tree. The tarball is
now the only dependency of a wrapper project, audited with --omit=dev.
This also audits the package itself, which npm audit skips for a root.
2026-11-23 18:07:00 +00:00
lukaszraczylo 65aa2e25dc fix(grype): parse file sources and scan packages by purl
grype 0.121 prints source.target as a string for file, directory and
purl sources. The parser expected an object and failed every scan.

A bare npm, PyPI or Go archive holds nothing grype can catalog, so a
scan of the archive read minimist 0.0.8 as clean. The scanner now passes
a purl for these registries and falls back to the file for others.
2026-11-23 18:06:57 +00:00
lukaszraczylo 3731ca05ce fix(scanner): leave failed scanner results out of the merge
A scanner that returns a result with status error now counts as a failed
scanner, like one that returns an error. Its result no longer joins the
merge, and the manager counts it as an infrastructure failure or another
failure by its cause.

The merged status is error only when every applicable scanner failed.
The fail_closed setting then decides that case as before. One scanner
failing while another returns clean now reads clean.
2026-11-23 18:06:54 +00:00
lukaszraczylo 8adb1e0c87 build: pin the scanner image tool versions
The scanner image installed trivy and grype from install scripts on the main branch, govulncheck at latest and pip-audit unpinned, so every build could pull different tools. They are now pinned: trivy v0.76.2, grype v0.121.2, govulncheck v1.9.0 and pip-audit 2.10.1, each released at least two weeks ago.
2026-11-23 17:37:51 +00:00
lukaszraczylo 16fb52ed3e feat(config): make the first-download scan wait configurable
The cache waited a fixed 30 seconds for a first download's scan, and the app never set the wait. Scanners run one after another, so a deployment with several scanners and fail_closed refused most first downloads. security.scan_wait_timeout now sets the wait; 0 keeps 30 seconds.
2026-11-23 17:37:45 +00:00
lukaszraczylo 13abb140d7 docs(lean): record the GH-24 fix commit 2026-11-23 17:24:58 +00:00
lukaszraczylo 378b8731fc fix(app): start the rescan worker
The app created the rescan worker when security.rescan_interval was set but never started it; only Shutdown called Stop. A scan lost to a restart therefore left its package unscanned for good, and old results were never refreshed with new CVEs. startWorkers now starts the worker. The ledger records it as GH-24.
2026-11-23 17:24:55 +00:00
lukaszraczylo a83cc20058 docs(lean): record the GH-23 fix commit 2026-11-23 17:08:24 +00:00
lukaszraczylo 501bf1aec8 fix(pypi): serve pip's PEP 658 metadata requests
pip builds the PEP 658 URL by appending .metadata to the whole link, so the suffix lands on original_url, not the path. The filename binding from GH-01 then rejected the request with 400, and every pip install through the proxy failed. The handler now treats that form as the requested wheel's sidecar and streams it without storing it. A sidecar of another file is still refused. The Lean model and the ledger cover the new form (GH-23).
2026-11-23 17:08:20 +00:00
lukaszraczylo 527c1759f9 fix(frontend): revalidate index.html on every load
nginx sent index.html without Cache-Control, so browsers cached it heuristically. After a deploy, a browser kept loading the previous hashed bundle until the cache expired, and fixes did not appear. The SPA location now sends Cache-Control: no-cache. Hashed assets stay immutable. scripts/check_frontend_html_cache.sh checks both.
2026-11-23 16:36:10 +00:00
lukaszraczylo 933b5a75c0 fix(ui): read nested stats from stats_update events
The server sends stats_update as {stats, timestamp}, but the realtime store read the counters from the top level of the payload. About 30 seconds after load, the first broadcast replaced the polled stats with undefined values, and the dashboard tiles showed 0. The store now unwraps the nested stats object.
2026-11-23 16:30:22 +00:00
lukaszraczylo f4cf96e1e8 fix(api): resolve Go module paths to cache keys for vulnerability details
The dashboard links Go packages by module path, but Go rows are stored under cache keys (module/@v/version.zip, .mod, .info). The vulnerability details lookup used the module path, so every Go details page returned 404 "package not found". The handler now falls back to the .zip key, then .mod and .info.
2026-11-23 15:49:33 +00:00
lukaszraczylo aa8487ad87 build: pull pinned base images from mirror.gcr.io
Docker Hub rate-limited the v0.1.328 release build, so goreleaser kept retrying the base image pulls. The Dockerfiles now pull alpine 3.24.4 and nginx 1.31.9-alpine from mirror.gcr.io, pinned by digest. Those digests are what alpine:latest and nginx:alpine resolved to, so the images are unchanged, and a release no longer moves silently with a floating tag.
2026-11-23 15:28:01 +00:00
lukaszraczylo 2ada975065 fix(ui): name trend series by the packages they count
The severity series now read "Packages with <severity> vulnerabilities",
which matches the severity tiles and the snapshot counts.
2026-11-23 15:12:15 +00:00
lukaszraczylo b98e761c90 fix(stats): count a package under every severity it holds
The trend snapshot counted each vulnerable package once, under its
highest severity. The Vulnerable packages tiles and the severity
filter count a package under every severity its latest scan holds.
The two views disagreed, for example low 0 against 8 packages.

The snapshot and the backfill now use the filter definition, so a
package with high and low findings counts under both. A test compares
the snapshot with the filter result on one fixture.
2026-11-23 15:12:12 +00:00
lukaszraczylo a457e3d2e8 test(metadata): stop the aggregation worker before counting statements 2026-11-23 14:58:44 +00:00
lukaszraczylo ba8bc392ec feat(cache): purge soft-deleted package rows after a retention period
The cleanup worker now hard-deletes package rows whose deleted_at is
older than cache.deleted_retention. The default is 30 days. A value of
0 keeps the rows. The purge runs in bounded batches, with at most 100
batches per cleanup pass, and removes child rows with the package.

History tables have no foreign key to packages, and stats_snapshots
holds its own counts, so the purge leaves both untouched. The cleanup
log line now reports purged_deleted and deleted_retention.
2026-11-23 14:55:26 +00:00
lukaszraczylo 1512230ab3 feat(stats): record daily snapshots and serve a trend API
The aggregation worker now writes one row per UTC day to
stats_snapshots. The row holds package count, total size, vulnerable
package count, the four severity counts and the blocked count. The
write is an idempotent upsert per day.

A migration backfills package counts from cached_at and deleted_at as
the number of packages alive at the end of each day. Vulnerability
fields backfill from scan_results timestamps and stay empty before the
first scan. GET /api/stats/trend returns daily points for 30day, 90day
or 1year with a constant number of queries.

The Stats page shows a chart of cached and vulnerable packages with a
period selector and severity toggles. The Dashboard shows a compact
version. The Lean model gains theorems for the backfill and upsert.
2026-11-23 14:55:19 +00:00
lukaszraczylo bd9d686383 feat(vulnerable): filter vulnerable packages by severity
The four severity tiles on the vulnerable packages page are now toggle
buttons with aria-pressed. Each tile shows "Filter on" while active.
A tile selects packages with at least one vulnerability of that
severity. Several tiles combine with OR. A second click clears the
tile, and a Clear filters control clears all of them.

The selection lives in the URL (?severity=critical,high), so it
survives a reload and works as a link. An empty result shows the
library empty state with a clear action.

GET /api/packages accepts a severity list. The page uses it to load
only vulnerable packages instead of the whole cache. The filter is a
subquery on the latest scan result, so the statement count does not
grow with the number of rows. An unknown severity returns 400.
2026-11-23 14:54:44 +00:00
107 changed files with 8065 additions and 593 deletions
+3 -1
View File
@@ -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
@@ -147,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
View File
@@ -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
+5 -5
View File
@@ -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
@@ -23,17 +23,17 @@ RUN apk add --no-cache \
&& update-ca-certificates
# Install Trivy for container scanning
RUN curl -sfL https://raw.githubusercontent.com/aquasecurity/trivy/main/contrib/install.sh | sh -s -- -b /usr/local/bin
RUN curl -sfL https://raw.githubusercontent.com/aquasecurity/trivy/v0.76.2/contrib/install.sh | sh -s -- -b /usr/local/bin v0.76.2
# Install Grype for vulnerability scanning
RUN curl -sSfL https://raw.githubusercontent.com/anchore/grype/main/install.sh | sh -s -- -b /usr/local/bin
RUN curl -sSfL https://raw.githubusercontent.com/anchore/grype/v0.121.2/install.sh | sh -s -- -b /usr/local/bin v0.121.2
# Install govulncheck for Go vulnerability scanning
RUN go install golang.org/x/vuln/cmd/govulncheck@latest && \
RUN go install golang.org/x/vuln/cmd/govulncheck@v1.9.0 && \
mv /root/go/bin/govulncheck /usr/local/bin/
# Install pip-audit for Python package vulnerability scanning
RUN pip3 install --no-cache-dir pip-audit --break-system-packages
RUN pip3 install --no-cache-dir pip-audit==2.10.1 --break-system-packages
# Create non-root user
RUN addgroup -g 1000 scanner && \
+1 -1
View File
@@ -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
+3
View File
@@ -236,6 +236,7 @@ security:
cache:
default_ttl: 24h # Freshness window for metadata pages (version lists, package documents)
idle_ttl: 168h # Remove cached items not requested for 7 days; 0 disables
deleted_retention: 720h # Purge deleted package rows after 30 days; 0 keeps them
ttl_overrides: # Per-registry metadata freshness (npm, pypi, go); replaces default_ttl, never applies to artifacts
pypi: 12h
cleanup_interval: 1h
@@ -257,6 +258,8 @@ Every `cleanup_interval` the cleanup run removes:
- **Idle items.** Any cached item, artifact or metadata page, whose last request is older than `idle_ttl` (default `168h`, seven days). Each request, hit or miss, resets the clock. Set `idle_ttl: 0` to turn idle eviction off.
- **Stale metadata.** Version lists, package documents and Go `.mod`/`.info` files past `default_ttl` (default `24h`, below the 72h release-age gate clients apply). They refresh on the next request.
- **Deleted rows.** Evicting or deleting a package marks its database row deleted. Rows deleted longer ago than `deleted_retention` (default `720h`, 30 days) are removed for good, in batches of 500. Download history and the daily trend snapshots are kept. Set `deleted_retention: 0` to keep every row.
Artifacts (tarballs, wheels, module zips) never expire by age, so a package that clients keep requesting stays cached. Size-based LRU eviction at `max_size_bytes` is unchanged. Removed items keep their download history in the statistics.
### Environment Variables
+6
View File
@@ -97,6 +97,7 @@ cache:
default_ttl: "24h" # Freshness window for metadata pages (version lists, packuments, .mod/.info); artifacts never expire by age
cleanup_interval: "1h"
idle_ttl: "168h" # Remove cached items not requested for this long; "0" disables
deleted_retention: "720h" # Purge deleted package rows after this long; "0" keeps them forever
max_size_bytes: 536870912000 # 500GB
per_project_quota: 53687091200 # 50GB
ttl_overrides: # Per-registry metadata freshness; replaces default_ttl for that registry. Keys: npm, pypi, go
@@ -109,9 +110,14 @@ security:
block_on_severity: "high" # none, low, medium, high, critical
scan_on_download: true # Scan packages on first download
rescan_interval: "24h" # How often to re-scan packages (e.g., 24h, 168h for weekly)
rescan_active_window: "0s" # Rescan only packages requested within this window (e.g., 720h); 0 = all packages
rescan_on_access: false # Rescan a cached package on download when its scan is older than rescan_interval, before serving it
rescan_concurrency: 1 # Scans run in parallel during one rescan cycle; values below 1 mean 1
# When a scan fails on infrastructure (timeout, upstream 5xx) the package is served and the
# scan is retried every scan_retry_interval. Set fail_closed to refuse such packages instead.
fail_closed: false
# How long a first download waits for its scan before it is served (or refused with fail_closed). Default 30s.
scan_wait_timeout: "30s"
scan_retry_interval: "5m"
update_db_on_startup: false # Update vulnerability databases on startup
allowed_packages: [] # Packages that bypass security checks (format: "registry/name@version")
+7 -2
View File
@@ -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
+33 -29
View File
@@ -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'
+52 -5
View File
@@ -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>
+3
View File
@@ -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'
+213
View File
@@ -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])
})
})
+196
View File
@@ -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')
})
})
+79 -8
View File
@@ -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) => {
+2 -1
View File
@@ -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 } }
+63
View File
@@ -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)
}
+15
View File
@@ -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 } })
+7 -3
View File
@@ -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
+16
View File
@@ -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'))
+3 -1
View File
@@ -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
}
}
+3
View File
@@ -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";
+16
View File
@@ -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 },
],
}
+1
View File
@@ -76,6 +76,7 @@ data:
default_ttl: {{ .Values.cache.defaultTTL | quote }}
cleanup_interval: {{ .Values.cache.cleanupInterval | quote }}
idle_ttl: {{ .Values.cache.idleTTL | quote }}
deleted_retention: {{ .Values.cache.deletedRetention | default "720h" | quote }}
max_size_bytes: {{ .Values.cache.maxSizeBytes }}
per_project_quota: {{ .Values.cache.perProjectQuota }}
ttl_overrides:
+1
View File
@@ -381,6 +381,7 @@ cache:
defaultTTL: "24h" # Freshness window for metadata pages; keep below the 72h client release-age gate
cleanupInterval: "1h"
idleTTL: "168h" # Remove cached items not requested for this long; "0" disables
deletedRetention: "720h" # Purge deleted package rows after this long; "0" keeps them forever
maxSizeBytes: 536870912000 # 500GB
perProjectQuota: 53687091200 # 50GB
ttlOverrides: # Per-registry metadata freshness; replaces defaultTTL for that registry. Keys: npm, pypi, go
+25 -2
View File
@@ -26,7 +26,11 @@ 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` | this change |
| 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 |
| GH-25 | scanners | an error result from one scanner is left out of the merge, so the row reads error only when every scanner failed; grype, npm-audit, govulncheck and pip-audit give correct results with the scanner image tool versions | correctness (false error, false clean) | high (grype, npm-audit and pip-audit failed on every package; govulncheck and a bare-archive grype scan read vulnerable packages clean) | `Security.old_error_poisons_clean`, `error_and_clean_reads_clean`, `all_error_reads_error`, `merged_not_error_when_one_ran` / `TestScanPackage_ErrorResultPlusCleanReadsClean`, `TestScanPackage_AllErrorResultsReadError`, `TestScanPackage_InfrastructureErrorResultsCountAsInfrastructure`, `TestScanMapsRealOutput`, `TestParseKeepsBothViaShapes`, `TestScanReadsPrettyPrintedFindings`, `TestScanAuditsTheReleaseFromARequirement` | 3731ca0 |
| GH-26 | rescan | the rescan worker skips the entries the serve path skips, so Go `.mod` and `.info` rows are no longer scanned | cost (1316 of about 2780 rescans on production were these rows, about 3.3 s each) | low | `Cache.old_rescan_scanned_go_metadata`, `rescan_skips_what_serve_skips` / `TestRescanSkipsMetadataEntries` | d6044cd |
### Exploit paths and reach
@@ -65,8 +69,27 @@ Currency: `sh lean4/scripts/check_currency.sh origin/main`.
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-25.** `scan` treats an error-status result like a returned error: it is left out of the merge and counted as an
infrastructure failure (`infrastructure_error` in its details, set on a deadline or an unreachable network) or another failure.
Before, one such result made the merged row an error and `evaluateScan` blocked the package even with `fail_closed: false`.
Defects found by running the published scanner image (grype 0.121.2, npm 11.12.1, govulncheck 1.9.0, pip-audit 2.10.1,
go 1.26), each with a fixture of real output under the scanner's `testdata/`:
grype: `source.target` is a string for file and purl sources, and a bare archive has nothing to catalog, so minimist 0.0.8 read clean;
the scanner now passes a purl. npm audit: `via` is an array and `metadata.dependencies` an object in npm 11; the lockfile
step resolved devDependencies (dayjs: 1567 packages, 142 findings, 28s) and `npm audit` cannot report the root package itself;
the tarball is now installed into a wrapper project and audited with `--omit=dev` (under 1s). govulncheck: the JSON stream is
indented, so the line parser read nothing, and govulncheck never reports the main module of the tree it scans (x/text 0.3.5
read clean); the module is now a dependency of a wrapper module and scanned at module level. pip-audit: its positional
argument is a project directory and `--pyproject` does not exist, so every scan failed; the release is audited from a pinned
requirement, an advisory is listed once, and `skip_reason` is an error. trivy is not covered: it reads a bare npm archive
as clean the same way grype did.
- **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.
- **GH-26.** `rescanPackages` kept its own list of metadata versions and never called `IsMetadataEntry`, so Go `.mod` and `.info`
rows were scanned every cycle. Related options, whose defaults keep the old behaviour: `rescan_active_window` skips packages idle longer than the
window, `rescan_concurrency` runs scans in parallel, and `rescan_on_access` rescans a stale cache hit before serving it.
Model of the last: `Security.finished_rescan_verdict_younger_than_interval`, `old_verdict_only_on_timeout`,
`stale_clean_fresh_vulnerable_blocked`, `timeout_keeps_previous`, `timeout_without_previous_is_miss_rule`, `off_is_old_hit_path`.
## Not fixed
@@ -76,7 +99,7 @@ Currency: `sh lean4/scripts/check_currency.sh origin/main`.
| GH-11 | cache hit | the stored SHA-256 is not re-verified on read | by-design | `Put` verifies the stream it just hashed; no doc promises read-side integrity. A check reads up to 2 GB per hit. Disk corruption is outside the proxy's threat model. |
| GH-12 | idle purge | check and delete are two steps, so a request inside the window loses its blob | by-design | `Cache.purge_window_deletes_fresh_entry`. The consequence is a refetch; GH-07 covers the in-flight request. |
| GH-13 | scan policy | with `fail_closed: false` a package whose scan keeps failing on infrastructure is served unscanned | by-design, accepted | See "Decision" below. |
| GH-14 | scan merge | one scanner failing while another returns clean saves a clean result and schedules no retry | by-design | `Security.partial_failure_reads_clean`. `scan` handles only the all-failed case; redundancy across scanners is the intent. |
| GH-14 | scan merge | one scanner failing while another returns clean saves a clean result and schedules no retry | by-design | `Security.error_and_clean_reads_clean` (a returned error and, since GH-25, an error-status result). `scan` handles only the all-failed case; redundancy across scanners is the intent. |
| GH-16 | admin API | `requireAdmin` accepts the `bypasses:manage` permission and also guards key minting | tested-clean | Only the admin role holds that permission: `Access.admin_gate_implies_key_manager`. |
### Decision: `fail_closed: false` with recurring infrastructure errors
+24
View File
@@ -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
+12
View File
@@ -208,4 +208,16 @@ theorem old_exempted_npm_package : scanExemptOld true "1.0.0" = true := by decid
theorem go_metadata_still_exempt : scanExempt "go" true "v1.0.0" = true := by decide
/-- `pkg/scanner/rescanner.go` before the fix: the worker skipped only the version names, not the Go suffixes. -/
def rescanSkipOld (version : String) : Bool := decide (version ∈ metaVersions)
/-- After the fix the worker asks `IsMetadataEntry`, the same predicate as the serve path. -/
def rescanSkip : String → Bool → String → Bool := scanExempt
theorem old_rescan_scanned_go_metadata :
rescanSkipOld "v1.0.0" = false ∧ scanExempt "go" true "v1.0.0" = true := by decide
theorem rescan_skips_what_serve_skips (registry : String) (suffixMeta : Bool) (version : String) :
rescanSkip registry suffixMeta version = scanExempt registry suffixMeta version := rfl
end Gohoarder.Cache
+151 -5
View File
@@ -3,7 +3,7 @@ import Mathlib
/-!
# Security decision logic
Models `pkg/scanner/scanner.go` `CheckVulnerabilities`, `scan`, `mergeResults`, `scheduleRetry`,
Models `pkg/scanner/scanner.go` `CheckVulnerabilities`, `scan`, `mergeResults`, `succeeded`, `scheduleRetry`,
`pkg/metadata/gormstore/gormstore_v2.go` `GetActiveCVEBypasses`, and the scan gate in
`pkg/cache/cache.go` `getOrFetch`. Severities are ranks (low 1 .. critical 4). Omits: the
scanners themselves, threshold counters (`block_thresholds`), network.
@@ -193,7 +193,7 @@ theorem npm_scan_keeps_cache_version (cacheVersion : String) :
theorem file_name_is_not_release_version :
"requests-2.19.0-py3-none-any.whl" ≠ "2.19.0" := by decide
/-! ### Merge: worst status wins, but a failed scanner leaves no trace -/
/-! ### Merge: worst status wins among scanners that ran; a failed scanner leaves no trace -/
/-- ranks: clean 0, pending 1, error 2, vulnerable 3 (`mergeResults`). -/
def mergeRank (xs : List ℕ) : ℕ := xs.foldr max 0
@@ -207,8 +207,154 @@ theorem merge_dominates (xs : List ℕ) (x : ℕ) (h : x ∈ xs) : x ≤ mergeRa
· exact le_max_left _ _
· exact le_trans (ih h) (le_max_right _ _)
/-- Results exist only for scanners that returned; with one scanner failing and one clean, the
merged status is clean and no retry is scheduled (`scan`: retry only when no scanner succeeded). -/
theorem partial_failure_reads_clean : mergeRank [0] = 0 := by decide
def errorRank : ℕ := 2
/-- Before GH-25 a scanner's error-status result took part in the merge, as the rank `errorRank`. -/
def oldMerge (xs : List ℕ) : ℕ := mergeRank xs
/-- `scan` after GH-25: a scanner that returns an error-status result failed, like one that returns
an error. Only results of scanners that ran are merged; with none left every scanner failed. -/
def newMerge (xs : List ℕ) : ℕ :=
if (xs.filter (· ≠ errorRank)).isEmpty then errorRank else mergeRank (xs.filter (· ≠ errorRank))
/-- GH-25: one scanner's error result turned a clean package into an error row. -/
theorem old_error_poisons_clean : oldMerge [0, errorRank] = errorRank := by decide
theorem error_and_clean_reads_clean : newMerge [0, errorRank] = 0 := by decide
theorem error_never_hides_vulnerable : newMerge [errorRank, 3] = 3 := by decide
theorem all_error_reads_error (xs : List ℕ) (h : ∀ x ∈ xs, x = errorRank) : newMerge xs = errorRank := by
have : xs.filter (· ≠ errorRank) = [] := by
rw [List.filter_eq_nil_iff]
intro x hx
simp [h x hx]
unfold newMerge
rw [this]
rfl
theorem error_result_ignored (xs : List ℕ) : newMerge (errorRank :: xs) = newMerge xs := by
simp [newMerge]
theorem mergeRank_not_error (ys : List ℕ) (h : ∀ y ∈ ys, y ≠ errorRank) : mergeRank ys ≠ errorRank := by
induction ys with
| nil => simp [mergeRank, errorRank]
| cons y ys ih =>
simp only [mergeRank, List.foldr_cons]
have hy : y ≠ errorRank := h y (List.mem_cons_self ..)
have hys : mergeRank ys ≠ errorRank := ih (fun z hz => h z (List.mem_cons_of_mem _ hz))
rcases max_choice y (ys.foldr max 0) with e | e
· rw [e]; exact hy
· rw [e]; exact hys
/-- With any scanner that ran, the merged status is not an error, so `fail_closed` never decides it. -/
theorem merged_not_error_when_one_ran (xs : List ℕ) (h : ∃ x ∈ xs, x ≠ errorRank) :
newMerge xs ≠ errorRank := by
obtain ⟨x, hx, hne⟩ := h
have hmem : x ∈ xs.filter (· ≠ errorRank) := List.mem_filter.mpr ⟨hx, by simpa using hne⟩
unfold newMerge
have hne' : ¬ (xs.filter (· ≠ errorRank)).isEmpty = true := by
intro hempty
rw [List.isEmpty_iff] at hempty
rw [hempty] at hmem
simp at hmem
simp only [hne']
apply mergeRank_not_error
intro y hy
simpa using (List.mem_filter.mp hy).2
/-- The retry is for infrastructure only: `scan` counts each failure by cause and the row is an
infrastructure error only when there was a failure and every failure was infrastructure. -/
def infraOnly (failures : List Bool) : Bool := decide (failures ≠ []) && failures.all id
theorem one_package_failure_is_not_infra : infraOnly [true, false] = false := by decide
theorem all_infra_failures_are_infra : infraOnly [true, true] = true := by decide
/-! ### Rescan on access (`pkg/cache/rescan_on_access.go` `refreshStaleScan`)
Ages are seconds since `ScannedAt`; `interval` is `Config.RescanAfter` (0 = off). A rescan that timed out
or failed is `none`: the previous verdict stands, and with no previous verdict the first-download rule applies. -/
structure Verdict where
scan : Scan
age : ℕ
/-- The hit is rescanned when the feature is on and its result is missing or at least `interval` old. -/
def rescans (interval : ℕ) (prev : Option Verdict) : Bool :=
decide (0 < interval) && (match prev with
| none => true
| some v => decide (interval ≤ v.age))
/-- The verdict the gate decides on; a finished rescan is brand new (age 0). -/
def hitVerdict (interval : ℕ) (prev : Option Verdict) (rescan : Option Scan) : Option Verdict :=
if rescans interval prev then
(match rescan with
| some s => some ⟨s, 0⟩
| none => prev)
else prev
/-- No verdict at all is a scan still in flight: `fail_closed` refuses, otherwise the package is served. -/
def servesOnAccess (failClosed pkgBypass : Bool) (policy : Option ℕ) (now : ℤ) (bs : List Bypass)
(interval : ℕ) (prev : Option Verdict) (rescan : Option Scan) : Bool :=
match hitVerdict interval prev rescan with
| some v => serves failClosed pkgBypass policy now bs v.scan
| none => serves failClosed pkgBypass policy now bs (Scan.missing true)
/-- Key property: with the feature on, a rescan that finished leaves no verdict as old as `interval`. -/
theorem finished_rescan_verdict_younger_than_interval (interval : ℕ) (hi : 0 < interval)
(prev : Option Verdict) (s : Scan) (v : Verdict)
(h : hitVerdict interval prev (some s) = some v) : v.age < interval := by
unfold hitVerdict at h
by_cases hr : rescans interval prev = true
· simp only [hr, ite_true, Option.some.injEq] at h
subst h
simpa using hi
· simp only [hr] at h
subst h
simp only [rescans, hi, decide_true, Bool.true_and, Bool.not_eq_true] at hr
simpa using hr
/-- A verdict older than `interval` survives only when the rescan timed out or failed. -/
theorem old_verdict_only_on_timeout (interval : ℕ) (hi : 0 < interval) (prev : Option Verdict)
(rescan : Option Scan) (v : Verdict) (h : hitVerdict interval prev rescan = some v)
(hold : interval ≤ v.age) : rescan = none := by
cases rescan with
| none => rfl
| some s => exact absurd (finished_rescan_verdict_younger_than_interval interval hi prev s v h) (not_lt.mpr hold)
/-- A stale hit is judged on the fresh scan: a clean result that now holds a blocked vulnerability is refused. -/
theorem stale_clean_fresh_vulnerable_blocked (policy : Option ℕ) (t : ℕ) (hp : policy = some t)
(failClosed : Bool) (now : ℤ) (bs : List Bypass) (interval age : ℕ) (hi : 0 < interval)
(hage : interval ≤ age) (vs : List Vuln) (v : Vuln) (hv : v ∈ vs) (hsev : t ≤ v.sev)
(hun : v.id ∉ bypassedIds now bs) :
servesOnAccess failClosed false policy now bs interval (some ⟨Scan.ok [], age⟩) (some (Scan.ok vs)) = false := by
have hr : rescans interval (some ⟨Scan.ok [], age⟩) = true := by simp [rescans, hi, hage]
simp only [servesOnAccess, hitVerdict, hr, ite_true]
exact vulnerable_not_served policy t hp failClosed now bs vs v hv hsev hun
/-- A fresh result is served as is: no rescan, whatever the rescan outcome. -/
theorem fresh_hit_not_rescanned (interval : ℕ) (v : Verdict) (hfresh : v.age < interval)
(rescan : Option Scan) : hitVerdict interval (some v) rescan = some v := by
have : rescans interval (some v) = false := by simp [rescans, not_le.mpr hfresh]
simp [hitVerdict, this]
/-- A timeout keeps the previous verdict. -/
theorem timeout_keeps_previous (interval : ℕ) (prev : Option Verdict) :
hitVerdict interval prev none = prev := by
unfold hitVerdict
split <;> rfl
/-- A timeout with no previous verdict follows the first-download rule. -/
theorem timeout_without_previous_is_miss_rule (failClosed pkgBypass : Bool) (policy : Option ℕ) (now : ℤ)
(bs : List Bypass) (interval : ℕ) :
servesOnAccess failClosed pkgBypass policy now bs interval none none = (pkgBypass || !failClosed) := by
simp only [servesOnAccess, timeout_keeps_previous]
cases failClosed <;> cases pkgBypass <;> simp [serves]
/-- `rescan_on_access` off (`RescanAfter` 0) is the old hit path: the stored verdict decides. -/
theorem off_is_old_hit_path (prev : Option Verdict) (rescan : Option Scan) :
hitVerdict 0 prev rescan = prev := by
simp [hitVerdict, rescans]
end Gohoarder.Security
+112
View File
@@ -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
+28 -7
View File
@@ -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{
@@ -230,13 +234,20 @@ func (a *App) initializeComponents() error {
if cleanupInterval == 0 {
cleanupInterval = 5 * time.Minute
}
var rescanAfter time.Duration
if a.config.Security.RescanOnAccess {
rescanAfter = a.config.Security.RescanInterval
}
a.cache, err = cache.New(a.storage, a.metadata, a.scanManager, a.analyticsEngine, cache.Config{
DefaultTTL: a.config.Cache.DefaultTTL,
TTLOverrides: a.config.Cache.MetadataTTLOverrides(),
CleanupInterval: cleanupInterval,
IdleTTL: a.config.Cache.IdleTTL,
MaxPackageSize: a.config.Security.Scanners.Static.MaxPackageSize,
FailClosed: a.config.Security.FailClosed,
RescanAfter: rescanAfter,
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,
ScanWaitTimeout: a.config.Security.ScanWaitTimeout,
})
if err != nil {
return fmt.Errorf("failed to initialize cache: %w", err)
@@ -314,7 +325,10 @@ 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.config.Security.RescanInterval)
a.rescanWorker = scanner.NewRescanWorker(a.scanManager, a.metadata, a.config.Security.RescanInterval,
scanner.WithActiveWindow(a.config.Security.RescanActiveWindow),
scanner.WithConcurrency(a.config.Security.RescanConcurrency),
)
}
// Initialize WebSocket server
@@ -446,6 +460,7 @@ func (a *App) setupServer() error {
a.app.All("/api/packages/*", mwAuth, a.handlePackages) // OPTIONS, preflight, vulnerabilities
a.app.Get("/api/stats", mwAuth, a.handleStats)
a.app.Get("/api/stats/timeseries", mwAuth, a.handleTimeSeriesStats)
a.app.Get("/api/stats/trend", mwAuth, a.handleStatsTrend)
a.app.Get("/api/info", mwAuth, a.handleInfo)
a.app.Get("/api/analytics/top", mwAuth, a.handleAnalyticsTopPackages)
@@ -460,6 +475,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)
@@ -610,6 +626,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 {
+34 -16
View File
@@ -3,6 +3,8 @@ package app
import (
"context"
stderrors "errors"
"fmt"
"slices"
"strings"
"time"
@@ -69,9 +71,25 @@ type listParams struct {
paged bool
}
// parseListParams reads page, page_size, registry, q, sort and order. Without
// page or page_size the list is unpaginated, as it was before paging existed.
func parseListParams(c fiber.Ctx) listParams {
// parseSeverities reads a comma-separated severity filter such as "critical,high".
func parseSeverities(raw string) ([]string, error) {
var out []string
for _, part := range strings.Split(raw, ",") {
sev := strings.ToLower(strings.TrimSpace(part))
if sev == "" || slices.Contains(out, sev) {
continue
}
if !slices.Contains(metadata.Severities, sev) {
return nil, fmt.Errorf("invalid severity %q, must be one of: %s", sev, strings.Join(metadata.Severities, ", "))
}
out = append(out, sev)
}
return out, nil
}
// parseListParams reads page, page_size, registry, q, sort, order and severity.
// Without page or page_size the list is unpaginated, as it was before paging existed.
func parseListParams(c fiber.Ctx) (listParams, error) {
p := listParams{opts: metadata.GroupListOptions{
Registry: c.Query("registry"),
Query: c.Query("q"),
@@ -88,6 +106,11 @@ func parseListParams(c fiber.Ctx) listParams {
case "desc":
p.opts.SortDesc = true
}
severities, err := parseSeverities(c.Query("severity"))
if err != nil {
return p, err
}
p.opts.Severities = severities
if c.Query("page") != "" || c.Query("page_size") != "" {
p.paged = true
p.opts.Page = max(fiber.Query[int](c, "page", 1), 1)
@@ -97,7 +120,7 @@ func parseListParams(c fiber.Ctx) listParams {
}
p.opts.PageSize = min(p.opts.PageSize, maxPageSize)
}
return p
return p, nil
}
// scanDecisions judges scanned packages, falling back to plain summaries without a scan manager.
@@ -145,7 +168,10 @@ func vulnerabilityInfo(pkg *metadata.Package, decisions map[string]scanner.ScanD
// page_size is given and every group otherwise.
func (a *App) handleListPackages(c fiber.Ctx) error {
ctx := c.Context()
params := parseListParams(c)
params, err := parseListParams(c)
if err != nil {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": err.Error()})
}
page, err := a.metadata.ListPackageGroups(ctx, params.opts)
if err != nil {
@@ -365,17 +391,9 @@ func (a *App) handleStats(c fiber.Ctx) error {
}
// Blocked packages need the blocking policy, so judge every scanned package in one batch.
blockedCount := int64(0)
if a.config.Security.Enabled && a.scanManager != nil {
decisions, err := a.scanManager.ScanDecisions(ctx, nil)
if err != nil {
log.Error().Err(err).Msg("Failed to judge scanned packages")
}
for _, d := range decisions {
if d.Blocked && !metadata.IsMetadataVersion(d.Summary.Version) {
blockedCount++
}
}
blockedCount, err := a.countBlocked(ctx)
if err != nil {
log.Error().Err(err).Msg("Failed to judge scanned packages")
}
// Combine statistics using database stats for accuracy
+77
View File
@@ -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))
}
+23 -2
View File
@@ -1,6 +1,7 @@
package app
import (
"context"
"strings"
"github.com/gofiber/fiber/v3"
@@ -42,14 +43,14 @@ func (a *App) handleVulnerabilities(c fiber.Ctx) error {
Str("version", version).
Msg("Getting vulnerabilities for package")
pkg, pkgErr := a.metadata.GetPackage(ctx, registry, name, version)
key, pkg, pkgErr := a.resolvePackageKey(ctx, registry, name, version)
releaseVersion := ""
if pkgErr == nil && pkg != nil {
releaseVersion = pkg.ReleaseVersion
}
// Get scan result from metadata store
scanResult, err := a.metadata.GetScanResult(ctx, registry, name, version)
scanResult, err := a.metadata.GetScanResult(ctx, registry, key, version)
if err != nil {
if pkgErr != nil {
return c.Status(fiber.StatusNotFound).JSON(fiber.Map{"error": "package not found"})
@@ -169,3 +170,23 @@ func (a *App) handleVulnerabilities(c fiber.Ctx) error {
return c.Status(fiber.StatusOK).JSON(response)
}
// goCacheKeyExts orders the Go cache files a module version is stored under; the
// .zip carries the scan result.
var goCacheKeyExts = []string{"zip", "mod", "info"}
// resolvePackageKey maps the name the dashboard shows to the stored row name.
// Go rows are stored under cache keys (module/@v/version.ext), not the module path.
func (a *App) resolvePackageKey(ctx context.Context, registry, name, version string) (string, *metadata.Package, error) {
pkg, err := a.metadata.GetPackage(ctx, registry, name, version)
if err == nil || registry != "go" || strings.Contains(name, "/@v/") {
return name, pkg, err
}
for _, ext := range goCacheKeyExts {
key := name + "/@v/" + version + "." + ext
if p, kerr := a.metadata.GetPackage(ctx, registry, key, version); kerr == nil {
return key, p, nil
}
}
return name, nil, err
}
+56
View File
@@ -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")
}
+58
View File
@@ -0,0 +1,58 @@
package app
import (
"context"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/lukaszraczylo/gohoarder/pkg/cache"
"github.com/lukaszraczylo/gohoarder/pkg/config"
"github.com/lukaszraczylo/gohoarder/pkg/errors"
)
// security.scan_wait_timeout bounds how long a first download waits for its scan; with
// fail_closed a slow scan is refused at that bound instead of the 30s default.
func TestScanWaitTimeoutComesFromConfig(t *testing.T) {
release := make(chan struct{})
osv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
<-release
_, _ = w.Write([]byte(`{"vulns":[]}`))
}))
defer osv.Close()
defer close(release)
a := newTestApp(t, func(c *config.Config) {
c.Security.Enabled = true
c.Security.FailClosed = true
c.Security.ScanWaitTimeout = 150 * time.Millisecond
c.Security.Scanners.OSV.Enabled = true
c.Security.Scanners.OSV.APIURL = osv.URL
})
fetch := func(context.Context) (*cache.FetchResult, error) {
return &cache.FetchResult{Data: io.NopCloser(strings.NewReader("tarball"))}, nil
}
start := time.Now()
_, err := a.cache.Get(context.Background(), "npm", "left-pad", "1.3.0", fetch)
elapsed := time.Since(start)
var ghErr *errors.Error
if err == nil || !asError(err, &ghErr) || ghErr.Code != errors.ErrCodeServiceUnavailable {
t.Fatalf("Get = %v, want a service-unavailable refusal", err)
}
if elapsed > 5*time.Second {
t.Fatalf("refusal took %s; the configured 150ms wait was not applied", elapsed)
}
}
func asError(err error, target **errors.Error) bool {
e, ok := err.(*errors.Error)
if ok {
*target = e
}
return ok
}
+49
View File
@@ -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)
}
}
}
+130
View File
@@ -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)
}
}
}
+60
View File
@@ -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)
}
}
+6
View File
@@ -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.
+35
View File
@@ -47,6 +47,7 @@ type Manager struct {
bgCtx context.Context // cancelled by Close; parent of background scans
bgCancel context.CancelFunc
sf singleflight.Group
rescanSF singleflight.Group
config Config
cleanupWG sync.WaitGroup
bcMu sync.RWMutex
@@ -85,11 +86,13 @@ type Config struct {
DefaultTTL time.Duration // Freshness TTL for metadata entries
CleanupInterval time.Duration // How often to run cleanup
IdleTTL time.Duration // Remove entries not requested for this long (0 = off)
DeletedRetention time.Duration // Hard-delete soft-deleted rows older than this (0 = keep forever)
EvictionThreshold float64 // Trigger eviction when usage > threshold (0.0-1.0)
MaxConcurrent int // Max concurrent upstream fetches
MaxPackageSize int64 // Maximum package size in bytes (0 = default 2GB)
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
RescanAfter time.Duration // Rescan a cache hit whose scan result is older than this before serving (0 = off)
}
const defaultScanWaitTimeout = 30 * time.Second
@@ -97,6 +100,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
@@ -328,6 +334,9 @@ func (m *Manager) getOrFetch(ctx context.Context, registry, name, version string
// the extra database round-trip.
isMetadataEntry := metadata.IsMetadataEntry(registry, name, version)
if m.scanner != nil && !isMetadataEntry {
if rescanErr := m.refreshStaleScan(ctx, registry, name, version); rescanErr != nil {
return nil, rescanErr
}
blocked, reason, vulnErr := m.scanner.CheckVulnerabilities(ctx, registry, name, version)
if vulnErr != nil {
log.Warn().Err(vulnErr).Str("package", name).Msg("Failed to check vulnerabilities")
@@ -917,14 +926,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)
+8
View File
@@ -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.
+90
View File
@@ -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")
}
+71
View File
@@ -0,0 +1,71 @@
package cache
import (
"context"
"fmt"
"time"
"github.com/lukaszraczylo/gohoarder/pkg/errors"
"github.com/rs/zerolog/log"
)
// refreshStaleScan rescans a cache hit whose scan result is missing or older than
// Config.RescanAfter, so the verdict served is never older than that interval. It
// waits up to ScanWaitTimeout; on a timeout or scan failure the previous verdict
// stands, or the miss-path rule applies when there is none.
func (m *Manager) refreshStaleScan(ctx context.Context, registry, name, version string) error {
if m.config.RescanAfter <= 0 {
return nil
}
prev, err := m.metadata.GetScanResult(ctx, registry, name, version)
hasPrev := err == nil && prev != nil
if hasPrev && m.now().Sub(prev.ScannedAt) < m.config.RescanAfter {
return nil
}
key := fmt.Sprintf("%s/%s/%s", registry, name, version)
done := m.rescanSF.DoChan(key, func() (interface{}, error) {
return nil, m.rescanArtifact(registry, name, version)
})
timer := time.NewTimer(m.config.ScanWaitTimeout)
defer timer.Stop()
select {
case res := <-done:
if res.Err == nil {
return nil
}
log.Warn().Err(res.Err).Str("package", name).Str("version", version).Msg("Rescan on access failed")
case <-timer.C:
log.Warn().Str("package", name).Str("version", version).Msg("Rescan on access timed out, scan continues in background")
case <-ctx.Done():
return ctx.Err()
}
if hasPrev {
log.Warn().Str("package", name).Str("version", version).Time("scanned_at", prev.ScannedAt).
Msg("Serving decision uses the previous scan result")
return nil
}
if m.config.FailClosed {
log.Warn().Str("package", name).Str("version", version).
Msg("No scan result and rescan unfinished - refusing to serve (fail-closed)")
return errors.New(errors.ErrCodeServiceUnavailable, "package scan in progress, retry shortly")
}
log.Warn().Str("package", name).Str("version", version).
Msg("No scan result and rescan unfinished - serving package, scan continues in background")
return nil
}
// rescanArtifact scans the cached artifact under the manager's background context so a
// client disconnect does not abort it.
func (m *Manager) rescanArtifact(registry, name, version string) error {
path, cleanup, err := m.ScanFile(m.bgCtx, registry, name, version)
if err != nil {
return err
}
defer cleanup()
return m.scanner.ScanPackage(m.bgCtx, registry, name, version, path)
}
+176
View File
@@ -0,0 +1,176 @@
package cache
import (
"context"
"errors"
"io"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
hoardererrors "github.com/lukaszraczylo/gohoarder/pkg/errors"
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
)
const rescanInterval = 24 * time.Hour
// rescanScanner blocks a scan until release closes and blocks the package once scanned.
type rescanScanner struct {
release chan struct{}
scanCtx atomic.Pointer[context.Context]
scans atomic.Int32
blockOnScan atomic.Bool
}
func (s *rescanScanner) ScanPackage(ctx context.Context, _, _, _, _ string) error {
s.scans.Add(1)
s.scanCtx.Store(&ctx)
if s.release != nil {
<-s.release
}
s.blockOnScan.Store(true)
return nil
}
func (s *rescanScanner) CheckVulnerabilities(context.Context, string, string, string) (bool, string, error) {
if s.scans.Load() > 0 && s.release == nil {
return s.blockOnScan.Load(), "critical vulnerability", nil
}
return false, "", nil
}
func newHitManager(t *testing.T, sc ScannerInterface, cfg Config, registry, name, version string, prev *metadata.ScanResult) (*Manager, *MockMetadataStore) {
t.Helper()
st := &MockStorageBackend{}
md := &MockMetadataStore{}
key := registry + "/" + name + "/" + version
md.On("GetPackage", mock.Anything, registry, name, version).
Return(&metadata.Package{Registry: registry, Name: name, Version: version, StorageKey: key}, nil)
st.On("Get", mock.Anything, key).Return(io.NopCloser(strings.NewReader("data")), nil)
md.On("UpdateDownloadCount", mock.Anything, registry, name, version).Return(nil)
if prev == nil {
md.On("GetScanResult", mock.Anything, registry, name, version).Return(nil, hoardererrors.NotFound("none")).Maybe()
} else {
md.On("GetScanResult", mock.Anything, registry, name, version).Return(prev, nil).Maybe()
}
st.On("Close").Return(nil)
md.On("Close").Return(nil)
m, err := New(st, md, sc, nil, cfg)
require.NoError(t, err)
t.Cleanup(func() { _ = m.Close() })
return m, md
}
func scanAged(age time.Duration) *metadata.ScanResult {
return &metadata.ScanResult{ScannedAt: time.Now().Add(-age), Status: metadata.ScanStatusClean}
}
func errorCode(err error) string {
var appErr *hoardererrors.Error
if errors.As(err, &appErr) {
return appErr.Code
}
return ""
}
func TestGetHit_RescanOnAccess(t *testing.T) {
tests := []struct {
prev *metadata.ScanResult
name string
wantCode string
rescan time.Duration
wantScans int32
hang bool
failClose bool
}{
{name: "stale clean result, fresh scan finds critical: blocked before serve", prev: scanAged(48 * time.Hour), rescan: rescanInterval, wantScans: 1, wantCode: hoardererrors.ErrCodeSecurityViolation},
{name: "missing result is scanned before serving", prev: nil, rescan: rescanInterval, wantScans: 1, wantCode: hoardererrors.ErrCodeSecurityViolation},
{name: "fresh result is not rescanned", prev: scanAged(time.Hour), rescan: rescanInterval, wantScans: 0},
{name: "rescan_on_access off keeps the old hit path", prev: scanAged(48 * time.Hour), rescan: 0, wantScans: 0},
{name: "timeout with previous result serves", prev: scanAged(48 * time.Hour), rescan: rescanInterval, wantScans: 1, hang: true},
{name: "timeout with previous result serves under fail-closed", prev: scanAged(48 * time.Hour), rescan: rescanInterval, wantScans: 1, hang: true, failClose: true},
{name: "timeout without result serves when fail-open", prev: nil, rescan: rescanInterval, wantScans: 1, hang: true},
{name: "timeout without result is 503 when fail-closed", prev: nil, rescan: rescanInterval, wantScans: 1, hang: true, failClose: true, wantCode: hoardererrors.ErrCodeServiceUnavailable},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
sc := &rescanScanner{}
if tt.hang {
sc.release = make(chan struct{})
t.Cleanup(func() { close(sc.release) })
}
m, _ := newHitManager(t, sc, Config{RescanAfter: tt.rescan, ScanWaitTimeout: 150 * time.Millisecond, FailClosed: tt.failClose},
"npm", "lodash", "4.17.21", tt.prev)
entry, err := m.Get(context.Background(), "npm", "lodash", "4.17.21", nil)
if tt.wantCode != "" {
require.Error(t, err)
assert.Equal(t, tt.wantCode, errorCode(err))
} else {
require.NoError(t, err)
require.NotNil(t, entry)
_ = entry.Data.Close()
}
assert.Equal(t, tt.wantScans, sc.scans.Load())
})
}
}
func TestGetHit_RescanOffDoesNotReadScanResult(t *testing.T) {
sc := &rescanScanner{}
m, md := newHitManager(t, sc, Config{}, "npm", "lodash", "4.17.21", scanAged(48*time.Hour))
entry, err := m.Get(context.Background(), "npm", "lodash", "4.17.21", nil)
require.NoError(t, err)
_ = entry.Data.Close()
md.AssertNotCalled(t, "GetScanResult", mock.Anything, mock.Anything, mock.Anything, mock.Anything)
}
func TestGetHit_RescanSkipsGoMetadataRows(t *testing.T) {
sc := &rescanScanner{}
m, _ := newHitManager(t, sc, Config{RescanAfter: rescanInterval}, "go", "example.com/m/@v/v1.0.0.mod", "v1.0.0", nil)
entry, err := m.Get(context.Background(), "go", "example.com/m/@v/v1.0.0.mod", "v1.0.0", nil)
require.NoError(t, err)
_ = entry.Data.Close()
assert.Zero(t, sc.scans.Load())
}
// Concurrent stale hits share one scan, and a client that disconnects does not cancel it.
func TestRefreshStaleScan_SingleflightAndBackgroundContext(t *testing.T) {
sc := &rescanScanner{release: make(chan struct{})}
m, _ := newHitManager(t, sc, Config{RescanAfter: rescanInterval, ScanWaitTimeout: 5 * time.Second},
"npm", "lodash", "4.17.21", scanAged(48*time.Hour))
const callers = 5
ctx, cancelClient := context.WithCancel(context.Background())
errs := make(chan error, callers)
var wg sync.WaitGroup
for i := 0; i < callers; i++ {
wg.Add(1)
go func() {
defer wg.Done()
errs <- m.refreshStaleScan(ctx, "npm", "lodash", "4.17.21")
}()
}
require.Eventually(t, func() bool { return sc.scans.Load() >= 1 }, 2*time.Second, 5*time.Millisecond)
cancelClient()
wg.Wait()
close(errs)
for err := range errs {
assert.ErrorIs(t, err, context.Canceled)
}
scanCtx := sc.scanCtx.Load()
require.NotNil(t, scanCtx)
assert.NoError(t, (*scanCtx).Err(), "scan must outlive the client request")
close(sc.release)
assert.Equal(t, int32(1), sc.scans.Load(), "concurrent hits must share one scan")
}
+31 -18
View File
@@ -157,29 +157,38 @@ func (c CacheConfig) MetadataTTLOverrides() map[string]time.Duration {
// DefaultIdleTTL is how long a cached item can go unrequested before cleanup removes it.
const DefaultIdleTTL = 7 * 24 * time.Hour
// DefaultDeletedRetention is how long a soft-deleted package row is kept before cleanup purges it.
const DefaultDeletedRetention = 30 * 24 * time.Hour
// CacheConfig contains cache management configuration
type CacheConfig struct {
TTLOverrides map[string]time.Duration `mapstructure:"ttl_overrides" json:"ttl_overrides"`
DefaultTTL time.Duration `mapstructure:"default_ttl" json:"default_ttl"`
CleanupInterval time.Duration `mapstructure:"cleanup_interval" json:"cleanup_interval"`
IdleTTL time.Duration `mapstructure:"idle_ttl" json:"idle_ttl"` // 0 disables idle eviction
MaxSizeBytes int64 `mapstructure:"max_size_bytes" json:"max_size_bytes"`
PerProjectQuota int64 `mapstructure:"per_project_quota" json:"per_project_quota"`
// DeletedRetention is how long soft-deleted package rows stay before cleanup purges them; 0 keeps them forever.
DeletedRetention time.Duration `mapstructure:"deleted_retention" json:"deleted_retention"`
MaxSizeBytes int64 `mapstructure:"max_size_bytes" json:"max_size_bytes"`
PerProjectQuota int64 `mapstructure:"per_project_quota" json:"per_project_quota"`
}
// SecurityConfig contains security scanning configuration
type SecurityConfig struct {
BlockOnSeverity string `mapstructure:"block_on_severity" json:"block_on_severity"`
AllowedPackages []string `mapstructure:"allowed_packages" json:"allowed_packages"`
IgnoredCVEs []string `mapstructure:"ignored_cves" json:"ignored_cves"`
Scanners ScannersConfig `mapstructure:"scanners" json:"scanners"`
BlockThresholds VulnerabilityThresholds `mapstructure:"block_thresholds" json:"block_thresholds"`
RescanInterval time.Duration `mapstructure:"rescan_interval" json:"rescan_interval"`
ScanRetryInterval time.Duration `mapstructure:"scan_retry_interval" json:"scan_retry_interval"` // wait before retrying a scan that failed on infrastructure; 0 = 5m
FailClosed bool `mapstructure:"fail_closed" json:"fail_closed"` // refuse packages whose scan failed on infrastructure
Enabled bool `mapstructure:"enabled" json:"enabled"`
ScanOnDownload bool `mapstructure:"scan_on_download" json:"scan_on_download"`
UpdateDBOnStartup bool `mapstructure:"update_db_on_startup" json:"update_db_on_startup"`
BlockOnSeverity string `mapstructure:"block_on_severity" json:"block_on_severity"`
AllowedPackages []string `mapstructure:"allowed_packages" json:"allowed_packages"`
IgnoredCVEs []string `mapstructure:"ignored_cves" json:"ignored_cves"`
Scanners ScannersConfig `mapstructure:"scanners" json:"scanners"`
BlockThresholds VulnerabilityThresholds `mapstructure:"block_thresholds" json:"block_thresholds"`
RescanInterval time.Duration `mapstructure:"rescan_interval" json:"rescan_interval"`
RescanActiveWindow time.Duration `mapstructure:"rescan_active_window" json:"rescan_active_window"` // rescan only packages accessed within this window; 0 = all
RescanConcurrency int `mapstructure:"rescan_concurrency" json:"rescan_concurrency"` // scans run in parallel per rescan cycle; <1 = 1
ScanRetryInterval time.Duration `mapstructure:"scan_retry_interval" json:"scan_retry_interval"` // wait before retrying a scan that failed on infrastructure; 0 = 5m
ScanWaitTimeout time.Duration `mapstructure:"scan_wait_timeout" json:"scan_wait_timeout"` // how long a first download waits for its scan; 0 = 30s
FailClosed bool `mapstructure:"fail_closed" json:"fail_closed"` // refuse packages whose scan failed on infrastructure
Enabled bool `mapstructure:"enabled" json:"enabled"`
ScanOnDownload bool `mapstructure:"scan_on_download" json:"scan_on_download"`
RescanOnAccess bool `mapstructure:"rescan_on_access" json:"rescan_on_access"` // rescan a stale cache hit before serving it; needs rescan_interval
UpdateDBOnStartup bool `mapstructure:"update_db_on_startup" json:"update_db_on_startup"`
}
// VulnerabilityThresholds defines max allowed vulnerabilities per severity
@@ -377,11 +386,12 @@ func Default() *Config {
},
},
Cache: CacheConfig{
DefaultTTL: DefaultMetadataTTL,
CleanupInterval: 1 * time.Hour,
IdleTTL: DefaultIdleTTL,
MaxSizeBytes: 500 * 1024 * 1024 * 1024, // 500GB
PerProjectQuota: 50 * 1024 * 1024 * 1024, // 50GB
DefaultTTL: DefaultMetadataTTL,
CleanupInterval: 1 * time.Hour,
IdleTTL: DefaultIdleTTL,
DeletedRetention: DefaultDeletedRetention,
MaxSizeBytes: 500 * 1024 * 1024 * 1024, // 500GB
PerProjectQuota: 50 * 1024 * 1024 * 1024, // 50GB
},
Security: SecurityConfig{
Enabled: false,
@@ -541,6 +551,9 @@ func (c *Config) Validate() error {
return fmt.Errorf("cache.ttl_overrides.%s must be positive, got %s", key, ttl)
}
}
if c.Cache.DeletedRetention < 0 {
return fmt.Errorf("cache.deleted_retention cannot be negative")
}
if c.Cache.MaxSizeBytes < 0 {
return fmt.Errorf("cache.max_size_bytes cannot be negative")
}
+41
View File
@@ -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)
})
}
}
+30
View File
@@ -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)
+10
View File
@@ -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)
+13 -1
View File
@@ -1,6 +1,7 @@
package gormstore
import (
"context"
"sync"
"time"
@@ -18,8 +19,10 @@ type AggregationWorker struct {
stopChan chan struct{}
ticker *time.Ticker
now func() time.Time // nil means time.Now
blocked func(context.Context) (int64, error)
wg sync.WaitGroup
stopOnce sync.Once
mu sync.Mutex // guards blocked
}
// NewAggregationWorker creates a new aggregation worker
@@ -289,7 +292,7 @@ func (w *AggregationWorker) AggregateDaily() error {
dayEnd := w.clock().UTC().Truncate(24 * time.Hour)
firstDay := dayEnd.Add(-rollupDays * 24 * time.Hour)
return w.db.Transaction(func(tx *gorm.DB) error {
err := w.db.Transaction(func(tx *gorm.DB) error {
var aggregateSQL string
switch dialectName {
@@ -384,6 +387,15 @@ func (w *AggregationWorker) AggregateDaily() error {
return nil
})
if err != nil {
return err
}
// The snapshot is not part of the rollup: a failure here must not undo it.
if err := w.SnapshotStats(context.Background()); err != nil {
log.Error().Err(err).Msg("Failed to record stats snapshot")
}
return nil
}
// UpdatePackageAccessCounts synchronizes package access_count from download stats
+36
View File
@@ -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 {
+7
View File
@@ -125,6 +125,13 @@ func NewV2(cfg Config) (*GORMStoreV2, error) {
}
}
// History must exist before the worker writes today's snapshot.
if days, err := BackfillStatsSnapshots(context.Background(), db, time.Now()); err != nil {
log.Warn().Err(err).Msg("Failed to backfill stats snapshots")
} else if days > 0 {
log.Info().Int("days", days).Msg("Backfilled stats snapshots")
}
// Start aggregation worker (skip for in-memory databases used in tests)
if !strings.Contains(cfg.DSN, ":memory:") {
store.aggregationWorker = NewAggregationWorker(db)
+16
View File
@@ -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",
+22
View File
@@ -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{},
}
}
+44
View File
@@ -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
}
+16
View File
@@ -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)
}
+111
View File
@@ -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))
}
+389
View File
@@ -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")
}
+257
View File
@@ -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")
}
+43 -3
View File
@@ -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()
+5
View File
@@ -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).
+28
View File
@@ -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())
}
}
+118
View File
@@ -0,0 +1,118 @@
package scanner
import (
"context"
"testing"
"time"
"github.com/lukaszraczylo/gohoarder/pkg/config"
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func stubResult(name string, status metadata.ScanStatus, details map[string]interface{}, vulns ...metadata.Vulnerability) *stubScanner {
return &stubScanner{name: name, result: &metadata.ScanResult{
ID: name, Scanner: name, ScannedAt: time.Now(), Status: status, Details: details,
Vulnerabilities: vulns, VulnerabilityCount: len(vulns),
}}
}
func scanWith(t *testing.T, cfg config.SecurityConfig, scanners ...Scanner) *metadata.ScanResult {
t.Helper()
store := &stubMetadataStore{}
mgr, err := New(cfg, store)
require.NoError(t, err)
t.Cleanup(mgr.Stop)
for _, s := range scanners {
mgr.RegisterScanner(s)
}
require.NoError(t, mgr.ScanPackage(context.Background(), "npm", "left-pad", "1.0.0", "/tmp/x"))
require.Len(t, store.savedResults, 1)
return store.savedResults[0]
}
func TestScanPackage_ErrorResultPlusCleanReadsClean(t *testing.T) {
for _, failClosed := range []bool{false, true} {
saved := scanWith(t, config.SecurityConfig{Enabled: true, FailClosed: failClosed},
stubResult("npm-audit", metadata.ScanStatusError, map[string]interface{}{"error": "parse"}),
stubResult("osv", metadata.ScanStatusClean, nil))
assert.Equal(t, metadata.ScanStatusClean, saved.Status, "fail_closed=%v", failClosed)
assert.Equal(t, "osv", saved.Scanner, "a failed scanner is not part of the merge")
assert.NotContains(t, saved.Details, "npm-audit")
}
}
func TestScanPackage_ErrorResultDoesNotHideFindings(t *testing.T) {
saved := scanWith(t, config.SecurityConfig{Enabled: true},
stubResult("npm-audit", metadata.ScanStatusError, nil),
stubResult("osv", metadata.ScanStatusVulnerable, nil, vuln("CVE-1", "HIGH")))
assert.Equal(t, metadata.ScanStatusVulnerable, saved.Status)
assert.Len(t, saved.Vulnerabilities, 1)
}
func TestScanPackage_AllErrorResultsReadError(t *testing.T) {
saved := scanWith(t, config.SecurityConfig{Enabled: true},
stubResult("npm-audit", metadata.ScanStatusError, map[string]interface{}{"error": "parse"}),
stubResult("grype", metadata.ScanStatusError, nil))
assert.Equal(t, metadata.ScanStatusError, saved.Status)
assert.NotEqual(t, true, saved.Details[DetailInfrastructureError], "no failure was infrastructure")
}
func TestScanPackage_InfrastructureErrorResultsCountAsInfrastructure(t *testing.T) {
infra := map[string]interface{}{DetailInfrastructureError: true}
t.Run("all infrastructure", func(t *testing.T) {
saved := scanWith(t, config.SecurityConfig{Enabled: true},
stubResult("npm-audit", metadata.ScanStatusError, infra),
stubResult("trivy", metadata.ScanStatusError, infra))
assert.Equal(t, metadata.ScanStatusError, saved.Status)
assert.Equal(t, true, saved.Details[DetailInfrastructureError])
})
t.Run("one other failure makes it a package failure", func(t *testing.T) {
saved := scanWith(t, config.SecurityConfig{Enabled: true},
stubResult("npm-audit", metadata.ScanStatusError, infra),
stubResult("grype", metadata.ScanStatusError, nil))
assert.NotEqual(t, true, saved.Details[DetailInfrastructureError])
})
}
func TestScanPackage_ErrorPlusCleanIsServedEvenWhenFailClosed(t *testing.T) {
cfg := config.SecurityConfig{Enabled: true, FailClosed: true}
saved := scanWith(t, cfg,
stubResult("npm-audit", metadata.ScanStatusError, nil),
stubResult("osv", metadata.ScanStatusClean, nil))
mgr, err := New(cfg, &resultStore{stubMetadataStore: &stubMetadataStore{}, scan: saved})
require.NoError(t, err)
blocked, reason, err := mgr.CheckVulnerabilities(context.Background(), "npm", "left-pad", "1.0.0")
require.NoError(t, err)
assert.False(t, blocked, "reason %q", reason)
}
func TestScanPackage_BlockingStillAppliesToRealFindings(t *testing.T) {
cfg := config.SecurityConfig{Enabled: true, BlockOnSeverity: "high",
BlockThresholds: config.VulnerabilityThresholds{Critical: -1, High: -1, Medium: -1, Low: -1}}
saved := scanWith(t, cfg,
stubResult("npm-audit", metadata.ScanStatusError, nil),
stubResult("osv", metadata.ScanStatusVulnerable, nil, vuln("CVE-1", "HIGH")))
mgr, err := New(cfg, &resultStore{stubMetadataStore: &stubMetadataStore{}, scan: saved})
require.NoError(t, err)
blocked, _, err := mgr.CheckVulnerabilities(context.Background(), "npm", "left-pad", "1.0.0")
require.NoError(t, err)
assert.True(t, blocked)
}
func TestMergeResults_IgnoresErrorResults(t *testing.T) {
mgr := newTestManager(t, &stubMetadataStore{})
ok := stubResult("osv", metadata.ScanStatusClean, nil).result
bad := stubResult("grype", metadata.ScanStatusError, nil).result
assert.Equal(t, metadata.ScanStatusClean, mgr.mergeResults([]*metadata.ScanResult{bad, ok}, []string{"grype", "osv"}).Status)
assert.Equal(t, metadata.ScanStatusError, mgr.mergeResults([]*metadata.ScanResult{bad, bad}, []string{"a", "b"}).Status)
}
+20
View File
@@ -0,0 +1,20 @@
// Package gomodule maps a Go cache key to a module path.
package gomodule
import "strings"
// Path returns the module path of a cache key "module/@v/version.zip", with the module proxy's
// case encoding ("!a" is "A") reversed. A name without "/@v/" is taken as the module path.
func Path(cacheKey string) string {
module, _, _ := strings.Cut(cacheKey, "/@v/")
var b strings.Builder
for i := 0; i < len(module); i++ {
if module[i] == '!' && i+1 < len(module) {
i++
b.WriteString(strings.ToUpper(string(module[i])))
continue
}
b.WriteByte(module[i])
}
return b.String()
}
+13
View File
@@ -0,0 +1,13 @@
package gomodule
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestPath(t *testing.T) {
assert.Equal(t, "golang.org/x/text", Path("golang.org/x/text/@v/v0.3.5.zip"))
assert.Equal(t, "github.com/Azure/go-x", Path("github.com/!azure/go-x/@v/v1.2.3.zip"))
assert.Equal(t, "github.com/a/b/v2", Path("github.com/a/b/v2"))
}
+177 -88
View File
@@ -3,17 +3,24 @@
package govulncheck
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"regexp"
"slices"
"strings"
"time"
"github.com/lukaszraczylo/gohoarder/pkg/config"
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
"github.com/lukaszraczylo/gohoarder/pkg/scanner/gomodule"
"github.com/lukaszraczylo/gohoarder/pkg/scanner/scanerr"
"github.com/lukaszraczylo/gohoarder/pkg/uuid"
"github.com/rs/zerolog/log"
)
@@ -64,62 +71,67 @@ func (s *Scanner) Scan(ctx context.Context, registry, packageName, version strin
Str("version", version).
Msg("Starting govulncheck scan")
// Create a temporary directory for extraction
module := gomodule.Path(packageName)
if !validModule.MatchString(module) || !validVersion.MatchString(version) {
return s.errorResult(ctx, registry, packageName, version,
fmt.Sprintf("not a module path and version: %q %q", module, version), ""), nil
}
tmpDir, err := os.MkdirTemp("", "govulncheck-*")
if err != nil {
return nil, fmt.Errorf("failed to create temp dir: %w", err)
}
defer func() { _ = os.RemoveAll(tmpDir) }()
// Extract the .zip file
if extractErr := s.extractZip(filePath, tmpDir); extractErr != nil {
return nil, fmt.Errorf("failed to extract zip: %w", extractErr)
// govulncheck never reports advisories against the main module of the tree it scans, so
// scanning the module's own source reports a vulnerable module clean. The module is
// scanned as a dependency of a wrapper module instead, and the wrapper imports its
// packages because module-mode scanning only considers modules that provide an import.
// Resolving the module reaches the module proxy.
env := append(os.Environ(), "GOFLAGS=-mod=mod", "GOTOOLCHAIN=local", "GOWORK=off")
goMod := fmt.Sprintf("module gohoarder.audit\n\nrequire %s %s\n", module, version)
if err = os.WriteFile(filepath.Join(tmpDir, "go.mod"), []byte(goMod), 0o600); err != nil {
return nil, fmt.Errorf("failed to write go.mod: %w", err)
}
// Locate the Go module root (directory containing go.mod). Go modules
// in the proxy zip layout are nested under <module>@<version>/.
moduleDir, err := findGoModDir(tmpDir)
listCmd := exec.CommandContext(ctx, "go", "list", "-e", "-f", listFormat, module+"/...") // #nosec G204 -- module path is validated
listCmd.Dir = tmpDir
listCmd.Env = env
var listErr bytes.Buffer
listCmd.Stderr = &listErr
listOut, err := listCmd.Output()
if err != nil {
log.Warn().
Err(err).
Str("package", packageName).
Str("version", version).
Msg("Could not locate go.mod in extracted module, skipping govulncheck")
return s.skippedResult(registry, packageName, version, "no go.mod in extracted module"), nil
return s.errorResult(ctx, registry, packageName, version,
fmt.Sprintf("go list failed: %v: %s", err, strings.TrimSpace(listErr.String())), listErr.String()), nil
}
// Run govulncheck in source mode against the module's package set.
// -mode=binary requires a compiled binary which we do not have; the
// default (source) mode wants a Go source tree with a go.mod.
cmd := exec.CommandContext(ctx, "govulncheck", "-json", "./...") // #nosec G204 -- fixed args, cwd is controlled temp dir
cmd.Dir = moduleDir
output, _ := cmd.CombinedOutput()
imports := importable(string(listOut))
if len(imports) == 0 {
return s.skippedResult(registry, packageName, version, "no importable package in module"), nil
}
var mainSrc strings.Builder
mainSrc.WriteString("package main\n\nimport (\n")
for _, pkg := range imports {
fmt.Fprintf(&mainSrc, "\t_ %q\n", pkg)
}
mainSrc.WriteString(")\n\nfunc main() {}\n")
if err = os.WriteFile(filepath.Join(tmpDir, "main.go"), []byte(mainSrc.String()), 0o600); err != nil {
return nil, fmt.Errorf("failed to write main.go: %w", err)
}
// govulncheck returns non-zero when vulnerabilities are found
// Parse output regardless of error
var vulns []GovulncheckVuln
if len(output) > 0 {
// Parse line-delimited JSON
lines := strings.Split(string(output), "\n")
for _, line := range lines {
if strings.TrimSpace(line) == "" {
continue
}
var entry GovulncheckEntry
if err := json.Unmarshal([]byte(line), &entry); err != nil {
log.Warn().Err(err).Str("line", line).Msg("Failed to parse govulncheck line")
continue
}
if entry.Finding != nil && entry.Finding.OSV != "" {
vulns = append(vulns, GovulncheckVuln{
OSV: entry.Finding.OSV,
FixedVersion: entry.Finding.FixedVersion,
})
}
}
cmd := exec.CommandContext(ctx, "govulncheck", "-json", "-scan", "module") // #nosec G204 -- fixed args, cwd is controlled temp dir
cmd.Dir = tmpDir
cmd.Env = env
var stderr bytes.Buffer
cmd.Stderr = &stderr
output, _ := cmd.Output() // govulncheck -json exits 0 whether or not it finds anything
vulns, err := parseFindings(output)
if err != nil {
return s.errorResult(ctx, registry, packageName, version,
fmt.Sprintf("govulncheck failed: %v: %s", err, strings.TrimSpace(stderr.String())), stderr.String()), nil
}
// Convert to our format
result := s.convertResult(vulns, registry, packageName, version)
log.Info().
@@ -131,6 +143,76 @@ func (s *Scanner) Scan(ctx context.Context, registry, packageName, version strin
return result, nil
}
// listFormat prints "import-path name go-files cgo-files [ERR]" per package.
const listFormat = "{{.ImportPath}} {{.Name}} {{len .GoFiles}} {{len .CgoFiles}} {{if .Error}}ERR{{end}}"
var (
validModule = regexp.MustCompile(`^[A-Za-z0-9._~/-]+$`)
validVersion = regexp.MustCompile(`^v[0-9A-Za-z.+_-]+$`)
)
// importable lists the packages of `go list` output that another module can import.
func importable(listOut string) []string {
var pkgs []string
for _, line := range strings.Split(listOut, "\n") {
f := strings.Fields(line)
if len(f) < 4 || f[1] == "main" || (len(f) > 4 && f[4] == "ERR") {
continue
}
if f[2] == "0" && f[3] == "0" {
continue
}
if hasPathElement(f[0], "internal") || hasPathElement(f[0], "testdata") || hasPathElement(f[0], "vendor") {
continue
}
pkgs = append(pkgs, f[0])
}
return pkgs
}
func hasPathElement(importPath, element string) bool {
return slices.Contains(strings.Split(importPath, "/"), element)
}
// parseFindings reads govulncheck's stream of JSON messages. An output without the config
// message did not come from a completed run.
func parseFindings(output []byte) ([]GovulncheckVuln, error) {
summaries := make(map[string]string)
var vulns []GovulncheckVuln
seen := make(map[string]bool)
sawConfig := false
dec := json.NewDecoder(bytes.NewReader(output))
for {
var msg GovulncheckEntry
if err := dec.Decode(&msg); err == io.EOF {
break
} else if err != nil {
return nil, fmt.Errorf("parse govulncheck output: %w", err)
}
switch {
case msg.Config != nil:
sawConfig = true
case msg.OSV != nil:
summaries[msg.OSV.ID] = msg.OSV.Summary
case msg.Finding != nil && msg.Finding.OSV != "" && !seen[msg.Finding.OSV]:
seen[msg.Finding.OSV] = true
v := GovulncheckVuln{OSV: msg.Finding.OSV, FixedVersion: msg.Finding.FixedVersion}
if len(msg.Finding.Trace) > 0 {
v.Module = msg.Finding.Trace[0].Module
v.ModuleVersion = msg.Finding.Trace[0].Version
}
vulns = append(vulns, v)
}
}
if !sawConfig {
return nil, errors.New("no config message in output")
}
for i := range vulns {
vulns[i].Summary = summaries[vulns[i].OSV]
}
return vulns, nil
}
// Health checks if govulncheck is available
func (s *Scanner) Health(ctx context.Context) error {
cmd := exec.CommandContext(ctx, "govulncheck", "-version")
@@ -140,48 +222,26 @@ func (s *Scanner) Health(ctx context.Context) error {
return nil
}
// extractZip extracts a zip file to destination
func (s *Scanner) extractZip(zipPath, destDir string) error {
cmd := exec.Command("unzip", "-q", zipPath, "-d", destDir)
return cmd.Run()
// errorResult returns a scan-error result. The manager leaves it out of the merge and counts it as
// an infrastructure failure when the context ended or the tool output shows the network was unreachable.
func (s *Scanner) errorResult(ctx context.Context, registry, packageName, version, reason, toolOutput string) *metadata.ScanResult {
infra := ctx.Err() != nil || scanerr.NetworkFailure(toolOutput)
return &metadata.ScanResult{
ID: uuid.New().String(),
Registry: registry,
PackageName: packageName,
PackageVersion: version,
Scanner: ScannerName,
ScannedAt: time.Now(),
Status: metadata.ScanStatusError,
VulnerabilityCount: 0,
Vulnerabilities: []metadata.Vulnerability{},
Details: scanerr.ErrorDetails(reason, infra),
}
}
// findGoModDir walks the directory tree under root looking for a directory
// that contains a go.mod file. The Go module proxy ships zips with layout
// "<module>@<version>/...", so the module root is typically one or two
// levels below the extraction directory. Returns an error if none is found.
func findGoModDir(root string) (string, error) {
// Quick check: does the root itself contain go.mod?
if _, err := os.Stat(filepath.Join(root, "go.mod")); err == nil {
return root, nil
}
var found string
err := filepath.WalkDir(root, func(path string, d os.DirEntry, err error) error {
if err != nil {
return nil // keep searching
}
if d.IsDir() {
return nil
}
if d.Name() == "go.mod" {
found = filepath.Dir(path)
return filepath.SkipAll
}
return nil
})
if err != nil {
return "", err
}
if found == "" {
return "", fmt.Errorf("go.mod not found under %s", root)
}
return found, nil
}
// skippedResult returns a clean ScanResult marked as skipped with an
// explanation. Using clean (not error) here because the package is simply
// not a Go module we can analyse — not a scanner failure.
// skippedResult returns a clean ScanResult marked as skipped with an explanation: the module has
// nothing another module can import, so there is nothing to audit.
func (s *Scanner) skippedResult(registry, packageName, version, reason string) *metadata.ScanResult {
return &metadata.ScanResult{
ID: uuid.New().String(),
@@ -221,7 +281,7 @@ func (s *Scanner) convertResult(vulns []GovulncheckVuln, registry, packageName,
ID: vuln.OSV,
Severity: severity,
Title: vuln.OSV,
Description: fmt.Sprintf("Vulnerability %s found by govulncheck", vuln.OSV),
Description: describe(vuln),
References: []string{fmt.Sprintf("https://pkg.go.dev/vuln/%s", vuln.OSV)},
FixedIn: vuln.FixedVersion,
})
@@ -249,17 +309,46 @@ func (s *Scanner) convertResult(vulns []GovulncheckVuln, registry, packageName,
}
}
// GovulncheckEntry represents a single line of govulncheck JSON output
func describe(v GovulncheckVuln) string {
desc := v.Summary
if desc == "" {
desc = "Vulnerability " + v.OSV
}
if v.Module != "" {
desc += fmt.Sprintf(" (%s@%s)", v.Module, v.ModuleVersion)
}
return desc
}
// GovulncheckEntry is one message of govulncheck's JSON stream; exactly one field is set.
type GovulncheckEntry struct {
Config *struct{} `json:"config,omitempty"`
OSV *GovulncheckOSV `json:"osv,omitempty"`
Finding *GovulncheckFinding `json:"finding,omitempty"`
}
// GovulncheckOSV is the advisory a finding refers to.
type GovulncheckOSV struct {
ID string `json:"id"`
Summary string `json:"summary"`
}
type GovulncheckFinding struct {
OSV string `json:"osv"`
FixedVersion string `json:"fixed_version,omitempty"`
OSV string `json:"osv"`
FixedVersion string `json:"fixed_version,omitempty"`
Trace []GovulncheckModule `json:"trace"`
}
// GovulncheckModule is the module a finding is in.
type GovulncheckModule struct {
Module string `json:"module"`
Version string `json:"version"`
}
type GovulncheckVuln struct {
OSV string
FixedVersion string
OSV string
FixedVersion string
Module string
ModuleVersion string
Summary string
}
+194
View File
@@ -0,0 +1,194 @@
package govulncheck
import (
"archive/zip"
"context"
"fmt"
"os"
"path/filepath"
"testing"
"github.com/lukaszraczylo/gohoarder/pkg/config"
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
"github.com/lukaszraczylo/gohoarder/pkg/scanner/scanerr"
"github.com/lukaszraczylo/gohoarder/pkg/scanner/scannertest"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// The .stream fixtures are real govulncheck 1.9.0 `-json` output, cut down to the config, finding and
// referenced osv messages, and real `go list` output (see FINDINGS GH-25).
func abs(t *testing.T, name string) string {
t.Helper()
p, err := filepath.Abs(filepath.Join("testdata", name))
require.NoError(t, err)
return p
}
// module is a zip as the module proxy serves it; the scanner audits the module by path and version.
func module(t *testing.T) string {
t.Helper()
p := filepath.Join(t.TempDir(), "m.zip")
f, err := os.Create(p) // #nosec G304 -- test temp dir
require.NoError(t, err)
zw := zip.NewWriter(f)
w, err := zw.Create("example.com/[email protected]/go.mod")
require.NoError(t, err)
_, err = w.Write([]byte("module example.com/m\n"))
require.NoError(t, err)
require.NoError(t, zw.Close())
require.NoError(t, f.Close())
return p
}
// fakeGo fakes `go list`, recording the working directory's go.mod and main.go for the audit.
func fakeGo(t *testing.T, listFixture string, exit int, stderr string) (rec string) {
t.Helper()
rec = t.TempDir()
body := fmt.Sprintf(`
case "$1" in
list) cp go.mod %[1]q/go.mod; echo "$GOFLAGS|$GOTOOLCHAIN" > %[1]q/env; %[2]s; printf '%%s' %[3]q >&2; exit %[4]d ;;
esac`, rec, catOrNothing(listFixture), stderr, exit)
scannertest.Script(t, "go", body)
return rec
}
func catOrNothing(path string) string {
if path == "" {
return "true"
}
return "cat " + fmt.Sprintf("%q", path)
}
// fakeGovulncheck fakes govulncheck: it records main.go and the arguments, prints fixture.
func fakeGovulncheck(t *testing.T, fixture string, exit int, stderr string) (argsFile, mainCopy string) {
t.Helper()
dir := t.TempDir()
argsFile = filepath.Join(dir, "args")
mainCopy = filepath.Join(dir, "main.go")
scannertest.Script(t, "govulncheck", fmt.Sprintf(`
cp main.go %[2]q
for a in "$@"; do echo "$a" >> %[1]q; done
%[3]s
printf '%%s' %[4]q >&2
exit %[5]d`, argsFile, mainCopy, catOrNothing(fixture), stderr, exit))
return argsFile, mainCopy
}
func ids(res *metadata.ScanResult) map[string]string {
out := map[string]string{}
for _, v := range res.Vulnerabilities {
out[v.ID] = v.FixedIn
}
return out
}
func TestScanReadsPrettyPrintedFindings(t *testing.T) {
// govulncheck -json prints indented objects, not one object per line.
fakeGo(t, abs(t, "golist-gin-v1.6.0.txt"), 0, "")
fakeGovulncheck(t, abs(t, "gin-v1.6.0-source-scan.stream"), 0, "")
res, err := New(config.GovulncheckConfig{}).Scan(context.Background(), "go", "github.com/gin-gonic/gin/@v/v1.6.0.zip", "v1.6.0", module(t))
require.NoError(t, err)
assert.Equal(t, metadata.ScanStatusVulnerable, res.Status)
assert.Equal(t, map[string]string{
"GO-2022-0493": "v0.0.0-20220412211240-33da011f77ad",
"GO-2026-5024": "v0.44.0",
}, ids(res), "one entry per advisory, with the fixed version")
}
func TestScanAuditsTheModuleItself(t *testing.T) {
rec := fakeGo(t, abs(t, "golist-x-text-v0.3.5.txt"), 0, "")
args, mainCopy := fakeGovulncheck(t, abs(t, "x-text-v0.3.5.stream"), 0, "")
res, err := New(config.GovulncheckConfig{}).Scan(context.Background(), "go", "golang.org/x/text/@v/v0.3.5.zip", "v0.3.5", module(t))
require.NoError(t, err)
assert.Equal(t, metadata.ScanStatusVulnerable, res.Status)
assert.Equal(t, map[string]string{
"GO-2021-0113": "v0.3.7", "GO-2022-1059": "v0.3.8", "GO-2026-5970": "v0.39.0", "GO-2026-6629": "v0.41.0",
}, ids(res), "advisories against the scanned module, which a scan of its own source never reports")
for _, v := range res.Vulnerabilities {
assert.Equal(t, "HIGH", v.Severity)
assert.Equal(t, []string{"https://pkg.go.dev/vuln/" + v.ID}, v.References)
}
gomod, err := os.ReadFile(filepath.Join(rec, "go.mod")) // #nosec G304 -- test temp dir
require.NoError(t, err)
assert.Contains(t, string(gomod), "require golang.org/x/text v0.3.5")
env, err := os.ReadFile(filepath.Join(rec, "env")) // #nosec G304 -- test temp dir
require.NoError(t, err)
assert.Equal(t, "-mod=mod|local\n", string(env))
assert.Equal(t, []string{"-json", "-scan", "module"}, scannertest.Args(t, args))
src, err := os.ReadFile(mainCopy) // #nosec G304 -- test temp dir
require.NoError(t, err)
imports := string(src)
assert.Contains(t, imports, `_ "golang.org/x/text/language"`)
assert.NotContains(t, imports, "/cmd/gotext\"", "package main cannot be imported")
assert.NotContains(t, imports, "/internal", "internal packages cannot be imported")
}
func TestScanCleanModule(t *testing.T) {
scannertest.Script(t, "go", `echo "github.com/google/uuid uuid 12 0 "`)
_, _ = fakeGovulncheck(t, abs(t, "google-uuid-v1.6.0.stream"), 0, "")
res, err := New(config.GovulncheckConfig{}).Scan(context.Background(), "go", "github.com/google/uuid/@v/v1.6.0.zip", "v1.6.0", module(t))
require.NoError(t, err)
assert.Equal(t, metadata.ScanStatusClean, res.Status)
}
func TestScanModuleWithoutImportablePackagesIsSkipped(t *testing.T) {
scannertest.Script(t, "go", `echo "example.com/m/cmd/tool main 1 0 "`)
res, err := New(config.GovulncheckConfig{}).Scan(context.Background(), "go", "example.com/m/@v/v1.0.0.zip", "v1.0.0", module(t))
require.NoError(t, err)
assert.Equal(t, metadata.ScanStatusClean, res.Status)
assert.Contains(t, res.Details["skipped"], "no importable package")
}
func TestScanFailuresAreErrorResultsWithACause(t *testing.T) {
cases := []struct {
setup func(t *testing.T)
name string
infra bool
}{
{name: "module download fails on the network", setup: func(t *testing.T) { fakeGo(t, "", 1, "dial tcp: lookup proxy.golang.org: no such host") }, infra: true},
{name: "module is not in the proxy", setup: func(t *testing.T) { fakeGo(t, "", 1, "reading example.com/m/@v/v1.0.0.mod: 404 Not Found") }, infra: false},
{name: "govulncheck prints nothing", setup: func(t *testing.T) {
fakeGo(t, abs(t, "golist-gin-v1.6.0.txt"), 0, "")
fakeGovulncheck(t, "", 1, "govulncheck: loading packages: boom")
}, infra: false},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
tc.setup(t)
res, err := New(config.GovulncheckConfig{}).Scan(context.Background(), "go", "example.com/m/@v/v1.0.0.zip", "v1.0.0", module(t))
require.NoError(t, err)
assert.Equal(t, metadata.ScanStatusError, res.Status)
assert.Equal(t, tc.infra, res.Details[scanerr.DetailInfrastructure])
})
}
}
func TestScanRefusesModuleCoordinatesThatCouldInjectGoMod(t *testing.T) {
fakeGo(t, abs(t, "golist-gin-v1.6.0.txt"), 0, "")
res, err := New(config.GovulncheckConfig{}).Scan(context.Background(), "go", "example.com/m/@v/v1.0.0\nreplace x => y.zip", "v1.0.0\nreplace a => b", module(t))
require.NoError(t, err)
assert.Equal(t, metadata.ScanStatusError, res.Status)
}
func TestScanSkipsOtherRegistries(t *testing.T) {
res, err := New(config.GovulncheckConfig{}).Scan(context.Background(), "npm", "p", "1", "/x")
require.NoError(t, err)
assert.Equal(t, metadata.ScanStatusClean, res.Status)
}
@@ -0,0 +1,338 @@
{
"config": {
"protocol_version": "v1.0.0",
"scanner_name": "govulncheck",
"scanner_version": "v1.9.0",
"db": "https://vuln.go.dev",
"db_last_modified": "2026-11-11T02:51:11Z",
"go_version": "go1.26.11",
"scan_level": "symbol",
"scan_mode": "source"
}
}
{
"progress": {
"message": "Fetching vulnerabilities from the database..."
}
}
{
"osv": {
"schema_version": "1.3.1",
"id": "GO-2022-0493",
"modified": "2024-05-20T16:03:47Z",
"published": "2022-07-15T23:30:12Z",
"aliases": [
"CVE-2022-29526",
"GHSA-p782-xgp4-8hr8"
],
"summary": "Incorrect privilege reporting in syscall and golang.org/x/sys/unix",
"details": "When called with a non-zero flags parameter, the Faccessat function can incorrectly report that a file is accessible.",
"affected": [
{
"package": {
"name": "stdlib",
"ecosystem": "Go"
},
"ranges": [
{
"type": "SEMVER",
"events": [
{
"introduced": "0"
},
{
"fixed": "1.17.10"
},
{
"introduced": "1.18.0-0"
},
{
"fixed": "1.18.2"
}
]
}
],
"ecosystem_specific": {
"imports": [
{
"path": "syscall",
"symbols": [
"Faccessat"
]
}
]
}
},
{
"package": {
"name": "golang.org/x/sys",
"ecosystem": "Go"
},
"ranges": [
{
"type": "SEMVER",
"events": [
{
"introduced": "0"
},
{
"fixed": "0.0.0-20220412211240-33da011f77ad"
}
]
}
],
"ecosystem_specific": {
"imports": [
{
"path": "golang.org/x/sys/unix",
"symbols": [
"Faccessat"
]
}
]
}
}
],
"references": [
{
"type": "FIX",
"url": "https://go.dev/cl/399539"
},
{
"type": "REPORT",
"url": "https://go.dev/issue/52313"
},
{
"type": "FIX",
"url": "https://go.dev/cl/400074"
},
{
"type": "WEB",
"url": "https://groups.google.com/g/golang-announce/c/Y5qrqw_lWdU"
}
],
"credits": [
{
"name": "Jo\u00ebl G\u00e4hwiler (@256dpi)"
}
],
"database_specific": {
"url": "https://pkg.go.dev/vuln/GO-2022-0493",
"review_status": "REVIEWED"
}
}
}
{
"osv": {
"schema_version": "1.3.1",
"id": "GO-2026-5024",
"modified": "2026-05-22T18:28:47Z",
"published": "2026-05-22T18:28:47Z",
"aliases": [
"CVE-2026-39824"
],
"summary": "Invoking integer overflow in NewNTUnicodeString in golang.org/x/sys/windows",
"details": "NewNTUnicodeString does not check for string length overflow. When provided with a string that overflows the maximum size of a NTUnicodeString (a 16-bit number of bytes), it returns a truncated string rather than an error.",
"affected": [
{
"package": {
"name": "golang.org/x/sys",
"ecosystem": "Go"
},
"ranges": [
{
"type": "SEMVER",
"events": [
{
"introduced": "0"
},
{
"fixed": "0.44.0"
}
]
}
],
"ecosystem_specific": {
"imports": [
{
"path": "golang.org/x/sys/windows",
"goos": [
"windows"
],
"symbols": [
"NewNTUnicodeString"
]
}
]
}
}
],
"references": [
{
"type": "REPORT",
"url": "https://go.dev/issue/78916"
},
{
"type": "FIX",
"url": "https://go.dev/cl/770080"
},
{
"type": "WEB",
"url": "https://groups.google.com/g/golang-announce/c/6MMI8Lj-Atg"
}
],
"database_specific": {
"url": "https://pkg.go.dev/vuln/GO-2026-5024",
"review_status": "REVIEWED"
}
}
}
{
"osv": {
"schema_version": "1.3.1",
"id": "GO-2022-0493",
"modified": "2024-05-20T16:03:47Z",
"published": "2022-07-15T23:30:12Z",
"aliases": [
"CVE-2022-29526",
"GHSA-p782-xgp4-8hr8"
],
"summary": "Incorrect privilege reporting in syscall and golang.org/x/sys/unix",
"details": "When called with a non-zero flags parameter, the Faccessat function can incorrectly report that a file is accessible.",
"affected": [
{
"package": {
"name": "stdlib",
"ecosystem": "Go"
},
"ranges": [
{
"type": "SEMVER",
"events": [
{
"introduced": "0"
},
{
"fixed": "1.17.10"
},
{
"introduced": "1.18.0-0"
},
{
"fixed": "1.18.2"
}
]
}
],
"ecosystem_specific": {
"imports": [
{
"path": "syscall",
"symbols": [
"Faccessat"
]
}
]
}
},
{
"package": {
"name": "golang.org/x/sys",
"ecosystem": "Go"
},
"ranges": [
{
"type": "SEMVER",
"events": [
{
"introduced": "0"
},
{
"fixed": "0.0.0-20220412211240-33da011f77ad"
}
]
}
],
"ecosystem_specific": {
"imports": [
{
"path": "golang.org/x/sys/unix",
"symbols": [
"Faccessat"
]
}
]
}
}
],
"references": [
{
"type": "FIX",
"url": "https://go.dev/cl/399539"
},
{
"type": "REPORT",
"url": "https://go.dev/issue/52313"
},
{
"type": "FIX",
"url": "https://go.dev/cl/400074"
},
{
"type": "WEB",
"url": "https://groups.google.com/g/golang-announce/c/Y5qrqw_lWdU"
}
],
"credits": [
{
"name": "Jo\u00ebl G\u00e4hwiler (@256dpi)"
}
],
"database_specific": {
"url": "https://pkg.go.dev/vuln/GO-2022-0493",
"review_status": "REVIEWED"
}
}
}
{
"progress": {
"message": "Checking the code against the vulnerabilities..."
}
}
{
"finding": {
"osv": "GO-2022-0493",
"fixed_version": "v0.0.0-20220412211240-33da011f77ad",
"trace": [
{
"module": "golang.org/x/sys",
"version": "v0.0.0-20200116001909-b77594299b42"
}
]
}
}
{
"finding": {
"osv": "GO-2026-5024",
"fixed_version": "v0.44.0",
"trace": [
{
"module": "golang.org/x/sys",
"version": "v0.0.0-20200116001909-b77594299b42"
}
]
}
}
{
"finding": {
"osv": "GO-2022-0493",
"fixed_version": "v0.0.0-20220412211240-33da011f77ad",
"trace": [
{
"module": "golang.org/x/sys",
"version": "v0.0.0-20200116001909-b77594299b42",
"package": "golang.org/x/sys/unix"
}
]
}
}
+522
View File
@@ -0,0 +1,522 @@
{
"config": {
"protocol_version": "v1.0.0",
"scanner_name": "govulncheck",
"scanner_version": "v1.9.0",
"db": "https://vuln.go.dev",
"db_last_modified": "2026-11-11T02:51:11Z",
"go_version": "go1.26.11",
"scan_level": "module",
"scan_mode": "source"
}
}
{
"progress": {
"message": "Fetching vulnerabilities from the database..."
}
}
{
"osv": {
"schema_version": "1.3.1",
"id": "GO-2022-0493",
"modified": "2024-05-20T16:03:47Z",
"published": "2022-07-15T23:30:12Z",
"aliases": [
"CVE-2022-29526",
"GHSA-p782-xgp4-8hr8"
],
"summary": "Incorrect privilege reporting in syscall and golang.org/x/sys/unix",
"details": "When called with a non-zero flags parameter, the Faccessat function can incorrectly report that a file is accessible.",
"affected": [
{
"package": {
"name": "stdlib",
"ecosystem": "Go"
},
"ranges": [
{
"type": "SEMVER",
"events": [
{
"introduced": "0"
},
{
"fixed": "1.17.10"
},
{
"introduced": "1.18.0-0"
},
{
"fixed": "1.18.2"
}
]
}
],
"ecosystem_specific": {
"imports": [
{
"path": "syscall",
"symbols": [
"Faccessat"
]
}
]
}
},
{
"package": {
"name": "golang.org/x/sys",
"ecosystem": "Go"
},
"ranges": [
{
"type": "SEMVER",
"events": [
{
"introduced": "0"
},
{
"fixed": "0.0.0-20220412211240-33da011f77ad"
}
]
}
],
"ecosystem_specific": {
"imports": [
{
"path": "golang.org/x/sys/unix",
"symbols": [
"Faccessat"
]
}
]
}
}
],
"references": [
{
"type": "FIX",
"url": "https://go.dev/cl/399539"
},
{
"type": "REPORT",
"url": "https://go.dev/issue/52313"
},
{
"type": "FIX",
"url": "https://go.dev/cl/400074"
},
{
"type": "WEB",
"url": "https://groups.google.com/g/golang-announce/c/Y5qrqw_lWdU"
}
],
"credits": [
{
"name": "Jo\u00ebl G\u00e4hwiler (@256dpi)"
}
],
"database_specific": {
"url": "https://pkg.go.dev/vuln/GO-2022-0493",
"review_status": "REVIEWED"
}
}
}
{
"osv": {
"schema_version": "1.3.1",
"id": "GO-2021-0052",
"modified": "2024-05-20T16:03:47Z",
"published": "2021-04-14T20:04:52Z",
"aliases": [
"CVE-2020-28483",
"GHSA-h395-qcrw-5vmq"
],
"summary": "Inconsistent interpretation of HTTP Requests in github.com/gin-gonic/gin",
"details": "Due to improper HTTP header sanitization, a malicious user can spoof their source IP address by setting the X-Forwarded-For header. This may allow a user to bypass IP based restrictions, or obfuscate their true source.",
"affected": [
{
"package": {
"name": "github.com/gin-gonic/gin",
"ecosystem": "Go"
},
"ranges": [
{
"type": "SEMVER",
"events": [
{
"introduced": "0"
},
{
"fixed": "1.7.7"
}
]
}
],
"ecosystem_specific": {
"imports": [
{
"path": "github.com/gin-gonic/gin",
"symbols": [
"Context.ClientIP",
"Context.Next",
"Context.RemoteIP",
"Engine.HandleContext",
"Engine.Run",
"Engine.RunFd",
"Engine.RunListener",
"Engine.RunTLS",
"Engine.RunUnix",
"Engine.ServeHTTP"
]
}
]
}
}
],
"references": [
{
"type": "REPORT",
"url": "https://github.com/gin-gonic/gin/issues/2862"
},
{
"type": "REPORT",
"url": "https://github.com/gin-gonic/gin/issues/2473"
},
{
"type": "REPORT",
"url": "https://github.com/gin-gonic/gin/issues/2232"
},
{
"type": "FIX",
"url": "https://github.com/gin-gonic/gin/pull/2844"
},
{
"type": "FIX",
"url": "https://github.com/gin-gonic/gin/commit/5929d521715610c9dd14898ebbe1d188d5de8937"
},
{
"type": "FIX",
"url": "https://github.com/gin-gonic/gin/pull/2632"
},
{
"type": "FIX",
"url": "https://github.com/gin-gonic/gin/commit/bfc8ca285eb46dad60e037d57c545cd260636711"
},
{
"type": "FIX",
"url": "https://github.com/gin-gonic/gin/pull/2675"
},
{
"type": "FIX",
"url": "https://github.com/gin-gonic/gin/commit/03e5e05ae089bc989f1ca41841f05504d29e3fd9"
},
{
"type": "WEB",
"url": "https://github.com/gin-gonic/gin/pull/2474"
}
],
"credits": [
{
"name": "@sorenisanerd"
}
],
"database_specific": {
"url": "https://pkg.go.dev/vuln/GO-2021-0052",
"review_status": "REVIEWED"
}
}
}
{
"osv": {
"schema_version": "1.3.1",
"id": "GO-2023-1737",
"modified": "2024-05-20T16:03:47Z",
"published": "2023-05-11T18:59:56Z",
"aliases": [
"CVE-2023-29401",
"GHSA-2c4m-59x9-fr2g"
],
"summary": "Improper handling of filenames in Content-Disposition HTTP header in github.com/gin-gonic/gin",
"details": "The filename parameter of the Context.FileAttachment function is not properly sanitized. A maliciously crafted filename can cause the Content-Disposition header to be sent with an unexpected filename value or otherwise modify the Content-Disposition header. For example, a filename of \"setup.bat&quot;;x=.txt\" will be sent as a file named \"setup.bat\".\n\nIf the FileAttachment function is called with names provided by an untrusted source, this may permit an attacker to cause a file to be served with a name different than provided. Maliciously crafted attachment file name can modify the Content-Disposition header.",
"affected": [
{
"package": {
"name": "github.com/gin-gonic/gin",
"ecosystem": "Go"
},
"ranges": [
{
"type": "SEMVER",
"events": [
{
"introduced": "1.3.1-0.20190301021747-ccb9e902956d"
},
{
"fixed": "1.9.1"
}
]
}
],
"ecosystem_specific": {
"imports": [
{
"path": "github.com/gin-gonic/gin",
"symbols": [
"Context.FileAttachment"
]
}
]
}
}
],
"references": [
{
"type": "REPORT",
"url": "https://github.com/gin-gonic/gin/issues/3555"
},
{
"type": "FIX",
"url": "https://github.com/gin-gonic/gin/pull/3556"
},
{
"type": "WEB",
"url": "https://github.com/gin-gonic/gin/releases/tag/v1.9.1"
}
],
"credits": [
{
"name": "motoyasu-saburi"
}
],
"database_specific": {
"url": "https://pkg.go.dev/vuln/GO-2023-1737",
"review_status": "REVIEWED"
}
}
}
{
"osv": {
"schema_version": "1.3.1",
"id": "GO-2022-0493",
"modified": "2024-05-20T16:03:47Z",
"published": "2022-07-15T23:30:12Z",
"aliases": [
"CVE-2022-29526",
"GHSA-p782-xgp4-8hr8"
],
"summary": "Incorrect privilege reporting in syscall and golang.org/x/sys/unix",
"details": "When called with a non-zero flags parameter, the Faccessat function can incorrectly report that a file is accessible.",
"affected": [
{
"package": {
"name": "stdlib",
"ecosystem": "Go"
},
"ranges": [
{
"type": "SEMVER",
"events": [
{
"introduced": "0"
},
{
"fixed": "1.17.10"
},
{
"introduced": "1.18.0-0"
},
{
"fixed": "1.18.2"
}
]
}
],
"ecosystem_specific": {
"imports": [
{
"path": "syscall",
"symbols": [
"Faccessat"
]
}
]
}
},
{
"package": {
"name": "golang.org/x/sys",
"ecosystem": "Go"
},
"ranges": [
{
"type": "SEMVER",
"events": [
{
"introduced": "0"
},
{
"fixed": "0.0.0-20220412211240-33da011f77ad"
}
]
}
],
"ecosystem_specific": {
"imports": [
{
"path": "golang.org/x/sys/unix",
"symbols": [
"Faccessat"
]
}
]
}
}
],
"references": [
{
"type": "FIX",
"url": "https://go.dev/cl/399539"
},
{
"type": "REPORT",
"url": "https://go.dev/issue/52313"
},
{
"type": "FIX",
"url": "https://go.dev/cl/400074"
},
{
"type": "WEB",
"url": "https://groups.google.com/g/golang-announce/c/Y5qrqw_lWdU"
}
],
"credits": [
{
"name": "Jo\u00ebl G\u00e4hwiler (@256dpi)"
}
],
"database_specific": {
"url": "https://pkg.go.dev/vuln/GO-2022-0493",
"review_status": "REVIEWED"
}
}
}
{
"osv": {
"schema_version": "1.3.1",
"id": "GO-2026-5024",
"modified": "2026-05-22T18:28:47Z",
"published": "2026-05-22T18:28:47Z",
"aliases": [
"CVE-2026-39824"
],
"summary": "Invoking integer overflow in NewNTUnicodeString in golang.org/x/sys/windows",
"details": "NewNTUnicodeString does not check for string length overflow. When provided with a string that overflows the maximum size of a NTUnicodeString (a 16-bit number of bytes), it returns a truncated string rather than an error.",
"affected": [
{
"package": {
"name": "golang.org/x/sys",
"ecosystem": "Go"
},
"ranges": [
{
"type": "SEMVER",
"events": [
{
"introduced": "0"
},
{
"fixed": "0.44.0"
}
]
}
],
"ecosystem_specific": {
"imports": [
{
"path": "golang.org/x/sys/windows",
"goos": [
"windows"
],
"symbols": [
"NewNTUnicodeString"
]
}
]
}
}
],
"references": [
{
"type": "REPORT",
"url": "https://go.dev/issue/78916"
},
{
"type": "FIX",
"url": "https://go.dev/cl/770080"
},
{
"type": "WEB",
"url": "https://groups.google.com/g/golang-announce/c/6MMI8Lj-Atg"
}
],
"database_specific": {
"url": "https://pkg.go.dev/vuln/GO-2026-5024",
"review_status": "REVIEWED"
}
}
}
{
"progress": {
"message": "Checking the code against the vulnerabilities..."
}
}
{
"finding": {
"osv": "GO-2021-0052",
"fixed_version": "v1.7.7",
"trace": [
{
"module": "github.com/gin-gonic/gin",
"version": "v1.6.0"
}
]
}
}
{
"finding": {
"osv": "GO-2023-1737",
"fixed_version": "v1.9.1",
"trace": [
{
"module": "github.com/gin-gonic/gin",
"version": "v1.6.0"
}
]
}
}
{
"finding": {
"osv": "GO-2022-0493",
"fixed_version": "v0.0.0-20220412211240-33da011f77ad",
"trace": [
{
"module": "golang.org/x/sys",
"version": "v0.0.0-20200116001909-b77594299b42"
}
]
}
}
{
"finding": {
"osv": "GO-2026-5024",
"fixed_version": "v0.44.0",
"trace": [
{
"module": "golang.org/x/sys",
"version": "v0.0.0-20200116001909-b77594299b42"
}
]
}
}
@@ -0,0 +1,6 @@
github.com/gin-gonic/gin gin 18 0
github.com/gin-gonic/gin/binding binding 13 0
github.com/gin-gonic/gin/ginS ginS 1 0
github.com/gin-gonic/gin/internal/bytesconv bytesconv 1 0
github.com/gin-gonic/gin/internal/json json 1 0
github.com/gin-gonic/gin/render render 11 0
@@ -0,0 +1,63 @@
golang.org/x/text text 1 0
golang.org/x/text/cases cases 7 0
golang.org/x/text/cmd/gotext main 7 0
golang.org/x/text/cmd/gotext/examples/extract main 2 0
golang.org/x/text/cmd/gotext/examples/extract_http main 2 0
golang.org/x/text/cmd/gotext/examples/extract_http/pkg pkg 1 0
golang.org/x/text/cmd/gotext/examples/rewrite main 1 0
golang.org/x/text/collate collate 5 0
golang.org/x/text/collate/build build 6 0
golang.org/x/text/collate/tools/colcmp main 4 0
golang.org/x/text/currency currency 5 0
golang.org/x/text/date date 1 0
golang.org/x/text/encoding encoding 1 0
golang.org/x/text/encoding/charmap charmap 2 0
golang.org/x/text/encoding/htmlindex htmlindex 3 0
golang.org/x/text/encoding/ianaindex ianaindex 3 0
golang.org/x/text/encoding/internal internal 1 0
golang.org/x/text/encoding/internal/enctest enctest 1 0
golang.org/x/text/encoding/internal/identifier identifier 2 0
golang.org/x/text/encoding/japanese japanese 5 0
golang.org/x/text/encoding/korean korean 2 0
golang.org/x/text/encoding/simplifiedchinese simplifiedchinese 4 0
golang.org/x/text/encoding/traditionalchinese traditionalchinese 2 0
golang.org/x/text/encoding/unicode unicode 2 0
golang.org/x/text/encoding/unicode/utf32 utf32 1 0
golang.org/x/text/feature/plural plural 4 0
golang.org/x/text/internal internal 2 0
golang.org/x/text/internal/catmsg catmsg 3 0
golang.org/x/text/internal/cldrtree cldrtree 5 0
golang.org/x/text/internal/colltab colltab 8 0
golang.org/x/text/internal/export/idna idna 5 0
golang.org/x/text/internal/export/unicode unicode 1 0
golang.org/x/text/internal/format format 2 0
golang.org/x/text/internal/gen gen 2 0
golang.org/x/text/internal/gen/bitfield bitfield 1 0
golang.org/x/text/internal/language language 10 0
golang.org/x/text/internal/language/compact compact 5 0
golang.org/x/text/internal/number number 7 0
golang.org/x/text/internal/stringset stringset 1 0
golang.org/x/text/internal/tag tag 1 0
golang.org/x/text/internal/testtext testtext 5 0
golang.org/x/text/internal/triegen triegen 3 0
golang.org/x/text/internal/ucd ucd 1 0
golang.org/x/text/internal/utf8internal utf8internal 1 0
golang.org/x/text/language language 8 0
golang.org/x/text/language/display display 4 0
golang.org/x/text/message message 5 0
golang.org/x/text/message/catalog catalog 3 0
golang.org/x/text/message/pipeline pipeline 5 0
golang.org/x/text/number number 4 0
golang.org/x/text/runes runes 2 0
golang.org/x/text/search search 4 0
golang.org/x/text/secure secure 1 0
golang.org/x/text/secure/bidirule bidirule 2 0
golang.org/x/text/secure/precis precis 10 0
golang.org/x/text/transform transform 1 0
golang.org/x/text/unicode unicode 1 0
golang.org/x/text/unicode/bidi bidi 6 0
golang.org/x/text/unicode/cldr cldr 7 0
golang.org/x/text/unicode/norm norm 9 0
golang.org/x/text/unicode/rangetable rangetable 3 0
golang.org/x/text/unicode/runenames runenames 2 0
golang.org/x/text/width width 5 0
@@ -0,0 +1,22 @@
{
"config": {
"protocol_version": "v1.0.0",
"scanner_name": "govulncheck",
"scanner_version": "v1.9.0",
"db": "https://vuln.go.dev",
"db_last_modified": "2026-11-11T02:51:11Z",
"go_version": "go1.26.11",
"scan_level": "module",
"scan_mode": "source"
}
}
{
"progress": {
"message": "Fetching vulnerabilities from the database..."
}
}
{
"progress": {
"message": "Checking the code against the vulnerabilities..."
}
}
+369
View File
@@ -0,0 +1,369 @@
{
"config": {
"protocol_version": "v1.0.0",
"scanner_name": "govulncheck",
"scanner_version": "v1.9.0",
"db": "https://vuln.go.dev",
"db_last_modified": "2026-11-11T02:51:11Z",
"go_version": "go1.26.11",
"scan_level": "module",
"scan_mode": "source"
}
}
{
"progress": {
"message": "Fetching vulnerabilities from the database..."
}
}
{
"osv": {
"schema_version": "1.3.1",
"id": "GO-2021-0113",
"modified": "2024-05-20T16:03:47Z",
"published": "2021-10-06T17:51:21Z",
"aliases": [
"CVE-2021-38561",
"GHSA-ppp9-7jff-5vj2"
],
"summary": "Out-of-bounds read in golang.org/x/text/language",
"details": "Due to improper index calculation, an incorrectly formatted language tag can cause Parse to panic via an out of bounds read. If Parse is used to process untrusted user inputs, this may be used as a vector for a denial of service attack.",
"affected": [
{
"package": {
"name": "golang.org/x/text",
"ecosystem": "Go"
},
"ranges": [
{
"type": "SEMVER",
"events": [
{
"introduced": "0"
},
{
"fixed": "0.3.7"
}
]
}
],
"ecosystem_specific": {
"imports": [
{
"path": "golang.org/x/text/language",
"symbols": [
"MatchStrings",
"MustParse",
"Parse",
"ParseAcceptLanguage"
]
}
]
}
}
],
"references": [
{
"type": "FIX",
"url": "https://go.dev/cl/340830"
},
{
"type": "FIX",
"url": "https://go.googlesource.com/text/+/383b2e75a7a4198c42f8f87833eefb772868a56f"
}
],
"credits": [
{
"name": "Guido Vranken"
}
],
"database_specific": {
"url": "https://pkg.go.dev/vuln/GO-2021-0113",
"review_status": "REVIEWED"
}
}
}
{
"osv": {
"schema_version": "1.3.1",
"id": "GO-2022-1059",
"modified": "2024-05-20T16:03:47Z",
"published": "2022-10-11T18:16:24Z",
"aliases": [
"CVE-2022-32149",
"GHSA-69ch-w2m2-3vjp"
],
"summary": "Denial of service via crafted Accept-Language header in golang.org/x/text/language",
"details": "An attacker may cause a denial of service by crafting an Accept-Language header which ParseAcceptLanguage will take significant time to parse.",
"affected": [
{
"package": {
"name": "golang.org/x/text",
"ecosystem": "Go"
},
"ranges": [
{
"type": "SEMVER",
"events": [
{
"introduced": "0"
},
{
"fixed": "0.3.8"
}
]
}
],
"ecosystem_specific": {
"imports": [
{
"path": "golang.org/x/text/language",
"symbols": [
"MatchStrings",
"ParseAcceptLanguage"
]
}
]
}
}
],
"references": [
{
"type": "REPORT",
"url": "https://go.dev/issue/56152"
},
{
"type": "FIX",
"url": "https://go.dev/cl/442235"
},
{
"type": "WEB",
"url": "https://groups.google.com/g/golang-announce/c/-hjNw559_tE/m/KlGTfid5CAAJ"
}
],
"credits": [
{
"name": "Adam Korczynski (ADA Logics)"
},
{
"name": "OSS-Fuzz"
}
],
"database_specific": {
"url": "https://pkg.go.dev/vuln/GO-2022-1059",
"review_status": "REVIEWED"
}
}
}
{
"osv": {
"schema_version": "1.3.1",
"id": "GO-2026-5970",
"modified": "2026-08-10T22:42:36Z",
"published": "2026-07-14T17:29:56Z",
"aliases": [
"CVE-2026-56852"
],
"summary": "Infinite loop on invalid input in golang.org/x/text",
"details": "A norm.Iter can enter an infinite loop when handling input containing invalid UTF-8 bytes.",
"affected": [
{
"package": {
"name": "golang.org/x/text",
"ecosystem": "Go"
},
"ranges": [
{
"type": "SEMVER",
"events": [
{
"introduced": "0"
},
{
"fixed": "0.39.0"
}
]
}
],
"ecosystem_specific": {
"imports": [
{
"path": "golang.org/x/text/unicode/norm",
"symbols": [
"Form.Append",
"Form.AppendString",
"Form.Bytes",
"Form.FirstBoundary",
"Form.FirstBoundaryInString",
"Form.IsNormal",
"Form.IsNormalString",
"Form.LastBoundary",
"Form.NextBoundary",
"Form.NextBoundaryInString",
"Form.Properties",
"Form.PropertiesString",
"Form.QuickSpan",
"Form.QuickSpanString",
"Form.Span",
"Form.SpanString",
"Form.String",
"Form.Transform",
"Iter.Init",
"Iter.InitString",
"Iter.Next",
"Iter.Seek",
"nextComposed",
"normReader.Read",
"normWriter.Write"
]
}
]
}
}
],
"references": [
{
"type": "REPORT",
"url": "https://go.dev/issue/80142"
},
{
"type": "FIX",
"url": "https://go.dev/cl/794100"
}
],
"credits": [
{
"name": "Viky Choi (\"vikychoi\" on GitHub)"
}
],
"database_specific": {
"url": "https://pkg.go.dev/vuln/GO-2026-5970",
"review_status": "REVIEWED"
}
}
}
{
"osv": {
"schema_version": "1.3.1",
"id": "GO-2026-6629",
"modified": "2026-10-07T14:09:43Z",
"published": "2026-10-07T14:09:43Z",
"aliases": [
"CVE-2026-56851"
],
"summary": "Panic parsing crafted input in x/text/secure/precis in golang.org/x/text",
"details": "The Nickname profile can panic with an out-of-bounds slice error when transforming crafted input into a short destination buffer.",
"affected": [
{
"package": {
"name": "golang.org/x/text",
"ecosystem": "Go"
},
"ranges": [
{
"type": "SEMVER",
"events": [
{
"introduced": "0"
},
{
"fixed": "0.41.0"
}
]
}
],
"ecosystem_specific": {
"imports": [
{
"path": "golang.org/x/text/secure/precis",
"symbols": [
"Profile.Append",
"Profile.AppendCompareKey",
"Profile.Bytes",
"Profile.Compare",
"Profile.CompareKey",
"Profile.NewTransformer",
"Profile.String",
"Transformer.Bytes",
"Transformer.String",
"Transformer.Transform",
"nickAdditionalMapping.Transform"
]
}
]
}
}
],
"references": [
{
"type": "FIX",
"url": "https://go.dev/cl/793360"
},
{
"type": "REPORT",
"url": "https://go.dev/issue/80112"
}
],
"credits": [
{
"name": "Omkhar Arasaratnam (GitHub: omkhar)"
}
],
"database_specific": {
"url": "https://pkg.go.dev/vuln/GO-2026-6629",
"review_status": "REVIEWED"
}
}
}
{
"progress": {
"message": "Checking the code against the vulnerabilities..."
}
}
{
"finding": {
"osv": "GO-2021-0113",
"fixed_version": "v0.3.7",
"trace": [
{
"module": "golang.org/x/text",
"version": "v0.3.5"
}
]
}
}
{
"finding": {
"osv": "GO-2022-1059",
"fixed_version": "v0.3.8",
"trace": [
{
"module": "golang.org/x/text",
"version": "v0.3.5"
}
]
}
}
{
"finding": {
"osv": "GO-2026-5970",
"fixed_version": "v0.39.0",
"trace": [
{
"module": "golang.org/x/text",
"version": "v0.3.5"
}
]
}
}
{
"finding": {
"osv": "GO-2026-6629",
"fixed_version": "v0.41.0",
"trace": [
{
"module": "golang.org/x/text",
"version": "v0.3.5"
}
]
}
}
+46 -16
View File
@@ -3,14 +3,17 @@
package grype
import (
"bytes"
"context"
"encoding/json"
"fmt"
"os/exec"
"strings"
"time"
"github.com/lukaszraczylo/gohoarder/pkg/config"
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
"github.com/lukaszraczylo/gohoarder/pkg/scanner/gomodule"
"github.com/lukaszraczylo/gohoarder/pkg/uuid"
"github.com/rs/zerolog/log"
)
@@ -44,25 +47,25 @@ func (s *Scanner) Scan(ctx context.Context, registry, packageName, version strin
Str("file", filePath).
Msg("Starting Grype scan")
// Run grype scan
cmd := exec.CommandContext(ctx, "grype", filePath, "-o", "json", "-q")
output, err := cmd.CombinedOutput()
if err != nil {
// Grype returns non-zero exit code when vulnerabilities are found
// Only treat it as error if we got no output
if len(output) == 0 {
return nil, fmt.Errorf("grype scan failed: %w (output: %s)", err, string(output))
}
target := purl(registry, packageName, version)
if target == "" {
target = filePath
}
cmd := exec.CommandContext(ctx, "grype", target, "-o", "json", "-q") // #nosec G204 -- target is a purl or the stored artifact path
var stderr bytes.Buffer
cmd.Stderr = &stderr
output, err := cmd.Output()
if err != nil && len(output) == 0 {
return nil, fmt.Errorf("grype scan failed: %w (stderr: %s)", err, strings.TrimSpace(stderr.String()))
}
// Parse Grype JSON output
var grypeResult GrypeResult
if err := json.Unmarshal(output, &grypeResult); err != nil {
return nil, fmt.Errorf("failed to parse grype output: %w", err)
grypeResult, err := parse(output)
if err != nil {
return nil, err
}
// Convert to our format
result := s.convertGrypeResult(&grypeResult, registry, packageName, version)
result := s.convertGrypeResult(grypeResult, registry, packageName, version)
log.Info().
Str("scanner", ScannerName).
@@ -73,6 +76,33 @@ func (s *Scanner) Scan(ctx context.Context, registry, packageName, version strin
return result, nil
}
// purl names the package for grype. A bare npm, PyPI or Go archive has no lockfile or installed
// metadata, so grype catalogs nothing in it and reports clean; a purl is matched against the
// database directly. Empty means no purl can be built.
func purl(registry, name, version string) string {
if name == "" || version == "" {
return ""
}
version = strings.ReplaceAll(version, "+", "%2B")
switch registry {
case "npm":
return "pkg:npm/" + strings.Replace(name, "@", "%40", 1) + "@" + version
case "go":
return "pkg:golang/" + gomodule.Path(name) + "@" + version
case "pypi":
return "pkg:pypi/" + strings.ToLower(strings.NewReplacer("_", "-", ".", "-").Replace(name)) + "@" + version
}
return ""
}
func parse(output []byte) (*GrypeResult, error) {
var res GrypeResult
if err := json.Unmarshal(output, &res); err != nil {
return nil, fmt.Errorf("failed to parse grype output: %w", err)
}
return &res, nil
}
// Health checks if Grype is available
func (s *Scanner) Health(ctx context.Context) error {
cmd := exec.CommandContext(ctx, "grype", "version")
@@ -166,8 +196,8 @@ type GrypeDescriptor struct {
}
type GrypeSource struct {
Target map[string]interface{} `json:"target"`
Type string `json:"type"`
Type string `json:"type"`
Target json.RawMessage `json:"target"` // a string for file, directory and purl sources, an object for images
}
type GrypeMatch struct {
+126
View File
@@ -0,0 +1,126 @@
package grype
import (
"context"
"os"
"path/filepath"
"testing"
"github.com/lukaszraczylo/gohoarder/pkg/config"
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
"github.com/lukaszraczylo/gohoarder/pkg/scanner/scannertest"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// The fixtures are real `grype -o json -q` output from grype 0.121.2 (see FINDINGS GH-25).
func fixture(name string) string { return filepath.Join("testdata", name) }
func TestParseFileScanTargetIsAString(t *testing.T) {
data, err := os.ReadFile(fixture("file-minimist-0.0.8.json"))
require.NoError(t, err)
res, err := parse(data)
require.NoError(t, err)
assert.Equal(t, "file", res.Source.Type)
}
func TestScanMapsRealOutput(t *testing.T) {
cases := []struct {
wantSeverities map[string]string
wantFixedIn map[string]string
name, fixture, registry, pkg, version string
wantPurl string
wantStatus metadata.ScanStatus
}{
{
name: "npm vulnerable", fixture: "purl-minimist-0.0.8.json", registry: "npm", pkg: "minimist", version: "0.0.8",
wantPurl: "pkg:npm/[email protected]", wantStatus: metadata.ScanStatusVulnerable,
wantSeverities: map[string]string{"GHSA-xvch-5gv4-984h": "CRITICAL", "GHSA-vh95-rmgr-6w4m": "MODERATE"},
wantFixedIn: map[string]string{"GHSA-xvch-5gv4-984h": "0.2.4"},
},
{
name: "npm clean", fixture: "purl-dayjs-1.11.13.json", registry: "npm", pkg: "dayjs", version: "1.11.13",
wantPurl: "pkg:npm/[email protected]", wantStatus: metadata.ScanStatusClean,
},
{
name: "go vulnerable", fixture: "purl-go-text-0.3.5.json", registry: "go", pkg: "golang.org/x/text/@v/v0.3.5.zip", version: "v0.3.5",
wantPurl: "pkg:golang/golang.org/x/[email protected]", wantStatus: metadata.ScanStatusVulnerable,
wantSeverities: map[string]string{"GHSA-69ch-w2m2-3vjp": "HIGH", "GO-2026-6629": "HIGH"},
},
{
name: "pypi vulnerable", fixture: "purl-pypi-requests-2.19.0.json", registry: "pypi", pkg: "requests", version: "2.19.0",
wantPurl: "pkg:pypi/[email protected]", wantStatus: metadata.ScanStatusVulnerable,
wantSeverities: map[string]string{"GHSA-x84v-xcm2-53pg": "HIGH", "GHSA-j8r2-6x86-q33q": "MODERATE"},
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
args := scannertest.Fake(t, "grype", fixture(tc.fixture), "", 0)
res, err := New(config.GrypeConfig{}).Scan(context.Background(), tc.registry, tc.pkg, tc.version, "/tmp/artifact")
require.NoError(t, err)
assert.Equal(t, tc.wantStatus, res.Status)
assert.Equal(t, tc.wantPurl, scannertest.Args(t, args)[0], "the package is scanned by purl, not by its archive")
got := map[string]string{}
fixed := map[string]string{}
for _, v := range res.Vulnerabilities {
got[v.ID] = v.Severity
fixed[v.ID] = v.FixedIn
}
for id, sev := range tc.wantSeverities {
assert.Equal(t, sev, got[id], id)
}
for id, f := range tc.wantFixedIn {
assert.Equal(t, f, fixed[id], id)
}
assert.Equal(t, len(res.Vulnerabilities), res.VulnerabilityCount)
})
}
}
func TestScanFallsBackToFileForUnknownRegistry(t *testing.T) {
args := scannertest.Fake(t, "grype", fixture("file-minimist-0.0.8.json"), "", 0)
res, err := New(config.GrypeConfig{}).Scan(context.Background(), "docker", "x", "1", "/tmp/artifact.tar")
require.NoError(t, err)
assert.Equal(t, metadata.ScanStatusClean, res.Status)
assert.Equal(t, "/tmp/artifact.tar", scannertest.Args(t, args)[0])
}
func TestScanIgnoresStderrNoise(t *testing.T) {
scannertest.Fake(t, "grype", fixture("purl-dayjs-1.11.13.json"), "[0000] WARN something\n", 0)
res, err := New(config.GrypeConfig{}).Scan(context.Background(), "npm", "dayjs", "1.11.13", "/tmp/a.tgz")
require.NoError(t, err)
assert.Equal(t, metadata.ScanStatusClean, res.Status)
}
func TestScanFailureWithoutOutputIsAnError(t *testing.T) {
scannertest.Fake(t, "grype", "", "failed to load vulnerability db", 1)
_, err := New(config.GrypeConfig{}).Scan(context.Background(), "npm", "dayjs", "1.11.13", "/tmp/a.tgz")
require.Error(t, err)
assert.Contains(t, err.Error(), "failed to load vulnerability db")
}
func TestPurl(t *testing.T) {
cases := []struct{ registry, name, version, want string }{
{"npm", "left-pad", "1.3.0", "pkg:npm/[email protected]"},
{"npm", "@babel/traverse", "7.0.0", "pkg:npm/%40babel/[email protected]"},
{"go", "github.com/!azure/go-x/@v/v1.2.3.zip", "v1.2.3", "pkg:golang/github.com/Azure/[email protected]"},
{"go", "github.com/a/b/v2/@v/v2.0.0+incompatible.zip", "v2.0.0+incompatible", "pkg:golang/github.com/a/b/[email protected]%2Bincompatible"},
{"pypi", "Zope.Interface_x", "5.0", "pkg:pypi/[email protected]"},
{"npm", "", "1", ""},
{"npm", "x", "", ""},
{"docker", "x", "1", ""},
}
for _, tc := range cases {
assert.Equal(t, tc.want, purl(tc.registry, tc.name, tc.version), "%s %s", tc.registry, tc.name)
}
}
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+68
View File
@@ -0,0 +1,68 @@
package scanner
import (
"context"
"errors"
"sync/atomic"
"testing"
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
)
type healthProbe struct {
err error
calls atomic.Int32
}
func (s *healthProbe) Name() string { return "counting" }
func (s *healthProbe) Scan(context.Context, string, string, string, string) (*metadata.ScanResult, error) {
return nil, nil
}
func (s *healthProbe) Health(context.Context) error {
s.calls.Add(1)
return s.err
}
// Health runs each scanner's version command; under scan load that took over a second, so
// repeated probes must reuse a recent result.
func TestHealthReusesRecentResult(t *testing.T) {
tests := []struct {
err error
name string
}{
{name: "healthy", err: nil},
{name: "unhealthy", err: errors.New("grype missing")},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
s := &healthProbe{err: tt.err}
m := &Manager{enabled: true, scanners: []Scanner{s}}
for range 3 {
if err := m.Health(context.Background()); (err != nil) != (tt.err != nil) {
t.Fatalf("Health() error = %v, want error %v", err, tt.err != nil)
}
}
if got := s.calls.Load(); got != 1 {
t.Fatalf("scanner health ran %d times, want 1", got)
}
})
}
}
// A probe whose context was cancelled must not pin its failure for the cache period.
func TestHealthDoesNotCacheCancelledProbe(t *testing.T) {
s := &healthProbe{err: context.Canceled}
m := &Manager{enabled: true, scanners: []Scanner{s}}
ctx, cancel := context.WithCancel(context.Background())
cancel()
_ = m.Health(ctx)
s.err = nil
if err := m.Health(context.Background()); err != nil {
t.Fatalf("Health() after cancelled probe = %v, want nil", err)
}
if got := s.calls.Load(); got != 2 {
t.Fatalf("scanner health ran %d times, want 2", got)
}
}
+151 -107
View File
@@ -3,16 +3,20 @@
package npmaudit
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"sort"
"strings"
"time"
"github.com/lukaszraczylo/gohoarder/pkg/config"
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
"github.com/lukaszraczylo/gohoarder/pkg/scanner/scanerr"
"github.com/lukaszraczylo/gohoarder/pkg/uuid"
"github.com/rs/zerolog/log"
)
@@ -63,71 +67,60 @@ func (s *Scanner) Scan(ctx context.Context, registry, packageName, version strin
Str("version", version).
Msg("Starting npm audit scan")
// Create a temporary directory
tmpDir, err := os.MkdirTemp("", "npm-audit-*")
if err != nil {
return nil, fmt.Errorf("failed to create temp dir: %w", err)
}
defer func() { _ = os.RemoveAll(tmpDir) }()
// Extract the .tgz file
if err := s.extractTgz(filePath, tmpDir); err != nil {
return nil, fmt.Errorf("failed to extract tgz: %w", err)
if err = writeWrapper(tmpDir, packageName, filePath); err != nil {
return s.scanErrorResult(ctx, registry, packageName, version, fmt.Sprintf("prepare audit project: %v", err), ""), nil
}
// Find the package directory (usually "package/")
packageDir := filepath.Join(tmpDir, "package")
if _, err := os.Stat(packageDir); os.IsNotExist(err) {
// Try the tmpDir itself
packageDir = tmpDir
}
// npm tarballs ship only package.json — there is no lockfile. We must
// generate one before `npm audit` can resolve the dependency tree.
// NOTE: this performs network egress (npm registry lookups for
// transitive deps). Acceptable here because the scanner runs server-
// side and the operator already trusts upstream resolution to cache
// the package; we use --ignore-scripts to avoid running install hooks.
// npm audit needs a lockfile and a tarball ships none. The tarball is installed into a
// wrapper project, so its own advisories are audited with its production dependencies, and
// its devDependencies are never resolved. This step reaches the npm registry.
log.Info().
Str("scanner", ScannerName).
Str("package", packageName).
Msg("Generating package-lock.json for npm audit (network egress)")
installCmd := exec.CommandContext(ctx, "npm", "install",
installCmd := exec.CommandContext(ctx, "npm", "install", // #nosec G204 -- fixed args
"--package-lock-only",
"--omit=dev",
"--ignore-scripts",
"--no-audit",
"--no-fund",
)
installCmd.Dir = packageDir
if installOut, err := installCmd.CombinedOutput(); err != nil {
installCmd.Dir = tmpDir
if installOut, installErr := installCmd.CombinedOutput(); installErr != nil {
log.Warn().
Err(err).
Err(installErr).
Str("package", packageName).
Str("output", string(installOut)).
Msg("npm install --package-lock-only failed; returning scan-error")
return s.scanErrorResult(registry, packageName, version,
fmt.Sprintf("npm install --package-lock-only failed: %v", err)), nil
return s.scanErrorResult(ctx, registry, packageName, version,
fmt.Sprintf("npm install --package-lock-only failed: %v", installErr), string(installOut)), nil
}
// Run npm audit against the freshly generated lockfile.
cmd := exec.CommandContext(ctx, "npm", "audit", "--json")
cmd.Dir = packageDir
output, _ := cmd.CombinedOutput() // npm audit returns non-zero when vulns found
cmd := exec.CommandContext(ctx, "npm", "audit", "--omit=dev", "--json") // #nosec G204 -- fixed args
cmd.Dir = tmpDir
var stderr bytes.Buffer
cmd.Stderr = &stderr
output, _ := cmd.Output() // npm audit exits non-zero when it finds vulnerabilities
// Parse npm audit output
var auditResult NpmAuditResult
if len(output) > 0 {
if err := json.Unmarshal(output, &auditResult); err != nil {
log.Warn().Err(err).Msg("Failed to parse npm audit output")
// Parse failure means we couldn't determine vulnerability state — fail closed.
return s.scanErrorResult(registry, packageName, version,
fmt.Sprintf("failed to parse npm audit output: %v", err)), nil
}
auditResult, err := parse(output)
if err != nil {
log.Warn().Err(err).Msg("Failed to parse npm audit output")
return s.scanErrorResult(ctx, registry, packageName, version,
fmt.Sprintf("failed to parse npm audit output: %v", err), stderr.String()), nil
}
if auditResult.Error != nil {
return s.scanErrorResult(ctx, registry, packageName, version,
fmt.Sprintf("npm audit failed: %s %s", auditResult.Error.Code, auditResult.Error.Summary), stderr.String()), nil
}
// Convert to our format
result := s.convertResult(&auditResult, registry, packageName, version)
result := s.convertResult(auditResult, registry, packageName, version)
log.Info().
Str("scanner", ScannerName).
@@ -138,6 +131,44 @@ func (s *Scanner) Scan(ctx context.Context, registry, packageName, version strin
return result, nil
}
// wrapperTarball is the archive's name inside the wrapper project.
const wrapperTarball = "artifact.tgz"
// writeWrapper makes dir a project whose only dependency is the archive.
func writeWrapper(dir, packageName, archive string) error {
src, err := os.Open(archive) // #nosec G304 -- path from the cache, not user input
if err != nil {
return err
}
defer func() { _ = src.Close() }()
root, err := os.OpenRoot(dir)
if err != nil {
return err
}
defer func() { _ = root.Close() }()
dst, err := root.Create(wrapperTarball)
if err != nil {
return err
}
if _, err = io.Copy(dst, src); err != nil {
_ = dst.Close()
return err
}
if err = dst.Close(); err != nil {
return err
}
manifest, err := json.Marshal(map[string]interface{}{
"name": "gohoarder-audit",
"version": "1.0.0",
"private": true,
"dependencies": map[string]string{packageName: "file:./" + wrapperTarball},
})
if err != nil {
return err
}
return root.WriteFile("package.json", manifest, 0o600)
}
// Health checks if npm is available
func (s *Scanner) Health(ctx context.Context) error {
cmd := exec.CommandContext(ctx, "npm", "--version")
@@ -147,18 +178,11 @@ func (s *Scanner) Health(ctx context.Context) error {
return nil
}
// extractTgz extracts a .tgz file
func (s *Scanner) extractTgz(tgzPath, destDir string) error {
cmd := exec.Command("tar", "-xzf", tgzPath, "-C", destDir)
return cmd.Run()
}
// emptyResult returns an empty scan result
// scanErrorResult returns a result marked as scan-error so the manager merge
// and CheckVulnerabilities can fail closed. Use this when the scan could not
// complete and we therefore have no signal about vulnerabilities.
func (s *Scanner) scanErrorResult(registry, packageName, version, reason string) *metadata.ScanResult {
// scanErrorResult returns a result marked scan-error. The manager leaves it out of the merge
// and counts it as an infrastructure failure when the context ended or the tool output shows
// the network was unreachable.
func (s *Scanner) scanErrorResult(ctx context.Context, registry, packageName, version, reason, toolOutput string) *metadata.ScanResult {
infra := ctx.Err() != nil || scanerr.NetworkFailure(toolOutput)
return &metadata.ScanResult{
ID: uuid.New().String(),
Registry: registry,
@@ -169,9 +193,7 @@ func (s *Scanner) scanErrorResult(registry, packageName, version, reason string)
Status: metadata.ScanStatusError,
VulnerabilityCount: 0,
Vulnerabilities: []metadata.Vulnerability{},
Details: map[string]interface{}{
"error": reason,
},
Details: scanerr.ErrorDetails(reason, infra),
}
}
@@ -180,37 +202,35 @@ func (s *Scanner) convertResult(auditResult *NpmAuditResult, registry, packageNa
vulnerabilities := make([]metadata.Vulnerability, 0)
severityCounts := make(map[string]int)
// Process vulnerabilities from the audit result
for _, vuln := range auditResult.Vulnerabilities {
// Normalize severity
normalizedSeverity := metadata.NormalizeSeverity(vuln.Severity)
severityCounts[normalizedSeverity]++
// Get references
refs := make([]string, 0)
if vuln.URL != "" {
refs = append(refs, vuln.URL)
}
for _, ref := range vuln.References {
if ref.URL != "" {
refs = append(refs, ref.URL)
// Each advisory is listed once, under the package it affects. A string in `via` only says
// that the package is affected through another one, whose own entry lists the advisory.
seen := make(map[int]bool)
names := make([]string, 0, len(auditResult.Vulnerabilities))
for name := range auditResult.Vulnerabilities {
names = append(names, name)
}
sort.Strings(names)
for _, name := range names {
for _, via := range auditResult.Vulnerabilities[name].Via {
adv := via.Advisory
if adv == nil || seen[adv.Source] {
continue
}
seen[adv.Source] = true
normalizedSeverity := metadata.NormalizeSeverity(adv.Severity)
severityCounts[normalizedSeverity]++
refs := make([]string, 0, 1)
if adv.URL != "" {
refs = append(refs, adv.URL)
}
vulnerabilities = append(vulnerabilities, metadata.Vulnerability{
ID: advisoryID(adv),
Severity: normalizedSeverity,
Title: adv.Title,
Description: fmt.Sprintf("%s: %s (affected %s)", adv.Name, adv.Title, adv.Range),
References: refs,
})
}
// Get fixed version
fixedIn := ""
if vuln.FixAvailable != nil {
fixedIn = fmt.Sprintf("%v", vuln.FixAvailable)
}
vulnerabilities = append(vulnerabilities, metadata.Vulnerability{
ID: vuln.Via,
Severity: normalizedSeverity,
Title: vuln.Name,
Description: vuln.Name,
References: refs,
FixedIn: fixedIn,
})
}
status := metadata.ScanStatusClean
@@ -234,38 +254,62 @@ func (s *Scanner) convertResult(auditResult *NpmAuditResult, registry, packageNa
}
}
// NpmAuditResult represents npm audit JSON output
// advisoryID is the GHSA id from the advisory URL, or the npm advisory number.
func advisoryID(adv *NpmAdvisory) string {
if i := strings.LastIndex(adv.URL, "/"); i >= 0 && i+1 < len(adv.URL) {
return adv.URL[i+1:]
}
return fmt.Sprintf("npm:%d", adv.Source)
}
func parse(output []byte) (*NpmAuditResult, error) {
var res NpmAuditResult
if err := json.Unmarshal(output, &res); err != nil {
return nil, err
}
return &res, nil
}
// NpmAuditResult represents `npm audit --json` output (auditReportVersion 2), or its error document.
type NpmAuditResult struct {
Vulnerabilities map[string]NpmVulnerability `json:"vulnerabilities"`
Metadata NpmAuditMetadata `json:"metadata"`
AuditReportVersion int `json:"auditReportVersion"`
Vulnerabilities map[string]NpmVulnerability `json:"vulnerabilities"`
Error *NpmAuditError `json:"error"`
}
// NpmAuditError is the document npm prints in place of a report, e.g. ENOLOCK.
type NpmAuditError struct {
Code string `json:"code"`
Summary string `json:"summary"`
}
// NpmVulnerability is one affected package.
type NpmVulnerability struct {
Name string `json:"name"`
Severity string `json:"severity"`
Via string `json:"via"`
Effects []string `json:"effects"`
Range string `json:"range"`
FixAvailable interface{} `json:"fixAvailable"`
URL string `json:"url"`
References []NpmReference `json:"references"`
Name string `json:"name"`
Severity string `json:"severity"`
Via []NpmVia `json:"via"`
}
type NpmReference struct {
URL string `json:"url"`
// NpmVia is a package name (affected through that package) or an advisory.
type NpmVia struct {
Advisory *NpmAdvisory
Package string
}
type NpmAuditMetadata struct {
Vulnerabilities NpmVulnCounts `json:"vulnerabilities"`
Dependencies int `json:"dependencies"`
// UnmarshalJSON accepts both shapes of an element of `via`.
func (v *NpmVia) UnmarshalJSON(data []byte) error {
if len(data) > 0 && data[0] == '"' {
return json.Unmarshal(data, &v.Package)
}
v.Advisory = &NpmAdvisory{}
return json.Unmarshal(data, v.Advisory)
}
type NpmVulnCounts struct {
Info int `json:"info"`
Low int `json:"low"`
Moderate int `json:"moderate"`
High int `json:"high"`
Critical int `json:"critical"`
Total int `json:"total"`
// NpmAdvisory is a security advisory attached to a package.
type NpmAdvisory struct {
Name string `json:"name"`
Title string `json:"title"`
URL string `json:"url"`
Severity string `json:"severity"`
Range string `json:"range"`
Source int `json:"source"`
}
+204
View File
@@ -0,0 +1,204 @@
package npmaudit
import (
"context"
"encoding/json"
"fmt"
"os"
"path/filepath"
"sort"
"testing"
"github.com/lukaszraczylo/gohoarder/pkg/config"
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
"github.com/lukaszraczylo/gohoarder/pkg/scanner/scanerr"
"github.com/lukaszraczylo/gohoarder/pkg/scanner/scannertest"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// The fixtures are real `npm audit --json` output from npm 11.12.1 (see FINDINGS GH-25).
func fixture(name string) string { return filepath.Join("testdata", name) }
func readFixture(t *testing.T, name string) []byte {
t.Helper()
data, err := os.ReadFile(fixture(name))
require.NoError(t, err)
return data
}
func severities(res *metadata.ScanResult) map[string]string {
out := map[string]string{}
for _, v := range res.Vulnerabilities {
out[v.ID] = v.Severity
}
return out
}
func TestParseKeepsBothViaShapes(t *testing.T) {
// `via` is an array of package names for a transitive finding and an array of advisory
// objects for a direct one; mkdirp-0.5.1.json has both, the dev-tree file many of each.
for _, name := range []string{"dayjs-1.11.13.json", "minimist-0.0.8.json", "mkdirp-0.5.1.json", "request-2.88.2.json", "mkdirp-0.5.1-dev-tree.json"} {
t.Run(name, func(t *testing.T) {
_, err := parse(readFixture(t, name))
require.NoError(t, err)
})
}
}
func TestConvertMapsAdvisories(t *testing.T) {
cases := []struct {
want map[string]string
fixture string
}{
{fixture: "dayjs-1.11.13.json", want: map[string]string{}},
{fixture: "minimist-0.0.8.json", want: map[string]string{"GHSA-vh95-rmgr-6w4m": "MODERATE", "GHSA-xvch-5gv4-984h": "CRITICAL"}},
// mkdirp has no advisory of its own: its entry only points at minimist.
{fixture: "mkdirp-0.5.1.json", want: map[string]string{"GHSA-vh95-rmgr-6w4m": "MODERATE", "GHSA-xvch-5gv4-984h": "CRITICAL"}},
{fixture: "request-2.88.2.json", want: map[string]string{
"GHSA-fjxv-7rqg-78g4": "CRITICAL", "GHSA-hmw2-7cc7-3qxx": "HIGH", "GHSA-6rw7-vpxm-498p": "MODERATE",
"GHSA-4mjr-xmp4-gh2g": "MODERATE", "GHSA-p8p7-x288-28g6": "MODERATE", "GHSA-72xf-g2v4-qvf3": "MODERATE",
"GHSA-w5hq-g745-h8pq": "MODERATE",
}},
}
for _, tc := range cases {
t.Run(tc.fixture, func(t *testing.T) {
audit, err := parse(readFixture(t, tc.fixture))
require.NoError(t, err)
res := New(config.NpmAuditConfig{}).convertResult(audit, "npm", "p", "1")
assert.Equal(t, tc.want, severities(res))
assert.Equal(t, len(tc.want), res.VulnerabilityCount)
if len(tc.want) == 0 {
assert.Equal(t, metadata.ScanStatusClean, res.Status)
} else {
assert.Equal(t, metadata.ScanStatusVulnerable, res.Status)
}
})
}
}
func TestConvertCarriesTitleAndReference(t *testing.T) {
audit, err := parse(readFixture(t, "minimist-0.0.8.json"))
require.NoError(t, err)
res := New(config.NpmAuditConfig{}).convertResult(audit, "npm", "minimist", "0.0.8")
ids := make([]string, 0)
for _, v := range res.Vulnerabilities {
ids = append(ids, v.ID)
assert.Equal(t, "Prototype Pollution in minimist", v.Title)
assert.Equal(t, []string{"https://github.com/advisories/" + v.ID}, v.References)
}
sort.Strings(ids)
assert.Equal(t, []string{"GHSA-vh95-rmgr-6w4m", "GHSA-xvch-5gv4-984h"}, ids)
}
// npmScript fakes npm: `install` exits installExit, `audit` prints stdout and exits 1.
func npmScript(t *testing.T, auditFixture string, installExit int, installStderr string) (recDir string) {
t.Helper()
recDir = t.TempDir()
audit := "cat " + fmt.Sprintf("%q", mustAbs(t, auditFixture))
if auditFixture == "" {
audit = "printf '%s' 'not json'"
}
scannertest.Script(t, "npm", fmt.Sprintf(`
case "$1" in
install) cat package.json > %[1]q/package.json; echo "$@" > %[1]q/install; printf '%%s' %[2]q >&2; exit %[3]d ;;
audit) echo "$@" > %[1]q/audit; %[4]s; exit 1 ;;
esac`, recDir, installStderr, installExit, audit))
return recDir
}
func mustAbs(t *testing.T, name string) string {
t.Helper()
if name == "" {
return ""
}
abs, err := filepath.Abs(fixture(name))
require.NoError(t, err)
return abs
}
func artifact(t *testing.T) string {
t.Helper()
p := filepath.Join(t.TempDir(), "pkg.tgz")
require.NoError(t, os.WriteFile(p, []byte("tgz"), 0o600))
return p
}
func TestScanAuditsThePackageItselfWithoutItsDevTree(t *testing.T) {
rec := npmScript(t, "minimist-0.0.8.json", 0, "")
res, err := New(config.NpmAuditConfig{}).Scan(context.Background(), "npm", "minimist", "0.0.8", artifact(t))
require.NoError(t, err)
assert.Equal(t, metadata.ScanStatusVulnerable, res.Status)
assert.Len(t, res.Vulnerabilities, 2)
pkgJSON, err := os.ReadFile(filepath.Join(rec, "package.json")) // #nosec G304 -- test temp dir
require.NoError(t, err)
var wrapper struct {
Dependencies map[string]string `json:"dependencies"`
}
require.NoError(t, json.Unmarshal(pkgJSON, &wrapper))
assert.Equal(t, map[string]string{"minimist": "file:./artifact.tgz"}, wrapper.Dependencies,
"the tarball is a dependency of a wrapper project, so its own advisories are audited and its devDependencies are never resolved")
audit, err := os.ReadFile(filepath.Join(rec, "audit")) // #nosec G304 -- test temp dir
require.NoError(t, err)
assert.Contains(t, string(audit), "--omit=dev")
}
func TestScanCleanPackage(t *testing.T) {
npmScript(t, "dayjs-1.11.13.json", 0, "")
res, err := New(config.NpmAuditConfig{}).Scan(context.Background(), "npm", "dayjs", "1.11.13", artifact(t))
require.NoError(t, err)
assert.Equal(t, metadata.ScanStatusClean, res.Status)
}
func TestScanFailuresAreErrorResultsWithACause(t *testing.T) {
cases := []struct {
name string
fixture string
installOut string
installRC int
infra bool
}{
{"network down", "", "npm error code ENOTFOUND", 1, true},
{"unresolvable tree", "", "npm error code ERESOLVE", 1, false},
{"unparseable audit", "", "", 0, false},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
npmScript(t, tc.fixture, tc.installRC, tc.installOut)
res, err := New(config.NpmAuditConfig{}).Scan(context.Background(), "npm", "p", "1", artifact(t))
require.NoError(t, err)
assert.Equal(t, metadata.ScanStatusError, res.Status)
assert.Equal(t, tc.infra, res.Details[scanerr.DetailInfrastructure])
})
}
}
func TestScanAuditErrorDocumentIsAnErrorResult(t *testing.T) {
doc := filepath.Join(t.TempDir(), "enolock.json")
require.NoError(t, os.WriteFile(doc, []byte(`{"error":{"code":"ENOLOCK","summary":"This command requires an existing lockfile.","detail":""}}`), 0o600))
scannertest.Script(t, "npm", fmt.Sprintf(`case "$1" in audit) cat %q; exit 1 ;; esac`, doc))
res, err := New(config.NpmAuditConfig{}).Scan(context.Background(), "npm", "p", "1", artifact(t))
require.NoError(t, err)
assert.Equal(t, metadata.ScanStatusError, res.Status)
assert.Contains(t, res.Details["error"], "ENOLOCK")
}
func TestScanSkipsOtherRegistries(t *testing.T) {
res, err := New(config.NpmAuditConfig{}).Scan(context.Background(), "pypi", "p", "1", "/x")
require.NoError(t, err)
assert.Equal(t, metadata.ScanStatusClean, res.Status)
}
+22
View File
@@ -0,0 +1,22 @@
{
"auditReportVersion": 2,
"vulnerabilities": {},
"metadata": {
"vulnerabilities": {
"info": 0,
"low": 0,
"moderate": 0,
"high": 0,
"critical": 0,
"total": 0
},
"dependencies": {
"prod": 2,
"dev": 0,
"optional": 0,
"peer": 0,
"peerOptional": 0,
"total": 1
}
}
}
+68
View File
@@ -0,0 +1,68 @@
{
"auditReportVersion": 2,
"vulnerabilities": {
"minimist": {
"name": "minimist",
"severity": "critical",
"isDirect": true,
"via": [
{
"source": 1096466,
"name": "minimist",
"dependency": "minimist",
"title": "Prototype Pollution in minimist",
"url": "https://github.com/advisories/GHSA-vh95-rmgr-6w4m",
"severity": "moderate",
"cwe": [
"CWE-1321"
],
"cvss": {
"score": 5.6,
"vectorString": "CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:L/I:L/A:L"
},
"range": "<0.2.1"
},
{
"source": 1097677,
"name": "minimist",
"dependency": "minimist",
"title": "Prototype Pollution in minimist",
"url": "https://github.com/advisories/GHSA-xvch-5gv4-984h",
"severity": "critical",
"cwe": [
"CWE-1321"
],
"cvss": {
"score": 9.8,
"vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H"
},
"range": "<0.2.4"
}
],
"effects": [],
"range": "<=0.2.3",
"nodes": [
"node_modules/minimist"
],
"fixAvailable": false
}
},
"metadata": {
"vulnerabilities": {
"info": 0,
"low": 0,
"moderate": 0,
"high": 0,
"critical": 1,
"total": 1
},
"dependencies": {
"prod": 2,
"dev": 0,
"optional": 0,
"peer": 0,
"peerOptional": 0,
"total": 1
}
}
}
File diff suppressed because it is too large Load Diff
+84
View File
@@ -0,0 +1,84 @@
{
"auditReportVersion": 2,
"vulnerabilities": {
"minimist": {
"name": "minimist",
"severity": "critical",
"isDirect": false,
"via": [
{
"source": 1096466,
"name": "minimist",
"dependency": "minimist",
"title": "Prototype Pollution in minimist",
"url": "https://github.com/advisories/GHSA-vh95-rmgr-6w4m",
"severity": "moderate",
"cwe": [
"CWE-1321"
],
"cvss": {
"score": 5.6,
"vectorString": "CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:L/I:L/A:L"
},
"range": "<0.2.1"
},
{
"source": 1097677,
"name": "minimist",
"dependency": "minimist",
"title": "Prototype Pollution in minimist",
"url": "https://github.com/advisories/GHSA-xvch-5gv4-984h",
"severity": "critical",
"cwe": [
"CWE-1321"
],
"cvss": {
"score": 9.8,
"vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H"
},
"range": "<0.2.4"
}
],
"effects": [
"mkdirp"
],
"range": "<=0.2.3",
"nodes": [
"node_modules/minimist"
],
"fixAvailable": false
},
"mkdirp": {
"name": "mkdirp",
"severity": "critical",
"isDirect": true,
"via": [
"minimist"
],
"effects": [],
"range": "0.4.1 - 0.5.1",
"nodes": [
"node_modules/mkdirp"
],
"fixAvailable": false
}
},
"metadata": {
"vulnerabilities": {
"info": 0,
"low": 0,
"moderate": 0,
"high": 0,
"critical": 2,
"total": 2
},
"dependencies": {
"prod": 3,
"dev": 0,
"optional": 0,
"peer": 0,
"peerOptional": 0,
"total": 2
}
}
}
+214
View File
@@ -0,0 +1,214 @@
{
"auditReportVersion": 2,
"vulnerabilities": {
"form-data": {
"name": "form-data",
"severity": "critical",
"isDirect": false,
"via": [
{
"source": 1109540,
"name": "form-data",
"dependency": "form-data",
"title": "form-data uses unsafe random function in form-data for choosing boundary",
"url": "https://github.com/advisories/GHSA-fjxv-7rqg-78g4",
"severity": "critical",
"cwe": [
"CWE-330"
],
"cvss": {
"score": 0,
"vectorString": null
},
"range": "<2.5.4"
},
{
"source": 1120745,
"name": "form-data",
"dependency": "form-data",
"title": "form-data: CRLF injection in form-data via unescaped multipart field names and filenames",
"url": "https://github.com/advisories/GHSA-hmw2-7cc7-3qxx",
"severity": "high",
"cwe": [
"CWE-93"
],
"cvss": {
"score": 7.5,
"vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:H/A:N"
},
"range": "<2.5.6"
}
],
"effects": [
"request"
],
"range": "<=2.5.5",
"nodes": [
"node_modules/form-data"
],
"fixAvailable": false
},
"qs": {
"name": "qs",
"severity": "moderate",
"isDirect": false,
"via": [
{
"source": 1113719,
"name": "qs",
"dependency": "qs",
"title": "qs's arrayLimit bypass in its bracket notation allows DoS via memory exhaustion",
"url": "https://github.com/advisories/GHSA-6rw7-vpxm-498p",
"severity": "moderate",
"cwe": [
"CWE-20"
],
"cvss": {
"score": 3.7,
"vectorString": "CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:N/I:N/A:L"
},
"range": "<6.14.1"
},
{
"source": 1158507,
"name": "qs",
"dependency": "qs",
"title": "qs: Denial of Service via Attacker Controlled isBuffer",
"url": "https://github.com/advisories/GHSA-4mjr-xmp4-gh2g",
"severity": "moderate",
"cwe": [
"CWE-248",
"CWE-703"
],
"cvss": {
"score": 5.3,
"vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:L"
},
"range": ">=2.2.5 <6.16.0"
}
],
"effects": [
"request"
],
"range": "<=6.15.4",
"nodes": [
"node_modules/qs"
],
"fixAvailable": false
},
"request": {
"name": "request",
"severity": "critical",
"isDirect": true,
"via": [
{
"source": 1096727,
"name": "request",
"dependency": "request",
"title": "Server-Side Request Forgery in Request",
"url": "https://github.com/advisories/GHSA-p8p7-x288-28g6",
"severity": "moderate",
"cwe": [
"CWE-918"
],
"cvss": {
"score": 6.1,
"vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N"
},
"range": "<=2.88.2"
},
"form-data",
"qs",
"tough-cookie",
"uuid"
],
"effects": [],
"range": "*",
"nodes": [
"node_modules/request"
],
"fixAvailable": false
},
"tough-cookie": {
"name": "tough-cookie",
"severity": "moderate",
"isDirect": false,
"via": [
{
"source": 1097682,
"name": "tough-cookie",
"dependency": "tough-cookie",
"title": "tough-cookie Prototype Pollution vulnerability",
"url": "https://github.com/advisories/GHSA-72xf-g2v4-qvf3",
"severity": "moderate",
"cwe": [
"CWE-1321"
],
"cvss": {
"score": 6.5,
"vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:L/I:L/A:N"
},
"range": "<4.1.3"
}
],
"effects": [
"request"
],
"range": "<4.1.3",
"nodes": [
"node_modules/tough-cookie"
],
"fixAvailable": false
},
"uuid": {
"name": "uuid",
"severity": "moderate",
"isDirect": false,
"via": [
{
"source": 1119441,
"name": "uuid",
"dependency": "uuid",
"title": "uuid: Missing buffer bounds check in v3/v5/v6 when buf is provided",
"url": "https://github.com/advisories/GHSA-w5hq-g745-h8pq",
"severity": "moderate",
"cwe": [
"CWE-787",
"CWE-1285"
],
"cvss": {
"score": 7.5,
"vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:H/A:N"
},
"range": "<11.1.1"
}
],
"effects": [
"request"
],
"range": "<11.1.1",
"nodes": [
"node_modules/uuid"
],
"fixAvailable": false
}
},
"metadata": {
"vulnerabilities": {
"info": 0,
"low": 0,
"moderate": 3,
"high": 0,
"critical": 2,
"total": 5
},
"dependencies": {
"prod": 48,
"dev": 0,
"optional": 0,
"peer": 0,
"peerOptional": 0,
"total": 47
}
}
}
-35
View File
@@ -1,35 +0,0 @@
package pipaudit
import (
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/require"
)
func TestCopyInto(t *testing.T) {
s := &Scanner{}
src := filepath.Join(t.TempDir(), "pkg.whl")
require.NoError(t, os.WriteFile(src, []byte("wheel"), 0600))
t.Run("copies inside dir", func(t *testing.T) {
dir := t.TempDir()
require.NoError(t, s.copyInto(src, dir, "pkg.whl"))
got, err := os.ReadFile(filepath.Join(dir, "pkg.whl"))
require.NoError(t, err)
require.Equal(t, "wheel", string(got))
})
t.Run("refuses name escaping dir", func(t *testing.T) {
parent := t.TempDir()
dir := filepath.Join(parent, "sub")
require.NoError(t, os.Mkdir(dir, 0750))
require.Error(t, s.copyInto(src, dir, "../escape.whl"))
require.NoFileExists(t, filepath.Join(parent, "escape.whl"))
})
t.Run("missing source", func(t *testing.T) {
require.Error(t, s.copyInto(filepath.Join(t.TempDir(), "none"), t.TempDir(), "x"))
})
}
+47 -128
View File
@@ -3,17 +3,20 @@
package pipaudit
import (
"bytes"
"context"
"encoding/json"
"fmt"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
"time"
"github.com/lukaszraczylo/gohoarder/pkg/config"
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
"github.com/lukaszraczylo/gohoarder/pkg/scanner/scanerr"
"github.com/lukaszraczylo/gohoarder/pkg/uuid"
"github.com/rs/zerolog/log"
)
@@ -64,47 +67,43 @@ func (s *Scanner) Scan(ctx context.Context, registry, packageName, version strin
Str("version", version).
Msg("Starting pip-audit scan")
// Create a temporary directory
if !validName.MatchString(packageName) || !validVersion.MatchString(version) {
return s.scanErrorResult(ctx, registry, packageName, version,
fmt.Sprintf("not a project name and version: %q %q", packageName, version), ""), nil
}
tmpDir, err := os.MkdirTemp("", "pip-audit-*")
if err != nil {
return nil, fmt.Errorf("failed to create temp dir: %w", err)
}
defer func() { _ = os.RemoveAll(tmpDir) }()
// Copy the wheel/tar.gz file to temp directory
tmpFile := filepath.Join(tmpDir, filepath.Base(filePath))
if err := s.copyInto(filePath, tmpDir, filepath.Base(tmpFile)); err != nil {
return nil, fmt.Errorf("failed to copy file: %w", err)
// pip-audit has no wheel or sdist input: its positional argument is a project directory. The
// release is audited by its pinned name and version. --no-deps and --disable-pip keep it to
// that release, with no resolution of its dependencies.
reqFile := filepath.Join(tmpDir, "requirements.txt")
if err := os.WriteFile(reqFile, []byte(packageName+"=="+version+"\n"), 0o600); err != nil {
return nil, fmt.Errorf("failed to write requirements: %w", err)
}
// Build the appropriate pip-audit invocation based on artifact type.
// `-r` expects requirements.txt — passing a wheel/tarball there is wrong.
// Wheels can be scanned directly via positional arg. Source distributions
// (tarballs) need to be extracted; if they contain a pyproject.toml we
// can scan that, otherwise we fail closed.
cmd, prepErr := s.buildAuditCmd(ctx, tmpDir, tmpFile)
if prepErr != nil {
log.Warn().
Err(prepErr).
Str("package", packageName).
Str("version", version).
Msg("pip-audit could not prepare input artifact, returning scan-error")
return s.scanErrorResult(registry, packageName, version, prepErr.Error()), nil
}
output, _ := cmd.CombinedOutput() // pip-audit returns non-zero when vulns found
cmd := exec.CommandContext(ctx, "pip-audit", "-r", reqFile, "--no-deps", "--disable-pip", "-f", "json") // #nosec G204 -- name and version are validated, file is in a controlled temp dir
var stderr bytes.Buffer
cmd.Stderr = &stderr
output, _ := cmd.Output() // pip-audit exits non-zero when it finds vulnerabilities
// Parse pip-audit output
var auditResult PipAuditResult
if len(output) > 0 {
if err := json.Unmarshal(output, &auditResult); err != nil {
log.Warn().Err(err).Msg("Failed to parse pip-audit output")
// Parse failure → no signal → fail closed.
return s.scanErrorResult(registry, packageName, version,
fmt.Sprintf("failed to parse pip-audit output: %v", err)), nil
if err := json.Unmarshal(output, &auditResult); err != nil {
log.Warn().Err(err).Str("stderr", stderr.String()).Msg("Failed to parse pip-audit output")
return s.scanErrorResult(ctx, registry, packageName, version,
fmt.Sprintf("failed to parse pip-audit output: %v: %s", err, strings.TrimSpace(stderr.String())), stderr.String()), nil
}
for _, dep := range auditResult.Dependencies {
if dep.SkipReason != "" {
// pip-audit exits 0 for a package it could not audit; that is no verdict.
return s.scanErrorResult(ctx, registry, packageName, version, dep.SkipReason, ""), nil
}
}
// Convert to our format
result := s.convertResult(&auditResult, registry, packageName, version)
log.Info().
@@ -116,6 +115,11 @@ func (s *Scanner) Scan(ctx context.Context, registry, packageName, version strin
return result, nil
}
var (
validName = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]*$`)
validVersion = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9.+!_-]*$`)
)
// Health checks if pip-audit is available
func (s *Scanner) Health(ctx context.Context) error {
cmd := exec.CommandContext(ctx, "pip-audit", "--version")
@@ -125,98 +129,10 @@ func (s *Scanner) Health(ctx context.Context) error {
return nil
}
// copyInto copies src to name inside dir; name cannot escape dir.
func (s *Scanner) copyInto(src, dir, name string) error {
input, err := os.ReadFile(src) // #nosec G304 -- Source path is from scanner, controlled
if err != nil {
return err
}
root, err := os.OpenRoot(dir)
if err != nil {
return err
}
defer func() { _ = root.Close() }()
return root.WriteFile(name, input, 0600)
}
// buildAuditCmd constructs the right pip-audit command for the input artifact.
//
// - .whl -> pip-audit <wheel> --format json
// - .tar.gz / .tgz / .zip (sdist) -> extract; if pyproject.toml exists
// run `pip-audit --pyproject <pyproject> --format json`; otherwise error.
//
// extractDir is used as a workspace for sdist extraction.
func (s *Scanner) buildAuditCmd(ctx context.Context, extractDir, artifact string) (*exec.Cmd, error) {
lower := strings.ToLower(artifact)
switch {
case strings.HasSuffix(lower, ".whl"):
// pip-audit can scan a wheel directly via positional argument.
return exec.CommandContext(ctx, "pip-audit", artifact, "--format", "json"), nil // #nosec G204 -- artifact path is in controlled tmp dir
case strings.HasSuffix(lower, ".tar.gz"),
strings.HasSuffix(lower, ".tgz"),
strings.HasSuffix(lower, ".zip"):
// Source distributions must be unpacked first.
sdistDir := filepath.Join(extractDir, "sdist")
if err := os.MkdirAll(sdistDir, 0o750); err != nil {
return nil, fmt.Errorf("create sdist dir: %w", err)
}
if err := s.extractSdist(artifact, sdistDir); err != nil {
return nil, fmt.Errorf("extract sdist: %w", err)
}
pyproject, err := findPyProject(sdistDir)
if err != nil {
return nil, fmt.Errorf("no pyproject.toml in sdist: %w", err)
}
return exec.CommandContext(ctx, "pip-audit", "--pyproject", pyproject, "--format", "json"), nil // #nosec G204 -- pyproject path under controlled tmp dir
default:
return nil, fmt.Errorf("unsupported pip artifact extension: %s", filepath.Base(artifact))
}
}
// extractSdist unpacks a Python source distribution into destDir.
func (s *Scanner) extractSdist(archive, destDir string) error {
lower := strings.ToLower(archive)
switch {
case strings.HasSuffix(lower, ".tar.gz"), strings.HasSuffix(lower, ".tgz"):
return exec.Command("tar", "-xzf", archive, "-C", destDir).Run()
case strings.HasSuffix(lower, ".zip"):
return exec.Command("unzip", "-q", archive, "-d", destDir).Run()
default:
return fmt.Errorf("unknown archive type: %s", archive)
}
}
// findPyProject returns the path to a pyproject.toml within root, walking
// one level deep (sdists typically extract to <pkg>-<ver>/).
func findPyProject(root string) (string, error) {
var found string
err := filepath.WalkDir(root, func(path string, d os.DirEntry, err error) error {
if err != nil {
return nil
}
if d.IsDir() {
return nil
}
if d.Name() == "pyproject.toml" {
found = path
return filepath.SkipAll
}
return nil
})
if err != nil {
return "", err
}
if found == "" {
return "", fmt.Errorf("pyproject.toml not found under %s", root)
}
return found, nil
}
// scanErrorResult returns a result marked scan-error so manager merge and
// CheckVulnerabilities can fail closed when this scanner could not run.
func (s *Scanner) scanErrorResult(registry, packageName, version, reason string) *metadata.ScanResult {
// scanErrorResult returns a scan-error result. The manager leaves it out of the merge and counts it
// as an infrastructure failure when the context ended or the tool output shows the network was unreachable.
func (s *Scanner) scanErrorResult(ctx context.Context, registry, packageName, version, reason, toolOutput string) *metadata.ScanResult {
infra := ctx.Err() != nil || scanerr.NetworkFailure(toolOutput)
return &metadata.ScanResult{
ID: uuid.New().String(),
Registry: registry,
@@ -227,21 +143,23 @@ func (s *Scanner) scanErrorResult(registry, packageName, version, reason string)
Status: metadata.ScanStatusError,
VulnerabilityCount: 0,
Vulnerabilities: []metadata.Vulnerability{},
Details: map[string]interface{}{
"error": reason,
},
Details: scanerr.ErrorDetails(reason, infra),
}
}
// emptyResult returns an empty scan result
// convertResult converts pip-audit output to our ScanResult format
func (s *Scanner) convertResult(auditResult *PipAuditResult, registry, packageName, version string) *metadata.ScanResult {
vulnerabilities := make([]metadata.Vulnerability, 0)
severityCounts := make(map[string]int)
seen := make(map[string]bool)
for _, dep := range auditResult.Dependencies {
for _, vuln := range dep.Vulns {
// pip-audit lists an advisory once per alias.
if seen[vuln.ID] {
continue
}
seen[vuln.ID] = true
// Map pip-audit severity to our standard
severity := s.mapSeverity(vuln.ID)
normalizedSeverity := metadata.NormalizeSeverity(severity)
@@ -298,9 +216,10 @@ type PipAuditResult struct {
}
type PipDependency struct {
Name string `json:"name"`
Version string `json:"version"`
Vulns []PipVuln `json:"vulns"`
Name string `json:"name"`
Version string `json:"version"`
SkipReason string `json:"skip_reason"`
Vulns []PipVuln `json:"vulns"`
}
type PipVuln struct {
+142
View File
@@ -0,0 +1,142 @@
package pipaudit
import (
"context"
"os"
"path/filepath"
"testing"
"github.com/lukaszraczylo/gohoarder/pkg/config"
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
"github.com/lukaszraczylo/gohoarder/pkg/scanner/scanerr"
"github.com/lukaszraczylo/gohoarder/pkg/scanner/scannertest"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// The fixtures are real `pip-audit -f json` output from pip-audit 2.10.1 (see FINDINGS GH-25); the
// example proxy credential in the requests 2.19.0 advisory text is replaced by a placeholder.
func fixture(name string) string { return filepath.Join("testdata", name) }
func ids(res *metadata.ScanResult) []string {
out := make([]string, 0, len(res.Vulnerabilities))
for _, v := range res.Vulnerabilities {
out = append(out, v.ID)
}
return out
}
// artifactNamed is a stand-in for the cached file: the scanner audits the release by name and version.
func artifactNamed(t *testing.T, name string) string {
t.Helper()
p := filepath.Join(t.TempDir(), name)
require.NoError(t, os.WriteFile(p, []byte("x"), 0o600))
return p
}
func TestScanAuditsTheReleaseFromARequirement(t *testing.T) {
// pip-audit has no wheel argument: its positional argument is a project directory, and it
// has no --pyproject flag. A wheel or sdist is audited by name and version.
for _, file := range []string{"requests-2.19.0-py2.py3-none-any.whl", "requests-2.19.0.tar.gz"} {
t.Run(file, func(t *testing.T) {
args := scannertest.Fake(t, "pip-audit", fixture("requests-2.19.0.json"), "WARNING:pip_audit._cli:--no-deps is supported\n", 1)
res, err := New(config.PipAuditConfig{}).Scan(context.Background(), "pypi", "requests", "2.19.0", artifactNamed(t, file))
require.NoError(t, err)
assert.Equal(t, metadata.ScanStatusVulnerable, res.Status)
assert.ElementsMatch(t, []string{"PYSEC-2018-28", "PYSEC-2023-74", "PYSEC-2026-1872", "PYSEC-2026-1873", "PYSEC-2026-2275"}, ids(res),
"pip-audit lists an advisory once per alias; the result lists it once")
assert.Equal(t, 5, res.VulnerabilityCount)
got := scannertest.Args(t, args)
assert.Equal(t, []string{"-r"}, got[:1])
assert.Equal(t, []string{"--no-deps", "--disable-pip", "-f", "json"}, got[2:])
})
}
}
func TestScanWritesAPinnedRequirement(t *testing.T) {
dir := t.TempDir()
scannertest.Script(t, "pip-audit", `cat "$2" > `+filepath.Join(dir, "req")+`; cat `+mustAbs(t, "six-1.16.0.json"))
res, err := New(config.PipAuditConfig{}).Scan(context.Background(), "pypi", "six", "1.16.0", artifactNamed(t, "six-1.16.0-py2.py3-none-any.whl"))
require.NoError(t, err)
assert.Equal(t, metadata.ScanStatusClean, res.Status)
req, err := os.ReadFile(filepath.Join(dir, "req")) // #nosec G304 -- test temp dir
require.NoError(t, err)
assert.Equal(t, "six==1.16.0\n", string(req))
}
func mustAbs(t *testing.T, name string) string {
t.Helper()
p, err := filepath.Abs(fixture(name))
require.NoError(t, err)
return p
}
func TestScanSeverityAndFix(t *testing.T) {
scannertest.Fake(t, "pip-audit", fixture("requests-2.32.0.json"), "", 1)
res, err := New(config.PipAuditConfig{}).Scan(context.Background(), "pypi", "requests", "2.32.0", artifactNamed(t, "requests-2.32.0.tar.gz"))
require.NoError(t, err)
fixed := map[string]string{}
for _, v := range res.Vulnerabilities {
fixed[v.ID] = v.FixedIn
assert.Equal(t, "MODERATE", v.Severity, "pip-audit reports no severity")
}
assert.Equal(t, map[string]string{"PYSEC-2026-1872": "2.32.4", "PYSEC-2026-2275": "2.33.0"}, fixed)
}
func TestScanPackageUnknownToPyPIIsAnError(t *testing.T) {
// pip-audit exits 0 with a skip_reason; reading that as clean would pass an unaudited package.
scannertest.Fake(t, "pip-audit", fixture("not-on-pypi.json"), "", 0)
res, err := New(config.PipAuditConfig{}).Scan(context.Background(), "pypi", "nopkg-zzz", "1.0", artifactNamed(t, "nopkg_zzz-1.0.tar.gz"))
require.NoError(t, err)
assert.Equal(t, metadata.ScanStatusError, res.Status)
assert.Contains(t, res.Details["error"], "not found on PyPI")
assert.Equal(t, false, res.Details[scanerr.DetailInfrastructure])
}
func TestScanFailuresAreErrorResultsWithACause(t *testing.T) {
cases := []struct {
name, stderr string
infra bool
}{
{"network", "ERROR: HTTPSConnectionPool: Max retries exceeded: ConnectionError ECONNREFUSED", true},
{"other", "ERROR:pip_audit._cli:boom", false},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
scannertest.Fake(t, "pip-audit", "", tc.stderr, 1)
res, err := New(config.PipAuditConfig{}).Scan(context.Background(), "pypi", "six", "1.16.0", artifactNamed(t, "six-1.16.0.tar.gz"))
require.NoError(t, err)
assert.Equal(t, metadata.ScanStatusError, res.Status)
assert.Equal(t, tc.infra, res.Details[scanerr.DetailInfrastructure])
})
}
}
func TestScanRefusesNameAndVersionThatCouldBeOptions(t *testing.T) {
args := scannertest.Fake(t, "pip-audit", fixture("six-1.16.0.json"), "", 0)
for _, c := range [][2]string{{"--index-url=http://evil", "1.0"}, {"six", "1.0\n--index-url=x"}, {"", "1.0"}, {"six", ""}} {
res, err := New(config.PipAuditConfig{}).Scan(context.Background(), "pypi", c[0], c[1], artifactNamed(t, "x.whl"))
require.NoError(t, err)
assert.Equal(t, metadata.ScanStatusError, res.Status, "%q %q", c[0], c[1])
}
_, statErr := os.Stat(args)
assert.True(t, os.IsNotExist(statErr), "pip-audit never ran")
}
func TestScanSkipsOtherRegistries(t *testing.T) {
res, err := New(config.PipAuditConfig{}).Scan(context.Background(), "npm", "p", "1", "/x")
require.NoError(t, err)
assert.Equal(t, metadata.ScanStatusClean, res.Status)
}
+1
View File
@@ -0,0 +1 @@
{"dependencies": [{"name": "nopkg-zzz", "skip_reason": "Dependency not found on PyPI and could not be audited: nopkg-zzz (1.0)"}], "fixes": []}
File diff suppressed because one or more lines are too long
+1
View File
@@ -0,0 +1 @@
{"dependencies": [{"name": "requests", "version": "2.32.0", "vulns": [{"id": "PYSEC-2026-1872", "fix_versions": ["2.32.4"], "aliases": ["CVE-2024-47081", "GHSA-9hjg-9r4m-mvj7"], "description": "### Impact Due to a URL parsing issue, Requests releases prior to 2.32.4 may leak .netrc credentials to third parties for specific maliciously-crafted URLs. ### Workarounds For older versions of Requests, use of the .netrc file can be disabled with `trust_env=False` on your Requests Session ([docs](https://requests.readthedocs.io/en/latest/api/#requests.Session.trust_env)). ### References https://github.com/psf/requests/pull/6965 https://seclists.org/fulldisclosure/2025/Jun/2"}, {"id": "PYSEC-2026-2275", "fix_versions": ["2.33.0"], "aliases": ["CVE-2026-25645", "GHSA-gc5v-m9x4-r6x2"], "description": "### Impact The `requests.utils.extract_zipped_paths()` utility function uses a predictable filename when extracting files from zip archives into the system temporary directory. If the target file already exists, it is reused without validation. A local attacker with write access to the temp directory could pre-create a malicious file that would be loaded in place of the legitimate one. ### Affected usages **Standard usage of the Requests library is not affected by this vulnerability.** Only applications that call `extract_zipped_paths()` directly are impacted. ### Remediation Upgrade to at least Requests 2.33.0, where the library now extracts files to a non-deterministic location. If developers are unable to upgrade, they can set `TMPDIR` in their environment to a directory with restricted write access."}, {"id": "PYSEC-2026-1872", "fix_versions": ["2.32.4"], "aliases": ["CVE-2024-47081", "GHSA-9hjg-9r4m-mvj7"], "description": "### Impact Due to a URL parsing issue, Requests releases prior to 2.32.4 may leak .netrc credentials to third parties for specific maliciously-crafted URLs. ### Workarounds For older versions of Requests, use of the .netrc file can be disabled with `trust_env=False` on your Requests Session ([docs](https://requests.readthedocs.io/en/latest/api/#requests.Session.trust_env)). ### References https://github.com/psf/requests/pull/6965 https://seclists.org/fulldisclosure/2025/Jun/2"}, {"id": "PYSEC-2026-2275", "fix_versions": ["2.33.0"], "aliases": ["CVE-2026-25645", "GHSA-gc5v-m9x4-r6x2"], "description": "Requests is a HTTP library. Prior to version 2.33.0, the `requests.utils.extract_zipped_paths()` utility function uses a predictable filename when extracting files from zip archives into the system temporary directory. If the target file already exists, it is reused without validation. A local attacker with write access to the temp directory could pre-create a malicious file that would be loaded in place of the legitimate one. Standard usage of the Requests library is not affected by this vulnerability. Only applications that call `extract_zipped_paths()` directly are impacted. Starting in version 2.33.0, the library extracts files to a non-deterministic location. If developers are unable to upgrade, they can set `TMPDIR` in their environment to a directory with restricted write access."}]}], "fixes": []}
+1
View File
@@ -0,0 +1 @@
{"dependencies": [{"name": "six", "version": "1.16.0", "vulns": []}], "fixes": []}
+166 -94
View File
@@ -3,6 +3,7 @@ package scanner
import (
"context"
"sync"
"sync/atomic"
"time"
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
@@ -16,16 +17,41 @@ type RescanWorker struct {
stopCh chan struct{}
stopOnce sync.Once
interval time.Duration
activeWindow time.Duration
concurrency int
}
// RescanOption tunes a RescanWorker.
type RescanOption func(*RescanWorker)
// WithActiveWindow skips packages not accessed within window (0 = scan all).
func WithActiveWindow(window time.Duration) RescanOption {
return func(w *RescanWorker) { w.activeWindow = window }
}
// WithConcurrency sets the scans run in parallel within a cycle; values below 1 mean 1.
func WithConcurrency(n int) RescanOption {
return func(w *RescanWorker) {
if n < 1 {
n = 1
}
w.concurrency = n
}
}
// NewRescanWorker creates a new rescan worker
func NewRescanWorker(manager *Manager, metadataStore metadata.MetadataStore, interval time.Duration) *RescanWorker {
return &RescanWorker{
func NewRescanWorker(manager *Manager, metadataStore metadata.MetadataStore, interval time.Duration, opts ...RescanOption) *RescanWorker {
w := &RescanWorker{
manager: manager,
metadataStore: metadataStore,
interval: interval,
concurrency: 1,
stopCh: make(chan struct{}),
}
for _, opt := range opts {
opt(w)
}
return w
}
// Start begins the periodic re-scanning process
@@ -70,115 +96,161 @@ func (w *RescanWorker) Stop() {
})
}
// rescanCounts tallies one rescan cycle; workers update it concurrently.
type rescanCounts struct {
scanned atomic.Int64
failed atomic.Int64
skipMetadata atomic.Int64
skipIdle atomic.Int64
skipFresh atomic.Int64
skipNoSource atomic.Int64
}
// rescanPackages re-scans packages that need updating
func (w *RescanWorker) rescanPackages(ctx context.Context) {
log.Info().Msg("Starting package rescan cycle - checking all packages for scan status")
// Get all packages
packages, err := w.metadataStore.ListPackages(ctx, &metadata.ListOptions{})
if err != nil {
log.Error().Err(err).Msg("Failed to list packages for rescan")
return
}
scanned := 0
skipped := 0
failed := 0
for _, pkg := range packages {
// Skip metadata entries (npm metadata pages, pypi pages, etc.)
if pkg.Version == "list" || pkg.Version == "latest" || pkg.Version == "metadata" || pkg.Version == "page" {
skipped++
continue
}
// Check if package needs rescanning
needsRescan, err := w.needsRescan(ctx, pkg)
if err != nil {
log.Error().
Err(err).
Str("package", pkg.Name).
Str("version", pkg.Version).
Msg("Failed to check rescan status")
failed++
continue
}
if !needsRescan {
log.Debug().
Str("package", pkg.Name).
Str("version", pkg.Version).
Bool("security_scanned", pkg.SecurityScanned).
Msg("Package does not need rescanning, skipping")
skipped++
continue
}
log.Info().
Str("registry", pkg.Registry).
Str("package", pkg.Name).
Str("version", pkg.Version).
Msg("Package needs rescanning")
if pkg.StorageKey == "" {
log.Warn().
Str("registry", pkg.Registry).
Str("package", pkg.Name).
Str("version", pkg.Version).
Msg("Package has no storage key, skipping rescan")
failed++
continue
}
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).
Str("registry", pkg.Registry).
Str("package", pkg.Name).
Str("version", pkg.Version).
Str("storage_key", pkg.StorageKey).
Msg("Failed to read package file, skipping rescan")
failed++
continue
}
// Perform the actual scan
err = w.manager.ScanPackage(ctx, pkg.Registry, pkg.Name, pkg.Version, filePath)
cleanup()
if err != nil {
log.Error().
Err(err).
Str("registry", pkg.Registry).
Str("package", pkg.Name).
Str("version", pkg.Version).
Msg("Failed to rescan package")
failed++
continue
}
scanned++
var counts rescanCounts
jobs := make(chan *metadata.Package)
var wg sync.WaitGroup
for i := 0; i < w.concurrency; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for pkg := range jobs {
w.rescanOne(ctx, pkg, &counts)
}
}()
}
dispatch:
for _, pkg := range packages {
if metadata.IsMetadataEntry(pkg.Registry, pkg.Name, pkg.Version) {
counts.skipMetadata.Add(1)
continue
}
if w.idle(pkg) {
counts.skipIdle.Add(1)
continue
}
select {
case jobs <- pkg:
case <-ctx.Done():
break dispatch
case <-w.stopCh:
break dispatch
}
}
close(jobs)
wg.Wait()
log.Info().
Int("total", len(packages)).
Int("scanned", scanned).
Int("skipped", skipped).
Int("failed", failed).
Int64("scanned", counts.scanned.Load()).
Int64("failed", counts.failed.Load()).
Int64("skipped_metadata", counts.skipMetadata.Load()).
Int64("skipped_idle", counts.skipIdle.Load()).
Int64("skipped_fresh", counts.skipFresh.Load()).
Int64("skipped_no_source", counts.skipNoSource.Load()).
Int("concurrency", w.concurrency).
Dur("active_window", w.activeWindow).
Msg("Rescan cycle completed")
}
// idle reports whether a package was last served longer ago than the active window.
// A zero LastAccessed is unknown, so the package is scanned.
func (w *RescanWorker) idle(pkg *metadata.Package) bool {
if w.activeWindow <= 0 || pkg.LastAccessed.IsZero() {
return false
}
return time.Since(pkg.LastAccessed) > w.activeWindow
}
// rescanOne scans a single package when its result is missing or stale.
func (w *RescanWorker) rescanOne(ctx context.Context, pkg *metadata.Package, counts *rescanCounts) {
needsRescan, err := w.needsRescan(ctx, pkg)
if err != nil {
log.Error().
Err(err).
Str("package", pkg.Name).
Str("version", pkg.Version).
Msg("Failed to check rescan status")
counts.failed.Add(1)
return
}
if !needsRescan {
log.Debug().
Str("package", pkg.Name).
Str("version", pkg.Version).
Bool("security_scanned", pkg.SecurityScanned).
Msg("Package does not need rescanning, skipping")
counts.skipFresh.Add(1)
return
}
log.Info().
Str("registry", pkg.Registry).
Str("package", pkg.Name).
Str("version", pkg.Version).
Msg("Package needs rescanning")
if pkg.StorageKey == "" {
log.Warn().
Str("registry", pkg.Registry).
Str("package", pkg.Name).
Str("version", pkg.Version).
Msg("Package has no storage key, skipping rescan")
counts.failed.Add(1)
return
}
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")
counts.skipNoSource.Add(1)
return
}
filePath, cleanup, err := source(ctx, pkg.Registry, pkg.Name, pkg.Version)
if err != nil {
log.Warn().
Err(err).
Str("registry", pkg.Registry).
Str("package", pkg.Name).
Str("version", pkg.Version).
Str("storage_key", pkg.StorageKey).
Msg("Failed to read package file, skipping rescan")
counts.failed.Add(1)
return
}
err = w.manager.ScanPackage(ctx, pkg.Registry, pkg.Name, pkg.Version, filePath)
cleanup()
if err != nil {
log.Error().
Err(err).
Str("registry", pkg.Registry).
Str("package", pkg.Name).
Str("version", pkg.Version).
Msg("Failed to rescan package")
counts.failed.Add(1)
return
}
counts.scanned.Add(1)
}
// needsRescan checks if a package needs to be rescanned
func (w *RescanWorker) needsRescan(ctx context.Context, pkg *metadata.Package) (bool, error) {
// Get latest scan result
+161
View File
@@ -0,0 +1,161 @@
package scanner
import (
"context"
"sync"
"testing"
"time"
hoardererrors "github.com/lukaszraczylo/gohoarder/pkg/errors"
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// rescanStore serves a fixed package list and keeps saved scan results.
type rescanStore struct {
results map[string]*metadata.ScanResult
packages []*metadata.Package
stubMetadataStore
rmu sync.Mutex
}
func (s *rescanStore) ListPackages(context.Context, *metadata.ListOptions) ([]*metadata.Package, error) {
return s.packages, nil
}
func (s *rescanStore) GetScanResult(_ context.Context, registry, name, version string) (*metadata.ScanResult, error) {
s.rmu.Lock()
defer s.rmu.Unlock()
if r, ok := s.results[scanKey(registry, name, version)]; ok {
return r, nil
}
return nil, hoardererrors.NotFound("no scan result")
}
func (s *rescanStore) SaveScanResult(ctx context.Context, r *metadata.ScanResult) error {
s.rmu.Lock()
s.results[scanKey(r.Registry, r.PackageName, r.PackageVersion)] = r
s.rmu.Unlock()
return s.stubMetadataStore.SaveScanResult(ctx, r)
}
// countingScanner records how often each package is scanned.
type countingScanner struct {
calls map[string]int
mu sync.Mutex
}
func (c *countingScanner) Name() string { return "counting" }
func (c *countingScanner) Scan(_ context.Context, registry, name, version, _ string) (*metadata.ScanResult, error) {
c.mu.Lock()
c.calls[scanKey(registry, name, version)]++
c.mu.Unlock()
return &metadata.ScanResult{
Registry: registry, PackageName: name, PackageVersion: version,
Scanner: "counting", ScannedAt: time.Now(), Status: metadata.ScanStatusClean,
}, nil
}
func (c *countingScanner) Health(context.Context) error { return nil }
func (c *countingScanner) snapshot() map[string]int {
c.mu.Lock()
defer c.mu.Unlock()
out := make(map[string]int, len(c.calls))
for k, v := range c.calls {
out[k] = v
}
return out
}
func pkgRow(registry, name, version string, lastAccessed time.Time) *metadata.Package {
return &metadata.Package{
Registry: registry, Name: name, Version: version,
StorageKey: registry + "/" + name + "/" + version, LastAccessed: lastAccessed,
}
}
func runRescan(t *testing.T, pkgs []*metadata.Package, opts ...RescanOption) map[string]int {
t.Helper()
store := &rescanStore{results: map[string]*metadata.ScanResult{}, packages: pkgs}
mgr := newTestManager(t, store)
cs := &countingScanner{calls: map[string]int{}}
mgr.RegisterScanner(cs)
mgr.SetFileSource(func(context.Context, string, string, string) (string, func(), error) {
return "/tmp/dummy", func() {}, nil
})
NewRescanWorker(mgr, store, time.Hour, opts...).rescanPackages(context.Background())
return cs.snapshot()
}
func TestRescanSkipsMetadataEntries(t *testing.T) {
now := time.Now()
pkgs := []*metadata.Package{
pkgRow("go", "example.com/m/@v/v1.0.0.mod", "v1.0.0", now),
pkgRow("go", "example.com/m/@v/v1.0.0.info", "v1.0.0", now),
pkgRow("go", "example.com/m/@v/v1.0.0.zip", "v1.0.0", now),
pkgRow("npm", "left-pad", "list", now),
pkgRow("npm", "left-pad", "1.3.0", now),
pkgRow("npm", "weird.mod", "1.0.0", now),
}
got := runRescan(t, pkgs)
assert.Equal(t, map[string]int{
scanKey("go", "example.com/m/@v/v1.0.0.zip", "v1.0.0"): 1,
scanKey("npm", "left-pad", "1.3.0"): 1,
scanKey("npm", "weird.mod", "1.0.0"): 1,
}, got)
}
func TestRescanActiveWindow(t *testing.T) {
now := time.Now()
pkgs := []*metadata.Package{
pkgRow("npm", "hot", "1.0.0", now.Add(-time.Hour)),
pkgRow("npm", "cold", "1.0.0", now.Add(-72*time.Hour)),
pkgRow("npm", "unknown", "1.0.0", time.Time{}),
}
tests := []struct {
name string
want []string
window time.Duration
}{
{"window off scans everything", []string{"hot", "cold", "unknown"}, 0},
{"window skips idle only", []string{"hot", "unknown"}, 24 * time.Hour},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := runRescan(t, pkgs, WithActiveWindow(tt.window))
want := map[string]int{}
for _, n := range tt.want {
want[scanKey("npm", n, "1.0.0")] = 1
}
assert.Equal(t, want, got)
})
}
}
func TestRescanConcurrencyScansEachOnce(t *testing.T) {
now := time.Now()
var pkgs []*metadata.Package
want := map[string]int{}
for i := 0; i < 40; i++ {
name := string(rune('a'+i%26)) + string(rune('a'+i/26))
pkgs = append(pkgs, pkgRow("npm", name, "1.0.0", now))
want[scanKey("npm", name, "1.0.0")] = 1
}
pkgs = append(pkgs, pkgRow("go", "m/@v/v1.mod", "v1", now))
for _, n := range []int{-2, 0, 1, 3, 8} {
got := runRescan(t, pkgs, WithConcurrency(n))
require.Equal(t, want, got, "concurrency %d", n)
}
}
func TestRescanConcurrencyFloor(t *testing.T) {
for _, n := range []int{-1, 0} {
w := NewRescanWorker(nil, nil, time.Hour, WithConcurrency(n))
assert.Equal(t, 1, w.concurrency)
}
assert.Equal(t, 1, NewRescanWorker(nil, nil, time.Hour).concurrency)
}

Some files were not shown because too many files have changed in this diff Show More