mirror of
https://github.com/lukaszraczylo/gohoarder.git
synced 2026-11-28 06:46:26 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
916e2b0aa5 | ||
|
|
30ebfaae3e | ||
|
|
3a7ffab4d5 | ||
|
|
22f2a8dfb9 | ||
|
|
4870f243fc | ||
|
|
fac30f59e6 | ||
|
|
775ed8a4aa | ||
|
|
e6d8ed0f2e | ||
|
|
40ed8f8213 | ||
|
|
ecf750adbb | ||
|
|
41f8369c43 | ||
|
|
d6044cdd2e | ||
|
|
1baa6b8e26 | ||
|
|
3d6bda3a5f | ||
|
|
e37c797602 | ||
|
|
157814cf08 | ||
|
|
65aa2e25dc | ||
|
|
3731ca05ce | ||
|
|
8adb1e0c87 | ||
|
|
16fb52ed3e | ||
|
|
13abb140d7 | ||
|
|
378b8731fc | ||
|
|
a83cc20058 | ||
|
|
501bf1aec8 | ||
|
|
527c1759f9 | ||
|
|
933b5a75c0 | ||
|
|
f4cf96e1e8 | ||
|
|
aa8487ad87 | ||
|
|
2ada975065 | ||
|
|
b98e761c90 | ||
|
|
a457e3d2e8 | ||
|
|
ba8bc392ec | ||
|
|
1512230ab3 | ||
|
|
bd9d686383 | ||
|
|
4d31e535ff | ||
|
|
fe2d9f8b3a | ||
|
|
a84f080b79 | ||
|
|
9b4659218c | ||
|
|
1256756057 | ||
|
|
262771d224 | ||
|
|
536f35ab55 | ||
|
|
5a9d104b37 | ||
|
|
f2049383cb | ||
|
|
549d56e0a1 | ||
|
|
31db940014 | ||
|
|
f46e079cee | ||
|
|
ae5167ffa9 | ||
|
|
787c757827 | ||
|
|
ac4f39322c | ||
|
|
db5ca2539f |
+6
-1
@@ -2,7 +2,7 @@
|
||||
# Combines frontend serving and backend proxy (previously separate gateway)
|
||||
# EXPECTS: Pre-built frontend files in frontend/dist/ directory
|
||||
|
||||
FROM nginx:alpine
|
||||
FROM mirror.gcr.io/library/nginx:1.31.9-alpine@sha256:fb4658584bd9a916ffb6f6e365f97c25cfdb2923801f551ea08356e695f14ff7
|
||||
|
||||
# Install envsubst for runtime configuration
|
||||
RUN apk add --no-cache gettext
|
||||
@@ -85,6 +85,8 @@ server {
|
||||
proxy_set_header X-Forwarded-Host $host;
|
||||
proxy_set_header X-Forwarded-Port $server_port;
|
||||
proxy_set_header Connection "";
|
||||
# The backend authenticates by API-key header; browser session cookies only bloat the request.
|
||||
proxy_set_header Cookie "";
|
||||
|
||||
# Timeouts for long-running operations
|
||||
proxy_connect_timeout 60s;
|
||||
@@ -122,6 +124,7 @@ server {
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_set_header Cookie "";
|
||||
|
||||
# WebSocket timeouts
|
||||
proxy_connect_timeout 7d;
|
||||
@@ -144,6 +147,8 @@ server {
|
||||
|
||||
# Frontend SPA - serve index.html for all other routes
|
||||
location / {
|
||||
# index.html names the hashed bundles; a cached copy keeps serving the previous release.
|
||||
add_header Cache-Control "no-cache" always;
|
||||
try_files $uri $uri/ /index.html;
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
# This Dockerfile expects a PRE-BUILT binary from GoReleaser (no compilation)
|
||||
# GoReleaser injects the platform-specific binary automatically
|
||||
|
||||
FROM --platform=$TARGETPLATFORM alpine:latest
|
||||
FROM --platform=$TARGETPLATFORM mirror.gcr.io/library/alpine:3.24.4@sha256:f59abe656b692d901e184be3445e084786602108599d2a51d229c0f5a48c71bf
|
||||
|
||||
ARG TARGETARCH
|
||||
|
||||
|
||||
+5
-5
@@ -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
@@ -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
|
||||
|
||||
|
||||
@@ -193,6 +193,7 @@ server:
|
||||
host: "0.0.0.0"
|
||||
read_timeout: "5m"
|
||||
write_timeout: "5m"
|
||||
allowed_origins: [] # Browser origins allowed to use /api and /ws; empty = same-origin only
|
||||
|
||||
storage:
|
||||
backend: "filesystem" # Options: filesystem, s3, smb
|
||||
@@ -235,6 +236,9 @@ security:
|
||||
cache:
|
||||
default_ttl: 24h # Freshness window for metadata pages (version lists, package documents)
|
||||
idle_ttl: 168h # Remove cached items not requested for 7 days; 0 disables
|
||||
deleted_retention: 720h # Purge deleted package rows after 30 days; 0 keeps them
|
||||
ttl_overrides: # Per-registry metadata freshness (npm, pypi, go); replaces default_ttl, never applies to artifacts
|
||||
pypi: 12h
|
||||
cleanup_interval: 1h
|
||||
|
||||
logging:
|
||||
@@ -252,7 +256,9 @@ upstream:
|
||||
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`. They refresh on the next request.
|
||||
- **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.
|
||||
|
||||
@@ -887,10 +893,29 @@ Access the web dashboard at **http://localhost:8080**
|
||||
**List Packages:**
|
||||
```bash
|
||||
GET /api/packages
|
||||
GET /api/packages?registry=npm
|
||||
GET /api/packages?status=vulnerable
|
||||
GET /api/packages?page=1&page_size=25
|
||||
GET /api/packages?registry=npm&q=axios&page_size=25
|
||||
GET /api/packages?sort=cached_at&order=desc&page_size=10
|
||||
```
|
||||
|
||||
The dashboard groups versions under a package, so paging counts packages (a
|
||||
registry and name pair), not rows. Without `page` and `page_size` the call
|
||||
returns every package in one response, with no row cap.
|
||||
|
||||
| Parameter | Meaning |
|
||||
|---|---|
|
||||
| `page` | 1-based page of groups. Default 1. |
|
||||
| `page_size` | Groups per page. Default 25 when `page` is set, at most 200. |
|
||||
| `registry` | Only this registry, for example `npm`, `pypi` or `go`. |
|
||||
| `q` | Case-insensitive search in name, version and release version. |
|
||||
| `sort` | `name` (default, ascending), `cached_at`, `downloads` or `size` (both descending). |
|
||||
| `order` | `asc` or `desc`, to override the default direction of `sort`. |
|
||||
|
||||
`packages` holds every version row of each group on the page, in group order
|
||||
and newest first within a group. `total` is the number of rows returned.
|
||||
`total_groups` is the number of groups that match the filters across all pages.
|
||||
A paged response also echoes `page` and `page_size`.
|
||||
|
||||
**Package Details:**
|
||||
```bash
|
||||
GET /api/packages/:registry/:name/:version
|
||||
@@ -920,7 +945,10 @@ GET /api/packages/:registry/:name/:version
|
||||
}
|
||||
}
|
||||
],
|
||||
"total": 42
|
||||
"total": 1,
|
||||
"total_groups": 42,
|
||||
"page": 1,
|
||||
"page_size": 25
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
+16
-5
@@ -10,8 +10,13 @@ server:
|
||||
host: "0.0.0.0"
|
||||
port: 8080 # Backend API server port
|
||||
read_timeout: "5m"
|
||||
read_buffer_size: 16384 # Bytes for the request line plus headers; larger requests get 431
|
||||
write_timeout: "5m"
|
||||
idle_timeout: "2m"
|
||||
# Origins allowed to call /api from a browser and to open the WebSocket. Exact
|
||||
# ("https://gohoarder.example.com") or wildcard ("https://*.example.com").
|
||||
# Empty: same-origin only. A cross-origin DELETE/POST/PATCH is refused with 403.
|
||||
allowed_origins: []
|
||||
tls:
|
||||
enabled: false
|
||||
cert_file: ""
|
||||
@@ -89,24 +94,30 @@ metadata:
|
||||
log_level: "warn" # GORM log level: silent, error, warn, info
|
||||
|
||||
cache:
|
||||
default_ttl: "168h" # Freshness window for metadata pages (version lists, packuments, .mod/.info); artifacts never expire by age
|
||||
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:
|
||||
npm: "168h"
|
||||
pip: "168h"
|
||||
go: "168h"
|
||||
ttl_overrides: # Per-registry metadata freshness; replaces default_ttl for that registry. Keys: npm, pypi, go
|
||||
npm: "24h"
|
||||
pypi: "24h"
|
||||
go: "24h"
|
||||
|
||||
security:
|
||||
enabled: false
|
||||
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")
|
||||
|
||||
@@ -32,6 +32,10 @@ data:
|
||||
severity_threshold: medium
|
||||
block_on_vulnerability: false
|
||||
rescan_interval: 24h
|
||||
rescan_active_window: 0s
|
||||
rescan_concurrency: 1
|
||||
rescan_on_access: false
|
||||
scan_wait_timeout: 30s
|
||||
|
||||
handlers:
|
||||
npm:
|
||||
|
||||
@@ -1,18 +1,23 @@
|
||||
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
|
||||
const store = usePackageStore()
|
||||
vi.spyOn(store, 'fetchStats').mockResolvedValue()
|
||||
vi.spyOn(store, 'fetchPackages').mockResolvedValue()
|
||||
vi.spyOn(store, 'fetchRecentPackages').mockResolvedValue()
|
||||
})
|
||||
|
||||
it('renders dashboard component', () => {
|
||||
@@ -127,7 +132,7 @@ describe('Dashboard.vue', () => {
|
||||
const store = usePackageStore()
|
||||
|
||||
store.loading = false
|
||||
store.packages = [
|
||||
store.recentPackages = [
|
||||
{
|
||||
id: '1',
|
||||
registry: 'npm',
|
||||
@@ -144,22 +149,12 @@ describe('Dashboard.vue', () => {
|
||||
expect(wrapper.text()).toContain('Recent packages')
|
||||
})
|
||||
|
||||
it('shows recent packages sorted by cached_at', async () => {
|
||||
it('lists recent packages in the order the store holds them, newest first', async () => {
|
||||
const wrapper = mount(Dashboard)
|
||||
const store = usePackageStore()
|
||||
|
||||
store.loading = false
|
||||
store.packages = [
|
||||
{
|
||||
id: '1',
|
||||
registry: 'npm',
|
||||
name: 'old-package',
|
||||
version: '1.0.0',
|
||||
size: 1024,
|
||||
cached_at: '2025-01-01T00:00:00Z',
|
||||
last_accessed: '2025-01-01T00:00:00Z',
|
||||
download_count: 10,
|
||||
},
|
||||
store.recentPackages = [
|
||||
{
|
||||
id: '2',
|
||||
registry: 'npm',
|
||||
@@ -170,46 +165,33 @@ describe('Dashboard.vue', () => {
|
||||
last_accessed: '2025-01-02T00:00:00Z',
|
||||
download_count: 5,
|
||||
},
|
||||
{
|
||||
id: '1',
|
||||
registry: 'npm',
|
||||
name: 'old-package',
|
||||
version: '1.0.0',
|
||||
size: 1024,
|
||||
cached_at: '2025-01-01T00:00:00Z',
|
||||
last_accessed: '2025-01-01T00:00:00Z',
|
||||
download_count: 10,
|
||||
},
|
||||
]
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
const recentPackagesSection = wrapper.text().split('Recent packages')[1]
|
||||
|
||||
// new-package should appear before old-package since it's more recent
|
||||
// The store sorts by cached_at; the view keeps that order
|
||||
expect(recentPackagesSection.indexOf('new-package')).toBeLessThan(
|
||||
recentPackagesSection.indexOf('old-package')
|
||||
)
|
||||
})
|
||||
|
||||
it('limits recent packages to 10 items', async () => {
|
||||
const wrapper = mount(Dashboard)
|
||||
const store = usePackageStore()
|
||||
|
||||
store.loading = false
|
||||
store.packages = Array.from({ length: 15 }, (_, i) => ({
|
||||
id: `${i}`,
|
||||
registry: 'npm',
|
||||
name: `package${i}`,
|
||||
version: '1.0.0',
|
||||
size: 1024,
|
||||
cached_at: `2025-01-${String(i + 1).padStart(2, '0')}T00:00:00Z`,
|
||||
last_accessed: `2025-01-${String(i + 1).padStart(2, '0')}T00:00:00Z`,
|
||||
download_count: i,
|
||||
}))
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
const recentSection = wrapper.text().split('Recent packages')[1]
|
||||
// Count how many "package" strings appear (each package has the word "package" in its name)
|
||||
const packageCount = (recentSection.match(/package\d+/g) || []).length
|
||||
expect(packageCount).toBeLessThanOrEqual(10)
|
||||
})
|
||||
|
||||
it('handles empty packages array', async () => {
|
||||
const wrapper = mount(Dashboard)
|
||||
const store = usePackageStore()
|
||||
|
||||
store.loading = false
|
||||
store.packages = []
|
||||
store.recentPackages = []
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
expect(wrapper.text()).toContain('0')
|
||||
|
||||
@@ -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>
|
||||
@@ -75,7 +78,7 @@
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<EmptyState
|
||||
v-if="packages.length === 0"
|
||||
v-if="recentPackages.length === 0"
|
||||
size="sm"
|
||||
:icon="faBoxOpen"
|
||||
title="No packages cached yet"
|
||||
@@ -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'
|
||||
@@ -140,7 +144,7 @@ import {
|
||||
} from '@/lib/icons'
|
||||
|
||||
const store = usePackageStore()
|
||||
const { packages, stats, loading, error } = storeToRefs(store)
|
||||
const { recentPackages, stats, loading, error } = storeToRefs(store)
|
||||
|
||||
const rt = useRealtimeStore()
|
||||
const { lastStats, events: rtEvents } = storeToRefs(rt)
|
||||
@@ -259,7 +263,7 @@ const packageColumns: DataTableColumn<Package>[] = [
|
||||
|
||||
function refresh() {
|
||||
void store.fetchStats()
|
||||
void store.fetchPackages()
|
||||
void store.fetchRecentPackages()
|
||||
}
|
||||
|
||||
function getChartLabel(index: number): string {
|
||||
@@ -291,14 +295,6 @@ function getChartLabel(index: number): string {
|
||||
return labels[selectedPeriod.value]?.(index) || `${index}`
|
||||
}
|
||||
|
||||
// API returns clean, deduplicated data - just sort and limit
|
||||
const recentPackages = computed(() => {
|
||||
return packages.value
|
||||
.slice()
|
||||
.sort((a, b) => new Date(b.cached_at).getTime() - new Date(a.cached_at).getTime())
|
||||
.slice(0, 10)
|
||||
})
|
||||
|
||||
// Watch for period changes and fetch new data
|
||||
watch(selectedPeriod, () => {
|
||||
fetchTimeSeriesData()
|
||||
@@ -309,9 +305,7 @@ onMounted(async () => {
|
||||
// initial polling resolves. Singleton survives navigation, so we
|
||||
// intentionally do not disconnect on unmount.
|
||||
rt.connect()
|
||||
await store.fetchStats()
|
||||
await store.fetchPackages()
|
||||
await fetchTimeSeriesData()
|
||||
await Promise.all([store.fetchStats(), store.fetchRecentPackages(), fetchTimeSeriesData()])
|
||||
})
|
||||
|
||||
</script>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest'
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
|
||||
import { mount } from '@vue/test-utils'
|
||||
import { createPinia, setActivePinia } from 'pinia'
|
||||
import { createRouter, createMemoryHistory, type Router } from 'vue-router'
|
||||
@@ -6,6 +6,14 @@ import { defineComponent, h } from 'vue'
|
||||
import PackageList from './PackageList.vue'
|
||||
import { usePackageStore } from '../stores/packages'
|
||||
|
||||
type Row = ReturnType<typeof usePackageStore>['packagePage']['packages'][number]
|
||||
|
||||
// A page as the server sends it: whole groups, flattened to rows.
|
||||
function setRows(store: ReturnType<typeof usePackageStore>, packages: Row[]) {
|
||||
const groups = new Set(packages.map((p) => `${p.registry}:${p.name}`))
|
||||
store.packagePage = { packages, totalGroups: groups.size, page: 1, pageSize: 25 }
|
||||
}
|
||||
|
||||
const Stub = defineComponent({ render: () => h('div') })
|
||||
|
||||
function createTestRouter(): Router {
|
||||
@@ -41,7 +49,7 @@ describe('PackageList.vue', () => {
|
||||
setActivePinia(createPinia())
|
||||
// Prevent real network calls from store actions on mount
|
||||
const store = usePackageStore()
|
||||
vi.spyOn(store, 'fetchPackages').mockResolvedValue()
|
||||
vi.spyOn(store, 'fetchPackagePage').mockResolvedValue()
|
||||
})
|
||||
|
||||
it('renders package list component', async () => {
|
||||
@@ -74,7 +82,7 @@ describe('PackageList.vue', () => {
|
||||
const store = usePackageStore()
|
||||
|
||||
store.loading = false
|
||||
store.packages = []
|
||||
setRows(store, [])
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
expect(wrapper.text()).toContain('No packages cached yet')
|
||||
@@ -85,7 +93,7 @@ describe('PackageList.vue', () => {
|
||||
const store = usePackageStore()
|
||||
|
||||
store.loading = false
|
||||
store.packages = [
|
||||
setRows(store, [
|
||||
{
|
||||
id: '1',
|
||||
registry: 'npm',
|
||||
@@ -96,17 +104,17 @@ describe('PackageList.vue', () => {
|
||||
last_accessed: '2025-01-01T00:00:00Z',
|
||||
download_count: 10,
|
||||
},
|
||||
]
|
||||
])
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
expect(wrapper.text()).toContain('test-package')
|
||||
expect(wrapper.text()).toContain('1 version')
|
||||
})
|
||||
|
||||
it('calls fetchPackages on mount', async () => {
|
||||
it('asks the server for the first page on mount', async () => {
|
||||
const store = usePackageStore()
|
||||
// beforeEach already spied with mockResolvedValue; reuse that spy
|
||||
const fetchSpy = store.fetchPackages as ReturnType<typeof vi.spyOn>
|
||||
const fetchSpy = store.fetchPackagePage as ReturnType<typeof vi.spyOn>
|
||||
fetchSpy.mockClear()
|
||||
|
||||
await mountWithRouter()
|
||||
@@ -119,7 +127,7 @@ describe('PackageList.vue', () => {
|
||||
const store = usePackageStore()
|
||||
|
||||
store.loading = false
|
||||
store.packages = [
|
||||
setRows(store, [
|
||||
{
|
||||
id: '1',
|
||||
registry: 'npm',
|
||||
@@ -140,7 +148,7 @@ describe('PackageList.vue', () => {
|
||||
last_accessed: '2025-01-02T00:00:00Z',
|
||||
download_count: 20,
|
||||
},
|
||||
]
|
||||
])
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
expect(wrapper.text()).toContain('test-package')
|
||||
@@ -152,7 +160,7 @@ describe('PackageList.vue', () => {
|
||||
const store = usePackageStore()
|
||||
|
||||
store.loading = false
|
||||
store.packages = [
|
||||
setRows(store, [
|
||||
{
|
||||
id: '1',
|
||||
registry: 'npm',
|
||||
@@ -163,7 +171,7 @@ describe('PackageList.vue', () => {
|
||||
last_accessed: '2025-01-01T00:00:00Z',
|
||||
download_count: 10,
|
||||
},
|
||||
]
|
||||
])
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
expect(wrapper.text()).toContain('1 MB')
|
||||
@@ -174,7 +182,17 @@ describe('PackageList.vue', () => {
|
||||
const store = usePackageStore()
|
||||
|
||||
store.loading = false
|
||||
store.packages = [
|
||||
setRows(store, [
|
||||
{
|
||||
id: '3',
|
||||
registry: 'go',
|
||||
name: 'go-module',
|
||||
version: '1.0.0',
|
||||
size: 1024,
|
||||
cached_at: '2025-01-01T00:00:00Z',
|
||||
last_accessed: '2025-01-01T00:00:00Z',
|
||||
download_count: 3,
|
||||
},
|
||||
{
|
||||
id: '1',
|
||||
registry: 'npm',
|
||||
@@ -195,21 +213,11 @@ describe('PackageList.vue', () => {
|
||||
last_accessed: '2025-01-01T00:00:00Z',
|
||||
download_count: 5,
|
||||
},
|
||||
{
|
||||
id: '3',
|
||||
registry: 'go',
|
||||
name: 'go-module',
|
||||
version: '1.0.0',
|
||||
size: 1024,
|
||||
cached_at: '2025-01-01T00:00:00Z',
|
||||
last_accessed: '2025-01-01T00:00:00Z',
|
||||
download_count: 3,
|
||||
},
|
||||
]
|
||||
])
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
// Verify that all registry badges are displayed
|
||||
// Packages are grouped and sorted alphabetically, so order is: go-module, npm-package, python-package
|
||||
// The server sends groups in name order: go-module, npm-package, python-package
|
||||
expect(wrapper.text()).toContain('npm')
|
||||
expect(wrapper.text()).toContain('pypi')
|
||||
expect(wrapper.text()).toContain('go')
|
||||
@@ -223,7 +231,7 @@ describe('PackageList.vue', () => {
|
||||
const wrapper = await mountWithRouter()
|
||||
const store = usePackageStore()
|
||||
|
||||
store.packages = [
|
||||
setRows(store, [
|
||||
{
|
||||
id: '1',
|
||||
registry: 'pypi',
|
||||
@@ -235,7 +243,7 @@ describe('PackageList.vue', () => {
|
||||
last_accessed: '2026-11-23T00:00:00Z',
|
||||
download_count: 0,
|
||||
},
|
||||
]
|
||||
])
|
||||
await wrapper.vm.$nextTick()
|
||||
await wrapper.find('button[aria-expanded]').trigger('click')
|
||||
await wrapper.vm.$nextTick()
|
||||
@@ -243,4 +251,75 @@ describe('PackageList.vue', () => {
|
||||
expect(wrapper.text()).toContain('v1.17.0')
|
||||
expect(wrapper.text()).not.toContain('py2.py3-none-any.whl')
|
||||
})
|
||||
|
||||
describe('server-side paging, search and registry filter', () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers()
|
||||
})
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('debounces the search box into one request with q and page 1', async () => {
|
||||
const wrapper = await mountWithRouter()
|
||||
const store = usePackageStore()
|
||||
const fetchSpy = store.fetchPackagePage as ReturnType<typeof vi.spyOn>
|
||||
fetchSpy.mockClear()
|
||||
|
||||
const input = wrapper.find('input[type="search"], input')
|
||||
await input.setValue('l')
|
||||
await input.setValue('le')
|
||||
await input.setValue('left')
|
||||
expect(fetchSpy).not.toHaveBeenCalled()
|
||||
|
||||
await vi.advanceTimersByTimeAsync(300)
|
||||
expect(fetchSpy).toHaveBeenCalledTimes(1)
|
||||
expect(fetchSpy).toHaveBeenCalledWith({ page: 1, pageSize: 25, registry: 'all', q: 'left' })
|
||||
})
|
||||
|
||||
it('sends the registry of the route with every request', async () => {
|
||||
const router = createTestRouter()
|
||||
router.push('/packages/pypi')
|
||||
await router.isReady()
|
||||
const store = usePackageStore()
|
||||
const fetchSpy = store.fetchPackagePage as ReturnType<typeof vi.spyOn>
|
||||
fetchSpy.mockClear()
|
||||
mount(PackageList, { props: { registry: 'pypi' }, global: { plugins: [router] } })
|
||||
expect(fetchSpy).toHaveBeenCalledWith({ page: 1, pageSize: 25, registry: 'pypi', q: '' })
|
||||
})
|
||||
|
||||
it('pages through the server, not the loaded rows', async () => {
|
||||
const wrapper = await mountWithRouter()
|
||||
const store = usePackageStore()
|
||||
store.loading = false
|
||||
store.packagePage = {
|
||||
packages: [
|
||||
{ id: '1', registry: 'npm', name: 'a', version: '1', size: 1, cached_at: '2025-01-01T00:00:00Z', last_accessed: '2025-01-01T00:00:00Z', download_count: 0 },
|
||||
],
|
||||
totalGroups: 60,
|
||||
page: 1,
|
||||
pageSize: 25,
|
||||
}
|
||||
await wrapper.vm.$nextTick()
|
||||
expect(wrapper.text()).toContain('Page 1 of 3 (60 total packages)')
|
||||
|
||||
const fetchSpy = store.fetchPackagePage as ReturnType<typeof vi.spyOn>
|
||||
fetchSpy.mockClear()
|
||||
window.scrollTo = vi.fn() as unknown as typeof window.scrollTo
|
||||
const next = wrapper.findAll('button').find((b) => /next/i.test(b.attributes('aria-label') ?? b.text()))
|
||||
await next!.trigger('click')
|
||||
expect(fetchSpy).toHaveBeenCalledWith({ page: 2, pageSize: 25, registry: 'all', q: '' })
|
||||
})
|
||||
|
||||
it('says no packages match when a filter empties the page', async () => {
|
||||
const wrapper = await mountWithRouter()
|
||||
const store = usePackageStore()
|
||||
store.loading = false
|
||||
setRows(store, [])
|
||||
await wrapper.find('input').setValue('zzz')
|
||||
await vi.advanceTimersByTimeAsync(300)
|
||||
expect(wrapper.text()).toContain('No packages match')
|
||||
expect(wrapper.text()).not.toContain('No packages cached yet')
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
<div class="flex flex-col gap-6">
|
||||
<PageHeader title="Packages" description="Everything the proxy has cached, grouped by package.">
|
||||
<template #actions>
|
||||
<Button variant="outline" :icon-start="faRotateRight" @click="store.fetchPackages()">Refresh</Button>
|
||||
<Button variant="outline" :icon-start="faRotateRight" @click="load()">Refresh</Button>
|
||||
</template>
|
||||
</PageHeader>
|
||||
|
||||
@@ -23,26 +23,26 @@
|
||||
variant="card"
|
||||
title="Could not load packages"
|
||||
:message="error"
|
||||
@retry="store.fetchPackages()"
|
||||
@retry="load()"
|
||||
/>
|
||||
|
||||
<Card v-else>
|
||||
<CardContent>
|
||||
<EmptyState
|
||||
v-if="packages.length === 0"
|
||||
v-if="totalGroups === 0 && !filtersActive"
|
||||
:icon="faBoxOpen"
|
||||
title="No packages cached yet"
|
||||
description="Packages will appear here once they are downloaded through the proxy."
|
||||
/>
|
||||
<EmptyState
|
||||
v-else-if="groupedPackages.length === 0"
|
||||
v-else-if="groups.length === 0"
|
||||
:icon="faMagnifyingGlass"
|
||||
title="No packages match"
|
||||
description="Change the registry filter or the search text."
|
||||
/>
|
||||
<Accordion v-else type="multiple" class="w-full">
|
||||
<AccordionItem
|
||||
v-for="group in groupedPackages"
|
||||
v-for="group in groups"
|
||||
:key="`${group.registry}:${group.name}`"
|
||||
:value="`${group.registry}:${group.name}`"
|
||||
>
|
||||
@@ -110,12 +110,12 @@
|
||||
|
||||
<div v-if="totalPages > 1" class="mt-6 flex flex-col gap-3 border-t pt-4 sm:flex-row sm:items-center sm:justify-between">
|
||||
<p class="m-0 text-sm text-muted-foreground">
|
||||
Page {{ currentPage }} of {{ totalPages }} ({{ allGroupedPackages.length }} total packages)
|
||||
Page {{ currentPage }} of {{ totalPages }} ({{ totalGroups }} total packages)
|
||||
</p>
|
||||
<Pagination
|
||||
:page="currentPage"
|
||||
:total="allGroupedPackages.length"
|
||||
:page-size="itemsPerPage"
|
||||
:total="totalGroups"
|
||||
:page-size="PAGE_SIZE"
|
||||
:show-edges="false"
|
||||
@update:page="changePage"
|
||||
/>
|
||||
@@ -136,7 +136,7 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { onMounted, ref, computed, watch } from 'vue'
|
||||
import { onBeforeUnmount, onMounted, ref, computed, watch } from 'vue'
|
||||
import { storeToRefs } from 'pinia'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import { usePackageStore, type Package } from '../stores/packages'
|
||||
@@ -179,7 +179,7 @@ const route = useRoute()
|
||||
const router = useRouter()
|
||||
const store = usePackageStore()
|
||||
const toasts = useToastStore()
|
||||
const { packages, loading, error } = storeToRefs(store)
|
||||
const { packagePage, loading, error } = storeToRefs(store)
|
||||
|
||||
const showDeleteModal = ref(false)
|
||||
const packageToDelete = ref<Package | null>(null)
|
||||
@@ -190,88 +190,77 @@ const REGISTRY_OPTIONS = [
|
||||
{ value: 'go', label: 'Go' },
|
||||
]
|
||||
|
||||
const PAGE_SIZE = 25
|
||||
const SEARCH_DEBOUNCE_MS = 300
|
||||
|
||||
const selectedRegistry = ref<string>(props.registry || 'all')
|
||||
const searchTerm = ref<string>('')
|
||||
// What the server was last asked: the search text lags the input by the debounce.
|
||||
const activeQuery = ref<string>('')
|
||||
const currentPage = ref<number>(1)
|
||||
const itemsPerPage = ref<number>(10)
|
||||
|
||||
// Group packages by name
|
||||
const allGroupedPackages = computed(() => {
|
||||
const groups = new Map<string, Package[]>()
|
||||
const totalGroups = computed(() => packagePage.value.totalGroups)
|
||||
const totalPages = computed(() => Math.ceil(totalGroups.value / PAGE_SIZE))
|
||||
const filtersActive = computed(() => selectedRegistry.value !== 'all' || activeQuery.value.trim() !== '')
|
||||
|
||||
// Filter packages by selected registry and search term
|
||||
let filteredPackages = selectedRegistry.value === 'all'
|
||||
? packages.value
|
||||
: packages.value.filter(pkg => pkg.registry === selectedRegistry.value)
|
||||
|
||||
// Apply search filter if search term exists
|
||||
if (searchTerm.value.trim()) {
|
||||
const searchLower = searchTerm.value.toLowerCase()
|
||||
filteredPackages = filteredPackages.filter(pkg =>
|
||||
pkg.name.toLowerCase().includes(searchLower) ||
|
||||
displayVersion(pkg).toLowerCase().includes(searchLower) ||
|
||||
pkg.version.toLowerCase().includes(searchLower)
|
||||
)
|
||||
// The server pages whole (registry, name) groups and sends every version row of each.
|
||||
const groups = computed(() => {
|
||||
const byKey = new Map<string, { registry: string; name: string; versions: Package[] }>()
|
||||
for (const pkg of packagePage.value.packages) {
|
||||
const key = `${pkg.registry}\u0000${pkg.name}`
|
||||
let group = byKey.get(key)
|
||||
if (!group) {
|
||||
group = { registry: pkg.registry, name: pkg.name, versions: [] }
|
||||
byKey.set(key, group)
|
||||
}
|
||||
group.versions.push(pkg)
|
||||
}
|
||||
return Array.from(byKey.values()).map((group) => ({
|
||||
...group,
|
||||
totalSize: group.versions.reduce((sum, v) => sum + v.size, 0),
|
||||
totalDownloads: group.versions.reduce((sum, v) => sum + v.download_count, 0),
|
||||
}))
|
||||
})
|
||||
|
||||
filteredPackages.forEach(pkg => {
|
||||
const key = `${pkg.registry}:${pkg.name}`
|
||||
if (!groups.has(key)) {
|
||||
groups.set(key, [])
|
||||
}
|
||||
groups.get(key)!.push(pkg)
|
||||
async function load() {
|
||||
await store.fetchPackagePage({
|
||||
page: currentPage.value,
|
||||
pageSize: PAGE_SIZE,
|
||||
registry: selectedRegistry.value,
|
||||
q: activeQuery.value,
|
||||
})
|
||||
|
||||
// Convert to array and sort versions within each group
|
||||
return Array.from(groups.entries()).map(([key, versions]) => {
|
||||
const [registry, name] = key.split(':')
|
||||
return {
|
||||
registry,
|
||||
name,
|
||||
versions: versions.sort((a, b) =>
|
||||
new Date(b.cached_at).getTime() - new Date(a.cached_at).getTime()
|
||||
),
|
||||
totalSize: versions.reduce((sum, v) => sum + v.size, 0),
|
||||
totalDownloads: versions.reduce((sum, v) => sum + v.download_count, 0),
|
||||
}
|
||||
}).sort((a, b) => a.name.localeCompare(b.name))
|
||||
})
|
||||
|
||||
// Pagination
|
||||
const totalPages = computed(() => Math.ceil(allGroupedPackages.value.length / itemsPerPage.value))
|
||||
|
||||
const groupedPackages = computed(() => {
|
||||
const start = (currentPage.value - 1) * itemsPerPage.value
|
||||
const end = start + itemsPerPage.value
|
||||
return allGroupedPackages.value.slice(start, end)
|
||||
})
|
||||
}
|
||||
|
||||
function changePage(page: number) {
|
||||
if (page >= 1 && page <= totalPages.value) {
|
||||
currentPage.value = page
|
||||
void load()
|
||||
// Scroll to top of packages list
|
||||
window.scrollTo({ top: 0, behavior: 'smooth' })
|
||||
}
|
||||
}
|
||||
|
||||
// Reset to page 1 when filters change
|
||||
function resetPagination() {
|
||||
currentPage.value = 1
|
||||
}
|
||||
|
||||
// Watch for filter/search changes and reset pagination
|
||||
watch([selectedRegistry, searchTerm], () => {
|
||||
resetPagination()
|
||||
// A burst of keystrokes asks the server once.
|
||||
let searchTimer: ReturnType<typeof setTimeout> | undefined
|
||||
watch(searchTerm, (term) => {
|
||||
clearTimeout(searchTimer)
|
||||
searchTimer = setTimeout(() => {
|
||||
if (term === activeQuery.value) return
|
||||
activeQuery.value = term
|
||||
currentPage.value = 1
|
||||
void load()
|
||||
}, SEARCH_DEBOUNCE_MS)
|
||||
})
|
||||
onBeforeUnmount(() => clearTimeout(searchTimer))
|
||||
|
||||
// Watch for route parameter changes to update filter
|
||||
watch(() => route.params.registry, (newRegistry) => {
|
||||
selectedRegistry.value = (newRegistry as string) || 'all'
|
||||
currentPage.value = 1
|
||||
void load()
|
||||
})
|
||||
|
||||
onMounted(async () => {
|
||||
await store.fetchPackages()
|
||||
})
|
||||
onMounted(load)
|
||||
|
||||
function confirmDelete(pkg: Package) {
|
||||
packageToDelete.value = pkg
|
||||
@@ -289,7 +278,15 @@ async function deletePackage() {
|
||||
toasts.error('Could not delete package', `${label}: ${store.error}`)
|
||||
// The toast reports it; the list loaded fine, so it must not be replaced by a load error.
|
||||
store.error = null
|
||||
} else toasts.success('Package deleted', label)
|
||||
} else {
|
||||
toasts.success('Package deleted', label)
|
||||
await load()
|
||||
// Deleting the last group of the last page leaves that page empty.
|
||||
if (packagePage.value.packages.length === 0 && totalGroups.value > 0 && currentPage.value > 1) {
|
||||
currentPage.value = Math.max(totalPages.value, 1)
|
||||
await load()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function showVulnerabilityDetails(registry: string, name: string, version: string) {
|
||||
|
||||
@@ -1,18 +1,65 @@
|
||||
<template>
|
||||
<StatGroup :columns="4" :aria-label="label">
|
||||
<KpiTile v-for="level in SEVERITY_LEVELS" :key="level" :label="formatSeverityName(level)" :value="counts[level]">
|
||||
<template #icon><StatusDot :tone="SEVERITY_TONES[level]" /></template>
|
||||
</KpiTile>
|
||||
<template v-if="selectable">
|
||||
<KpiTile
|
||||
v-for="level in SEVERITY_LEVELS"
|
||||
:key="level"
|
||||
as="button"
|
||||
type="button"
|
||||
variant="interactive"
|
||||
:label="formatSeverityName(level)"
|
||||
:value="counts[level]"
|
||||
:aria-pressed="isSelected(level)"
|
||||
:class="isSelected(level) && 'ring-2 ring-primary'"
|
||||
:data-severity="level"
|
||||
@click="toggle(level)"
|
||||
>
|
||||
<template #icon><StatusDot :tone="SEVERITY_TONES[level]" /></template>
|
||||
<template #hint>
|
||||
<span v-if="packageCounts">{{ formatPackageCount(packageCounts[level]) }}</span>
|
||||
<span v-if="isSelected(level)" class="font-medium text-foreground" data-testid="severity-filter-on">
|
||||
{{ packageCounts ? ' · ' : '' }}Filter on
|
||||
</span>
|
||||
</template>
|
||||
</KpiTile>
|
||||
</template>
|
||||
<template v-else>
|
||||
<KpiTile v-for="level in SEVERITY_LEVELS" :key="level" :label="formatSeverityName(level)" :value="counts[level]">
|
||||
<template #icon><StatusDot :tone="SEVERITY_TONES[level]" /></template>
|
||||
</KpiTile>
|
||||
</template>
|
||||
</StatGroup>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { KpiTile, StatGroup, StatusDot } from '@perfect-design/ui'
|
||||
import type { VulnerabilityCounts } from '../stores/packages'
|
||||
import { SEVERITY_LEVELS, SEVERITY_TONES, formatSeverityName } from '@/lib/severity'
|
||||
import { SEVERITY_LEVELS, SEVERITY_TONES, formatSeverityName, type SeverityLevel } from '@/lib/severity'
|
||||
|
||||
defineProps<{
|
||||
const props = defineProps<{
|
||||
counts: VulnerabilityCounts
|
||||
label: string
|
||||
/** Tiles become toggle buttons that edit `modelValue`. */
|
||||
selectable?: boolean
|
||||
/** Selected severities; several are allowed. */
|
||||
modelValue?: readonly SeverityLevel[]
|
||||
/** Packages per severity, shown on each tile in selectable mode. */
|
||||
packageCounts?: VulnerabilityCounts
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{ 'update:modelValue': [value: SeverityLevel[]] }>()
|
||||
|
||||
function isSelected(level: SeverityLevel): boolean {
|
||||
return props.modelValue?.includes(level) ?? false
|
||||
}
|
||||
|
||||
function toggle(level: SeverityLevel) {
|
||||
const current = props.modelValue ?? []
|
||||
const next = current.includes(level) ? current.filter((l) => l !== level) : [...current, level]
|
||||
emit('update:modelValue', SEVERITY_LEVELS.filter((l) => next.includes(l)))
|
||||
}
|
||||
|
||||
function formatPackageCount(n: number): string {
|
||||
return `${n} package${n === 1 ? '' : 's'}`
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -70,6 +70,8 @@
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<TrendChart />
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">Registry breakdown</CardTitle>
|
||||
@@ -109,6 +111,7 @@ import {
|
||||
StatGroup,
|
||||
type DataTableColumn,
|
||||
} from '@perfect-design/ui'
|
||||
import TrendChart from './TrendChart.vue'
|
||||
import { formatBytes, formatDuration, formatNumber } from '@/lib/format'
|
||||
import { faBan, faDownload, faHardDrive, faBoxesStacked, faCircleCheck, faTriangleExclamation } from '@/lib/icons'
|
||||
|
||||
|
||||
@@ -0,0 +1,213 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { createPinia, setActivePinia } from 'pinia'
|
||||
import axios from 'axios'
|
||||
import { flushPromises } from '@vue/test-utils'
|
||||
import TrendChart from './TrendChart.vue'
|
||||
import { TREND } from '@/test/fixtures'
|
||||
import { mountStrict } from '@/test/mountStrict'
|
||||
import { createTestRouter } from '@/test/router'
|
||||
import { formatTrendDate, trendValues } from '@/lib/trend'
|
||||
|
||||
vi.mock('axios')
|
||||
|
||||
let restore: (() => void) | undefined
|
||||
|
||||
beforeEach(() => {
|
||||
setActivePinia(createPinia())
|
||||
vi.mocked(axios.get).mockReset()
|
||||
vi.mocked(axios.get).mockResolvedValue({ data: TREND })
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
restore?.()
|
||||
restore = undefined
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
async function open(props: Record<string, unknown> = {}) {
|
||||
const router = await createTestRouter('/stats')
|
||||
const mounted = await mountStrict(TrendChart, { props, global: { plugins: [router] } })
|
||||
restore = mounted.restore
|
||||
await flushPromises()
|
||||
return mounted
|
||||
}
|
||||
|
||||
type Wrapper = Awaited<ReturnType<typeof open>>['wrapper']
|
||||
const charts = (w: Wrapper) => w.findAll('svg[role="img"]')
|
||||
const requested = () => vi.mocked(axios.get).mock.calls.map((c) => c[0])
|
||||
|
||||
describe('TrendChart', () => {
|
||||
it('requests the 30 day trend and draws both charts with accessible names', async () => {
|
||||
const { wrapper, problems } = await open()
|
||||
|
||||
expect(problems).toEqual([])
|
||||
expect(requested()).toEqual(['/api/stats/trend?period=30day'])
|
||||
const labels = charts(wrapper).map((c) => c.attributes('aria-label'))
|
||||
expect(labels).toHaveLength(2)
|
||||
expect(labels[0]).toContain('Cached packages per day, from 3 on 2 Jan 2026 to 4 on 4 Jan 2026')
|
||||
expect(labels[1]).toContain('Vulnerable packages per day, from 1 on 3 Jan 2026 to 2 on 4 Jan 2026')
|
||||
})
|
||||
|
||||
it('offers every value as text through the chart data table', async () => {
|
||||
const { wrapper } = await open()
|
||||
const tables = wrapper.findAll('table')
|
||||
|
||||
expect(tables.length).toBeGreaterThanOrEqual(2)
|
||||
expect(tables[0]!.text()).toContain('Cached packages')
|
||||
expect(tables[0]!.text()).toContain('4')
|
||||
})
|
||||
|
||||
it('refetches when the period changes', async () => {
|
||||
const { wrapper } = await open()
|
||||
const ninety = wrapper.findAll('[role="radio"]').find((r) => r.text() === '90 days')!
|
||||
|
||||
await ninety.trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
expect(requested()).toEqual(['/api/stats/trend?period=30day', '/api/stats/trend?period=90day'])
|
||||
})
|
||||
|
||||
it('draws the vulnerable total first and adds a line for each severity that is switched on', async () => {
|
||||
const { wrapper } = await open()
|
||||
const vulnerable = () => charts(wrapper)[1]!.attributes('aria-label')
|
||||
expect(vulnerable()).not.toContain('lines for')
|
||||
|
||||
const critical = wrapper.findAll('button[aria-pressed]').find((b) => b.text() === 'Critical')!
|
||||
expect(critical.attributes('aria-pressed')).toBe('false')
|
||||
await critical.trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
expect(critical.attributes('aria-pressed')).toBe('true')
|
||||
expect(vulnerable()).toContain('with lines for critical')
|
||||
expect(wrapper.text()).toContain('Packages with critical vulnerabilities')
|
||||
|
||||
await critical.trigger('click')
|
||||
await flushPromises()
|
||||
expect(vulnerable()).not.toContain('lines for')
|
||||
})
|
||||
|
||||
it('offers all four severities as toggle buttons', async () => {
|
||||
const { wrapper } = await open()
|
||||
const names = wrapper.findAll('button[aria-pressed]').map((b) => b.text())
|
||||
expect(names).toEqual(['Critical', 'High', 'Moderate', 'Low'])
|
||||
})
|
||||
|
||||
it('says plainly when vulnerability history starts after the first day', async () => {
|
||||
const { wrapper } = await open()
|
||||
expect(wrapper.get('[data-testid="trend-vulnerability-note"]').text()).toBe('Vulnerability history starts 3 Jan 2026.')
|
||||
})
|
||||
|
||||
it('shows no note when every day has vulnerability data', async () => {
|
||||
const full = { ...TREND, vulnerability_history_start: TREND.points[0]!.date }
|
||||
vi.mocked(axios.get).mockResolvedValue({ data: full })
|
||||
const { wrapper } = await open()
|
||||
expect(wrapper.find('[data-testid="trend-vulnerability-note"]').exists()).toBe(false)
|
||||
})
|
||||
|
||||
it('shows an empty state instead of the vulnerable chart while no scan data exists', async () => {
|
||||
const noScans = {
|
||||
...TREND,
|
||||
vulnerability_history_start: null,
|
||||
points: TREND.points.map((p) => ({ ...p, vulnerable_packages: null, critical: null, high: null, moderate: null, low: null })),
|
||||
}
|
||||
vi.mocked(axios.get).mockResolvedValue({ data: noScans })
|
||||
const { wrapper, problems } = await open()
|
||||
|
||||
expect(problems).toEqual([])
|
||||
expect(charts(wrapper)).toHaveLength(1)
|
||||
expect(wrapper.get('[data-slot="empty-state"]').text()).toContain('Vulnerability history has not started')
|
||||
expect(wrapper.get('[data-testid="trend-vulnerability-note"]').text()).toContain('has not started in this period')
|
||||
})
|
||||
|
||||
it('shows an empty state when the server holds no snapshots', async () => {
|
||||
vi.mocked(axios.get).mockResolvedValue({ data: { ...TREND, vulnerability_history_start: null, points: [] } })
|
||||
const { wrapper } = await open()
|
||||
|
||||
expect(wrapper.get('[data-slot="empty-state"]').text()).toContain('No history yet')
|
||||
expect(charts(wrapper)).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('shows a loading state until the first answer arrives', async () => {
|
||||
let resolve!: (value: unknown) => void
|
||||
vi.mocked(axios.get).mockReturnValue(new Promise((r) => (resolve = r)) as never)
|
||||
const { wrapper } = await open()
|
||||
|
||||
expect(wrapper.text()).toContain('Loading package history...')
|
||||
resolve({ data: TREND })
|
||||
await flushPromises()
|
||||
expect(wrapper.text()).not.toContain('Loading package history...')
|
||||
expect(charts(wrapper)).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('shows the error with a retry that fetches again', async () => {
|
||||
vi.mocked(axios.get).mockRejectedValueOnce(new Error('Request failed with status code 502'))
|
||||
const { wrapper, problems } = await open()
|
||||
|
||||
expect(problems).toEqual([])
|
||||
const state = wrapper.get('[data-slot="error-state"]')
|
||||
expect(state.text()).toContain('502')
|
||||
expect(charts(wrapper)).toHaveLength(0)
|
||||
|
||||
await state.get('button').trigger('click')
|
||||
await flushPromises()
|
||||
expect(wrapper.find('[data-slot="error-state"]').exists()).toBe(false)
|
||||
expect(charts(wrapper)).toHaveLength(2)
|
||||
expect(requested()).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('rejects a body without points as an error, not an empty chart', async () => {
|
||||
vi.mocked(axios.get).mockResolvedValue({ data: { stats: {} } })
|
||||
const { wrapper } = await open()
|
||||
expect(wrapper.get('[data-slot="error-state"]').text()).toContain('Unexpected response format')
|
||||
})
|
||||
|
||||
it('ignores an answer that a newer request has replaced', async () => {
|
||||
const answers: Array<(v: unknown) => void> = []
|
||||
vi.mocked(axios.get).mockImplementation(() => new Promise((r) => answers.push(r)) as never)
|
||||
const { wrapper } = await open()
|
||||
await wrapper.findAll('[role="radio"]').find((r) => r.text() === '1 year')!.trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
answers[1]!({ data: { ...TREND, period: '1year', points: [TREND.points[2]] } })
|
||||
await flushPromises()
|
||||
answers[0]!({ data: TREND })
|
||||
await flushPromises()
|
||||
|
||||
expect(wrapper.get('svg[role="img"]').attributes('aria-label')).toContain('from 4 on 4 Jan 2026 to 4 on 4 Jan 2026')
|
||||
})
|
||||
|
||||
describe('compact', () => {
|
||||
it('always asks for 30 days, draws one chart and links to the full history', async () => {
|
||||
const { wrapper, problems } = await open({ compact: true })
|
||||
|
||||
expect(problems).toEqual([])
|
||||
expect(requested()).toEqual(['/api/stats/trend?period=30day'])
|
||||
expect(charts(wrapper)).toHaveLength(1)
|
||||
expect(wrapper.find('[role="radiogroup"]').exists()).toBe(false)
|
||||
expect(wrapper.find('button[aria-pressed]').exists()).toBe(false)
|
||||
expect(wrapper.get('a[href="/stats"]').text()).toBe('Open the full history')
|
||||
expect(wrapper.get('[data-testid="trend-compact-vulnerable"]').text()).toBe('2 vulnerable packages on 4 Jan 2026.')
|
||||
})
|
||||
|
||||
it('says so when the latest day has no vulnerability data', async () => {
|
||||
const last = { ...TREND.points[2]!, vulnerable_packages: null }
|
||||
vi.mocked(axios.get).mockResolvedValue({ data: { ...TREND, points: [TREND.points[0]!, last] } })
|
||||
const { wrapper } = await open({ compact: true })
|
||||
expect(wrapper.get('[data-testid="trend-compact-vulnerable"]').text()).toBe('Vulnerability history has not started yet.')
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('trend helpers', () => {
|
||||
it('formats a UTC date without shifting it with the viewer zone', () => {
|
||||
expect(formatTrendDate('2026-11-23')).toBe('23 Nov')
|
||||
expect(formatTrendDate('2026-01-01', true)).toBe('1 Jan 2026')
|
||||
expect(formatTrendDate('not-a-date')).toBe('not-a-date')
|
||||
})
|
||||
|
||||
it('turns unknown counts into gaps, never zeros', () => {
|
||||
const values = trendValues(TREND.points, 'vulnerable_packages')
|
||||
expect(values[0]).toBeNaN()
|
||||
expect(values.slice(1)).toEqual([1, 2])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,196 @@
|
||||
<template>
|
||||
<Card data-testid="trend-card">
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">{{ compact ? 'Cached packages' : 'Packages over time' }}</CardTitle>
|
||||
<CardDescription>
|
||||
{{ compact ? 'Daily total, last 30 days.' : 'The cache at the end of each UTC day.' }}
|
||||
</CardDescription>
|
||||
<CardAction>
|
||||
<SegmentedControl v-if="!compact" v-model="period" :options="TREND_PERIODS" aria-label="Trend period" />
|
||||
<Button v-else as-child variant="link" size="sm">
|
||||
<RouterLink to="/stats">Open the full history</RouterLink>
|
||||
</Button>
|
||||
</CardAction>
|
||||
</CardHeader>
|
||||
<CardContent class="flex flex-col gap-8">
|
||||
<LoadingState v-if="loading && !data" layout="inline" label="Loading package history..." />
|
||||
<ErrorState
|
||||
v-else-if="error"
|
||||
variant="inline"
|
||||
title="Could not load the package history"
|
||||
:message="error"
|
||||
@retry="load"
|
||||
/>
|
||||
<EmptyState
|
||||
v-else-if="points.length === 0"
|
||||
title="No history yet"
|
||||
description="The server records the first daily snapshot when it starts, then one more each day."
|
||||
/>
|
||||
<template v-else>
|
||||
<section class="flex flex-col gap-3" aria-labelledby="trend-packages-heading">
|
||||
<h3 id="trend-packages-heading" class="text-sm font-medium">Cached packages</h3>
|
||||
<LineChart
|
||||
variant="area"
|
||||
:size="compact ? 'sm' : 'md'"
|
||||
:y-min="0"
|
||||
:labels="labels"
|
||||
:series="[{ name: 'Cached packages', data: values('total_packages'), tone: 'primary' }]"
|
||||
:label="packagesLabel"
|
||||
/>
|
||||
</section>
|
||||
|
||||
<p v-if="compact" class="text-sm text-muted-foreground" data-testid="trend-compact-vulnerable">
|
||||
{{ compactVulnerable }}
|
||||
</p>
|
||||
|
||||
<section v-else class="flex flex-col gap-3" aria-labelledby="trend-vulnerable-heading">
|
||||
<div class="flex flex-wrap items-center justify-between gap-3">
|
||||
<h3 id="trend-vulnerable-heading" class="text-sm font-medium">Vulnerable packages</h3>
|
||||
<ToggleGroup
|
||||
v-model="severities"
|
||||
type="multiple"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
aria-label="Add a line per severity"
|
||||
>
|
||||
<ToggleGroupItem v-for="level in SEVERITY_LEVELS" :key="level" :value="level">
|
||||
{{ formatSeverityName(level) }}
|
||||
</ToggleGroupItem>
|
||||
</ToggleGroup>
|
||||
</div>
|
||||
<p v-if="vulnerabilityNote" class="text-sm text-muted-foreground" data-testid="trend-vulnerability-note">
|
||||
{{ vulnerabilityNote }}
|
||||
</p>
|
||||
<LineChart
|
||||
v-if="data?.vulnerability_history_start"
|
||||
:y-min="0"
|
||||
:labels="labels"
|
||||
:series="vulnerableSeries"
|
||||
:label="vulnerableLabel"
|
||||
/>
|
||||
<EmptyState
|
||||
v-else
|
||||
size="sm"
|
||||
title="Vulnerability history has not started"
|
||||
description="Scan results are counted from the first daily snapshot that includes them."
|
||||
/>
|
||||
</section>
|
||||
</template>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import axios from 'axios'
|
||||
import { RouterLink } from 'vue-router'
|
||||
import {
|
||||
Button,
|
||||
Card,
|
||||
CardAction,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
EmptyState,
|
||||
ErrorState,
|
||||
LineChart,
|
||||
LoadingState,
|
||||
SegmentedControl,
|
||||
ToggleGroup,
|
||||
ToggleGroupItem,
|
||||
} from '@perfect-design/ui'
|
||||
import { SEVERITY_LEVELS, formatSeverityName, type SeverityLevel } from '@/lib/severity'
|
||||
import {
|
||||
DEFAULT_TREND_PERIOD,
|
||||
SEVERITY_LINE_TONES,
|
||||
TREND_PERIODS,
|
||||
formatTrendDate,
|
||||
trendValues,
|
||||
type TrendPeriod,
|
||||
type TrendPoint,
|
||||
type TrendResponse,
|
||||
} from '@/lib/trend'
|
||||
|
||||
const props = defineProps<{
|
||||
/** Dashboard card: 30 days, cached packages only, a link to the full history. */
|
||||
compact?: boolean
|
||||
}>()
|
||||
|
||||
const period = ref<TrendPeriod>(DEFAULT_TREND_PERIOD)
|
||||
const severities = ref<SeverityLevel[]>([])
|
||||
const data = ref<TrendResponse | null>(null)
|
||||
const loading = ref(false)
|
||||
const error = ref<string | null>(null)
|
||||
|
||||
let request = 0
|
||||
|
||||
async function load() {
|
||||
const current = ++request
|
||||
loading.value = true
|
||||
error.value = null
|
||||
try {
|
||||
const response = await axios.get(`/api/stats/trend?period=${props.compact ? DEFAULT_TREND_PERIOD : period.value}`)
|
||||
if (current !== request) return
|
||||
const body = response.data as TrendResponse | undefined
|
||||
if (!body || !Array.isArray(body.points)) {
|
||||
data.value = null
|
||||
error.value = 'Unexpected response format from server'
|
||||
return
|
||||
}
|
||||
data.value = body
|
||||
} catch (err) {
|
||||
if (current !== request) return
|
||||
data.value = null
|
||||
error.value = err instanceof Error ? err.message : 'Failed to load the package history'
|
||||
} finally {
|
||||
if (current === request) loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(load)
|
||||
watch(period, load)
|
||||
|
||||
const points = computed<TrendPoint[]>(() => data.value?.points ?? [])
|
||||
const labels = computed(() => points.value.map((p) => formatTrendDate(p.date, period.value === '1year')))
|
||||
const values = (key: keyof Omit<TrendPoint, 'date'>) => trendValues(points.value, key)
|
||||
|
||||
function span(key: keyof Omit<TrendPoint, 'date'>): string {
|
||||
const known = points.value.filter((p) => p[key] !== null)
|
||||
const first = known[0]
|
||||
const last = known[known.length - 1]
|
||||
if (!first || !last) return ''
|
||||
return `from ${first[key]} on ${formatTrendDate(first.date, true)} to ${last[key]} on ${formatTrendDate(last.date, true)}`
|
||||
}
|
||||
|
||||
const packagesLabel = computed(() => `Cached packages per day, ${span('total_packages')}`)
|
||||
const vulnerableLabel = computed(() => {
|
||||
const extra = severities.value.length ? `, with lines for ${severities.value.join(', ')}` : ''
|
||||
return `Vulnerable packages per day, ${span('vulnerable_packages')}${extra}`
|
||||
})
|
||||
|
||||
const vulnerableSeries = computed(() => [
|
||||
{ name: 'Vulnerable packages', data: values('vulnerable_packages'), tone: 'primary' as const },
|
||||
...SEVERITY_LEVELS.filter((level) => severities.value.includes(level)).map((level) => ({
|
||||
name: `Packages with ${level} vulnerabilities`,
|
||||
data: values(level),
|
||||
tone: SEVERITY_LINE_TONES[level],
|
||||
})),
|
||||
])
|
||||
|
||||
// Earlier days were never scanned, so their counts are unknown and drawn as a gap.
|
||||
const vulnerabilityNote = computed(() => {
|
||||
const start = data.value?.vulnerability_history_start
|
||||
const first = points.value[0]
|
||||
if (!start) return 'Vulnerability history has not started in this period.'
|
||||
if (first && start > first.date) return `Vulnerability history starts ${formatTrendDate(start, true)}.`
|
||||
return ''
|
||||
})
|
||||
|
||||
const compactVulnerable = computed(() => {
|
||||
const last = points.value[points.value.length - 1]
|
||||
const n = last?.vulnerable_packages
|
||||
if (n === null || n === undefined) return 'Vulnerability history has not started yet.'
|
||||
return `${n} vulnerable package${n === 1 ? '' : 's'} on ${formatTrendDate(last!.date, true)}.`
|
||||
})
|
||||
</script>
|
||||
@@ -0,0 +1,226 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { createPinia, setActivePinia } from 'pinia'
|
||||
import axios from 'axios'
|
||||
import { flushPromises } from '@vue/test-utils'
|
||||
import VulnerablePackages from './VulnerablePackages.vue'
|
||||
import type { Package, VulnerabilityCounts } from '@/stores/packages'
|
||||
import { mountStrict } from '@/test/mountStrict'
|
||||
import { createTestRouter } from '@/test/router'
|
||||
|
||||
vi.mock('axios')
|
||||
|
||||
function vulnerable(name: string, counts: Partial<VulnerabilityCounts>): Package {
|
||||
const full = { critical: 0, high: 0, moderate: 0, low: 0, ...counts }
|
||||
return {
|
||||
id: name,
|
||||
registry: 'npm',
|
||||
name,
|
||||
version: '1.0.0',
|
||||
size: 1024,
|
||||
cached_at: '2026-01-03T10:00:00Z',
|
||||
last_accessed: '2026-01-03T10:00:00Z',
|
||||
download_count: 1,
|
||||
vulnerabilities: {
|
||||
scanned: true,
|
||||
status: 'vulnerable',
|
||||
counts: full,
|
||||
total: full.critical + full.high + full.moderate + full.low,
|
||||
scannedAt: '2026-01-03T10:05:00Z',
|
||||
isBlocked: false,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
const ALL_SEVERITIES = 'critical,high,moderate,low'
|
||||
const FIXTURE: Package[] = [
|
||||
vulnerable('alpha-critical', { critical: 1 }),
|
||||
vulnerable('bravo-high', { high: 2 }),
|
||||
vulnerable('charlie-moderate', { moderate: 1 }),
|
||||
vulnerable('delta-mixed', { critical: 1, moderate: 3 }),
|
||||
]
|
||||
const NAMES = FIXTURE.map((p) => p.name)
|
||||
|
||||
let restore: (() => void) | undefined
|
||||
|
||||
beforeEach(() => {
|
||||
setActivePinia(createPinia())
|
||||
vi.mocked(axios.get).mockResolvedValue({ data: { packages: FIXTURE } })
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
restore?.()
|
||||
restore = undefined
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
async function open(path = '/vulnerable-packages') {
|
||||
const router = await createTestRouter(path)
|
||||
const pinia = createPinia()
|
||||
setActivePinia(pinia)
|
||||
const mounted = await mountStrict(VulnerablePackages, { global: { plugins: [pinia, router] } })
|
||||
restore = mounted.restore
|
||||
await flushPromises()
|
||||
return { ...mounted, router }
|
||||
}
|
||||
|
||||
type Wrapper = Awaited<ReturnType<typeof open>>['wrapper']
|
||||
|
||||
const tile = (wrapper: Wrapper, severity: string) => wrapper.get(`button[data-severity="${severity}"]`)
|
||||
const shown = (wrapper: Wrapper) => NAMES.filter((name) => wrapper.text().includes(name))
|
||||
const pressed = (wrapper: Wrapper) =>
|
||||
wrapper.findAll('button[data-severity]').map((b) => b.attributes('aria-pressed'))
|
||||
const clearButtons = (wrapper: Wrapper) => wrapper.findAll('button').filter((b) => b.text() === 'Clear filters')
|
||||
|
||||
describe('VulnerablePackages severity filter', () => {
|
||||
it('starts unfiltered: every vulnerable package, no tile pressed, no clear control', async () => {
|
||||
const { wrapper, problems, router } = await open()
|
||||
|
||||
expect(problems).toEqual([])
|
||||
expect(shown(wrapper)).toEqual(NAMES)
|
||||
expect(pressed(wrapper)).toEqual(['false', 'false', 'false', 'false'])
|
||||
expect(wrapper.text()).not.toContain('Filter on')
|
||||
expect(clearButtons(wrapper)).toHaveLength(0)
|
||||
expect(router.currentRoute.value.query.severity).toBeUndefined()
|
||||
})
|
||||
|
||||
it('asks the server for vulnerable packages only', async () => {
|
||||
await open()
|
||||
expect(axios.get).toHaveBeenCalledWith(`/api/packages?severity=${ALL_SEVERITIES}`)
|
||||
})
|
||||
|
||||
it('renders the four tiles as keyboard-operable buttons in severity order', async () => {
|
||||
const { wrapper } = await open()
|
||||
const tiles = wrapper.findAll('button[data-severity]')
|
||||
|
||||
expect(tiles.map((t) => t.attributes('data-severity'))).toEqual(['critical', 'high', 'moderate', 'low'])
|
||||
for (const t of tiles) {
|
||||
expect(t.element.tagName).toBe('BUTTON')
|
||||
expect(t.attributes('type')).toBe('button')
|
||||
expect(t.attributes('tabindex')).not.toBe('-1')
|
||||
expect(t.attributes('aria-pressed')).toBeDefined()
|
||||
}
|
||||
})
|
||||
|
||||
it('one click filters to that severity and shows the state in text, not colour alone', async () => {
|
||||
const { wrapper, router } = await open()
|
||||
|
||||
await tile(wrapper, 'high').trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
expect(shown(wrapper)).toEqual(['bravo-high'])
|
||||
expect(pressed(wrapper)).toEqual(['false', 'true', 'false', 'false'])
|
||||
expect(tile(wrapper, 'high').text()).toContain('Filter on')
|
||||
expect(tile(wrapper, 'critical').text()).not.toContain('Filter on')
|
||||
expect(wrapper.get('[data-testid="filter-bar"]').text()).toContain('Showing packages with high vulnerabilities.')
|
||||
expect(clearButtons(wrapper)).toHaveLength(1)
|
||||
expect(router.currentRoute.value.query.severity).toBe('high')
|
||||
})
|
||||
|
||||
it('keeps the tile counts of the whole list while a filter is on', async () => {
|
||||
const { wrapper } = await open()
|
||||
const before = tile(wrapper, 'critical').text()
|
||||
|
||||
await tile(wrapper, 'high').trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
expect(tile(wrapper, 'critical').text()).toBe(before)
|
||||
expect(tile(wrapper, 'critical').text()).toContain('2 packages')
|
||||
})
|
||||
|
||||
it('selects several severities with OR semantics', async () => {
|
||||
const { wrapper, router } = await open()
|
||||
|
||||
await tile(wrapper, 'critical').trigger('click')
|
||||
await flushPromises()
|
||||
expect(shown(wrapper)).toEqual(['alpha-critical', 'delta-mixed'])
|
||||
|
||||
await tile(wrapper, 'high').trigger('click')
|
||||
await flushPromises()
|
||||
expect(shown(wrapper)).toEqual(['alpha-critical', 'bravo-high', 'delta-mixed'])
|
||||
expect(pressed(wrapper)).toEqual(['true', 'true', 'false', 'false'])
|
||||
expect(router.currentRoute.value.query.severity).toBe('critical,high')
|
||||
expect(wrapper.get('[data-testid="filter-bar"]').text()).toContain('critical or high')
|
||||
})
|
||||
|
||||
it('a second click toggles the filter off and removes the query', async () => {
|
||||
const { wrapper, router } = await open()
|
||||
|
||||
await tile(wrapper, 'moderate').trigger('click')
|
||||
await flushPromises()
|
||||
expect(shown(wrapper)).toEqual(['charlie-moderate', 'delta-mixed'])
|
||||
|
||||
await tile(wrapper, 'moderate').trigger('click')
|
||||
await flushPromises()
|
||||
expect(shown(wrapper)).toEqual(NAMES)
|
||||
expect(pressed(wrapper)).toEqual(['false', 'false', 'false', 'false'])
|
||||
expect(clearButtons(wrapper)).toHaveLength(0)
|
||||
expect(router.currentRoute.value.query.severity).toBeUndefined()
|
||||
})
|
||||
|
||||
it('Clear filters resets every selected severity at once', async () => {
|
||||
const { wrapper, router } = await open()
|
||||
await tile(wrapper, 'critical').trigger('click')
|
||||
await tile(wrapper, 'high').trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
await clearButtons(wrapper)[0]!.trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
expect(shown(wrapper)).toEqual(NAMES)
|
||||
expect(pressed(wrapper)).toEqual(['false', 'false', 'false', 'false'])
|
||||
expect(router.currentRoute.value.query.severity).toBeUndefined()
|
||||
})
|
||||
|
||||
it('restores the filter from the URL, as after a reload or a shared link', async () => {
|
||||
const { wrapper } = await open('/vulnerable-packages?severity=high,critical')
|
||||
|
||||
expect(shown(wrapper)).toEqual(['alpha-critical', 'bravo-high', 'delta-mixed'])
|
||||
expect(pressed(wrapper)).toEqual(['true', 'true', 'false', 'false'])
|
||||
expect(clearButtons(wrapper)).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('ignores unknown severities in the URL and keeps the other query parameters', async () => {
|
||||
const { wrapper, router } = await open('/vulnerable-packages?severity=bogus&ref=mail')
|
||||
expect(shown(wrapper)).toEqual(NAMES)
|
||||
expect(clearButtons(wrapper)).toHaveLength(0)
|
||||
|
||||
await tile(wrapper, 'low').trigger('click')
|
||||
await flushPromises()
|
||||
expect(router.currentRoute.value.query).toEqual({ ref: 'mail', severity: 'low' })
|
||||
})
|
||||
|
||||
it('shows a library empty state with a clear control when no package matches', async () => {
|
||||
const { wrapper, router } = await open('/vulnerable-packages?severity=low')
|
||||
|
||||
const empty = wrapper.get('[data-slot="empty-state"]')
|
||||
expect(empty.text()).toContain('No packages match the filter')
|
||||
expect(shown(wrapper)).toEqual([])
|
||||
// The tiles stay so the filter can be changed without leaving the page.
|
||||
expect(pressed(wrapper)).toEqual(['false', 'false', 'false', 'true'])
|
||||
|
||||
await empty.findAll('button').find((b) => b.text() === 'Clear filters')!.trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
expect(shown(wrapper)).toEqual(NAMES)
|
||||
expect(wrapper.find('[data-slot="empty-state"]').exists()).toBe(false)
|
||||
expect(router.currentRoute.value.query.severity).toBeUndefined()
|
||||
})
|
||||
|
||||
it('keeps the success state when nothing is vulnerable, filter or not', async () => {
|
||||
vi.mocked(axios.get).mockResolvedValue({ data: { packages: [] } })
|
||||
const { wrapper } = await open('/vulnerable-packages?severity=critical')
|
||||
|
||||
expect(wrapper.text()).toContain('No vulnerable packages')
|
||||
expect(wrapper.find('button[data-severity]').exists()).toBe(false)
|
||||
})
|
||||
|
||||
it('still narrows to blocked packages on the blocked route', async () => {
|
||||
const blocked = vulnerable('echo-blocked', { critical: 1 })
|
||||
blocked.vulnerabilities!.isBlocked = true
|
||||
vi.mocked(axios.get).mockResolvedValue({ data: { packages: [...FIXTURE, blocked] } })
|
||||
const { wrapper } = await open('/blocked-packages?severity=critical')
|
||||
|
||||
expect(wrapper.text()).toContain('echo-blocked')
|
||||
expect(wrapper.text()).not.toContain('alpha-critical')
|
||||
})
|
||||
})
|
||||
@@ -23,7 +23,7 @@
|
||||
@retry="fetchVulnerablePackages"
|
||||
/>
|
||||
|
||||
<Card v-else-if="sortedVulnerablePackages.length === 0">
|
||||
<Card v-else-if="vulnerablePackages.length === 0">
|
||||
<CardContent>
|
||||
<EmptyState
|
||||
tone="success"
|
||||
@@ -35,9 +35,34 @@
|
||||
</Card>
|
||||
|
||||
<template v-else>
|
||||
<SeveritySummary :counts="totalCounts" label="Vulnerabilities by severity" />
|
||||
<SeveritySummary
|
||||
v-model="selectedSeverities"
|
||||
selectable
|
||||
:counts="totalCounts"
|
||||
:package-counts="packageCounts"
|
||||
label="Vulnerabilities by severity. Select a severity to filter the packages."
|
||||
/>
|
||||
|
||||
<Card>
|
||||
<div v-if="hasFilter" class="flex flex-wrap items-center justify-between gap-3" data-testid="filter-bar">
|
||||
<p class="text-sm text-muted-foreground" role="status">Showing packages with {{ filterSummary }} vulnerabilities.</p>
|
||||
<Button variant="outline" size="sm" @click="clearFilters">Clear filters</Button>
|
||||
</div>
|
||||
|
||||
<Card v-if="sortedVulnerablePackages.length === 0">
|
||||
<CardContent>
|
||||
<EmptyState
|
||||
:icon="faCircleCheck"
|
||||
title="No packages match the filter"
|
||||
:description="`No ${showOnlyBlocked ? 'blocked' : 'vulnerable'} package has a ${filterSummary} vulnerability.`"
|
||||
>
|
||||
<template #action>
|
||||
<Button variant="outline" @click="clearFilters">Clear filters</Button>
|
||||
</template>
|
||||
</EmptyState>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card v-else>
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">
|
||||
{{ showOnlyBlocked ? 'Blocked' : 'Vulnerable' }} packages ({{ sortedVulnerablePackages.length }})
|
||||
@@ -104,7 +129,7 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { useRouter, useRoute } from 'vue-router'
|
||||
import { usePackageStore, type Package } from '../stores/packages'
|
||||
import { usePackageStore, type Package, type VulnerabilityCounts } from '../stores/packages'
|
||||
import {
|
||||
Accordion,
|
||||
AccordionContent,
|
||||
@@ -128,12 +153,38 @@ import VulnerabilityBadge from './VulnerabilityBadge.vue'
|
||||
import SeveritySummary from './SeveritySummary.vue'
|
||||
import { formatBytes, formatDate, formatNumber, displayVersion, withVersionPrefix } from '@/lib/format'
|
||||
import { faArrowLeft, faCircleCheck } from '@/lib/icons'
|
||||
import { NO_VULNERABILITIES } from '@/lib/severity'
|
||||
import { NO_VULNERABILITIES, SEVERITY_LEVELS, formatSeverityName, type SeverityLevel } from '@/lib/severity'
|
||||
|
||||
const store = usePackageStore()
|
||||
const router = useRouter()
|
||||
const route = useRoute()
|
||||
|
||||
const SEVERITY_QUERY = 'severity'
|
||||
|
||||
/** Reads `?severity=critical,high`: known levels only, in severity order, each once. */
|
||||
function parseSeverityQuery(raw: unknown): SeverityLevel[] {
|
||||
const text = Array.isArray(raw) ? raw.join(',') : typeof raw === 'string' ? raw : ''
|
||||
const wanted = text.split(',').map((part) => part.trim().toLowerCase())
|
||||
return SEVERITY_LEVELS.filter((level) => wanted.includes(level))
|
||||
}
|
||||
|
||||
// The URL is the source of truth, so a reload or a shared link restores the filter.
|
||||
const selectedSeverities = computed<SeverityLevel[]>({
|
||||
get: () => parseSeverityQuery(route.query[SEVERITY_QUERY]),
|
||||
set: (levels) => {
|
||||
const { [SEVERITY_QUERY]: _previous, ...rest } = route.query
|
||||
void router.replace({ query: levels.length > 0 ? { ...rest, [SEVERITY_QUERY]: levels.join(',') } : rest })
|
||||
},
|
||||
})
|
||||
const hasFilter = computed(() => selectedSeverities.value.length > 0)
|
||||
const filterSummary = computed(() =>
|
||||
selectedSeverities.value.map((level) => formatSeverityName(level).toLowerCase()).join(' or '),
|
||||
)
|
||||
|
||||
function clearFilters() {
|
||||
selectedSeverities.value = []
|
||||
}
|
||||
|
||||
const loading = ref(false)
|
||||
const error = ref<string | null>(null)
|
||||
const vulnerablePackages = ref<Package[]>([])
|
||||
@@ -150,7 +201,8 @@ async function fetchVulnerablePackages() {
|
||||
error.value = null
|
||||
|
||||
try {
|
||||
await store.fetchPackages()
|
||||
// The server drops clean packages; the toggles below narrow the rest without another request.
|
||||
await store.fetchPackages({ severity: SEVERITY_LEVELS })
|
||||
// The store records a failed request in store.error and resolves; surface it instead of an empty list.
|
||||
if (store.error) {
|
||||
error.value = store.error
|
||||
@@ -171,9 +223,17 @@ async function fetchVulnerablePackages() {
|
||||
}
|
||||
}
|
||||
|
||||
// A package passes when it has at least one vulnerability of any selected severity.
|
||||
const filteredPackages = computed(() => {
|
||||
if (!hasFilter.value) return vulnerablePackages.value
|
||||
return vulnerablePackages.value.filter((pkg) =>
|
||||
selectedSeverities.value.some((level) => (pkg.vulnerabilities?.counts?.[level] ?? 0) > 0),
|
||||
)
|
||||
})
|
||||
|
||||
// Sort packages by risk: Critical count DESC, High count DESC, Moderate count DESC, Low count DESC
|
||||
const sortedVulnerablePackages = computed(() => {
|
||||
return [...vulnerablePackages.value].sort((a, b) => {
|
||||
return [...filteredPackages.value].sort((a, b) => {
|
||||
const aVulns = a.vulnerabilities?.counts || { critical: 0, high: 0, moderate: 0, low: 0 }
|
||||
const bVulns = b.vulnerabilities?.counts || { critical: 0, high: 0, moderate: 0, low: 0 }
|
||||
|
||||
@@ -227,7 +287,18 @@ const groupedPackages = computed(() => {
|
||||
return Array.from(groups.values())
|
||||
})
|
||||
|
||||
// Calculate total counts across all packages
|
||||
// Packages holding at least one vulnerability of each severity, before any filter.
|
||||
const packageCounts = computed<VulnerabilityCounts>(() => {
|
||||
const counts = { ...NO_VULNERABILITIES }
|
||||
for (const pkg of vulnerablePackages.value) {
|
||||
for (const level of SEVERITY_LEVELS) {
|
||||
if ((pkg.vulnerabilities?.counts?.[level] ?? 0) > 0) counts[level]++
|
||||
}
|
||||
}
|
||||
return counts
|
||||
})
|
||||
|
||||
// Calculate total counts across all packages, before any filter
|
||||
const totalCounts = computed(() =>
|
||||
vulnerablePackages.value.reduce(
|
||||
(sum, pkg) => {
|
||||
|
||||
@@ -12,7 +12,7 @@ import Stats from './Stats.vue'
|
||||
import VulnerabilityBadge from './VulnerabilityBadge.vue'
|
||||
import { __resetRealtimeSingleton, useRealtimeStore } from '@/stores/realtime'
|
||||
import { usePackageStore } from '@/stores/packages'
|
||||
import { BYPASSES, PACKAGES, REGISTRIES, STATS, TIMESERIES, VULNERABILITY_REPORT } from '@/test/fixtures'
|
||||
import { BYPASSES, PACKAGES, REGISTRIES, STATS, TIMESERIES, TREND, VULNERABILITY_REPORT } from '@/test/fixtures'
|
||||
import { mountStrict } from '@/test/mountStrict'
|
||||
import { createTestRouter } from '@/test/router'
|
||||
|
||||
@@ -22,6 +22,7 @@ const API_KEY_STORAGE = 'admin_api_key'
|
||||
|
||||
function respond(url: string) {
|
||||
if (url.startsWith('/api/stats/timeseries')) return { data: TIMESERIES }
|
||||
if (url.startsWith('/api/stats/trend')) return { data: TREND }
|
||||
if (url.startsWith('/api/stats')) return { data: { stats: STATS, registries: REGISTRIES } }
|
||||
if (url.endsWith('/vulnerabilities')) return { data: VULNERABILITY_REPORT }
|
||||
if (url.startsWith('/api/admin/bypasses')) return { data: { bypasses: BYPASSES } }
|
||||
@@ -208,7 +209,7 @@ describe('view smoke tests (strict mode throw, fixture data)', () => {
|
||||
|
||||
it('PackageList still fetches through the store on mount', async () => {
|
||||
await smoke(PackageList, '/packages')
|
||||
expect(usePackageStore().packages.length).toBe(PACKAGES.length)
|
||||
expect(usePackageStore().packagePage.packages.length).toBe(PACKAGES.length)
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { createPinia, setActivePinia } from 'pinia'
|
||||
import axios from 'axios'
|
||||
import { usePackageStore, RECENT_PACKAGES, type Package } from './packages'
|
||||
|
||||
vi.mock('axios')
|
||||
|
||||
function pkg(id: number, cachedAt: string, over: Partial<Package> = {}): Package {
|
||||
return {
|
||||
id: String(id),
|
||||
registry: 'npm',
|
||||
name: `p${id}`,
|
||||
version: '1.0.0',
|
||||
size: 1,
|
||||
cached_at: cachedAt,
|
||||
last_accessed: cachedAt,
|
||||
download_count: 0,
|
||||
...over,
|
||||
}
|
||||
}
|
||||
|
||||
describe('package store paging', () => {
|
||||
beforeEach(() => {
|
||||
setActivePinia(createPinia())
|
||||
vi.mocked(axios.get).mockReset()
|
||||
})
|
||||
afterEach(() => vi.restoreAllMocks())
|
||||
|
||||
it('sends page, page_size, registry and q; skips the all-registries and empty values', async () => {
|
||||
vi.mocked(axios.get).mockResolvedValue({ data: { packages: [], total_groups: 0 } })
|
||||
const store = usePackageStore()
|
||||
|
||||
await store.fetchPackagePage({ page: 2, pageSize: 25, registry: 'pypi', q: ' six ' })
|
||||
await store.fetchPackagePage({ page: 1, pageSize: 25, registry: 'all', q: '' })
|
||||
|
||||
expect(vi.mocked(axios.get).mock.calls.map((c) => c[0])).toEqual([
|
||||
'/api/packages?page=2&page_size=25®istry=pypi&q=six',
|
||||
'/api/packages?page=1&page_size=25',
|
||||
])
|
||||
})
|
||||
|
||||
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 } })
|
||||
await store.fetchPackagePage({ page: 3, pageSize: 25 })
|
||||
expect(store.packagePage).toMatchObject({ totalGroups: 80, page: 3, pageSize: 25 })
|
||||
|
||||
vi.mocked(axios.get).mockResolvedValueOnce({
|
||||
data: { packages: [pkg(1, '2026-01-01T00:00:00Z'), pkg(1, '2026-01-02T00:00:00Z', { version: '2.0.0' })] },
|
||||
})
|
||||
await store.fetchPackagePage({ page: 1, pageSize: 25 })
|
||||
expect(store.packagePage.totalGroups).toBe(1)
|
||||
})
|
||||
|
||||
it('drops the answer of a request a newer one has replaced', async () => {
|
||||
const store = usePackageStore()
|
||||
let release: (v: unknown) => void = () => {}
|
||||
vi.mocked(axios.get)
|
||||
.mockImplementationOnce(() => new Promise((resolve) => { release = resolve }))
|
||||
.mockResolvedValueOnce({ data: { packages: [pkg(2, '2026-01-01T00:00:00Z')], total_groups: 1 } })
|
||||
|
||||
const slow = store.fetchPackagePage({ page: 1, pageSize: 25, q: 'old' })
|
||||
await store.fetchPackagePage({ page: 1, pageSize: 25, q: 'new' })
|
||||
release({ data: { packages: [pkg(1, '2026-01-01T00:00:00Z')], total_groups: 1 } })
|
||||
await slow
|
||||
|
||||
expect(store.packagePage.packages.map((p) => p.id)).toEqual(['2'])
|
||||
expect(store.loading).toBe(false)
|
||||
})
|
||||
|
||||
it('reports a failed page request and leaves the last page in place', async () => {
|
||||
const store = usePackageStore()
|
||||
vi.spyOn(console, 'error').mockImplementation(() => {})
|
||||
vi.mocked(axios.get).mockResolvedValueOnce({ data: { packages: [pkg(1, '2026-01-01T00:00:00Z')], total_groups: 1 } })
|
||||
await store.fetchPackagePage({ page: 1, pageSize: 25 })
|
||||
vi.mocked(axios.get).mockRejectedValueOnce(new Error('502'))
|
||||
await store.fetchPackagePage({ page: 1, pageSize: 25 })
|
||||
|
||||
expect(store.error).toBe('502')
|
||||
expect(store.packagePage.packages).toHaveLength(1)
|
||||
expect(store.loading).toBe(false)
|
||||
})
|
||||
|
||||
it('recent packages: small page sorted by cached_at, newest ten rows, newest first', async () => {
|
||||
const rows = Array.from({ length: 14 }, (_, i) => pkg(i, `2026-01-${String(i + 1).padStart(2, '0')}T00:00:00Z`))
|
||||
vi.mocked(axios.get).mockResolvedValue({ data: { packages: rows, total_groups: 14 } })
|
||||
const store = usePackageStore()
|
||||
|
||||
await store.fetchRecentPackages()
|
||||
|
||||
expect(vi.mocked(axios.get)).toHaveBeenCalledWith(`/api/packages?page=1&page_size=${RECENT_PACKAGES}&sort=cached_at&order=desc`)
|
||||
expect(store.recentPackages).toHaveLength(RECENT_PACKAGES)
|
||||
expect(store.recentPackages[0].id).toBe('13')
|
||||
expect(store.recentPackages[9].id).toBe('4')
|
||||
})
|
||||
|
||||
it('loading stays on until the last overlapping request settles', async () => {
|
||||
const store = usePackageStore()
|
||||
const releases: Array<(v: unknown) => void> = []
|
||||
vi.mocked(axios.get).mockImplementation(() => new Promise((resolve) => releases.push(resolve)))
|
||||
|
||||
const stats = store.fetchStats()
|
||||
const recent = store.fetchRecentPackages()
|
||||
expect(store.loading).toBe(true)
|
||||
releases[0]({ data: { stats: { total_packages: 1 }, registries: {} } })
|
||||
await stats
|
||||
expect(store.loading).toBe(true)
|
||||
releases[1]({ data: { packages: [] } })
|
||||
await recent
|
||||
expect(store.loading).toBe(false)
|
||||
})
|
||||
|
||||
it('delete removes one version and leaves reloading to the caller', async () => {
|
||||
vi.mocked(axios.delete).mockResolvedValue({})
|
||||
const store = usePackageStore()
|
||||
await store.deletePackage('npm', 'left-pad', '1.0.0')
|
||||
expect(vi.mocked(axios.delete)).toHaveBeenCalledWith('/api/packages/npm/left-pad/1.0.0')
|
||||
expect(vi.mocked(axios.get)).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
+116
-10
@@ -44,18 +44,66 @@ export interface Stats {
|
||||
idle_ttl?: number
|
||||
}
|
||||
|
||||
export type PackageSort = 'name' | 'cached_at' | 'downloads' | 'size'
|
||||
|
||||
export interface PackagePageParams {
|
||||
page: number
|
||||
pageSize: number
|
||||
/** Empty or 'all' means every registry. */
|
||||
registry?: string
|
||||
/** Case-insensitive match on name, version or release version. */
|
||||
q?: string
|
||||
sort?: PackageSort
|
||||
order?: 'asc' | 'desc'
|
||||
}
|
||||
|
||||
/** One page of package groups: every version row of each group, in group order. */
|
||||
export interface PackagePage {
|
||||
packages: Package[]
|
||||
totalGroups: number
|
||||
page: number
|
||||
pageSize: number
|
||||
}
|
||||
|
||||
/** Rows shown under "Recent packages". */
|
||||
export const RECENT_PACKAGES = 10
|
||||
|
||||
function distinctGroups(rows: Package[]): number {
|
||||
return new Set(rows.map((p) => `${p.registry}\u0000${p.name}`)).size
|
||||
}
|
||||
|
||||
export const usePackageStore = defineStore('packages', () => {
|
||||
const packages = ref<Package[]>([])
|
||||
const packagePage = ref<PackagePage>({ packages: [], totalGroups: 0, page: 1, pageSize: 25 })
|
||||
const recentPackages = ref<Package[]>([])
|
||||
const stats = ref<Stats | null>(null)
|
||||
const registries = ref<Record<string, any>>({})
|
||||
const loading = ref(false)
|
||||
const error = ref<string | null>(null)
|
||||
|
||||
async function fetchPackages() {
|
||||
// Requests overlap (stats next to the recent list, a new search before the last answer),
|
||||
// so loading stays on until the last one settles.
|
||||
let inFlight = 0
|
||||
function begin() {
|
||||
inFlight++
|
||||
loading.value = true
|
||||
error.value = null
|
||||
}
|
||||
function settle() {
|
||||
inFlight = Math.max(inFlight - 1, 0)
|
||||
if (inFlight === 0) loading.value = false
|
||||
}
|
||||
let pageRequest = 0
|
||||
|
||||
/**
|
||||
* 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
|
||||
@@ -68,13 +116,68 @@ export const usePackageStore = defineStore('packages', () => {
|
||||
error.value = err.message
|
||||
// Don't clear packages on error - keep showing the cached data
|
||||
} finally {
|
||||
loading.value = false
|
||||
settle()
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchPackagePage(params: PackagePageParams) {
|
||||
const request = ++pageRequest
|
||||
begin()
|
||||
try {
|
||||
const query = new URLSearchParams({ page: String(params.page), page_size: String(params.pageSize) })
|
||||
if (params.registry && params.registry !== 'all') query.set('registry', params.registry)
|
||||
if (params.q?.trim()) query.set('q', params.q.trim())
|
||||
if (params.sort) query.set('sort', params.sort)
|
||||
if (params.order) query.set('order', params.order)
|
||||
const response = await axios.get(`/api/packages?${query.toString()}`)
|
||||
// A newer request is on its way; its answer must win.
|
||||
if (request !== pageRequest) return
|
||||
const data = response.data
|
||||
if (data && Array.isArray(data.packages)) {
|
||||
packagePage.value = {
|
||||
packages: data.packages,
|
||||
totalGroups: Number.isFinite(data.total_groups) ? data.total_groups : distinctGroups(data.packages),
|
||||
page: params.page,
|
||||
pageSize: params.pageSize,
|
||||
}
|
||||
} else {
|
||||
console.warn('Unexpected API response format:', data)
|
||||
error.value = 'Unexpected response format from server'
|
||||
}
|
||||
} catch (err: any) {
|
||||
if (request !== pageRequest) return
|
||||
console.error('Failed to fetch packages:', err)
|
||||
error.value = err.message
|
||||
} finally {
|
||||
settle()
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchRecentPackages() {
|
||||
begin()
|
||||
try {
|
||||
const response = await axios.get(
|
||||
`/api/packages?page=1&page_size=${RECENT_PACKAGES}&sort=cached_at&order=desc`,
|
||||
)
|
||||
if (response.data && Array.isArray(response.data.packages)) {
|
||||
// The page holds whole groups, so the newest rows are in there but not in order.
|
||||
recentPackages.value = [...response.data.packages]
|
||||
.sort((a: Package, b: Package) => new Date(b.cached_at).getTime() - new Date(a.cached_at).getTime())
|
||||
.slice(0, RECENT_PACKAGES)
|
||||
} else {
|
||||
console.warn('Unexpected API response format:', response.data)
|
||||
error.value = 'Unexpected response format from server'
|
||||
}
|
||||
} catch (err: any) {
|
||||
console.error('Failed to fetch recent packages:', err)
|
||||
error.value = err.message
|
||||
} finally {
|
||||
settle()
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchStats(registry = '') {
|
||||
loading.value = true
|
||||
error.value = null
|
||||
begin()
|
||||
try {
|
||||
const url = registry ? `/api/stats?registry=${registry}` : '/api/stats'
|
||||
const response = await axios.get(url)
|
||||
@@ -91,30 +194,33 @@ export const usePackageStore = defineStore('packages', () => {
|
||||
error.value = err.message
|
||||
// Don't clear stats on error - keep showing the cached data
|
||||
} finally {
|
||||
loading.value = false
|
||||
settle()
|
||||
}
|
||||
}
|
||||
|
||||
/** Deletes one version; the caller reloads whichever list it shows. */
|
||||
async function deletePackage(registry: string, name: string, version: string) {
|
||||
loading.value = true
|
||||
error.value = null
|
||||
begin()
|
||||
try {
|
||||
await axios.delete(`/api/packages/${registry}/${name}/${version}`)
|
||||
await fetchPackages()
|
||||
} catch (err: any) {
|
||||
error.value = err.message
|
||||
} finally {
|
||||
loading.value = false
|
||||
settle()
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
packages,
|
||||
packagePage,
|
||||
recentPackages,
|
||||
stats,
|
||||
registries,
|
||||
loading,
|
||||
error,
|
||||
fetchPackages,
|
||||
fetchPackagePage,
|
||||
fetchRecentPackages,
|
||||
fetchStats,
|
||||
deletePackage,
|
||||
}
|
||||
|
||||
@@ -53,6 +53,22 @@ describe('useRealtimeStore', () => {
|
||||
expect(store.lastStats).toMatchObject({ total_packages: 42, total_size: 1024 })
|
||||
})
|
||||
|
||||
it('unwraps the server stats_update shape {stats, timestamp}', () => {
|
||||
const store = useRealtimeStore()
|
||||
store.ingest(
|
||||
makeEvent('stats_update', {
|
||||
stats: { total_packages: 1454, total_size: 980870617, total_downloads: 5376, scanned_packages: 1451 },
|
||||
timestamp: '2026-11-23T16:00:00Z',
|
||||
}),
|
||||
)
|
||||
expect(store.lastStats).toMatchObject({
|
||||
total_packages: 1454,
|
||||
total_size: 980870617,
|
||||
total_downloads: 5376,
|
||||
scanned_packages: 1451,
|
||||
})
|
||||
})
|
||||
|
||||
it('exposes filtered computed slices', () => {
|
||||
const store = useRealtimeStore()
|
||||
store.ingest(makeEvent('package_cached'))
|
||||
|
||||
@@ -55,7 +55,9 @@ export const useRealtimeStore = defineStore('realtime', () => {
|
||||
events.value.splice(0, events.value.length - EVENTS_CAP)
|
||||
}
|
||||
if (event.type === 'stats_update') {
|
||||
lastStats.value = event.payload as RealtimeStats
|
||||
// The server nests the counters under `stats`; reading the payload flat shows zeros.
|
||||
const nested = event.payload.stats
|
||||
lastStats.value = (nested && typeof nested === 'object' ? nested : event.payload) as RealtimeStats
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/DataTable/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/DescriptionList/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/KpiTile/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/LineChart/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/Sparkline/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/StatGroup/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/Table/*.js";
|
||||
@@ -59,6 +60,8 @@
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/primitives/Spinner/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/primitives/StatusBadge/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/primitives/StatusDot/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/primitives/Toggle/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/primitives/ToggleGroup/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/typography/Markdown/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/typography/Markdown/parse/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/typography/RelativeTime/*.js";
|
||||
|
||||
@@ -158,3 +158,19 @@ export const BYPASSES = [
|
||||
active: false,
|
||||
},
|
||||
]
|
||||
|
||||
function trendDay(offset: number): string {
|
||||
return new Date(Date.UTC(2026, 0, 4 + offset)).toISOString().slice(0, 10)
|
||||
}
|
||||
|
||||
export const TREND = {
|
||||
period: '30day',
|
||||
from: trendDay(-2),
|
||||
to: trendDay(0),
|
||||
vulnerability_history_start: trendDay(-1),
|
||||
points: [
|
||||
{ date: trendDay(-2), total_packages: 3, total_size: 3072, vulnerable_packages: null, critical: null, high: null, moderate: null, low: null, blocked: null },
|
||||
{ date: trendDay(-1), total_packages: 4, total_size: 7168, vulnerable_packages: 1, critical: 0, high: 1, moderate: 0, low: 0, blocked: null },
|
||||
{ date: trendDay(0), total_packages: 4, total_size: 7168, vulnerable_packages: 2, critical: 1, high: 1, moderate: 0, low: 0, blocked: 1 },
|
||||
],
|
||||
}
|
||||
|
||||
@@ -10,8 +10,10 @@ data:
|
||||
host: {{ .Values.server.host | quote }}
|
||||
port: {{ .Values.server.port }}
|
||||
read_timeout: {{ .Values.server.readTimeout | quote }}
|
||||
read_buffer_size: {{ .Values.server.readBufferSize }}
|
||||
write_timeout: {{ .Values.server.writeTimeout | quote }}
|
||||
idle_timeout: {{ .Values.server.idleTimeout | quote }}
|
||||
allowed_origins: {{ .Values.server.allowedOrigins | default list | toJson }}
|
||||
tls:
|
||||
enabled: false
|
||||
|
||||
@@ -74,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:
|
||||
@@ -86,6 +89,10 @@ data:
|
||||
block_on_severity: {{ .Values.security.blockOnSeverity | quote }}
|
||||
scan_on_download: {{ .Values.security.scanOnDownload }}
|
||||
rescan_interval: {{ .Values.security.rescanInterval | quote }}
|
||||
rescan_active_window: {{ .Values.security.rescanActiveWindow | quote }}
|
||||
rescan_concurrency: {{ .Values.security.rescanConcurrency }}
|
||||
rescan_on_access: {{ .Values.security.rescanOnAccess }}
|
||||
scan_wait_timeout: {{ .Values.security.scanWaitTimeout | quote }}
|
||||
update_db_on_startup: {{ .Values.security.updateDbOnStartup }}
|
||||
block_thresholds:
|
||||
critical: {{ .Values.security.blockThresholds.critical }}
|
||||
|
||||
@@ -91,8 +91,11 @@ server:
|
||||
host: "0.0.0.0"
|
||||
port: 8080
|
||||
readTimeout: "5m"
|
||||
readBufferSize: 16384 # Bytes for the request line plus headers; larger requests get 431
|
||||
writeTimeout: "5m"
|
||||
idleTimeout: "2m"
|
||||
# Browser origins allowed to use /api and /ws; empty = same-origin only
|
||||
allowedOrigins: []
|
||||
|
||||
# Additional environment variables for server container
|
||||
# Use this to override config via environment variables
|
||||
@@ -375,15 +378,16 @@ migration:
|
||||
|
||||
# Cache configuration
|
||||
cache:
|
||||
defaultTTL: "168h" # 7 days
|
||||
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:
|
||||
npm: "168h"
|
||||
pip: "168h"
|
||||
go: "168h"
|
||||
ttlOverrides: # Per-registry metadata freshness; replaces defaultTTL for that registry. Keys: npm, pypi, go
|
||||
npm: "24h"
|
||||
pypi: "24h"
|
||||
go: "24h"
|
||||
|
||||
# Security scanning configuration
|
||||
security:
|
||||
@@ -391,6 +395,10 @@ security:
|
||||
blockOnSeverity: "high" # none, low, medium, high, critical
|
||||
scanOnDownload: true
|
||||
rescanInterval: "24h"
|
||||
rescanActiveWindow: "0s" # rescan only packages requested within this window; 0 = all
|
||||
rescanConcurrency: 1 # scans run in parallel per rescan cycle
|
||||
rescanOnAccess: false # rescan a stale cache hit before serving it
|
||||
scanWaitTimeout: "30s" # how long a first download waits for its scan
|
||||
updateDbOnStartup: false
|
||||
|
||||
blockThresholds:
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
// Package dbcount counts the SQL statements a GORM handle runs, for query-count tests.
|
||||
package dbcount
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/logger"
|
||||
)
|
||||
|
||||
// Counter holds the number of statements seen since the last Reset.
|
||||
type Counter struct {
|
||||
n atomic.Int64
|
||||
}
|
||||
|
||||
// Attach returns a session of db that counts every statement it executes. It
|
||||
// swaps the logger instead of registering callbacks, because callback
|
||||
// registration is not safe while other goroutines already run queries.
|
||||
// GORM runs a subquery as a dry run with a discarded logger, so subqueries do not count.
|
||||
func Attach(db *gorm.DB) (*gorm.DB, *Counter) {
|
||||
c := &Counter{}
|
||||
return db.Session(&gorm.Session{Logger: &countingLogger{Interface: logger.Discard, c: c}}), c
|
||||
}
|
||||
|
||||
// Reset zeroes the count.
|
||||
func (c *Counter) Reset() { c.n.Store(0) }
|
||||
|
||||
// Count returns the statements counted since the last Reset.
|
||||
func (c *Counter) Count() int { return int(c.n.Load()) }
|
||||
|
||||
type countingLogger struct {
|
||||
logger.Interface
|
||||
c *Counter
|
||||
}
|
||||
|
||||
func (l *countingLogger) LogMode(logger.LogLevel) logger.Interface { return l }
|
||||
|
||||
func (l *countingLogger) Trace(context.Context, time.Time, func() (string, int64), error) {
|
||||
l.c.n.Add(1)
|
||||
}
|
||||
+61
-7
@@ -20,6 +20,19 @@ Currency: `sh lean4/scripts/check_currency.sh origin/main`.
|
||||
| GH-07 | get vs purge | a purge between probe and open does not fail the request | correctness | low | `Cache.getOnce_errors_on_purge`, `getRetry_survives_one_purge` / `TestGetRecoversFromPurgeBetweenProbeAndOpen` | 990a1d3 |
|
||||
| GH-08 | stats rollup | every completed day still held hourly is rolled up | correctness (data loss) | medium | `Stats.old_loses_day_on_one_skip`, `new_repairs_after_skip`, `early_tick_leaves_last_hour` / `TestDailyRollupKeepsLastHourOfDay`, `TestDailyRollupCoversMissedDay`, `TestPostgresDailyRollupCoversMissedDay` | ad4e848 |
|
||||
| GH-09 | stats chart | a rollup never hides downloads counted after it ran | correctness | low | `Stats.chartOld_drops_late_download`, `chartNew_sound` / `TestTimeSeriesKeepsLateDownloadsAheadOfRollup` | 7192e4f |
|
||||
| GH-15 | release age | a cached packument or index stays fresh no longer than the client's 72h release-age gate | correctness (config default) | low | `Release.compiled_ttl_within_gate`, `old_default_ttl_exceeded_gate` / `TestMetadataEntryDefaultTTLIsBelowReleaseAgeGate`, `TestMetadataEntryExplicitTTLWins`, `TestDefaultMetadataTTL`, `TestShippedExamplesKeepMetadataTTLWithinGate` | 549d56e |
|
||||
| GH-17 | CORS, auth off | a page at a foreign origin cannot read `/api` or change state through a visitor's browser | security, CWE-352 / CWE-942 | medium with `auth.enabled: false` | `Access.old_cors_admits_any_page`, `fixed_refuses_foreign_origin` / `TestAPIDeleteFromDisallowedOriginForbidden`, `TestAPIDeleteFromAllowedOriginWorks`, `TestAPIPreflightAnswersOnlyAllowedOrigins`, `TestAPIGetStaysPublicWithoutWildcardCORS`, `TestAPISameOriginRuleWhenNoOriginsConfigured` | f204938 |
|
||||
| GH-18 | api keys | `ValidateAPIKey` costs one bcrypt compare, whatever the number of stored keys | hardening, CWE-400 | low | `Access.old_cost_grows_with_keys`, `new_cost_independent_of_keys` / `TestValidateAPIKeyCostIndependentOfKeyCount`, `TestLegacyComparesAreConcurrencyBounded` | ae5167f |
|
||||
| GH-19 | SSRF | every redirect hop passes the upstream allowlist, the scheme rule and a non-private address check | security, CWE-918 | medium | `Access.redirect_escapes_allowlist`, `fixed_redirect_stays_allowlisted` / `TestRedirectToDisallowedHostRefused`, `TestRedirectToLoopbackRefused`, `TestRedirectToPrivateLiteralRefused`, `TestRedirectAllowedToAllowedWorks`, `TestRedirectHopsCapped`, `TestSidecarRedirectOffAllowlistRefused` | 787c757 |
|
||||
| GH-20 | stats, sqlite | SQLite upserts hourly and daily rows as PostgreSQL does, one row per bucket | correctness | low (SQLite only) | `Stats.old_sqlite_duplicates_rows`, `fixed_sqlite_package_row_keeps_late_events` / `TestSQLiteHourlyTotalsMatchPostgresSemantics`, `TestPostgresHourlyTotalsMatchSQLite`, `TestSQLiteDailyRollupIsIdempotent`, `TestSQLiteStatsDedupeMigration` | f46e079 |
|
||||
| GH-21 | scan retry | a scan retry on S3 or SMB storage reads the stored blob instead of a removed temp file | correctness | low (file-based scanners on remote storage) | `Security.old_remote_retry_unreadable`, `fixed_retry_always_readable` / `TestScanRetryOnRemoteStorageReadsBlobAgain` | 31db940 |
|
||||
| GH-22 | dashboard API | an OIDC-logged-in browser can call `/api` with a long URL; the proxy hop neither forwards session cookies nor exceeds the read buffer | availability | medium (every `/api` call returned 431 for OIDC users) | not modelled (header size, no decision logic) / `TestLargeRequestHeadersAreAccepted`, `TestReadBufferSizeIsConfigurable`, `scripts/check_frontend_cookie_strip.sh` | 536f35a |
|
||||
| GH-23 | PyPI sidecar | pip's PEP 658 request (`<link>.metadata`, suffix on `original_url`) is served as its wheel's sidecar; another file's sidecar is still refused | correctness (pip install failed with 400) | medium (every pip install through the proxy) | `Access.pip_form_keeps_key_binding`, `pip_sidecar_of_other_file_rejected`, `pip_sidecar_of_same_file_accepted` / `TestPipSidecarFormIsStreamed`, `TestHandlePackageFile_OriginalURLFilenameBound` | 501bf1a |
|
||||
| GH-24 | rescan | with `security.rescan_interval` set, artifacts whose scan never completed are scanned and old results refreshed | correctness (scans lost to a restart stayed unscanned; new CVEs never picked up) | medium | not modelled (worker wiring) / `TestWorkersStartTheRescanWorker` | 378b873 |
|
||||
| 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 |
|
||||
| GH-27 | scanners | govulncheck counts findings in the scanned module only; dependency findings (minimum versions from its go.mod) and stdlib findings (the scanner toolchain) no longer attach to it | correctness (false vulnerable, and a false block when a dependency finding is critical) | medium (golang.org/x/net v0.56.0 carried x/crypto and x/text advisories on production) | `TestScanIgnoresFindingsInDependencies`, `TestScanReadsPrettyPrintedFindings` | 775ed8a |
|
||||
| GH-28 | scanners | OSV takes the fixed version from the range of the queried package | display (x/net findings showed the stdlib fix 1.26.9 instead of 0.60.0) | low | `TestScan_FixedVersionComesFromTheQueriedPackage` | fac30f5 |
|
||||
|
||||
### Exploit paths and reach
|
||||
|
||||
@@ -30,9 +43,56 @@ Currency: `sh lean4/scripts/check_currency.sh origin/main`.
|
||||
- **GH-03.** Live check against `api.osv.dev` for requests 2.19.0: the release version returns 10 advisories; the file name
|
||||
returns 12, missing PYSEC-2023-74 and GHSA-j8r2-6x86-q33q. Production has `block_on_severity: none`, so it shows wrong
|
||||
scan results rather than serving blocked packages; any deployment with a block policy served such packages.
|
||||
- **GH-17.** A page at any origin issued `DELETE /api/packages/<registry>/<name>/<version>` from a visitor's browser, and
|
||||
`Access-Control-Allow-Origin: *` let it read every `/api` response. Reach: any visitor to a hostile page when
|
||||
`auth.enabled` is false (production); impact is cache eviction. Fixed by `apiOriginGuard` against `server.allowed_origins`;
|
||||
with none set, only same-origin passes.
|
||||
- **GH-19.** An allowed host that answered 302 reached any target (`169.254.169.254`, `127.0.0.1`, `10.x`), by name or by
|
||||
DNS rebinding. No allowed host redirects today; the fix removes the dependency on that. Hops are capped at 10, limited to
|
||||
http(s), vetted against the allowlist, and a hop to another host dials through a guard that refuses private, loopback,
|
||||
link-local and carrier-grade addresses after resolution. A redirect inside one host is left alone: a private index is
|
||||
operator-trusted.
|
||||
- **GH-04.** The publisher of an npm or PyPI package named `x.info` skipped the scan and the block policy. Reach: any package
|
||||
publisher; needs a block policy to matter.
|
||||
|
||||
### Notes on the fixed rows
|
||||
|
||||
- **GH-15.** `cache.ttl_overrides` now has a consumer: `cache.Config.TTLOverrides` sets the metadata freshness per registry
|
||||
(`npm`, `pypi`, `go`; `pip` is an alias of `pypi`), and a registry without an override keeps `default_ttl`. Artifacts keep no
|
||||
age expiry. Defaults hold no override, so lowering `default_ttl` still applies everywhere. Config load rejects an unknown
|
||||
registry key or a non-positive value. Tests: `TestMetadataTTLOverridesApplyPerRegistry`, `TestMetadataTTLOverridesSkipArtifacts`,
|
||||
`TestNPMMetadataTTLOverrideReachesCache`, `TestTTLOverridesValidation`.
|
||||
- **GH-18.** New keys read `ghk_<id>.<secret>`; the hash covers the secret and one lookup selects the stored key. A miss
|
||||
compares a dummy hash. Keys minted before are accepted through a legacy path capped at 4 concurrent bcrypt compares. They
|
||||
cannot be migrated: the raw key holds no id and the stored hash covers the whole raw key. Re-issue them to leave the
|
||||
legacy path. Production holds none.
|
||||
- **GH-20.** SQLite startup merges old duplicate rows (package rows add up, derived rows keep one) and creates the unique indexes.
|
||||
- **GH-21.** `RescanWorker` reads each blob through the cache `ScanFile` source, so periodic rescans cover S3 and SMB as well as
|
||||
local storage. A remote blob is copied to a temp file for the scan and removed after it. Test: `TestRescanWorkerScansRemoteStorage`.
|
||||
- **GH-22.** Frontend nginx dropped the `Cookie` header on `/api/` and `/ws` (the backend reads none; keys travel in `Authorization` / `X-API-Key`).
|
||||
The server read buffer is `server.read_buffer_size`, default 16384 (Fiber's default is 8192): a long Referer or `Authorization` no longer gets 431.
|
||||
- **GH-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
|
||||
|
||||
| id | area | claim | verdict | why |
|
||||
@@ -41,14 +101,8 @@ 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-15 | release age | a cached packument or index hides new or yanked entries for up to the TTL | by-design | Quoted intent, `pkg/cache/cache.go` store: "TRADEOFF: metadata pages share the cache's DefaultTTL and are not refreshed based on upstream Cache-Control". Passthrough proved: `Release.rewrite_preserves_upload_time`, `stale_hides_only_gated` (needs TTL <= gate; production 24h <= 72h holds, the compiled default 168h does not, and then the proxy is stricter than the gate). |
|
||||
| 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`. |
|
||||
| GH-17 | auth off | with `auth.enabled: false` (production) `DELETE /api/packages/*` is unauthenticated, and `Access-Control-Allow-Origin: *` lets a browser page issue it | by-design, product decision | Quoted intent, `pkg/app/app.go`: "routes are mounted bare to preserve backward-compatible public access". Impact is cache eviction only. Enabling auth is a configuration change the operator owns. |
|
||||
| GH-18 | api keys | `ValidateAPIKey` bcrypt-compares every stored key per request | hardening, CWE-400 | N keys cost N bcrypt checks per bad key. A key-id prefix needs an API change. Zero keys in production. |
|
||||
| GH-19 | SSRF | `network.Client` follows redirects without re-checking the allowlist | hardening | `Access.redirect_escapes_allowlist`. No allowed host redirects (pypi.org, files.pythonhosted.org); a private index host is operator-trusted. |
|
||||
| GH-20 | stats, sqlite | `INSERT OR REPLACE` has no unique index on SQLite, so every pass duplicates registry rows | correctness, SQLite only | Seen in a row dump (three NULL-package hourly rows for one bucket after three passes). Production is PostgreSQL, where `statsUpsertIndexes` exist. Needs a dedupe migration; left open. |
|
||||
| GH-21 | scan retry | a retry on S3 or SMB storage rescans a temp file already removed | suspected, unconfirmed | `cache.go` store removes `tempPath` after the first scan. Production is filesystem. No test written. |
|
||||
|
||||
### Decision: `fail_closed: false` with recurring infrastructure errors
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ import Mathlib
|
||||
|
||||
Models `pkg/app/app.go` `buildCheckOrigin` / `normalizeOriginHost`, `pkg/app/handlers_admin.go`
|
||||
`requireAdmin`, `pkg/auth/auth.go` (`getPermissionsForRole`, `ValidateAPIKey` expiry),
|
||||
`pkg/proxy/pypi/pypi.go` (`isAllowedPyPIHost`, the `original_url` guards), `Dockerfile.frontend`.
|
||||
`pkg/proxy/pypi/pypi.go` (`isAllowedPyPIHost`, the `original_url` guards, `get`), `pkg/network/client.go` (`send`), `pkg/auth/auth.go` (`ValidateAPIKey` cost), `pkg/app/cors.go` (`apiOriginGuard`), `Dockerfile.frontend`.
|
||||
Omits: the TLS layer, bcrypt internals, DNS.
|
||||
-/
|
||||
|
||||
@@ -121,19 +121,92 @@ 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
|
||||
|
||||
/-- The allowlist is checked once, on the first hop. `network.Client` follows redirects without
|
||||
re-checking, so an allowed host that answers 302 reaches any target. Acceptable only while no
|
||||
allowed host redirects (pypi.org and files.pythonhosted.org do not). -/
|
||||
def hopAllowed (hops : List String) : Bool := hops.head?.any hostAllowed
|
||||
/-- Before the fix the allowlist was checked once, on the first hop. `network.Client` followed
|
||||
redirects without re-checking, so an allowed host that answers 302 reached any target. -/
|
||||
def hopAllowedOld (hops : List String) : Bool := hops.head?.any hostAllowed
|
||||
|
||||
/-- After the fix (`network.Client.send`, `pypi.Handler.get`) every hop must pass the allowlist. -/
|
||||
def hopAllowed (hops : List String) : Bool := hops.all hostAllowed
|
||||
|
||||
theorem redirect_escapes_allowlist :
|
||||
hopAllowed ["files.pythonhosted.org", "169.254.169.254"] = true ∧
|
||||
hopAllowedOld ["files.pythonhosted.org", "169.254.169.254"] = true ∧
|
||||
hostAllowed "169.254.169.254" = false := by decide
|
||||
|
||||
theorem fixed_redirect_stays_allowlisted :
|
||||
hopAllowed ["pypi.org", "files.pythonhosted.org"] = true ∧
|
||||
hopAllowed ["files.pythonhosted.org", "169.254.169.254"] = false := by decide
|
||||
|
||||
/-- A hop is accepted only if every hop is on the allowlist. -/
|
||||
theorem hopAllowed_implies_each (hops : List String) (h : hopAllowed hops = true) :
|
||||
∀ x ∈ hops, hostAllowed x = true := by
|
||||
simpa [hopAllowed] using h
|
||||
|
||||
/-! ### API key validation cost (`pkg/auth/auth.go` `ValidateAPIKey`) -/
|
||||
|
||||
/-- bcrypt compares for one request when every stored key is a candidate (before the fix). -/
|
||||
def compareCostOld (storedKeys : ℕ) : ℕ := storedKeys
|
||||
|
||||
/-- A key carrying its id selects one stored key: one compare, hit or miss (a miss compares a dummy hash). -/
|
||||
def compareCostNew (_storedKeys : ℕ) : ℕ := 1
|
||||
|
||||
theorem old_cost_grows_with_keys : compareCostOld 1000 = 1000 := rfl
|
||||
|
||||
theorem new_cost_independent_of_keys (n m : ℕ) : compareCostNew n = compareCostNew m := rfl
|
||||
|
||||
/-! ### Cross-origin writes on `/api` (`pkg/app/cors.go` `apiOriginGuard`) -/
|
||||
|
||||
/-- Before the fix every handler answered `Access-Control-Allow-Origin: *`, so any page could call them. -/
|
||||
def corsOld (_ : Origin) : Bool := true
|
||||
|
||||
/-- After the fix a state-changing request passes iff it names no origin (non-browser client) or an
|
||||
allowed one; the same rule as the WebSocket origin check. -/
|
||||
def writeAllowed (rules : List Origin) : Option Origin → Bool
|
||||
| none => true
|
||||
| some o => rules.any (fun r => matchesExact r o)
|
||||
|
||||
def dashboard : Origin := ⟨Scheme.https, "gohoarder.example.com".toList, none⟩
|
||||
def attacker : Origin := ⟨Scheme.https, "evil.example.net".toList, none⟩
|
||||
|
||||
theorem old_cors_admits_any_page : corsOld attacker = true := rfl
|
||||
|
||||
theorem fixed_refuses_foreign_origin : writeAllowed [dashboard] (some attacker) = false := by decide
|
||||
|
||||
theorem fixed_admits_dashboard_and_cli :
|
||||
writeAllowed [dashboard] (some dashboard) = true ∧ writeAllowed [dashboard] none = true := by decide
|
||||
|
||||
/-- With nothing configured only a request with no origin passes the allowlist step; browsers fall to the
|
||||
same-origin host comparison in the handler. -/
|
||||
theorem empty_allowlist_refuses_any_origin (o : Origin) : writeAllowed [] (some o) = false := by
|
||||
simp [writeAllowed]
|
||||
|
||||
/-! ### Frontend blocklist (`Dockerfile.frontend`) -/
|
||||
|
||||
/-- `location ~ ^/(npm|pypi|go|metrics)(/|$)` on the normalised URI. -/
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -47,15 +47,36 @@ theorem stale_hides_only_gated (gate ttl now s t : ℤ) (hstale : now - s ≤ tt
|
||||
(hnew : s < t) : ¬ gateAccepts gate now t := by
|
||||
unfold gateAccepts; omega
|
||||
|
||||
/-- Production: `default_ttl: 24h` against a 72h gate. -/
|
||||
theorem prod_ttl_within_gate : (24 : ℤ) ≤ 72 := by decide
|
||||
/-- Production and, since the fix, the compiled default (`config.DefaultMetadataTTL`): 24h against a 72h gate. -/
|
||||
theorem compiled_ttl_within_gate : (24 : ℤ) ≤ 72 := by decide
|
||||
|
||||
/-- The compiled default is 7 days. Against a 72h gate a version aged 84h is eligible but absent
|
||||
from a 7-day-old snapshot: the proxy withholds it, which is stricter than the gate, never looser. -/
|
||||
theorem default_ttl_exceeds_gate :
|
||||
/-- The compiled default used to be 7 days. Against a 72h gate a version aged 84h is eligible but
|
||||
absent from a 7-day-old snapshot: the proxy withheld it, stricter than the gate, never looser. -/
|
||||
theorem old_default_ttl_exceeded_gate :
|
||||
∃ gate ttl now s t : ℤ, now - s ≤ ttl ∧ s < t ∧ gateAccepts gate now t ∧ ttl = 168 ∧ gate = 72 := by
|
||||
exact ⟨72, 168, 200, 100, 116, by decide, by decide, by unfold gateAccepts; decide, rfl, rfl⟩
|
||||
|
||||
/-! ### Per-registry override (`cache.ttl_overrides`, `Manager.metadataTTL`) -/
|
||||
|
||||
/-- The freshness window of a metadata entry: the registry's override when set, else `default_ttl`. -/
|
||||
def effectiveTtl (override : Option ℤ) (default : ℤ) : ℤ := override.getD default
|
||||
|
||||
/-- The staleness bound holds for a registry exactly when its effective window is within the gate. -/
|
||||
theorem override_within_gate_hides_only_gated (gate default now s t : ℤ) (override : Option ℤ)
|
||||
(hcfg : effectiveTtl override default ≤ gate) (hstale : now - s ≤ effectiveTtl override default)
|
||||
(hnew : s < t) : ¬ gateAccepts gate now t :=
|
||||
stale_hides_only_gated gate _ now s t hstale hcfg hnew
|
||||
|
||||
/-- An override replaces `default_ttl`; it does not add to it, and an absent override keeps it. -/
|
||||
theorem override_replaces_default (default o : ℤ) :
|
||||
effectiveTtl (some o) default = o ∧ effectiveTtl none default = default := ⟨rfl, rfl⟩
|
||||
|
||||
/-- An override above the gate loses the bound: operator choice, not enforced by config load. -/
|
||||
theorem override_above_gate_breaks_bound :
|
||||
∃ gate default now s t : ℤ, effectiveTtl (some 168) default = 168 ∧ now - s ≤ 168 ∧ s < t ∧
|
||||
gateAccepts gate now t ∧ gate = 72 := by
|
||||
exact ⟨72, 24, 200, 100, 116, rfl, by decide, by decide, by unfold gateAccepts; decide, rfl⟩
|
||||
|
||||
/-- Publish times never change, so a version present in a stale snapshot is gated identically to a fresh one. -/
|
||||
theorem listed_versions_gated_identically (gate now t : ℤ) : gateAccepts gate now t ↔ gateAccepts gate now t :=
|
||||
Iff.rfl
|
||||
|
||||
@@ -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.
|
||||
@@ -137,6 +137,20 @@ theorem infra_error_served_forever (policy : Option ℕ) (now : ℤ) (bs : List
|
||||
/-- Scanner disabled: `CheckVulnerabilities` returns `(false, "", nil)` and `cache.New` drops the scanner. -/
|
||||
def servesDisabled : Bool := true
|
||||
|
||||
/-! ### Retry input (`pkg/cache/cache.go` `store`, `ScanFile`; `scheduleRetry`) -/
|
||||
|
||||
/-- Before the fix a retry reused the first scan's path. Remote storage scans a temp file removed
|
||||
after the first attempt, so only local backends kept it. -/
|
||||
def retryReadableOld (localBackend : Bool) : Bool := localBackend
|
||||
|
||||
/-- After the fix a retry whose file is gone re-reads the blob through the file source. -/
|
||||
def retryReadableNew (localBackend fileSourceSet : Bool) : Bool := localBackend || fileSourceSet
|
||||
|
||||
theorem old_remote_retry_unreadable : retryReadableOld false = false := rfl
|
||||
|
||||
theorem fixed_retry_always_readable : retryReadableNew false true = true ∧ retryReadableNew true false = true := by
|
||||
decide
|
||||
|
||||
/-! ### Retry budget -/
|
||||
|
||||
def maxRetries : ℕ := 6
|
||||
@@ -179,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
|
||||
@@ -193,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
|
||||
|
||||
@@ -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
|
||||
@@ -87,4 +91,132 @@ theorem chartNew_never_drops (rollup live : ℕ) : chartOld rollup live ≤ char
|
||||
/-- A download aggregated after the rollup ran: the old chart shows 1 of 2. -/
|
||||
theorem chartOld_drops_late_download : chartOld 1 2 < chartNew 1 2 := by decide
|
||||
|
||||
/-! ### SQLite upsert (`aggregation_worker.go`, `sqlite_stats.go`) -/
|
||||
|
||||
/-- A bucket is a list of stored rows; the chart sums them. Before the fix SQLite had no unique index,
|
||||
so `INSERT OR REPLACE` appended a row per pass. -/
|
||||
def chartTotal (rows : List ℕ) : ℕ := rows.sum
|
||||
|
||||
/-- Three passes over a bucket whose registry total is 3: three copies. -/
|
||||
theorem old_sqlite_duplicates_rows : chartTotal [3, 3, 3] ≠ 3 := by decide
|
||||
|
||||
/-- `ON CONFLICT ... DO UPDATE` over the unique index keeps one row per bucket: a derived row is set,
|
||||
a package row adds the new events, as on PostgreSQL. -/
|
||||
def upsertDerived (_old new : ℕ) : List ℕ := [new]
|
||||
def upsertAdditive (old new : ℕ) : List ℕ := [old + new]
|
||||
|
||||
theorem fixed_sqlite_registry_row_idempotent (old new : ℕ) :
|
||||
chartTotal (upsertDerived old new) = new := by simp [chartTotal, upsertDerived]
|
||||
|
||||
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
|
||||
|
||||
@@ -181,6 +181,7 @@ CREATE TABLE IF NOT EXISTS scan_results (
|
||||
FOREIGN KEY (package_id) REFERENCES packages(id) ON DELETE CASCADE ON UPDATE CASCADE,
|
||||
|
||||
INDEX idx_scan_package_scanner (package_id, scanner, deleted_at),
|
||||
INDEX idx_scan_package_scanned_at (package_id, scanned_at),
|
||||
INDEX idx_scan_scanned_at (scanned_at DESC),
|
||||
INDEX idx_scan_status (status),
|
||||
INDEX idx_scan_vuln_count (vuln_count)
|
||||
|
||||
@@ -190,6 +190,7 @@ CREATE TABLE IF NOT EXISTS scan_results (
|
||||
);
|
||||
|
||||
CREATE INDEX idx_scan_package_scanner ON scan_results(package_id, scanner) WHERE deleted_at IS NULL;
|
||||
CREATE INDEX idx_scan_package_scanned_at ON scan_results(package_id, scanned_at) WHERE deleted_at IS NULL;
|
||||
CREATE INDEX idx_scan_scanned_at ON scan_results(scanned_at DESC);
|
||||
CREATE INDEX idx_scan_status ON scan_results(status);
|
||||
CREATE INDEX idx_scan_vuln_count ON scan_results(vuln_count) WHERE vuln_count > 0;
|
||||
|
||||
+56
-19
@@ -60,6 +60,7 @@ type App struct {
|
||||
analyticsEngine *analytics.Engine
|
||||
wsServer *websocket.Server
|
||||
prewarmWorker *prewarming.Worker
|
||||
prewarmFetcher *prewarming.ProxyFetcher
|
||||
cdnMiddleware *cdn.Middleware
|
||||
}
|
||||
|
||||
@@ -215,6 +216,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,12 +235,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,
|
||||
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)
|
||||
@@ -308,10 +321,15 @@ func (a *App) initializeComponents() error {
|
||||
}
|
||||
bootCancel()
|
||||
|
||||
a.scanManager.SetFileSource(a.cache.ScanFile)
|
||||
|
||||
// Initialize rescan worker if enabled
|
||||
if a.config.Security.Enabled && a.config.Security.RescanInterval > 0 {
|
||||
log.Info().Dur("interval", a.config.Security.RescanInterval).Msg("Initializing package rescan worker")
|
||||
a.rescanWorker = scanner.NewRescanWorker(a.scanManager, a.metadata, a.storage, a.config.Security.RescanInterval)
|
||||
a.rescanWorker = scanner.NewRescanWorker(a.scanManager, a.metadata, a.config.Security.RescanInterval,
|
||||
scanner.WithActiveWindow(a.config.Security.RescanActiveWindow),
|
||||
scanner.WithConcurrency(a.config.Security.RescanConcurrency),
|
||||
)
|
||||
}
|
||||
|
||||
// Initialize WebSocket server
|
||||
@@ -331,14 +349,14 @@ func (a *App) initializeComponents() error {
|
||||
// Initialize pre-warming worker. Operator-controlled via cfg.Prewarming;
|
||||
// defaults are baked into config.Default() so unset fields stay sane.
|
||||
log.Info().Msg("Initializing pre-warming worker")
|
||||
a.prewarmFetcher = prewarming.NewProxyFetcher()
|
||||
a.prewarmWorker = prewarming.NewWorker(prewarming.Config{
|
||||
Enabled: a.config.Prewarming.Enabled,
|
||||
Interval: a.config.Prewarming.Interval,
|
||||
MaxConcurrent: a.config.Prewarming.MaxConcurrent,
|
||||
TopPackages: a.config.Prewarming.TopPackages,
|
||||
CacheManager: a.cache,
|
||||
Analytics: a.analyticsEngine,
|
||||
NetworkClient: a.networkClient,
|
||||
Popularity: a.analyticsEngine,
|
||||
Fetcher: a.prewarmFetcher,
|
||||
})
|
||||
|
||||
// Initialize CDN middleware
|
||||
@@ -389,10 +407,11 @@ func (a *App) initializeComponents() error {
|
||||
func (a *App) setupServer() error {
|
||||
// Create Fiber app
|
||||
a.app = fiber.New(fiber.Config{
|
||||
ReadTimeout: a.config.Server.ReadTimeout,
|
||||
WriteTimeout: a.config.Server.WriteTimeout,
|
||||
ServerHeader: "GoHoarder",
|
||||
AppName: "GoHoarder v1.0",
|
||||
ReadTimeout: a.config.Server.ReadTimeout,
|
||||
WriteTimeout: a.config.Server.WriteTimeout,
|
||||
ReadBufferSize: a.config.Server.ReadBufferSize,
|
||||
ServerHeader: "GoHoarder",
|
||||
AppName: "GoHoarder v1.0",
|
||||
})
|
||||
|
||||
// Auth middleware factories. Built once, reused on every gated route.
|
||||
@@ -411,6 +430,8 @@ func (a *App) setupServer() error {
|
||||
_ = mwOptional // reserved for future endpoints with anonymous fallback
|
||||
}
|
||||
|
||||
a.app.Use("/api", apiOriginGuard(a.config.Server.AllowedOrigins))
|
||||
|
||||
// Health endpoints — ALWAYS public (k8s liveness/readiness probes).
|
||||
a.app.Get("/health", adaptor.HTTPHandlerFunc(a.healthChecker.HealthHandler()))
|
||||
a.app.Get("/health/ready", adaptor.HTTPHandlerFunc(a.healthChecker.ReadyHandler()))
|
||||
@@ -440,6 +461,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)
|
||||
@@ -454,6 +476,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)
|
||||
@@ -514,7 +537,9 @@ func (a *App) setupServer() error {
|
||||
SumDBURL: sumDB,
|
||||
CredStore: credStore,
|
||||
})
|
||||
goProxyWithCDN := a.cdnMiddleware.Handler(http.StripPrefix("/go", goProxyHandler))
|
||||
goProxyMounted := http.StripPrefix("/go", goProxyHandler)
|
||||
a.prewarmFetcher.Mount("go", goProxyMounted)
|
||||
goProxyWithCDN := a.cdnMiddleware.Handler(goProxyMounted)
|
||||
if authEnabled {
|
||||
a.app.All("/go/*", mwAuth, adaptor.HTTPHandler(goProxyWithCDN))
|
||||
} else {
|
||||
@@ -530,7 +555,9 @@ func (a *App) setupServer() error {
|
||||
npmProxyHandler := npm.New(a.cache, a.networkClient, npm.Config{
|
||||
Upstream: npmUpstream,
|
||||
})
|
||||
npmProxyWithCDN := a.cdnMiddleware.Handler(http.StripPrefix("/npm", npmProxyHandler))
|
||||
npmProxyMounted := http.StripPrefix("/npm", npmProxyHandler)
|
||||
a.prewarmFetcher.Mount("npm", npmProxyMounted)
|
||||
npmProxyWithCDN := a.cdnMiddleware.Handler(npmProxyMounted)
|
||||
a.app.Use("/npm", func(c fiber.Ctx) error {
|
||||
if canonical := npm.CanonicalPath(c.Path()); canonical != c.Path() {
|
||||
c.Path(canonical)
|
||||
@@ -552,7 +579,9 @@ func (a *App) setupServer() error {
|
||||
pypiProxyHandler := pypi.New(a.cache, a.networkClient, pypi.Config{
|
||||
Upstream: pypiUpstream,
|
||||
})
|
||||
pypiProxyWithCDN := a.cdnMiddleware.Handler(http.StripPrefix("/pypi", pypiProxyHandler))
|
||||
pypiProxyMounted := http.StripPrefix("/pypi", pypiProxyHandler)
|
||||
a.prewarmFetcher.Mount("pypi", pypiProxyMounted)
|
||||
pypiProxyWithCDN := a.cdnMiddleware.Handler(pypiProxyMounted)
|
||||
if authEnabled {
|
||||
a.app.All("/pypi/*", mwAuth, adaptor.HTTPHandler(pypiProxyWithCDN))
|
||||
} else {
|
||||
@@ -604,6 +633,14 @@ 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)
|
||||
}
|
||||
|
||||
// Start is a no-op unless prewarming.enabled is set.
|
||||
a.prewarmWorker.Start(ctx)
|
||||
}
|
||||
|
||||
func (a *App) Run() error {
|
||||
@@ -888,13 +925,13 @@ func buildCheckOrigin(allowed []string) func(*http.Request) bool {
|
||||
}
|
||||
ou, err := url.Parse(origin)
|
||||
if err != nil || ou.Scheme == "" || ou.Host == "" {
|
||||
log.Warn().Str("origin", origin).Msg("Rejecting WebSocket upgrade: malformed Origin header")
|
||||
log.Warn().Str("origin", origin).Msg("Rejecting origin: malformed Origin header")
|
||||
return false
|
||||
}
|
||||
originScheme := strings.ToLower(ou.Scheme)
|
||||
originHost, ok := normalizeOriginHost(originScheme, ou.Host)
|
||||
if !ok {
|
||||
log.Warn().Str("origin", origin).Msg("Rejecting WebSocket upgrade: malformed Origin header")
|
||||
log.Warn().Str("origin", origin).Msg("Rejecting origin: malformed Origin header")
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -925,7 +962,7 @@ func buildCheckOrigin(allowed []string) func(*http.Request) bool {
|
||||
log.Warn().
|
||||
Str("origin", origin).
|
||||
Str("host", r.Host).
|
||||
Msg("Rejecting WebSocket upgrade: Origin not in allowlist")
|
||||
Msg("Rejecting origin: Origin not in allowlist")
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
const (
|
||||
headerOrigin = "Origin"
|
||||
corsAllowedMethods = "GET, POST, PATCH, DELETE, OPTIONS"
|
||||
corsAllowedHeaders = "Content-Type, Authorization, X-API-Key"
|
||||
corsPreflightMaxAge = "600"
|
||||
headerACRMethod = "Access-Control-Request-Method"
|
||||
headerACAllowOrigin = "Access-Control-Allow-Origin"
|
||||
headerACAllowMethods = "Access-Control-Allow-Methods"
|
||||
headerACAllowHeaders = "Access-Control-Allow-Headers"
|
||||
headerACMaxAge = "Access-Control-Max-Age"
|
||||
)
|
||||
|
||||
// apiOriginGuard enforces server.allowed_origins on /api. A browser at another origin cannot
|
||||
// read responses (no CORS grant) and cannot change state (403), whatever the handlers set.
|
||||
// With nothing configured only the request's own host counts as same-origin.
|
||||
// Requests with neither Origin nor Referer come from non-browser clients and pass.
|
||||
func apiOriginGuard(allowed []string) fiber.Handler {
|
||||
check := buildCheckOrigin(allowed)
|
||||
originAllowed := func(c fiber.Ctx, origin string) bool {
|
||||
r := &http.Request{Header: http.Header{headerOrigin: {origin}}, Host: c.Host()}
|
||||
return check(r)
|
||||
}
|
||||
|
||||
return func(c fiber.Ctx) error {
|
||||
origin := c.Get(headerOrigin)
|
||||
method := c.Method()
|
||||
|
||||
if method == http.MethodOptions && origin != "" && c.Get(headerACRMethod) != "" {
|
||||
if !originAllowed(c, origin) {
|
||||
return c.SendStatus(fiber.StatusForbidden)
|
||||
}
|
||||
setCORSGrant(c, origin)
|
||||
c.Set(headerACMaxAge, corsPreflightMaxAge)
|
||||
return c.SendStatus(fiber.StatusNoContent)
|
||||
}
|
||||
|
||||
if !isSafeMethod(method) {
|
||||
source := origin
|
||||
if source == "" {
|
||||
source = refererOrigin(c.Get(fiber.HeaderReferer))
|
||||
}
|
||||
if source != "" && !originAllowed(c, source) {
|
||||
log.Warn().Str("method", method).Str("path", c.Path()).Str("origin", source).Msg("Rejecting cross-origin state-changing request")
|
||||
return c.Status(fiber.StatusForbidden).JSON(fiber.Map{"error": "cross-origin request not allowed"})
|
||||
}
|
||||
}
|
||||
|
||||
err := c.Next()
|
||||
|
||||
// Drop any grant a handler or upstream set; the allowlist decides.
|
||||
c.Response().Header.Del(headerACAllowOrigin)
|
||||
c.Response().Header.Del(headerACAllowMethods)
|
||||
c.Response().Header.Del(headerACAllowHeaders)
|
||||
c.Vary(headerOrigin)
|
||||
if origin != "" && originAllowed(c, origin) {
|
||||
setCORSGrant(c, origin)
|
||||
}
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
func setCORSGrant(c fiber.Ctx, origin string) {
|
||||
c.Set(headerACAllowOrigin, origin)
|
||||
c.Set(headerACAllowMethods, corsAllowedMethods)
|
||||
c.Set(headerACAllowHeaders, corsAllowedHeaders)
|
||||
c.Vary(headerOrigin)
|
||||
}
|
||||
|
||||
func isSafeMethod(m string) bool {
|
||||
return m == http.MethodGet || m == http.MethodHead || m == http.MethodOptions
|
||||
}
|
||||
|
||||
// refererOrigin returns scheme://host of a Referer, or "" when it is absent or malformed.
|
||||
func refererOrigin(referer string) string {
|
||||
if strings.TrimSpace(referer) == "" {
|
||||
return ""
|
||||
}
|
||||
u, err := url.Parse(referer)
|
||||
if err != nil || u.Scheme == "" || u.Host == "" {
|
||||
return "null" // present but unusable: never matches the allowlist
|
||||
}
|
||||
return u.Scheme + "://" + u.Host
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/cache"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/config"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
const dashboardOrigin = "https://gohoarder.example.com"
|
||||
|
||||
func seedPackage(t *testing.T, a *App) {
|
||||
t.Helper()
|
||||
entry, err := a.cache.Get(context.Background(), "npm", "left-pad", "1.3.0", func(context.Context) (*cache.FetchResult, error) {
|
||||
return &cache.FetchResult{Data: io.NopCloser(strings.NewReader("tarball"))}, nil
|
||||
})
|
||||
require.NoError(t, err)
|
||||
_ = entry.Data.Close()
|
||||
}
|
||||
|
||||
func apiCall(t *testing.T, a *App, method, target string, headers map[string]string) *http.Response {
|
||||
t.Helper()
|
||||
req := httptest.NewRequest(method, target, nil)
|
||||
for k, v := range headers {
|
||||
req.Header.Set(k, v)
|
||||
}
|
||||
resp, err := a.app.Test(req, fiber.TestConfig{Timeout: 10 * time.Second})
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { _ = resp.Body.Close() })
|
||||
return resp
|
||||
}
|
||||
|
||||
func corsApp(t *testing.T, origins ...string) *App {
|
||||
return newTestApp(t, func(c *config.Config) { c.Server.AllowedOrigins = origins })
|
||||
}
|
||||
|
||||
const deletePath = "/api/packages/npm/left-pad/1.3.0"
|
||||
|
||||
func TestAPIDeleteFromDisallowedOriginForbidden(t *testing.T) {
|
||||
a := corsApp(t, dashboardOrigin)
|
||||
seedPackage(t, a)
|
||||
|
||||
for _, h := range []map[string]string{
|
||||
{"Origin": "https://evil.example.net"},
|
||||
{"Origin": "null"},
|
||||
{"Referer": "https://evil.example.net/page"},
|
||||
{"Origin": "https://evil.example.net", "Referer": dashboardOrigin + "/x"},
|
||||
} {
|
||||
resp := apiCall(t, a, http.MethodDelete, deletePath, h)
|
||||
assert.Equal(t, http.StatusForbidden, resp.StatusCode, "%v", h)
|
||||
}
|
||||
resp := apiCall(t, a, http.MethodGet, "/api/packages/npm", nil)
|
||||
assert.NotEqual(t, http.StatusForbidden, resp.StatusCode)
|
||||
_, err := a.metadata.GetPackage(context.Background(), "npm", "left-pad", "1.3.0")
|
||||
assert.NoError(t, err, "a refused request must not delete")
|
||||
}
|
||||
|
||||
func TestAPIDeleteFromAllowedOriginWorks(t *testing.T) {
|
||||
for name, h := range map[string]map[string]string{
|
||||
"origin": {"Origin": dashboardOrigin},
|
||||
"referer": {"Referer": dashboardOrigin + "/packages"},
|
||||
"no-fetch": nil, // curl and server-to-server callers send neither header
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
a := corsApp(t, dashboardOrigin)
|
||||
seedPackage(t, a)
|
||||
resp := apiCall(t, a, http.MethodDelete, deletePath, h)
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
_, err := a.metadata.GetPackage(context.Background(), "npm", "left-pad", "1.3.0")
|
||||
assert.Error(t, err, "package must be gone")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAPIPostFromDisallowedOriginForbidden(t *testing.T) {
|
||||
a := corsApp(t, dashboardOrigin)
|
||||
resp := apiCall(t, a, http.MethodPost, "/api/admin/prewarming/trigger", map[string]string{"Origin": "https://evil.example.net"})
|
||||
assert.Equal(t, http.StatusForbidden, resp.StatusCode)
|
||||
}
|
||||
|
||||
func TestAPIGetStaysPublicWithoutWildcardCORS(t *testing.T) {
|
||||
a := corsApp(t, dashboardOrigin)
|
||||
|
||||
resp := apiCall(t, a, http.MethodGet, "/api/stats", nil)
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
assert.Empty(t, resp.Header.Get("Access-Control-Allow-Origin"))
|
||||
|
||||
resp = apiCall(t, a, http.MethodGet, "/api/stats", map[string]string{"Origin": dashboardOrigin})
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
assert.Equal(t, dashboardOrigin, resp.Header.Get("Access-Control-Allow-Origin"))
|
||||
assert.Contains(t, resp.Header.Values("Vary"), "Origin")
|
||||
|
||||
// Served, but a browser at a foreign origin cannot read it.
|
||||
resp = apiCall(t, a, http.MethodGet, "/api/stats", map[string]string{"Origin": "https://evil.example.net"})
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
assert.Empty(t, resp.Header.Get("Access-Control-Allow-Origin"))
|
||||
}
|
||||
|
||||
func TestAPIPreflightAnswersOnlyAllowedOrigins(t *testing.T) {
|
||||
a := corsApp(t, dashboardOrigin)
|
||||
preflight := func(origin string) *http.Response {
|
||||
return apiCall(t, a, http.MethodOptions, deletePath, map[string]string{
|
||||
"Origin": origin, "Access-Control-Request-Method": "DELETE",
|
||||
})
|
||||
}
|
||||
|
||||
ok := preflight(dashboardOrigin)
|
||||
assert.Equal(t, http.StatusNoContent, ok.StatusCode)
|
||||
assert.Equal(t, dashboardOrigin, ok.Header.Get("Access-Control-Allow-Origin"))
|
||||
assert.Contains(t, ok.Header.Get("Access-Control-Allow-Methods"), "DELETE")
|
||||
|
||||
bad := preflight("https://evil.example.net")
|
||||
assert.Equal(t, http.StatusForbidden, bad.StatusCode)
|
||||
assert.Empty(t, bad.Header.Get("Access-Control-Allow-Origin"))
|
||||
}
|
||||
|
||||
// With nothing configured, only the host the request was sent to counts as same-origin.
|
||||
func TestAPISameOriginRuleWhenNoOriginsConfigured(t *testing.T) {
|
||||
a := corsApp(t)
|
||||
seedPackage(t, a)
|
||||
|
||||
resp := apiCall(t, a, http.MethodDelete, deletePath, map[string]string{"Origin": "https://evil.example.net"})
|
||||
assert.Equal(t, http.StatusForbidden, resp.StatusCode)
|
||||
|
||||
resp = apiCall(t, a, http.MethodDelete, deletePath, map[string]string{"Origin": "http://example.com"}) // httptest.NewRequest Host
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
}
|
||||
|
||||
func TestAPIOriginMatchingUsesAllowlistRules(t *testing.T) {
|
||||
a := corsApp(t, "https://*.example.org")
|
||||
resp := apiCall(t, a, http.MethodDelete, deletePath, map[string]string{"Origin": "https://ui.example.org"})
|
||||
assert.NotEqual(t, http.StatusForbidden, resp.StatusCode)
|
||||
resp = apiCall(t, a, http.MethodDelete, deletePath, map[string]string{"Origin": "https://example.org.evil.net"})
|
||||
assert.Equal(t, http.StatusForbidden, resp.StatusCode)
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"go/ast"
|
||||
"go/parser"
|
||||
"go/token"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/config"
|
||||
)
|
||||
|
||||
// Handlers must not set CORS headers themselves: apiOriginGuard owns the decision.
|
||||
func TestHandlersSetNoCORSHeaders(t *testing.T) {
|
||||
files, err := filepath.Glob("*.go")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fset := token.NewFileSet()
|
||||
for _, f := range files {
|
||||
if strings.HasSuffix(f, "_test.go") || f == "cors.go" {
|
||||
continue
|
||||
}
|
||||
parsed, err := parser.ParseFile(fset, f, nil, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("parse %s: %v", f, err)
|
||||
}
|
||||
ast.Inspect(parsed, func(n ast.Node) bool {
|
||||
lit, ok := n.(*ast.BasicLit)
|
||||
if !ok || lit.Kind != token.STRING {
|
||||
return true
|
||||
}
|
||||
if v, err := strconv.Unquote(lit.Value); err == nil && strings.HasPrefix(v, "Access-Control-") {
|
||||
t.Errorf("%s: handler sets %q; apiOriginGuard owns CORS", fset.Position(lit.Pos()), v)
|
||||
}
|
||||
return true
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAPIResponsesNeverCarryWildcardOrigin(t *testing.T) {
|
||||
const dashboard = "https://dash.example.com"
|
||||
a := newTestApp(t, func(c *config.Config) { c.Server.AllowedOrigins = []string{dashboard} })
|
||||
targets := []string{
|
||||
"/api/stats", "/api/info", "/api/config", "/api/packages",
|
||||
"/api/analytics/top", "/api/analytics/trending", "/api/analytics/trends", "/api/analytics/total",
|
||||
"/api/analytics/search?q=x", "/api/stats/timeseries",
|
||||
}
|
||||
for _, origin := range []string{"", dashboard, "https://evil.example.net"} {
|
||||
for _, target := range targets {
|
||||
hdr := map[string]string{}
|
||||
if origin != "" {
|
||||
hdr["Origin"] = origin
|
||||
}
|
||||
code, h, _ := doRequest(t, a, target, hdr)
|
||||
if code == http.StatusNotFound {
|
||||
t.Errorf("GET %s = 404, route missing", target)
|
||||
}
|
||||
if got := h.Get("Access-Control-Allow-Origin"); got == "*" {
|
||||
t.Errorf("GET %s Origin=%q carries Access-Control-Allow-Origin: *", target, origin)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
)
|
||||
|
||||
func doDelete(t *testing.T, a *App, target string) (int, string) {
|
||||
t.Helper()
|
||||
req := httptest.NewRequest(http.MethodDelete, target, nil)
|
||||
resp, err := a.app.Test(req, fiber.TestConfig{Timeout: 40 * time.Second})
|
||||
if err != nil {
|
||||
t.Fatalf("DELETE %s: %v", target, err)
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
t.Fatalf("read body: %v", err)
|
||||
}
|
||||
return resp.StatusCode, string(body)
|
||||
}
|
||||
|
||||
func TestDeleteMissingPackageIs404(t *testing.T) {
|
||||
a := newTestApp(t, nil)
|
||||
for _, target := range []string{
|
||||
"/api/packages/npm/nope/1.0.0",
|
||||
"/api/packages/pypi/nope/1.0.0",
|
||||
"/api/packages/go/example.com/nope/v1.0.0",
|
||||
} {
|
||||
code, body := doDelete(t, a, target)
|
||||
if code != http.StatusNotFound {
|
||||
t.Errorf("DELETE %s = %d %s, want 404", target, code, body)
|
||||
}
|
||||
var out map[string]string
|
||||
if err := json.Unmarshal([]byte(body), &out); err != nil || out["error"] == "" {
|
||||
t.Errorf("DELETE %s body %q is not a JSON error", target, body)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteExistingPackageIs200(t *testing.T) {
|
||||
a := newTestApp(t, nil)
|
||||
ctx := context.Background()
|
||||
err := a.metadata.SavePackage(ctx, &metadata.Package{
|
||||
Registry: "npm", Name: "left-pad", Version: "1.0.0", StorageKey: "npm/left-pad/1.0.0",
|
||||
Size: 10, CachedAt: time.Now(), LastAccessed: time.Now(),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("SavePackage: %v", err)
|
||||
}
|
||||
|
||||
code, body := doDelete(t, a, "/api/packages/npm/left-pad/1.0.0")
|
||||
if code != http.StatusOK || !strings.Contains(body, `"deleted":true`) {
|
||||
t.Fatalf("DELETE existing = %d %s, want 200 deleted", code, body)
|
||||
}
|
||||
if code, body := doDelete(t, a, "/api/packages/npm/left-pad/1.0.0"); code != http.StatusNotFound {
|
||||
t.Errorf("second DELETE = %d %s, want 404", code, body)
|
||||
}
|
||||
}
|
||||
+170
-184
@@ -1,12 +1,18 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
stderrors "errors"
|
||||
"fmt"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/lukaszraczylo/gohoarder/internal/version"
|
||||
apperrors "github.com/lukaszraczylo/gohoarder/pkg/errors"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/websocket"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
@@ -14,9 +20,6 @@ import (
|
||||
// handlePackages handles /api/packages endpoint
|
||||
func (a *App) handlePackages(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "application/json")
|
||||
c.Set("Access-Control-Allow-Origin", "*")
|
||||
c.Set("Access-Control-Allow-Methods", "GET, DELETE, OPTIONS")
|
||||
c.Set("Access-Control-Allow-Headers", "Content-Type")
|
||||
|
||||
if c.Method() == "OPTIONS" {
|
||||
return c.SendStatus(fiber.StatusOK)
|
||||
@@ -56,156 +59,165 @@ func packageSummary(pkg *metadata.Package) map[string]interface{} {
|
||||
return summary
|
||||
}
|
||||
|
||||
// handleListPackages returns list of cached packages
|
||||
// Pagination limits of GET /api/packages.
|
||||
const (
|
||||
defaultPageSize = 25
|
||||
maxPageSize = 200
|
||||
)
|
||||
|
||||
// listParams are the parsed query parameters of GET /api/packages.
|
||||
type listParams struct {
|
||||
opts metadata.GroupListOptions
|
||||
paged bool
|
||||
}
|
||||
|
||||
// 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"),
|
||||
SortBy: metadata.GroupSortName,
|
||||
}}
|
||||
switch sortBy := c.Query("sort"); sortBy {
|
||||
case metadata.GroupSortName, metadata.GroupSortCachedAt, metadata.GroupSortDownloads, metadata.GroupSortSize:
|
||||
p.opts.SortBy = sortBy
|
||||
p.opts.SortDesc = sortBy != metadata.GroupSortName
|
||||
}
|
||||
switch c.Query("order") {
|
||||
case "asc":
|
||||
p.opts.SortDesc = false
|
||||
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)
|
||||
p.opts.PageSize = fiber.Query[int](c, "page_size", defaultPageSize)
|
||||
if p.opts.PageSize < 1 {
|
||||
p.opts.PageSize = defaultPageSize
|
||||
}
|
||||
p.opts.PageSize = min(p.opts.PageSize, maxPageSize)
|
||||
}
|
||||
return p, nil
|
||||
}
|
||||
|
||||
// scanDecisions judges scanned packages, falling back to plain summaries without a scan manager.
|
||||
func (a *App) scanDecisions(ctx context.Context, ids []string) ([]scanner.ScanDecision, error) {
|
||||
if a.scanManager != nil {
|
||||
return a.scanManager.ScanDecisions(ctx, ids)
|
||||
}
|
||||
summaries, err := a.metadata.GetScanSummaries(ctx, ids, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make([]scanner.ScanDecision, len(summaries))
|
||||
for i, s := range summaries {
|
||||
out[i] = scanner.ScanDecision{Summary: s}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// vulnerabilityInfo is the per-row scan block of the list payload.
|
||||
func vulnerabilityInfo(pkg *metadata.Package, decisions map[string]scanner.ScanDecision) map[string]interface{} {
|
||||
if !pkg.SecurityScanned {
|
||||
return map[string]interface{}{"scanned": false, "status": "not_scanned", "isBlocked": false}
|
||||
}
|
||||
d, ok := decisions[pkg.ID]
|
||||
if !ok || !d.Summary.HasScan {
|
||||
return map[string]interface{}{"scanned": false, "status": "pending", "isBlocked": false}
|
||||
}
|
||||
sum := d.Summary
|
||||
return map[string]interface{}{
|
||||
"scanned": true,
|
||||
"status": sum.Status,
|
||||
"scannedAt": sum.ScannedAt.Format(time.RFC3339),
|
||||
"counts": map[string]int{
|
||||
"critical": sum.Critical,
|
||||
"high": sum.High,
|
||||
"moderate": sum.Moderate,
|
||||
"low": sum.Low,
|
||||
},
|
||||
"total": sum.Total,
|
||||
"isBlocked": d.Blocked,
|
||||
}
|
||||
}
|
||||
|
||||
// handleListPackages returns cached packages, one page of groups when page or
|
||||
// page_size is given and every group otherwise.
|
||||
func (a *App) handleListPackages(c fiber.Ctx) error {
|
||||
ctx := c.Context()
|
||||
params, err := parseListParams(c)
|
||||
if err != nil {
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": err.Error()})
|
||||
}
|
||||
|
||||
// Get packages from metadata store
|
||||
allPackages, err := a.metadata.ListPackages(ctx, &metadata.ListOptions{
|
||||
Limit: 1000, // Get more to account for duplicates
|
||||
Offset: 0,
|
||||
})
|
||||
page, err := a.metadata.ListPackageGroups(ctx, params.opts)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Failed to list packages")
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": "failed to list packages"})
|
||||
}
|
||||
|
||||
log.Debug().Int("total_packages_from_db", len(allPackages)).Msg("Retrieved packages from database")
|
||||
|
||||
// Filter, clean, and deduplicate packages
|
||||
// Map stores both cleaned package and original name for scan lookups
|
||||
type packageEntry struct {
|
||||
pkg *metadata.Package
|
||||
originalName string
|
||||
response := fiber.Map{
|
||||
"total": len(page.Packages),
|
||||
"total_groups": page.TotalGroups,
|
||||
}
|
||||
seen := make(map[string]*packageEntry)
|
||||
skippedCount := 0
|
||||
for _, pkg := range allPackages {
|
||||
// Skip metadata entries (npm metadata pages, pypi pages, etc.)
|
||||
if pkg.Version == "list" || pkg.Version == "latest" || pkg.Version == "metadata" || pkg.Version == "page" {
|
||||
skippedCount++
|
||||
log.Debug().
|
||||
Str("name", pkg.Name).
|
||||
Str("version", pkg.Version).
|
||||
Str("registry", pkg.Registry).
|
||||
Msg("Skipping metadata entry")
|
||||
continue
|
||||
if params.paged {
|
||||
response["page"] = params.opts.Page
|
||||
response["page_size"] = params.opts.PageSize
|
||||
}
|
||||
|
||||
if !a.config.Security.Enabled {
|
||||
response["packages"] = page.Packages
|
||||
return c.Status(fiber.StatusOK).JSON(response)
|
||||
}
|
||||
|
||||
var scannedIDs []string
|
||||
for _, pkg := range page.Packages {
|
||||
if pkg.SecurityScanned {
|
||||
scannedIDs = append(scannedIDs, pkg.ID)
|
||||
}
|
||||
|
||||
// Clean the package name (remove /@v/version.ext suffix)
|
||||
originalName := pkg.Name
|
||||
cleanName := pkg.Name
|
||||
if idx := strings.Index(cleanName, "/@v/"); idx != -1 {
|
||||
cleanName = cleanName[:idx]
|
||||
}
|
||||
decisions := map[string]scanner.ScanDecision{}
|
||||
if len(scannedIDs) > 0 {
|
||||
list, err := a.scanDecisions(ctx, scannedIDs)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Failed to load scan summaries")
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": "failed to list packages"})
|
||||
}
|
||||
|
||||
// Create deduplication key
|
||||
key := cleanName + "@" + pkg.Version
|
||||
|
||||
// Keep the entry with the largest size (typically .zip files)
|
||||
if existing, ok := seen[key]; !ok || pkg.Size > existing.pkg.Size {
|
||||
// Create a copy with cleaned name
|
||||
cleanPkg := *pkg
|
||||
cleanPkg.Name = cleanName
|
||||
seen[key] = &packageEntry{
|
||||
pkg: &cleanPkg,
|
||||
originalName: originalName,
|
||||
}
|
||||
for _, d := range list {
|
||||
decisions[d.Summary.PackageID] = d
|
||||
}
|
||||
}
|
||||
|
||||
log.Debug().
|
||||
Int("skipped_metadata", skippedCount).
|
||||
Int("unique_packages", len(seen)).
|
||||
Msg("Filtered and deduplicated packages")
|
||||
|
||||
// Convert map to slice, keeping track of original names
|
||||
type packageWithOriginalName struct {
|
||||
pkg *metadata.Package
|
||||
originalName string
|
||||
enhanced := make([]map[string]interface{}, 0, len(page.Packages))
|
||||
for _, pkg := range page.Packages {
|
||||
pkgMap := packageSummary(pkg)
|
||||
pkgMap["vulnerabilities"] = vulnerabilityInfo(pkg, decisions)
|
||||
enhanced = append(enhanced, pkgMap)
|
||||
}
|
||||
packagesWithNames := make([]packageWithOriginalName, 0, len(seen))
|
||||
for _, entry := range seen {
|
||||
packagesWithNames = append(packagesWithNames, packageWithOriginalName{
|
||||
pkg: entry.pkg,
|
||||
originalName: entry.originalName,
|
||||
})
|
||||
}
|
||||
|
||||
// Enhance packages with vulnerability information if security scanning is enabled
|
||||
var response map[string]interface{}
|
||||
if a.config.Security.Enabled {
|
||||
enhancedPackages := make([]map[string]interface{}, 0, len(packagesWithNames))
|
||||
for _, entry := range packagesWithNames {
|
||||
pkg := entry.pkg
|
||||
pkgMap := packageSummary(pkg)
|
||||
|
||||
// Add vulnerability info if scanned
|
||||
if pkg.SecurityScanned {
|
||||
// Use original name for scan result lookup (handles Go packages with /@v/ suffix)
|
||||
scanResult, err := a.metadata.GetScanResult(ctx, pkg.Registry, entry.originalName, pkg.Version)
|
||||
if err == nil && scanResult != nil {
|
||||
// Count vulnerabilities by severity
|
||||
severityCounts := make(map[string]int)
|
||||
for _, vuln := range scanResult.Vulnerabilities {
|
||||
severityCounts[metadata.NormalizeSeverity(vuln.Severity)]++
|
||||
}
|
||||
|
||||
// Check if package should be blocked based on thresholds
|
||||
isBlocked := false
|
||||
if a.scanManager != nil {
|
||||
blocked, _, _ := a.scanManager.CheckVulnerabilities(ctx, pkg.Registry, entry.originalName, pkg.Version)
|
||||
isBlocked = blocked
|
||||
}
|
||||
|
||||
pkgMap["vulnerabilities"] = map[string]interface{}{
|
||||
"scanned": true,
|
||||
"status": scanResult.Status,
|
||||
"scannedAt": scanResult.ScannedAt.Format(time.RFC3339),
|
||||
"counts": map[string]int{
|
||||
"critical": severityCounts["CRITICAL"],
|
||||
"high": severityCounts["HIGH"],
|
||||
"moderate": severityCounts["MODERATE"],
|
||||
"low": severityCounts["LOW"],
|
||||
},
|
||||
"total": scanResult.VulnerabilityCount,
|
||||
"isBlocked": isBlocked,
|
||||
}
|
||||
} else {
|
||||
pkgMap["vulnerabilities"] = map[string]interface{}{
|
||||
"scanned": false,
|
||||
"status": "pending",
|
||||
"isBlocked": false,
|
||||
}
|
||||
}
|
||||
} else {
|
||||
pkgMap["vulnerabilities"] = map[string]interface{}{
|
||||
"scanned": false,
|
||||
"status": "not_scanned",
|
||||
"isBlocked": false,
|
||||
}
|
||||
}
|
||||
|
||||
enhancedPackages = append(enhancedPackages, pkgMap)
|
||||
}
|
||||
|
||||
response = map[string]interface{}{
|
||||
"packages": enhancedPackages,
|
||||
"total": len(enhancedPackages),
|
||||
}
|
||||
} else {
|
||||
// Non-enhanced mode - just return the packages
|
||||
packages := make([]*metadata.Package, 0, len(packagesWithNames))
|
||||
for _, entry := range packagesWithNames {
|
||||
packages = append(packages, entry.pkg)
|
||||
}
|
||||
response = map[string]interface{}{
|
||||
"packages": packages,
|
||||
"total": len(packages),
|
||||
}
|
||||
}
|
||||
|
||||
// Success response
|
||||
response["packages"] = enhanced
|
||||
return c.Status(fiber.StatusOK).JSON(response)
|
||||
}
|
||||
|
||||
@@ -236,7 +248,8 @@ func (a *App) handleDeletePackage(c fiber.Ctx) error {
|
||||
if registry == "go" {
|
||||
// List all packages matching the base name and version
|
||||
allPackages, err := a.metadata.ListPackages(ctx, &metadata.ListOptions{
|
||||
Limit: 1000,
|
||||
Registry: registry,
|
||||
NamePrefix: name,
|
||||
})
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Failed to list packages for deletion")
|
||||
@@ -303,6 +316,10 @@ func (a *App) handleDeletePackage(c fiber.Ctx) error {
|
||||
} else {
|
||||
// For NPM and PyPI, delete directly
|
||||
if err := a.cache.Delete(ctx, registry, name, version); err != nil {
|
||||
var appErr *apperrors.Error
|
||||
if stderrors.As(err, &appErr) && appErr.Code == apperrors.ErrCodeNotFound {
|
||||
return c.Status(fiber.StatusNotFound).JSON(fiber.Map{"error": "package not found"})
|
||||
}
|
||||
log.Error().
|
||||
Err(err).
|
||||
Str("registry", registry).
|
||||
@@ -342,9 +359,6 @@ func (a *App) handleDeletePackage(c fiber.Ctx) error {
|
||||
// handleStats handles /api/stats endpoint
|
||||
func (a *App) handleStats(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "application/json")
|
||||
c.Set("Access-Control-Allow-Origin", "*")
|
||||
c.Set("Access-Control-Allow-Methods", "GET, OPTIONS")
|
||||
c.Set("Access-Control-Allow-Headers", "Content-Type")
|
||||
|
||||
if c.Method() == "OPTIONS" {
|
||||
return c.SendStatus(fiber.StatusOK)
|
||||
@@ -363,42 +377,23 @@ func (a *App) handleStats(c fiber.Ctx) error {
|
||||
cacheStats = &metadata.Stats{}
|
||||
}
|
||||
|
||||
// Get all packages to calculate per-registry breakdown
|
||||
packages, err := a.metadata.ListPackages(ctx, nil)
|
||||
registryStats := make(map[string]map[string]interface{})
|
||||
byRegistry, err := a.metadata.GetRegistryStats(ctx)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Failed to list packages")
|
||||
packages = []*metadata.Package{}
|
||||
log.Error().Err(err).Msg("Failed to get registry stats")
|
||||
}
|
||||
for _, rs := range byRegistry {
|
||||
registryStats[rs.Registry] = map[string]interface{}{
|
||||
"count": int(rs.Count),
|
||||
"size": rs.Size,
|
||||
"downloads": rs.Downloads,
|
||||
}
|
||||
}
|
||||
|
||||
// Calculate per-registry breakdown and blocked packages count
|
||||
registryStats := make(map[string]map[string]interface{})
|
||||
blockedCount := int64(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" {
|
||||
continue
|
||||
}
|
||||
|
||||
// Track per-registry stats
|
||||
if _, ok := registryStats[pkg.Registry]; !ok {
|
||||
registryStats[pkg.Registry] = map[string]interface{}{
|
||||
"count": 0,
|
||||
"size": int64(0),
|
||||
"downloads": int64(0),
|
||||
}
|
||||
}
|
||||
registryStats[pkg.Registry]["count"] = registryStats[pkg.Registry]["count"].(int) + 1
|
||||
registryStats[pkg.Registry]["size"] = registryStats[pkg.Registry]["size"].(int64) + pkg.Size
|
||||
registryStats[pkg.Registry]["downloads"] = registryStats[pkg.Registry]["downloads"].(int64) + int64(pkg.DownloadCount)
|
||||
|
||||
// Check if package is blocked (only if security scanning is enabled and package is scanned)
|
||||
if a.config.Security.Enabled && a.scanManager != nil && pkg.SecurityScanned {
|
||||
blocked, _, _ := a.scanManager.CheckVulnerabilities(ctx, pkg.Registry, pkg.Name, pkg.Version)
|
||||
if blocked {
|
||||
blockedCount++
|
||||
}
|
||||
}
|
||||
// Blocked packages need the blocking policy, so judge every scanned package in one batch.
|
||||
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
|
||||
@@ -433,9 +428,6 @@ func (a *App) handleStats(c fiber.Ctx) error {
|
||||
// Returns time-series download statistics for charts
|
||||
func (a *App) handleTimeSeriesStats(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "application/json")
|
||||
c.Set("Access-Control-Allow-Origin", "*")
|
||||
c.Set("Access-Control-Allow-Methods", "GET, OPTIONS")
|
||||
c.Set("Access-Control-Allow-Headers", "Content-Type")
|
||||
|
||||
if c.Method() == "OPTIONS" {
|
||||
return c.SendStatus(fiber.StatusOK)
|
||||
@@ -475,9 +467,6 @@ func (a *App) handleTimeSeriesStats(c fiber.Ctx) error {
|
||||
// Returns runtime configuration for the frontend
|
||||
func (a *App) handleConfig(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "application/json")
|
||||
c.Set("Access-Control-Allow-Origin", "*")
|
||||
c.Set("Access-Control-Allow-Methods", "GET, OPTIONS")
|
||||
c.Set("Access-Control-Allow-Headers", "Content-Type")
|
||||
|
||||
if c.Method() == "OPTIONS" {
|
||||
return c.SendStatus(fiber.StatusOK)
|
||||
@@ -509,9 +498,6 @@ func (a *App) handleConfig(c fiber.Ctx) error {
|
||||
// handleInfo handles /api/info endpoint
|
||||
func (a *App) handleInfo(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "application/json")
|
||||
c.Set("Access-Control-Allow-Origin", "*")
|
||||
c.Set("Access-Control-Allow-Methods", "GET, OPTIONS")
|
||||
c.Set("Access-Control-Allow-Headers", "Content-Type")
|
||||
|
||||
if c.Method() == "OPTIONS" {
|
||||
return c.SendStatus(fiber.StatusOK)
|
||||
|
||||
@@ -45,9 +45,6 @@ func (a *App) requireAdmin(c fiber.Ctx) error {
|
||||
// handleAdminBypasses handles /api/admin/bypasses endpoint
|
||||
func (a *App) handleAdminBypasses(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "application/json")
|
||||
c.Set("Access-Control-Allow-Origin", "*")
|
||||
c.Set("Access-Control-Allow-Methods", "GET, POST, PATCH, DELETE, OPTIONS")
|
||||
c.Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
|
||||
|
||||
if c.Method() == "OPTIONS" {
|
||||
return c.SendStatus(fiber.StatusOK)
|
||||
|
||||
@@ -10,7 +10,6 @@ import (
|
||||
// handleAnalyticsTopPackages returns the most downloaded packages
|
||||
func (a *App) handleAnalyticsTopPackages(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "application/json")
|
||||
c.Set("Access-Control-Allow-Origin", "*")
|
||||
|
||||
// Get limit from query params (default: 10)
|
||||
limit := 10
|
||||
@@ -31,7 +30,6 @@ func (a *App) handleAnalyticsTopPackages(c fiber.Ctx) error {
|
||||
// handleAnalyticsTrendingPackages returns trending packages
|
||||
func (a *App) handleAnalyticsTrendingPackages(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "application/json")
|
||||
c.Set("Access-Control-Allow-Origin", "*")
|
||||
|
||||
// Get limit from query params (default: 10)
|
||||
limit := 10
|
||||
@@ -52,7 +50,6 @@ func (a *App) handleAnalyticsTrendingPackages(c fiber.Ctx) error {
|
||||
// handleAnalyticsTrends returns download trends over time
|
||||
func (a *App) handleAnalyticsTrends(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "application/json")
|
||||
c.Set("Access-Control-Allow-Origin", "*")
|
||||
|
||||
trends := a.analyticsEngine.GetTrends()
|
||||
|
||||
@@ -64,7 +61,6 @@ func (a *App) handleAnalyticsTrends(c fiber.Ctx) error {
|
||||
// handleAnalyticsTotalStats returns overall statistics
|
||||
func (a *App) handleAnalyticsTotalStats(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "application/json")
|
||||
c.Set("Access-Control-Allow-Origin", "*")
|
||||
|
||||
stats := a.analyticsEngine.GetTotalStats()
|
||||
|
||||
@@ -74,7 +70,6 @@ func (a *App) handleAnalyticsTotalStats(c fiber.Ctx) error {
|
||||
// handleAnalyticsRegistryStats returns per-registry statistics
|
||||
func (a *App) handleAnalyticsRegistryStats(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "application/json")
|
||||
c.Set("Access-Control-Allow-Origin", "*")
|
||||
|
||||
registry := c.Params("registry")
|
||||
if registry == "" {
|
||||
@@ -91,7 +86,6 @@ func (a *App) handleAnalyticsRegistryStats(c fiber.Ctx) error {
|
||||
// handleAnalyticsPackageStats returns statistics for a specific package
|
||||
func (a *App) handleAnalyticsPackageStats(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "application/json")
|
||||
c.Set("Access-Control-Allow-Origin", "*")
|
||||
|
||||
registry := c.Params("registry")
|
||||
name := c.Params("name")
|
||||
@@ -117,7 +111,6 @@ func (a *App) handleAnalyticsPackageStats(c fiber.Ctx) error {
|
||||
// handleAnalyticsSearch searches for packages matching a query
|
||||
func (a *App) handleAnalyticsSearch(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "application/json")
|
||||
c.Set("Access-Control-Allow-Origin", "*")
|
||||
|
||||
query := c.Query("q")
|
||||
if query == "" {
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
// trendPeriods maps the period query value of /api/stats/trend to days of history.
|
||||
var trendPeriods = map[string]int{"30day": 30, "90day": 90, "1year": 365}
|
||||
|
||||
const defaultTrendPeriod = "30day"
|
||||
|
||||
// handleStatsTrend returns one snapshot per day for the period, oldest first.
|
||||
// Vulnerability fields are null for days before vulnerability history starts.
|
||||
func (a *App) handleStatsTrend(c fiber.Ctx) error {
|
||||
period := c.Query("period", defaultTrendPeriod)
|
||||
days, ok := trendPeriods[period]
|
||||
if !ok {
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"error": "invalid period, must be one of: 30day, 90day, 1year",
|
||||
})
|
||||
}
|
||||
|
||||
today := time.Now().UTC().Truncate(24 * time.Hour)
|
||||
from := today.AddDate(0, 0, -(days - 1))
|
||||
points, err := a.metadata.GetStatsTrend(c.Context(), from)
|
||||
if err != nil && !errors.Is(err, metadata.ErrNotImplemented) {
|
||||
log.Error().Err(err).Str("period", period).Msg("Failed to get stats trend")
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": "failed to get stats trend"})
|
||||
}
|
||||
if points == nil {
|
||||
points = []*metadata.StatsSnapshot{}
|
||||
}
|
||||
|
||||
var vulnStart *string
|
||||
for _, p := range points {
|
||||
if p.VulnerablePackages != nil {
|
||||
vulnStart = &p.Date
|
||||
break
|
||||
}
|
||||
}
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"period": period,
|
||||
"from": from.Format(metadata.StatsSnapshotDateLayout),
|
||||
"to": today.Format(metadata.StatsSnapshotDateLayout),
|
||||
"vulnerability_history_start": vulnStart,
|
||||
"points": points,
|
||||
})
|
||||
}
|
||||
|
||||
// countBlocked counts scanned artifacts the blocking policy refuses.
|
||||
func (a *App) countBlocked(ctx context.Context) (int64, error) {
|
||||
if !a.config.Security.Enabled || a.scanManager == nil {
|
||||
return 0, nil
|
||||
}
|
||||
decisions, err := a.scanManager.ScanDecisions(ctx, nil)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
var blocked int64
|
||||
for _, d := range decisions {
|
||||
if d.Blocked && !metadata.IsMetadataVersion(d.Summary.Version) {
|
||||
blocked++
|
||||
}
|
||||
}
|
||||
return blocked, nil
|
||||
}
|
||||
|
||||
// blockedCounterSetter is implemented by stores that snapshot blocked packages.
|
||||
type blockedCounterSetter interface {
|
||||
SetBlockedCounter(func(context.Context) (int64, error))
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
@@ -11,9 +12,6 @@ import (
|
||||
// handleVulnerabilities handles /api/packages/{registry}/{name}/{version}/vulnerabilities endpoint
|
||||
func (a *App) handleVulnerabilities(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "application/json")
|
||||
c.Set("Access-Control-Allow-Origin", "*")
|
||||
c.Set("Access-Control-Allow-Methods", "GET, OPTIONS")
|
||||
c.Set("Access-Control-Allow-Headers", "Content-Type")
|
||||
|
||||
if c.Method() == "OPTIONS" {
|
||||
return c.SendStatus(fiber.StatusOK)
|
||||
@@ -45,14 +43,14 @@ func (a *App) handleVulnerabilities(c fiber.Ctx) error {
|
||||
Str("version", version).
|
||||
Msg("Getting vulnerabilities for package")
|
||||
|
||||
pkg, pkgErr := a.metadata.GetPackage(ctx, registry, name, version)
|
||||
key, pkg, pkgErr := a.resolvePackageKey(ctx, registry, name, version)
|
||||
releaseVersion := ""
|
||||
if pkgErr == nil && pkg != nil {
|
||||
releaseVersion = pkg.ReleaseVersion
|
||||
}
|
||||
|
||||
// Get scan result from metadata store
|
||||
scanResult, err := a.metadata.GetScanResult(ctx, registry, name, version)
|
||||
scanResult, err := a.metadata.GetScanResult(ctx, registry, key, version)
|
||||
if err != nil {
|
||||
if pkgErr != nil {
|
||||
return c.Status(fiber.StatusNotFound).JSON(fiber.Map{"error": "package not found"})
|
||||
@@ -172,3 +170,23 @@ func (a *App) handleVulnerabilities(c fiber.Ctx) error {
|
||||
|
||||
return c.Status(fiber.StatusOK).JSON(response)
|
||||
}
|
||||
|
||||
// goCacheKeyExts orders the Go cache files a module version is stored under; the
|
||||
// .zip carries the scan result.
|
||||
var goCacheKeyExts = []string{"zip", "mod", "info"}
|
||||
|
||||
// resolvePackageKey maps the name the dashboard shows to the stored row name.
|
||||
// Go rows are stored under cache keys (module/@v/version.ext), not the module path.
|
||||
func (a *App) resolvePackageKey(ctx context.Context, registry, name, version string) (string, *metadata.Package, error) {
|
||||
pkg, err := a.metadata.GetPackage(ctx, registry, name, version)
|
||||
if err == nil || registry != "go" || strings.Contains(name, "/@v/") {
|
||||
return name, pkg, err
|
||||
}
|
||||
for _, ext := range goCacheKeyExts {
|
||||
key := name + "/@v/" + version + "." + ext
|
||||
if p, kerr := a.metadata.GetPackage(ctx, registry, key, version); kerr == nil {
|
||||
return key, p, nil
|
||||
}
|
||||
}
|
||||
return name, nil, err
|
||||
}
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
)
|
||||
|
||||
type listResponse struct {
|
||||
Packages []struct {
|
||||
Name string `json:"name"`
|
||||
Version string `json:"version"`
|
||||
Registry string `json:"registry"`
|
||||
Vulnerabilities struct {
|
||||
Status string `json:"status"`
|
||||
IsBlocked bool `json:"isBlocked"`
|
||||
Total int `json:"total"`
|
||||
Counts struct {
|
||||
Critical int `json:"critical"`
|
||||
} `json:"counts"`
|
||||
} `json:"vulnerabilities"`
|
||||
} `json:"packages"`
|
||||
Total int `json:"total"`
|
||||
TotalGroups int `json:"total_groups"`
|
||||
Page int `json:"page"`
|
||||
PageSize int `json:"page_size"`
|
||||
}
|
||||
|
||||
func getList(t *testing.T, a *App, target string) listResponse {
|
||||
t.Helper()
|
||||
code, _, body := doRequest(t, a, target, nil)
|
||||
if code != 200 {
|
||||
t.Fatalf("GET %s = %d %s", target, code, body)
|
||||
}
|
||||
var out listResponse
|
||||
if err := json.Unmarshal([]byte(body), &out); err != nil {
|
||||
t.Fatalf("decode %s: %v", body, err)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func TestListPackagesPagesGroupsAndAttachesScans(t *testing.T) {
|
||||
a, _ := newScanningApp(t)
|
||||
seedScanned(t, a, 0, 60)
|
||||
|
||||
page := getList(t, a, "/api/packages?page=2&page_size=25")
|
||||
if page.TotalGroups != 60 || page.Page != 2 || page.PageSize != 25 {
|
||||
t.Fatalf("paging fields = %+v", page)
|
||||
}
|
||||
if len(page.Packages) != 25 || page.Total != 25 {
|
||||
t.Fatalf("page 2 holds %d rows (total %d), want 25", len(page.Packages), page.Total)
|
||||
}
|
||||
if first := page.Packages[0].Name; first != "pkg-025" {
|
||||
t.Errorf("page 2 starts at %q, want pkg-025 (name order)", first)
|
||||
}
|
||||
|
||||
last := getList(t, a, "/api/packages?page=3&page_size=25")
|
||||
if len(last.Packages) != 10 {
|
||||
t.Errorf("last page holds %d rows, want 10", len(last.Packages))
|
||||
}
|
||||
|
||||
found := getList(t, a, "/api/packages?q=PKG-005&page_size=10")
|
||||
if found.TotalGroups != 1 || len(found.Packages) != 1 {
|
||||
t.Fatalf("search pkg-005 = %+v", found)
|
||||
}
|
||||
v := found.Packages[0].Vulnerabilities
|
||||
if v.Status != "vulnerable" || !v.IsBlocked || v.Total != 1 || v.Counts.Critical != 1 {
|
||||
t.Errorf("pkg-005 scan block = %+v, want vulnerable, blocked, one critical", v)
|
||||
}
|
||||
|
||||
clean := getList(t, a, "/api/packages?q=pkg-006&page_size=10")
|
||||
if cv := clean.Packages[0].Vulnerabilities; cv.Status != "clean" || cv.IsBlocked {
|
||||
t.Errorf("pkg-006 scan block = %+v, want clean and not blocked", cv)
|
||||
}
|
||||
|
||||
if none := getList(t, a, "/api/packages?registry=pypi&page_size=10"); none.TotalGroups != 0 || len(none.Packages) != 0 {
|
||||
t.Errorf("pypi filter = %+v, want empty", none)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListPackagesRecentFirst(t *testing.T) {
|
||||
a, _ := newScanningApp(t)
|
||||
seedScanned(t, a, 0, 30)
|
||||
recent := getList(t, a, "/api/packages?sort=cached_at&order=desc&page=1&page_size=3")
|
||||
got := []string{recent.Packages[0].Name, recent.Packages[1].Name, recent.Packages[2].Name}
|
||||
want := []string{"pkg-000", "pkg-001", "pkg-002"} // seedScanned caches pkg-N N minutes ago
|
||||
for i := range want {
|
||||
if got[i] != want[i] {
|
||||
t.Fatalf("recent = %v, want %v", got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The unpaginated list used to stop at 1000 rows without saying so.
|
||||
func TestListPackagesUnpaginatedHasNoCap(t *testing.T) {
|
||||
a := newTestApp(t, nil)
|
||||
ctx := context.Background()
|
||||
const rows = 1005
|
||||
now := time.Now()
|
||||
for i := 0; i < rows; i++ {
|
||||
name := fmt.Sprintf("bulk-%04d", i)
|
||||
if err := a.metadata.SavePackage(ctx, &metadata.Package{
|
||||
Registry: "npm", Name: name, Version: "1.0.0", StorageKey: "npm/" + name, Size: 1, CachedAt: now, LastAccessed: now,
|
||||
}); err != nil {
|
||||
t.Fatalf("SavePackage: %v", err)
|
||||
}
|
||||
}
|
||||
all := getList(t, a, "/api/packages")
|
||||
if len(all.Packages) != rows || all.Total != rows || all.TotalGroups != rows {
|
||||
t.Fatalf("unpaginated list = %d rows, total %d, groups %d; want %d", len(all.Packages), all.Total, all.TotalGroups, rows)
|
||||
}
|
||||
if capped := getList(t, a, "/api/packages?page_size=100000"); capped.PageSize != maxPageSize || len(capped.Packages) != maxPageSize {
|
||||
t.Errorf("page_size clamp: size %d, rows %d, want %d", capped.PageSize, len(capped.Packages), maxPageSize)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStatsFromAggregates(t *testing.T) {
|
||||
a, _ := newScanningApp(t)
|
||||
seedScanned(t, a, 0, 60)
|
||||
code, _, body := doRequest(t, a, "/api/stats", nil)
|
||||
if code != 200 {
|
||||
t.Fatalf("GET /api/stats = %d %s", code, body)
|
||||
}
|
||||
var out struct {
|
||||
Stats map[string]float64 `json:"stats"`
|
||||
Registries map[string]map[string]float64 `json:"registries"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(body), &out); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if out.Stats["total_packages"] != 60 || out.Stats["scanned_packages"] != 60 || out.Stats["vulnerable_packages"] != 12 {
|
||||
t.Errorf("stats = %v", out.Stats)
|
||||
}
|
||||
if out.Stats["blocked_packages"] != 12 {
|
||||
t.Errorf("blocked_packages = %v, want the 12 critical packages", out.Stats["blocked_packages"])
|
||||
}
|
||||
if npm := out.Registries["npm"]; npm["count"] != 60 || npm["size"] != 6000 {
|
||||
t.Errorf("npm registry = %v, want 60 rows and 6000 bytes", npm)
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package app
|
||||
import (
|
||||
"archive/zip"
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net"
|
||||
@@ -11,6 +12,7 @@ import (
|
||||
"net/url"
|
||||
"os"
|
||||
"os/exec"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
@@ -18,6 +20,7 @@ import (
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/config"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
)
|
||||
|
||||
// newTestApp builds a full App on temp storage with the given config tweaks.
|
||||
@@ -284,3 +287,65 @@ func TestPyPI_UVExcludeNewerResolvesThroughProxy(t *testing.T) {
|
||||
t.Fatalf("uv resolved foo although it was uploaded after the cutoff:\n%s", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNPMMetadataTTLOverrideReachesCache(t *testing.T) {
|
||||
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
_, _ = w.Write([]byte(`{"name":"left-pad","versions":{}}`))
|
||||
}))
|
||||
t.Cleanup(upstream.Close)
|
||||
|
||||
a := newTestApp(t, func(c *config.Config) {
|
||||
c.Handlers.NPM.UpstreamRegistry = upstream.URL
|
||||
c.Cache.TTLOverrides = map[string]time.Duration{"npm": 90 * time.Minute}
|
||||
})
|
||||
if code, _, body := doRequest(t, a, "/npm/left-pad", nil); code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body %q", code, body)
|
||||
}
|
||||
|
||||
pkgs, err := a.metadata.ListPackages(context.Background(), &metadata.ListOptions{Registry: "npm"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, p := range pkgs {
|
||||
if p.ExpiresAt == nil {
|
||||
continue
|
||||
}
|
||||
if got := p.ExpiresAt.Sub(p.CachedAt); got < 89*time.Minute || got > 91*time.Minute {
|
||||
t.Errorf("npm metadata freshness = %s, want 90m from cache.ttl_overrides", got)
|
||||
}
|
||||
return
|
||||
}
|
||||
t.Fatalf("no npm metadata entry with an expiry among %d packages", len(pkgs))
|
||||
}
|
||||
|
||||
// The mount already strips the registry prefix, so a package named after the registry must keep its name.
|
||||
func TestPackagesNamedAfterTheRegistryKeepTheirName(t *testing.T) {
|
||||
var npmSeen, pypiSeen []string
|
||||
npmUp := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
npmSeen = append(npmSeen, r.URL.Path)
|
||||
_, _ = w.Write([]byte(`{"name":"x","versions":{}}`))
|
||||
}))
|
||||
t.Cleanup(npmUp.Close)
|
||||
pypiUp := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
pypiSeen = append(pypiSeen, r.URL.Path)
|
||||
w.Header().Set("Content-Type", "text/html")
|
||||
_, _ = w.Write([]byte(`<html><body></body></html>`))
|
||||
}))
|
||||
t.Cleanup(pypiUp.Close)
|
||||
|
||||
a := newTestApp(t, func(c *config.Config) {
|
||||
c.Handlers.NPM.UpstreamRegistry = npmUp.URL
|
||||
c.Handlers.PyPI.SimpleAPIURL = pypiUp.URL + "/simple"
|
||||
})
|
||||
for _, target := range []string{"/npm/npm-run-all", "/npm/npm", "/pypi/simple/pypi-a/", "/pypi/pypi-b/"} {
|
||||
if code, _, body := doRequest(t, a, target, nil); code != http.StatusOK {
|
||||
t.Fatalf("GET %s: status = %d, body %q", target, code, body)
|
||||
}
|
||||
}
|
||||
if want := []string{"/npm-run-all", "/npm"}; !slices.Equal(npmSeen, want) {
|
||||
t.Errorf("npm upstream paths = %v, want %v", npmSeen, want)
|
||||
}
|
||||
if want := []string{"/simple/pypi-a/", "/simple/pypi-b/"}; !slices.Equal(pypiSeen, want) {
|
||||
t.Errorf("pypi upstream paths = %v, want %v", pypiSeen, want)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/internal/dbcount"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/config"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata/gormstore"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// seedScanned stores n scanned npm packages, every fifth with a critical finding.
|
||||
func seedScanned(t *testing.T, a *App, from, n int) {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
now := time.Now()
|
||||
for i := from; i < from+n; i++ {
|
||||
name := fmt.Sprintf("pkg-%03d", i)
|
||||
err := a.metadata.SavePackage(ctx, &metadata.Package{
|
||||
Registry: "npm", Name: name, Version: "1.0.0", StorageKey: "npm/" + name + "/1.0.0",
|
||||
Size: 100, CachedAt: now.Add(-time.Duration(i) * time.Minute), LastAccessed: now,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("SavePackage: %v", err)
|
||||
}
|
||||
res := &metadata.ScanResult{
|
||||
Registry: "npm", PackageName: name, PackageVersion: "1.0.0", Scanner: "test",
|
||||
Status: metadata.ScanStatusClean, ScannedAt: now,
|
||||
}
|
||||
if i%5 == 0 {
|
||||
res.Status = metadata.ScanStatusVulnerable
|
||||
res.VulnerabilityCount = 1
|
||||
res.Vulnerabilities = []metadata.Vulnerability{{ID: fmt.Sprintf("CVE-2026-%04d", i), Severity: "critical"}}
|
||||
}
|
||||
if err := a.metadata.SaveScanResult(ctx, res); err != nil {
|
||||
t.Fatalf("SaveScanResult: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func newScanningApp(t *testing.T) (*App, *dbcount.Counter) {
|
||||
t.Helper()
|
||||
a := newTestApp(t, func(c *config.Config) {
|
||||
c.Security.Enabled = true
|
||||
c.Security.Scanners.Static.Enabled = false
|
||||
c.Security.UpdateDBOnStartup = false
|
||||
})
|
||||
store, ok := a.metadata.(*gormstore.GORMStoreV2)
|
||||
if !ok {
|
||||
t.Fatalf("metadata store is %T, want *gormstore.GORMStoreV2", a.metadata)
|
||||
}
|
||||
var counter *dbcount.Counter
|
||||
store.WrapDB(func(db *gorm.DB) *gorm.DB {
|
||||
counted, c := dbcount.Attach(db)
|
||||
counter = c
|
||||
return counted
|
||||
})
|
||||
return a, counter
|
||||
}
|
||||
|
||||
// queriesFor reports how many SQL statements one GET runs.
|
||||
func queriesFor(t *testing.T, a *App, c *dbcount.Counter, target string) int {
|
||||
t.Helper()
|
||||
c.Reset()
|
||||
if code, _, body := doRequest(t, a, target, nil); code != http.StatusOK {
|
||||
t.Fatalf("GET %s = %d %s", target, code, body)
|
||||
}
|
||||
return c.Count()
|
||||
}
|
||||
|
||||
// The dashboard endpoints must cost the same number of statements for 20 rows and for 120.
|
||||
func TestDashboardEndpointsQueryCountIsConstant(t *testing.T) {
|
||||
a, counter := newScanningApp(t)
|
||||
targets := []string{"/api/packages", "/api/packages?page=1&page_size=25", "/api/stats"}
|
||||
|
||||
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("%-40s 20 rows: %3d queries, 120 rows: %3d queries", target, small[target], large)
|
||||
if large != small[target] {
|
||||
t.Errorf("%s: %d queries for 20 rows but %d for 120 rows; the count must not grow with rows", target, small[target], large)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/config"
|
||||
)
|
||||
|
||||
const recentPackagesURL = "/api/packages?page=1&page_size=10&sort=cached_at&order=desc"
|
||||
|
||||
// Fiber v3 defaults to an 8192-byte read buffer; OIDC session cookies plus a long Referer exceed it.
|
||||
func TestLargeRequestHeadersAreAccepted(t *testing.T) {
|
||||
a := newTestApp(t, nil)
|
||||
headers := map[string]string{
|
||||
"Cookie": "session=" + strings.Repeat("a", 5000),
|
||||
"Referer": "https://dash.example.com/" + strings.Repeat("r", 5000),
|
||||
}
|
||||
code, _, body := doRequest(t, a, recentPackagesURL, headers)
|
||||
if code != http.StatusOK {
|
||||
t.Fatalf("GET with ~10KB of headers = %d %q, want 200", code, body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadBufferSizeIsConfigurable(t *testing.T) {
|
||||
if got := config.Default().Server.ReadBufferSize; got != 16384 {
|
||||
t.Fatalf("default server.read_buffer_size = %d, want 16384", got)
|
||||
}
|
||||
a := newTestApp(t, func(c *config.Config) { c.Server.ReadBufferSize = 4096 })
|
||||
req := httptest.NewRequest(http.MethodGet, recentPackagesURL, nil)
|
||||
req.Header.Set("Cookie", "session="+strings.Repeat("a", 6000))
|
||||
if _, err := a.app.Test(req); err == nil || !strings.Contains(err.Error(), "small read buffer") {
|
||||
t.Errorf("6KB header with a 4096 buffer: err = %v, want a small-read-buffer rejection", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/config"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
)
|
||||
|
||||
// A cached artifact whose scan never completed (lost to a restart) is scanned once the
|
||||
// workers start, when security.rescan_interval is set.
|
||||
func TestWorkersStartTheRescanWorker(t *testing.T) {
|
||||
osv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"vulns":[]}`))
|
||||
}))
|
||||
defer osv.Close()
|
||||
|
||||
a := newTestApp(t, func(c *config.Config) {
|
||||
c.Security.Enabled = true
|
||||
c.Security.RescanInterval = time.Hour
|
||||
c.Security.Scanners.OSV.Enabled = true
|
||||
c.Security.Scanners.OSV.APIURL = osv.URL
|
||||
})
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
const key = "npm/left-pad/1.3.0"
|
||||
if err := a.storage.Put(ctx, key, strings.NewReader("tarball"), nil); err != nil {
|
||||
t.Fatalf("storage.Put: %v", err)
|
||||
}
|
||||
now := time.Now()
|
||||
err := a.metadata.SavePackage(ctx, &metadata.Package{
|
||||
Registry: "npm", Name: "left-pad", Version: "1.3.0", StorageKey: key,
|
||||
Size: 7, CachedAt: now, LastAccessed: now,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("SavePackage: %v", err)
|
||||
}
|
||||
|
||||
a.startWorkers(ctx)
|
||||
|
||||
deadline := time.Now().Add(20 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
if _, err := a.metadata.GetScanResult(ctx, "npm", "left-pad", "1.3.0"); err == nil {
|
||||
return
|
||||
}
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
}
|
||||
t.Fatal("no scan result after the workers started; the rescan worker never ran")
|
||||
}
|
||||
@@ -0,0 +1,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
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestSeverityFilterOnPackagesList(t *testing.T) {
|
||||
a, _ := newScanningApp(t)
|
||||
seedScanned(t, a, 0, 60) // every fifth package carries one critical finding
|
||||
|
||||
cases := []struct {
|
||||
query string
|
||||
want int
|
||||
}{
|
||||
{"", 60},
|
||||
{"?severity=", 60},
|
||||
{"?severity=critical", 12},
|
||||
{"?severity=Critical,high", 12},
|
||||
{"?severity=high", 0},
|
||||
{"?severity=high,moderate,low", 0},
|
||||
{"?severity=critical&q=pkg-005", 1},
|
||||
{"?severity=critical&q=pkg-006", 0},
|
||||
}
|
||||
for _, c := range cases {
|
||||
if got := getList(t, a, "/api/packages"+c.query); len(got.Packages) != c.want {
|
||||
t.Errorf("%q returned %d packages, want %d", c.query, len(got.Packages), c.want)
|
||||
}
|
||||
}
|
||||
|
||||
paged := getList(t, a, "/api/packages?severity=critical&page=1&page_size=5")
|
||||
if paged.TotalGroups != 12 || len(paged.Packages) != 5 {
|
||||
t.Errorf("paged severity list = %d groups, %d rows; want 12 groups, 5 rows", paged.TotalGroups, len(paged.Packages))
|
||||
}
|
||||
for _, p := range getList(t, a, "/api/packages?severity=critical").Packages {
|
||||
if p.Vulnerabilities.Counts.Critical == 0 {
|
||||
t.Errorf("%s has no critical finding but passed the critical filter", p.Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSeverityFilterRejectsUnknownValue(t *testing.T) {
|
||||
a, _ := newScanningApp(t)
|
||||
for _, q := range []string{"?severity=urgent", "?severity=critical,nope"} {
|
||||
if code, _, body := doRequest(t, a, "/api/packages"+q, nil); code != http.StatusBadRequest {
|
||||
t.Errorf("%q = %d %s, want 400", q, code, body)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/config"
|
||||
)
|
||||
|
||||
func listTree(t *testing.T, dir string) string {
|
||||
t.Helper()
|
||||
var names []string
|
||||
err := filepath.Walk(dir, func(p string, _ os.FileInfo, err error) error {
|
||||
if err == nil {
|
||||
names = append(names, p)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return strings.Join(names, "\n")
|
||||
}
|
||||
|
||||
// Shutdown must leave nothing running against the data directory: a late SQLite close deletes
|
||||
// its -wal/-shm files after Shutdown returned and breaks the removal of the directory.
|
||||
func TestShutdownLeavesDataDirectoryStable(t *testing.T) {
|
||||
for i := 0; i < 40; i++ {
|
||||
dir := t.TempDir()
|
||||
cfg := config.Default()
|
||||
cfg.Storage.Backend = "filesystem"
|
||||
cfg.Storage.Path = filepath.Join(dir, "store")
|
||||
cfg.Metadata.Backend = "sqlite"
|
||||
cfg.Metadata.SQLite.Path = filepath.Join(dir, "meta", "meta.db")
|
||||
if err := os.MkdirAll(filepath.Dir(cfg.Metadata.SQLite.Path), 0o750); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg.Security.Enabled = false
|
||||
cfg.Prewarming.Enabled = false
|
||||
cfg.Auth.Enabled = false
|
||||
a, err := New(cfg)
|
||||
if err != nil {
|
||||
t.Fatalf("New: %v", err)
|
||||
}
|
||||
doRequest(t, a, "/api/stats", nil)
|
||||
if err := a.Shutdown(); err != nil {
|
||||
t.Fatalf("Shutdown: %v", err)
|
||||
}
|
||||
before := listTree(t, dir)
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
if after := listTree(t, dir); before != after {
|
||||
t.Fatalf("iteration %d: data directory changed after Shutdown:\nbefore:\n%s\nafter:\n%s", i, before, after)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata/gormstore"
|
||||
)
|
||||
|
||||
type trendResponse struct {
|
||||
VulnerabilityHistoryStart *string `json:"vulnerability_history_start"`
|
||||
Period string `json:"period"`
|
||||
From string `json:"from"`
|
||||
To string `json:"to"`
|
||||
Points []struct {
|
||||
VulnerablePackages *int64 `json:"vulnerable_packages"`
|
||||
Blocked *int64 `json:"blocked"`
|
||||
Date string `json:"date"`
|
||||
TotalPackages int64 `json:"total_packages"`
|
||||
} `json:"points"`
|
||||
}
|
||||
|
||||
func trendDay(daysAgo int) string {
|
||||
return time.Now().UTC().AddDate(0, 0, -daysAgo).Format("2006-01-02")
|
||||
}
|
||||
|
||||
func getTrend(t *testing.T, a *App, target string) trendResponse {
|
||||
t.Helper()
|
||||
code, _, body := doRequest(t, a, target, nil)
|
||||
if code != http.StatusOK {
|
||||
t.Fatalf("GET %s = %d %s", target, code, body)
|
||||
}
|
||||
var out trendResponse
|
||||
if err := json.Unmarshal([]byte(body), &out); err != nil {
|
||||
t.Fatalf("decode %s: %v", body, err)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func TestSeverityAndTrendQueryCountIsConstant(t *testing.T) {
|
||||
a, counter := newScanningApp(t)
|
||||
targets := []string{
|
||||
"/api/packages?severity=critical,high",
|
||||
"/api/packages?severity=low&page=1&page_size=25",
|
||||
"/api/stats/trend?period=90day",
|
||||
}
|
||||
seedScanned(t, a, 0, 20)
|
||||
small := map[string]int{}
|
||||
for _, target := range targets {
|
||||
small[target] = queriesFor(t, a, counter, target)
|
||||
}
|
||||
seedScanned(t, a, 20, 100)
|
||||
for _, target := range targets {
|
||||
large := queriesFor(t, a, counter, target)
|
||||
t.Logf("%-50s 20 rows: %2d queries, 120 rows: %2d queries", target, small[target], large)
|
||||
if large != small[target] {
|
||||
t.Errorf("%s: %d queries for 20 rows but %d for 120 rows", target, small[target], large)
|
||||
}
|
||||
}
|
||||
if n := small["/api/stats/trend?period=90day"]; n != 1 {
|
||||
t.Errorf("trend costs %d statements, want 1", n)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStatsTrendEndpoint(t *testing.T) {
|
||||
a := newTestApp(t, nil)
|
||||
|
||||
empty := getTrend(t, a, "/api/stats/trend")
|
||||
if empty.Period != "30day" || empty.Points == nil || len(empty.Points) != 0 || empty.VulnerabilityHistoryStart != nil {
|
||||
t.Fatalf("empty trend = %+v, want the default period, no points and no vulnerability start", empty)
|
||||
}
|
||||
|
||||
store := a.metadata.(*gormstore.GORMStoreV2)
|
||||
one, two := int64(1), int64(2)
|
||||
for _, row := range []gormstore.StatsSnapshotModel{
|
||||
{Day: trendDay(100), TotalPackages: 5},
|
||||
{Day: trendDay(40), TotalPackages: 6},
|
||||
{Day: trendDay(2), TotalPackages: 7},
|
||||
{Day: trendDay(1), TotalPackages: 8, VulnerablePackages: &two, Blocked: &one},
|
||||
} {
|
||||
if err := store.DB().Create(&row).Error; err != nil {
|
||||
t.Fatalf("seed snapshot: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
cases := []struct {
|
||||
target string
|
||||
period string
|
||||
points int
|
||||
}{
|
||||
{"/api/stats/trend", "30day", 2},
|
||||
{"/api/stats/trend?period=30day", "30day", 2},
|
||||
{"/api/stats/trend?period=90day", "90day", 3},
|
||||
{"/api/stats/trend?period=1year", "1year", 4},
|
||||
}
|
||||
for _, c := range cases {
|
||||
got := getTrend(t, a, c.target)
|
||||
if got.Period != c.period || len(got.Points) != c.points {
|
||||
t.Errorf("%s = period %q, %d points; want %q, %d", c.target, got.Period, len(got.Points), c.period, c.points)
|
||||
}
|
||||
}
|
||||
|
||||
got := getTrend(t, a, "/api/stats/trend")
|
||||
if got.To != trendDay(0) || got.From != trendDay(29) {
|
||||
t.Errorf("window = %s..%s, want %s..%s", got.From, got.To, trendDay(29), trendDay(0))
|
||||
}
|
||||
if got.Points[0].Date != trendDay(2) || got.Points[1].Date != trendDay(1) {
|
||||
t.Errorf("points not oldest first: %+v", got.Points)
|
||||
}
|
||||
if got.Points[0].VulnerablePackages != nil || got.Points[0].Blocked != nil {
|
||||
t.Errorf("a day without vulnerability data must carry null, got %+v", got.Points[0])
|
||||
}
|
||||
if v := got.Points[1].VulnerablePackages; v == nil || *v != 2 {
|
||||
t.Errorf("vulnerable_packages = %v, want 2", v)
|
||||
}
|
||||
if got.VulnerabilityHistoryStart == nil || *got.VulnerabilityHistoryStart != trendDay(1) {
|
||||
t.Errorf("vulnerability_history_start = %v, want %s", got.VulnerabilityHistoryStart, trendDay(1))
|
||||
}
|
||||
}
|
||||
|
||||
func TestStatsTrendRejectsUnknownPeriod(t *testing.T) {
|
||||
a := newTestApp(t, nil)
|
||||
for _, p := range []string{"7day", "1day", "bogus", "1YEAR"} {
|
||||
if code, _, body := doRequest(t, a, "/api/stats/trend?period="+p, nil); code != http.StatusBadRequest {
|
||||
t.Errorf("period=%s = %d %s, want 400", p, code, body)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
)
|
||||
|
||||
// The list shows Go modules by module path, but rows are stored under cache keys.
|
||||
func TestGoVulnerabilityDetailsResolveCacheKeyNames(t *testing.T) {
|
||||
a := newTestApp(t, nil)
|
||||
ctx := context.Background()
|
||||
const module, version = "github.com/go-git/go-git/v5", "v5.3.0"
|
||||
for _, ext := range []string{"info", "mod", "zip"} {
|
||||
name := module + "/@v/" + version + "." + ext
|
||||
err := a.metadata.SavePackage(ctx, &metadata.Package{
|
||||
Registry: "go", Name: name, Version: version, StorageKey: "go/" + name,
|
||||
Size: 10, CachedAt: time.Now(), LastAccessed: time.Now(),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("SavePackage %s: %v", name, err)
|
||||
}
|
||||
}
|
||||
err := a.metadata.SaveScanResult(ctx, &metadata.ScanResult{
|
||||
Registry: "go", PackageName: module + "/@v/" + version + ".zip", PackageVersion: version,
|
||||
Scanner: "osv", Status: metadata.ScanStatusVulnerable, ScannedAt: time.Now(),
|
||||
Vulnerabilities: []metadata.Vulnerability{{ID: "GHSA-test", Severity: "critical"}},
|
||||
VulnerabilityCount: 1,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("SaveScanResult: %v", err)
|
||||
}
|
||||
|
||||
code, _, body := doRequest(t, a, "/api/packages/go/"+module+"/"+version+"/vulnerabilities", nil)
|
||||
if code != http.StatusOK {
|
||||
t.Fatalf("GET details = %d %s, want 200", code, body)
|
||||
}
|
||||
var out struct {
|
||||
Scanned bool `json:"scanned"`
|
||||
Count int `json:"vulnerability_count"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(body), &out); err != nil {
|
||||
t.Fatalf("decode %q: %v", body, err)
|
||||
}
|
||||
if !out.Scanned || out.Count != 1 {
|
||||
t.Errorf("details = %s, want the .zip scan with 1 vulnerability", body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGoVulnerabilityDetailsMissingModuleIs404(t *testing.T) {
|
||||
a := newTestApp(t, nil)
|
||||
code, _, body := doRequest(t, a, "/api/packages/go/example.com/nope/v1.0.0/vulnerabilities", nil)
|
||||
if code != http.StatusNotFound {
|
||||
t.Errorf("GET missing = %d %s, want 404", code, body)
|
||||
}
|
||||
}
|
||||
+60
-6
@@ -4,6 +4,10 @@ import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/analytics"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/config"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/prewarming"
|
||||
)
|
||||
|
||||
// TestWorkersDrainTheBroadcastChannel pins that the app starts the websocket
|
||||
@@ -16,15 +20,65 @@ func TestWorkersDrainTheBroadcastChannel(t *testing.T) {
|
||||
defer cancel()
|
||||
a.startWorkers(ctx)
|
||||
|
||||
const events = 1000
|
||||
for i := 0; i < events; i++ {
|
||||
a.wsServer.BroadcastEvent("cache_hit", map[string]interface{}{"i": i})
|
||||
if i%200 == 0 {
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
// Bursts stay under the 256-slot channel and wait for the loop to drain between them, so the
|
||||
// result depends on the loop running, not on how fast the scheduler runs it.
|
||||
const (
|
||||
bursts = 10
|
||||
burstLen = 100
|
||||
)
|
||||
for b := 0; b < bursts; b++ {
|
||||
for i := 0; i < burstLen; i++ {
|
||||
a.wsServer.BroadcastEvent("cache_hit", map[string]interface{}{"i": i})
|
||||
}
|
||||
deadline := time.Now().Add(10 * time.Second)
|
||||
for a.wsServer.Pending() > 0 && time.Now().Before(deadline) {
|
||||
time.Sleep(time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
if dropped := a.wsServer.Dropped(); dropped != 0 {
|
||||
t.Fatalf("dropped %d of %d events; the broadcast loop is not draining the channel", dropped, events)
|
||||
t.Fatalf("dropped %d of %d events; the broadcast loop is not draining the channel", dropped, bursts*burstLen)
|
||||
}
|
||||
}
|
||||
|
||||
type recordingFetcher struct{ got chan prewarming.PackageInfo }
|
||||
|
||||
func (f recordingFetcher) Fetch(_ context.Context, pkg prewarming.PackageInfo) error {
|
||||
f.got <- pkg
|
||||
return nil
|
||||
}
|
||||
|
||||
type fixedPopularity struct{}
|
||||
|
||||
func (fixedPopularity) GetTopPackages(int) []analytics.PopularPackage {
|
||||
return []analytics.PopularPackage{{Registry: "npm", Name: "lodash"}}
|
||||
}
|
||||
|
||||
func (fixedPopularity) GetTrendingPackages(int) []analytics.PopularPackage { return nil }
|
||||
|
||||
// TestEnabledPrewarmWorkerStartsWithTheApp pins that startWorkers starts the pre-warm loop.
|
||||
func TestEnabledPrewarmWorkerStartsWithTheApp(t *testing.T) {
|
||||
a := newTestApp(t, nil)
|
||||
f := recordingFetcher{got: make(chan prewarming.PackageInfo, 4)}
|
||||
a.prewarmWorker = prewarming.NewWorker(prewarming.Config{Enabled: true, Fetcher: f, Popularity: fixedPopularity{}})
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
a.startWorkers(ctx)
|
||||
defer a.prewarmWorker.Stop()
|
||||
|
||||
select {
|
||||
case pkg := <-f.got:
|
||||
if pkg.Name != "lodash" {
|
||||
t.Fatalf("pre-warmed %q, want lodash", pkg.Name)
|
||||
}
|
||||
case <-time.After(10 * time.Second):
|
||||
t.Fatal("pre-warm worker never ran after startWorkers")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPrewarmingStaysOffByDefault(t *testing.T) {
|
||||
if config.Default().Prewarming.Enabled {
|
||||
t.Fatal("prewarming.enabled must default to false")
|
||||
}
|
||||
}
|
||||
|
||||
+107
-31
@@ -8,6 +8,7 @@ import (
|
||||
"encoding/base64"
|
||||
stderrors "errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
@@ -154,10 +155,12 @@ func (m *Manager) GenerateAPIKey(name string, role Role, expiresIn *time.Duratio
|
||||
return nil, "", errors.Wrap(err, errors.ErrCodeInternalServer, "failed to generate random key")
|
||||
}
|
||||
|
||||
rawKey := base64.URLEncoding.EncodeToString(keyBytes)
|
||||
secret := base64.URLEncoding.EncodeToString(keyBytes)
|
||||
id := keyPrefix + generateID()
|
||||
rawKey := id + keySeparator + secret
|
||||
|
||||
// Hash the key with the configured cost.
|
||||
hashedKey, err := bcrypt.GenerateFromPassword([]byte(rawKey), m.cfg.BcryptCost)
|
||||
hashedKey, err := bcrypt.GenerateFromPassword([]byte(secret), m.cfg.BcryptCost)
|
||||
if err != nil {
|
||||
return nil, "", errors.Wrap(err, errors.ErrCodeInternalServer, "failed to hash key")
|
||||
}
|
||||
@@ -169,7 +172,7 @@ func (m *Manager) GenerateAPIKey(name string, role Role, expiresIn *time.Duratio
|
||||
}
|
||||
|
||||
apiKey := &APIKey{
|
||||
ID: generateID(),
|
||||
ID: id,
|
||||
Name: name,
|
||||
HashedKey: string(hashedKey),
|
||||
Role: role,
|
||||
@@ -198,46 +201,119 @@ func (m *Manager) GenerateAPIKey(name string, role Role, expiresIn *time.Duratio
|
||||
return apiKey, rawKey, nil
|
||||
}
|
||||
|
||||
// Key format: "<id>.<secret>" with id "ghk_<random>". The id is public and selects one stored
|
||||
// key; the bcrypt hash covers the secret only. Keys minted before the format
|
||||
// existed have no id in the raw key and hash the whole raw key.
|
||||
const (
|
||||
keyPrefix = "ghk_"
|
||||
keySeparator = "."
|
||||
// maxLegacyCompares bounds concurrent bcrypt checks against pre-id keys,
|
||||
// which can only be found by trying each one.
|
||||
maxLegacyCompares = 4
|
||||
// legacyIDLen is the length of base64url(16 bytes).
|
||||
legacyIDLen = 24
|
||||
)
|
||||
|
||||
var (
|
||||
bcryptCompare = bcrypt.CompareHashAndPassword
|
||||
legacySlots = make(chan struct{}, maxLegacyCompares)
|
||||
// dummyHash keeps the cost of an unknown id equal to a wrong secret.
|
||||
dummyHash = mustHash("gohoarder-dummy-secret")
|
||||
)
|
||||
|
||||
func mustHash(s string) []byte {
|
||||
h, err := bcrypt.GenerateFromPassword([]byte(s), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
panic(fmt.Sprintf("auth: dummy hash: %v", err))
|
||||
}
|
||||
return h
|
||||
}
|
||||
|
||||
// ValidateAPIKey validates an API key and returns the associated key object.
|
||||
// Hot path: snapshots candidates, runs bcrypt without holding the lock.
|
||||
// LastUsedAt is updated in-memory under the write lock and flushed to the
|
||||
// store via a fire-and-forget goroutine.
|
||||
// A key with an id costs exactly one bcrypt compare, whatever the number of
|
||||
// stored keys. LastUsedAt is updated in-memory under the write lock and
|
||||
// flushed to the store via a fire-and-forget goroutine.
|
||||
func (m *Manager) ValidateAPIKey(ctx context.Context, rawKey string) (*APIKey, error) {
|
||||
// Phase 1: snapshot non-expired candidates under RLock. We hold pointers
|
||||
// to APIKey; APIKey.HashedKey is an immutable string so reading it
|
||||
// without a lock is safe even if the key is later removed from the map.
|
||||
var apiKey *APIKey
|
||||
if id, secret, ok := splitKey(rawKey); ok {
|
||||
apiKey = m.validateByID(id, secret)
|
||||
} else {
|
||||
apiKey = m.validateLegacy(ctx, rawKey)
|
||||
}
|
||||
if apiKey == nil {
|
||||
return nil, errors.New(errors.ErrCodeUnauthorized, "invalid API key")
|
||||
}
|
||||
|
||||
// Re-check the key still exists to avoid resurrecting a revoked key's metadata.
|
||||
usedAt := time.Now()
|
||||
m.mu.Lock()
|
||||
if _, ok := m.keys[apiKey.ID]; ok {
|
||||
apiKey.LastUsedAt = usedAt
|
||||
}
|
||||
m.mu.Unlock()
|
||||
|
||||
// Async store update: never block validation on a DB write.
|
||||
m.persistLastUsedAsync(apiKey.ID, usedAt)
|
||||
return apiKey, nil
|
||||
}
|
||||
|
||||
func splitKey(rawKey string) (id, secret string, ok bool) {
|
||||
if !strings.HasPrefix(rawKey, keyPrefix) {
|
||||
return "", "", false
|
||||
}
|
||||
return strings.Cut(rawKey, keySeparator)
|
||||
}
|
||||
|
||||
// hasKeyID reports whether k was minted with an id embedded in its raw key.
|
||||
// Legacy ids are bare generateID output, which is always legacyIDLen long.
|
||||
func hasKeyID(k *APIKey) bool {
|
||||
return strings.HasPrefix(k.ID, keyPrefix) && len(k.ID) > legacyIDLen
|
||||
}
|
||||
|
||||
func (m *Manager) validateByID(id, secret string) *APIKey {
|
||||
m.mu.RLock()
|
||||
apiKey := m.keys[id]
|
||||
m.mu.RUnlock()
|
||||
|
||||
hash := dummyHash
|
||||
if apiKey != nil {
|
||||
hash = []byte(apiKey.HashedKey)
|
||||
}
|
||||
err := bcryptCompare(hash, []byte(secret))
|
||||
if apiKey == nil || err != nil || expired(apiKey, time.Now()) {
|
||||
return nil
|
||||
}
|
||||
return apiKey
|
||||
}
|
||||
|
||||
func (m *Manager) validateLegacy(ctx context.Context, rawKey string) *APIKey {
|
||||
m.mu.RLock()
|
||||
candidates := make([]*APIKey, 0, len(m.keys))
|
||||
now := time.Now()
|
||||
for _, apiKey := range m.keys {
|
||||
if apiKey.ExpiresAt != nil && now.After(*apiKey.ExpiresAt) {
|
||||
continue
|
||||
for _, k := range m.keys {
|
||||
if !hasKeyID(k) && !expired(k, now) {
|
||||
candidates = append(candidates, k)
|
||||
}
|
||||
candidates = append(candidates, apiKey)
|
||||
}
|
||||
m.mu.RUnlock()
|
||||
|
||||
// Phase 2: run bcrypt comparisons without holding any lock so concurrent
|
||||
// auth checks can proceed in parallel.
|
||||
for _, apiKey := range candidates {
|
||||
if err := bcrypt.CompareHashAndPassword([]byte(apiKey.HashedKey), []byte(rawKey)); err == nil {
|
||||
// Phase 3: briefly take the write lock to update LastUsedAt.
|
||||
// Re-check the key still exists in the map to avoid resurrecting
|
||||
// a revoked key's metadata.
|
||||
usedAt := time.Now()
|
||||
m.mu.Lock()
|
||||
if _, ok := m.keys[apiKey.ID]; ok {
|
||||
apiKey.LastUsedAt = usedAt
|
||||
}
|
||||
m.mu.Unlock()
|
||||
|
||||
// Async store update: never block validation on a DB write.
|
||||
m.persistLastUsedAsync(apiKey.ID, usedAt)
|
||||
return apiKey, nil
|
||||
for _, k := range candidates {
|
||||
select {
|
||||
case legacySlots <- struct{}{}:
|
||||
case <-ctx.Done():
|
||||
return nil
|
||||
}
|
||||
err := bcryptCompare([]byte(k.HashedKey), []byte(rawKey))
|
||||
<-legacySlots
|
||||
if err == nil {
|
||||
return k
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
return nil, errors.New(errors.ErrCodeUnauthorized, "invalid API key")
|
||||
func expired(k *APIKey, now time.Time) bool {
|
||||
return k.ExpiresAt != nil && now.After(*k.ExpiresAt)
|
||||
}
|
||||
|
||||
// persistLastUsedAsync flushes a LastUsedAt update to the store off the hot
|
||||
|
||||
@@ -116,6 +116,15 @@ func (f *fakeStore) DeletePackage(context.Context, string, string, string) error
|
||||
func (f *fakeStore) ListPackages(context.Context, *metadata.ListOptions) ([]*metadata.Package, error) {
|
||||
return nil, metadata.ErrNotImplemented
|
||||
}
|
||||
func (f *fakeStore) ListPackageGroups(context.Context, metadata.GroupListOptions) (*metadata.GroupPage, error) {
|
||||
return nil, metadata.ErrNotImplemented
|
||||
}
|
||||
func (f *fakeStore) GetScanSummaries(context.Context, []string, bool) ([]*metadata.ScanSummary, error) {
|
||||
return nil, metadata.ErrNotImplemented
|
||||
}
|
||||
func (f *fakeStore) GetRegistryStats(context.Context) ([]metadata.RegistryStat, error) {
|
||||
return nil, metadata.ErrNotImplemented
|
||||
}
|
||||
func (f *fakeStore) UpdateDownloadCount(context.Context, string, string, string) error {
|
||||
return metadata.ErrNotImplemented
|
||||
}
|
||||
@@ -156,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.
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
// countBcrypt wraps bcryptCompare and returns the call counter.
|
||||
func countBcrypt(t *testing.T) *atomic.Int64 {
|
||||
t.Helper()
|
||||
var n atomic.Int64
|
||||
orig := bcryptCompare
|
||||
bcryptCompare = func(h, p []byte) error {
|
||||
n.Add(1)
|
||||
return orig(h, p)
|
||||
}
|
||||
t.Cleanup(func() { bcryptCompare = orig })
|
||||
return &n
|
||||
}
|
||||
|
||||
func newTestManager() *Manager { return NewWithStore(Config{BcryptCost: bcrypt.MinCost}, nil) }
|
||||
|
||||
// addLegacyKey stores a key in the pre-key-id format: bcrypt of the whole raw key, no id in the key.
|
||||
func addLegacyKey(t *testing.T, m *Manager) string {
|
||||
t.Helper()
|
||||
b := make([]byte, 32)
|
||||
_, _ = rand.Read(b)
|
||||
raw := base64.URLEncoding.EncodeToString(b)
|
||||
h, err := bcrypt.GenerateFromPassword([]byte(raw), bcrypt.MinCost)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
k := &APIKey{ID: generateID(), Name: "legacy", HashedKey: string(h), Role: RoleReadOnly, CreatedAt: time.Now(), Permissions: getPermissionsForRole(RoleReadOnly)}
|
||||
m.mu.Lock()
|
||||
m.keys[k.ID] = k
|
||||
m.mu.Unlock()
|
||||
return raw
|
||||
}
|
||||
|
||||
func TestValidateAPIKeyCostIndependentOfKeyCount(t *testing.T) {
|
||||
m := newTestManager()
|
||||
_, good, err := m.GenerateAPIKey("target", RoleReadWrite, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for i := 0; i < 50; i++ {
|
||||
if _, _, err := m.GenerateAPIKey("filler", RoleReadOnly, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
n := countBcrypt(t)
|
||||
|
||||
if _, err := m.ValidateAPIKey(context.Background(), good); err != nil {
|
||||
t.Fatalf("valid key rejected: %v", err)
|
||||
}
|
||||
if got := n.Load(); got != 1 {
|
||||
t.Errorf("valid key: %d bcrypt compares, want 1", got)
|
||||
}
|
||||
|
||||
n.Store(0)
|
||||
idPart := strings.SplitN(good, keySeparator, 2)[0]
|
||||
cases := map[string]string{
|
||||
"known id, wrong secret": idPart + keySeparator + "AAAA",
|
||||
"unknown id": keyPrefix + "nope" + keySeparator + "AAAA",
|
||||
"no secret": idPart + keySeparator,
|
||||
}
|
||||
for name, raw := range cases {
|
||||
n.Store(0)
|
||||
if _, err := m.ValidateAPIKey(context.Background(), raw); err == nil {
|
||||
t.Errorf("%s: accepted", name)
|
||||
}
|
||||
if got := n.Load(); got != 1 {
|
||||
t.Errorf("%s: %d bcrypt compares, want exactly 1", name, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateAPIKeyRejectsSecretOfAnotherKey(t *testing.T) {
|
||||
m := newTestManager()
|
||||
a, _, _ := m.GenerateAPIKey("a", RoleAdmin, nil)
|
||||
_, rawB, _ := m.GenerateAPIKey("b", RoleReadOnly, nil)
|
||||
secretB := strings.SplitN(rawB, keySeparator, 2)[1]
|
||||
if _, err := m.ValidateAPIKey(context.Background(), a.ID+keySeparator+secretB); err == nil {
|
||||
t.Fatal("id of one key with the secret of another was accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLegacyKeysStillValidate(t *testing.T) {
|
||||
m := newTestManager()
|
||||
raw := addLegacyKey(t, m)
|
||||
for i := 0; i < 3; i++ {
|
||||
addLegacyKey(t, m)
|
||||
}
|
||||
k, err := m.ValidateAPIKey(context.Background(), raw)
|
||||
if err != nil || k == nil || k.Name != "legacy" {
|
||||
t.Fatalf("legacy key rejected: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewFormatKeyNeverTouchesLegacyKeys(t *testing.T) {
|
||||
m := newTestManager()
|
||||
for i := 0; i < 20; i++ {
|
||||
addLegacyKey(t, m)
|
||||
}
|
||||
_, raw, _ := m.GenerateAPIKey("new", RoleReadOnly, nil)
|
||||
n := countBcrypt(t)
|
||||
if _, err := m.ValidateAPIKey(context.Background(), raw+"x"); err == nil {
|
||||
t.Fatal("bad key accepted")
|
||||
}
|
||||
if got := n.Load(); got != 1 {
|
||||
t.Errorf("%d bcrypt compares with 20 legacy keys stored, want 1", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLegacyComparesAreConcurrencyBounded(t *testing.T) {
|
||||
m := newTestManager()
|
||||
for i := 0; i < 5; i++ {
|
||||
addLegacyKey(t, m)
|
||||
}
|
||||
var cur, peak atomic.Int64
|
||||
orig := bcryptCompare
|
||||
bcryptCompare = func(h, p []byte) error {
|
||||
c := cur.Add(1)
|
||||
for {
|
||||
p := peak.Load()
|
||||
if c <= p || peak.CompareAndSwap(p, c) {
|
||||
break
|
||||
}
|
||||
}
|
||||
time.Sleep(2 * time.Millisecond)
|
||||
cur.Add(-1)
|
||||
return orig(h, p)
|
||||
}
|
||||
t.Cleanup(func() { bcryptCompare = orig })
|
||||
|
||||
var wg sync.WaitGroup
|
||||
for i := 0; i < 40; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
_, _ = m.ValidateAPIKey(context.Background(), "bad-legacy-key-bad-legacy-key-bad-legacy-key-0000")
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
if got := peak.Load(); got > maxLegacyCompares {
|
||||
t.Errorf("peak concurrent legacy compares %d, want <= %d", got, maxLegacyCompares)
|
||||
}
|
||||
}
|
||||
Vendored
+89
-11
@@ -12,6 +12,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/analytics"
|
||||
hoarderconfig "github.com/lukaszraczylo/gohoarder/pkg/config"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/errors"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/events"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
@@ -46,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
|
||||
@@ -79,15 +81,18 @@ func (m *Manager) emit(eventType string, payload map[string]interface{}) {
|
||||
|
||||
// Config holds cache manager configuration
|
||||
type Config struct {
|
||||
Now func() time.Time // Clock; nil means time.Now
|
||||
DefaultTTL time.Duration // Freshness TTL for metadata entries
|
||||
CleanupInterval time.Duration // How often to run cleanup
|
||||
IdleTTL time.Duration // Remove entries not requested for this long (0 = off)
|
||||
EvictionThreshold float64 // Trigger eviction when usage > threshold (0.0-1.0)
|
||||
MaxConcurrent int // Max concurrent upstream fetches
|
||||
MaxPackageSize int64 // Maximum package size in bytes (0 = default 2GB)
|
||||
ScanWaitTimeout time.Duration // How long the first download waits for its scan (0 = 30s)
|
||||
FailClosed bool // Refuse a package whose scan did not finish in time
|
||||
Now func() time.Time // Clock; nil means time.Now
|
||||
TTLOverrides map[string]time.Duration // Per-registry metadata freshness TTL; falls back to DefaultTTL
|
||||
DefaultTTL time.Duration // Freshness TTL for metadata entries
|
||||
CleanupInterval time.Duration // How often to run cleanup
|
||||
IdleTTL time.Duration // Remove entries not requested for this long (0 = off)
|
||||
DeletedRetention time.Duration // Hard-delete soft-deleted rows older than this (0 = keep forever)
|
||||
EvictionThreshold float64 // Trigger eviction when usage > threshold (0.0-1.0)
|
||||
MaxConcurrent int // Max concurrent upstream fetches
|
||||
MaxPackageSize int64 // Maximum package size in bytes (0 = default 2GB)
|
||||
ScanWaitTimeout time.Duration // How long the first download waits for its scan (0 = 30s)
|
||||
FailClosed bool // Refuse a package whose scan did not finish in time
|
||||
RescanAfter time.Duration // Rescan a cache hit whose scan result is older than this before serving (0 = off)
|
||||
}
|
||||
|
||||
const defaultScanWaitTimeout = 30 * time.Second
|
||||
@@ -95,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
|
||||
|
||||
@@ -172,7 +180,7 @@ func New(storage storage.StorageBackend, metadata metadata.MetadataStore, scanne
|
||||
}
|
||||
|
||||
if config.DefaultTTL == 0 {
|
||||
config.DefaultTTL = 7 * 24 * time.Hour // 7 days default
|
||||
config.DefaultTTL = hoarderconfig.DefaultMetadataTTL
|
||||
}
|
||||
|
||||
if config.CleanupInterval == 0 {
|
||||
@@ -326,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")
|
||||
@@ -585,7 +596,7 @@ func (m *Manager) store(ctx context.Context, registry, name, version, releaseVer
|
||||
// entries must refresh and keep a freshness expiry.
|
||||
var expiresAt *time.Time
|
||||
if isMetadataEntry {
|
||||
exp := now.Add(m.config.DefaultTTL)
|
||||
exp := now.Add(m.metadataTTL(registry))
|
||||
expiresAt = &exp
|
||||
}
|
||||
|
||||
@@ -693,6 +704,39 @@ func (m *Manager) store(ctx context.Context, registry, name, version, releaseVer
|
||||
return pkg, nil
|
||||
}
|
||||
|
||||
// ScanFile returns a local file holding a cached package, for a scan retry. Backends with a
|
||||
// local path serve it directly; others are copied to a temp file that cleanup removes.
|
||||
func (m *Manager) ScanFile(ctx context.Context, registry, name, version string) (string, func(), error) {
|
||||
pkg, err := m.metadata.GetPackage(ctx, registry, name, version)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
if local, ok := m.storage.(storage.LocalPathProvider); ok {
|
||||
path, pathErr := local.GetLocalPath(ctx, pkg.StorageKey)
|
||||
return path, func() {}, pathErr
|
||||
}
|
||||
rc, err := m.storage.Get(ctx, pkg.StorageKey)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
defer func() { _ = rc.Close() }()
|
||||
tmp, err := os.CreateTemp(os.TempDir(), "gohoarder-rescan-*")
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
cleanup := func() { _ = os.Remove(tmp.Name()) } // #nosec G104 -- cleanup
|
||||
if _, err := io.Copy(tmp, rc); err != nil {
|
||||
_ = tmp.Close() // #nosec G104 -- cleanup
|
||||
cleanup()
|
||||
return "", nil, err
|
||||
}
|
||||
if err := tmp.Close(); err != nil {
|
||||
cleanup()
|
||||
return "", nil, err
|
||||
}
|
||||
return tmp.Name(), cleanup, nil
|
||||
}
|
||||
|
||||
// Delete removes a package from cache
|
||||
func (m *Manager) Delete(ctx context.Context, registry, name, version string) error {
|
||||
pkg, err := m.metadata.GetPackage(ctx, registry, name, version)
|
||||
@@ -703,6 +747,14 @@ func (m *Manager) Delete(ctx context.Context, registry, name, version string) er
|
||||
return m.deletePackage(ctx, pkg)
|
||||
}
|
||||
|
||||
// metadataTTL returns the freshness window for a registry's metadata entries.
|
||||
func (m *Manager) metadataTTL(registry string) time.Duration {
|
||||
if ttl, ok := m.config.TTLOverrides[registry]; ok {
|
||||
return ttl
|
||||
}
|
||||
return m.config.DefaultTTL
|
||||
}
|
||||
|
||||
// deletePackage deletes a package from both storage and metadata
|
||||
func (m *Manager) deletePackage(ctx context.Context, pkg *metadata.Package) error {
|
||||
// Delete from storage
|
||||
@@ -874,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)
|
||||
|
||||
Vendored
+33
-1
@@ -145,6 +145,30 @@ func (m *MockMetadataStore) ListPackages(ctx context.Context, opts *metadata.Lis
|
||||
return args.Get(0).([]*metadata.Package), args.Error(1)
|
||||
}
|
||||
|
||||
func (m *MockMetadataStore) ListPackageGroups(ctx context.Context, opts metadata.GroupListOptions) (*metadata.GroupPage, error) {
|
||||
args := m.Called(ctx, opts)
|
||||
if args.Get(0) == nil {
|
||||
return nil, args.Error(1)
|
||||
}
|
||||
return args.Get(0).(*metadata.GroupPage), args.Error(1)
|
||||
}
|
||||
|
||||
func (m *MockMetadataStore) GetScanSummaries(ctx context.Context, packageIDs []string, withDetails bool) ([]*metadata.ScanSummary, error) {
|
||||
args := m.Called(ctx, packageIDs, withDetails)
|
||||
if args.Get(0) == nil {
|
||||
return nil, args.Error(1)
|
||||
}
|
||||
return args.Get(0).([]*metadata.ScanSummary), args.Error(1)
|
||||
}
|
||||
|
||||
func (m *MockMetadataStore) GetRegistryStats(ctx context.Context) ([]metadata.RegistryStat, error) {
|
||||
args := m.Called(ctx)
|
||||
if args.Get(0) == nil {
|
||||
return nil, args.Error(1)
|
||||
}
|
||||
return args.Get(0).([]metadata.RegistryStat), args.Error(1)
|
||||
}
|
||||
|
||||
func (m *MockMetadataStore) UpdateDownloadCount(ctx context.Context, registry, name, version string) error {
|
||||
args := m.Called(ctx, registry, name, version)
|
||||
return args.Error(0)
|
||||
@@ -241,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.
|
||||
@@ -346,7 +378,7 @@ func TestNew(t *testing.T) {
|
||||
|
||||
// Verify defaults were set
|
||||
if tt.config.DefaultTTL == 0 {
|
||||
assert.Equal(t, 7*24*time.Hour, manager.config.DefaultTTL)
|
||||
assert.Equal(t, 24*time.Hour, manager.config.DefaultTTL)
|
||||
}
|
||||
if tt.config.CleanupInterval == 0 {
|
||||
assert.Equal(t, 1*time.Hour, manager.config.CleanupInterval)
|
||||
|
||||
Vendored
+24
@@ -0,0 +1,24 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// Clients gate on a 72h release age; a metadata page that stays fresh longer would hide the gate's inputs.
|
||||
func TestMetadataEntryDefaultTTLIsBelowReleaseAgeGate(t *testing.T) {
|
||||
h := newIdleHarness(t, Config{})
|
||||
entry := h.get(t, "left-pad", "metadata")
|
||||
|
||||
require.NotNil(t, entry.Package.ExpiresAt)
|
||||
require.Equal(t, 24*time.Hour, entry.Package.ExpiresAt.Sub(h.clock.Now()))
|
||||
}
|
||||
|
||||
func TestMetadataEntryExplicitTTLWins(t *testing.T) {
|
||||
h := newIdleHarness(t, Config{DefaultTTL: 6 * time.Hour})
|
||||
entry := h.get(t, "left-pad", "metadata")
|
||||
|
||||
require.Equal(t, 6*time.Hour, entry.Package.ExpiresAt.Sub(h.clock.Now()))
|
||||
}
|
||||
Vendored
+90
@@ -0,0 +1,90 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// purgeRecorder plays a store holding `pending` soft-deleted rows.
|
||||
type purgeRecorder struct {
|
||||
*memMetadata
|
||||
err error
|
||||
cutoffs []time.Time
|
||||
limits []int
|
||||
pending int64
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
func (p *purgeRecorder) PurgeDeletedPackages(_ context.Context, before time.Time, limit int) (int64, error) {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
p.cutoffs = append(p.cutoffs, before)
|
||||
p.limits = append(p.limits, limit)
|
||||
if p.err != nil {
|
||||
return 0, p.err
|
||||
}
|
||||
n := min(p.pending, int64(limit))
|
||||
p.pending -= n
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func newPurgeHarness(t *testing.T, retention time.Duration, pending int64) (*idleHarness, *purgeRecorder) {
|
||||
t.Helper()
|
||||
h := &idleHarness{clock: newFakeClock(), store: newMemStorage()}
|
||||
rec := &purgeRecorder{memMetadata: newMemMetadata(h.clock), pending: pending}
|
||||
h.meta = rec.memMetadata
|
||||
mgr, err := New(h.store, rec, nil, nil, Config{Now: h.clock.Now, CleanupInterval: 24 * time.Hour, DeletedRetention: retention})
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { _ = mgr.Close() })
|
||||
h.mgr = mgr
|
||||
return h, rec
|
||||
}
|
||||
|
||||
func TestCleanupPurgesDeletedRowsPastRetention(t *testing.T) {
|
||||
h, rec := newPurgeHarness(t, 30*day, 3*int64(cleanupBatchSize)+7)
|
||||
|
||||
h.mgr.cleanup(context.Background())
|
||||
|
||||
require.Zero(t, rec.pending, "batches continue until the store runs dry")
|
||||
require.Len(t, rec.limits, 4, "three full batches and a short one")
|
||||
for _, limit := range rec.limits {
|
||||
require.Equal(t, cleanupBatchSize, limit, "every batch is bounded")
|
||||
}
|
||||
require.Equal(t, h.clock.Now().Add(-30*day), rec.cutoffs[0], "the cutoff is now minus the retention")
|
||||
}
|
||||
|
||||
func TestCleanupPurgeIsBoundedPerPass(t *testing.T) {
|
||||
_, rec := newPurgeHarness(t, 30*day, int64(maxPurgeBatches+50)*int64(cleanupBatchSize))
|
||||
h := &Manager{config: Config{DeletedRetention: day, Now: time.Now}, metadata: rec}
|
||||
|
||||
got := h.purgeDeleted(context.Background(), time.Now())
|
||||
|
||||
require.EqualValues(t, maxPurgeBatches*cleanupBatchSize, got)
|
||||
require.EqualValues(t, 50*cleanupBatchSize, rec.pending, "the next pass continues where this one stopped")
|
||||
}
|
||||
|
||||
func TestCleanupSkipsPurgeWhenRetentionIsZero(t *testing.T) {
|
||||
h, rec := newPurgeHarness(t, 0, 10)
|
||||
|
||||
h.mgr.cleanup(context.Background())
|
||||
|
||||
require.Empty(t, rec.limits, "zero keeps every row")
|
||||
require.EqualValues(t, 10, rec.pending)
|
||||
}
|
||||
|
||||
func TestCleanupPurgeFailureDoesNotStopCleanup(t *testing.T) {
|
||||
h, rec := newPurgeHarness(t, 30*day, 10)
|
||||
rec.err = errors.New("db down")
|
||||
h.get(t, "lodash", "metadata")
|
||||
h.clock.Advance(2 * day)
|
||||
|
||||
h.mgr.cleanup(context.Background())
|
||||
|
||||
require.Len(t, rec.limits, 1, "one failed attempt, no retry loop")
|
||||
require.False(t, h.exists("lodash", "metadata"), "expired metadata is still removed")
|
||||
}
|
||||
Vendored
+71
@@ -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)
|
||||
}
|
||||
Vendored
+176
@@ -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")
|
||||
}
|
||||
Vendored
+75
@@ -0,0 +1,75 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/config"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// listingMetadata adds the full listing the rescan worker walks.
|
||||
type listingMetadata struct{ scanMetadata }
|
||||
|
||||
func (m listingMetadata) ListPackages(context.Context, *metadata.ListOptions) ([]*metadata.Package, error) {
|
||||
return m.list(0, func(*metadata.Package) bool { return true }, func(a, b *metadata.Package) bool { return a.Name < b.Name }), nil
|
||||
}
|
||||
|
||||
// bodyScanner reports the bytes it can read at the path it is given.
|
||||
type bodyScanner struct{ seen chan string }
|
||||
|
||||
func (*bodyScanner) Name() string { return "body-scanner" }
|
||||
func (*bodyScanner) Health(context.Context) error { return nil }
|
||||
func (s *bodyScanner) Scan(_ context.Context, registry, name, version, path string) (*metadata.ScanResult, error) {
|
||||
body, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
s.seen <- "unreadable"
|
||||
return nil, err
|
||||
}
|
||||
s.seen <- string(body)
|
||||
return &metadata.ScanResult{Registry: registry, PackageName: name, PackageVersion: version, Scanner: s.Name(), Status: metadata.ScanStatusClean}, nil
|
||||
}
|
||||
|
||||
// A backend with no local path (S3, SMB) must still be rescanned: the worker reads the blob
|
||||
// through the cache's file source instead of skipping the package.
|
||||
func TestRescanWorkerScansRemoteStorage(t *testing.T) {
|
||||
clock := newFakeClock()
|
||||
store := newMemStorage() // no GetLocalPath, like S3 and SMB
|
||||
meta := listingMetadata{scanMetadata{newMemMetadata(clock)}}
|
||||
|
||||
scanMgr, err := scanner.New(config.SecurityConfig{Enabled: true}, meta)
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(scanMgr.Stop)
|
||||
bs := &bodyScanner{seen: make(chan string, 8)}
|
||||
scanMgr.RegisterScanner(bs)
|
||||
|
||||
mgr, err := New(store, meta, scanMgr, nil, Config{Now: clock.Now, CleanupInterval: 24 * time.Hour})
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { _ = mgr.Close() })
|
||||
scanMgr.SetFileSource(mgr.ScanFile)
|
||||
|
||||
ctx := context.Background()
|
||||
require.NoError(t, store.Put(ctx, "npm/left-pad/1.3.0", strings.NewReader("tarball-bytes"), nil))
|
||||
require.NoError(t, meta.SavePackage(ctx, &metadata.Package{
|
||||
Registry: "npm", Name: "left-pad", Version: "1.3.0", StorageKey: "npm/left-pad/1.3.0",
|
||||
CachedAt: clock.Now(), LastAccessed: clock.Now(),
|
||||
}))
|
||||
|
||||
worker := scanner.NewRescanWorker(scanMgr, meta, time.Hour)
|
||||
runCtx, cancel := context.WithCancel(ctx)
|
||||
done := make(chan struct{})
|
||||
go func() { worker.Start(runCtx); close(done) }()
|
||||
t.Cleanup(func() { cancel(); <-done })
|
||||
|
||||
select {
|
||||
case got := <-bs.seen:
|
||||
require.Equal(t, "tarball-bytes", got)
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("rescan never scanned the remote-storage package")
|
||||
}
|
||||
}
|
||||
Vendored
+92
@@ -0,0 +1,92 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/config"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner/scanerr"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// scanMetadata lets the real scanner.Manager record results against the in-memory store.
|
||||
type scanMetadata struct {
|
||||
*memMetadata
|
||||
}
|
||||
|
||||
func (scanMetadata) SaveScanResult(context.Context, *metadata.ScanResult) error { return nil }
|
||||
func (scanMetadata) GetScanResult(context.Context, string, string, string) (*metadata.ScanResult, error) {
|
||||
return nil, fmt.Errorf("no result")
|
||||
}
|
||||
|
||||
// fileScanner fails on infrastructure once, then succeeds; it records what it could read.
|
||||
type fileScanner struct {
|
||||
seen chan string
|
||||
mu sync.Mutex
|
||||
n int
|
||||
}
|
||||
|
||||
func (*fileScanner) Name() string { return "file-scanner" }
|
||||
func (*fileScanner) Health(context.Context) error { return nil }
|
||||
func (s *fileScanner) Scan(_ context.Context, registry, name, version, path string) (*metadata.ScanResult, error) {
|
||||
s.mu.Lock()
|
||||
s.n++
|
||||
n := s.n
|
||||
s.mu.Unlock()
|
||||
body, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
s.seen <- "unreadable"
|
||||
} else {
|
||||
s.seen <- string(body)
|
||||
}
|
||||
if n == 1 {
|
||||
return nil, fmt.Errorf("%w: scanner timed out", scanerr.ErrInfrastructure)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &metadata.ScanResult{Registry: registry, PackageName: name, PackageVersion: version, Scanner: "file-scanner", Status: metadata.ScanStatusClean}, nil
|
||||
}
|
||||
|
||||
// On a backend with no local path (S3, SMB) the scan source is a temp file removed after the
|
||||
// first scan; a retry must read the blob again instead of scanning a path that is gone.
|
||||
func TestScanRetryOnRemoteStorageReadsBlobAgain(t *testing.T) {
|
||||
clock := newFakeClock()
|
||||
store := newMemStorage() // no GetLocalPath, like S3 and SMB
|
||||
meta := scanMetadata{newMemMetadata(clock)}
|
||||
|
||||
scanMgr, err := scanner.New(config.SecurityConfig{Enabled: true, ScanRetryInterval: 50 * time.Millisecond}, meta)
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(scanMgr.Stop)
|
||||
fs := &fileScanner{seen: make(chan string, 8)}
|
||||
scanMgr.RegisterScanner(fs)
|
||||
|
||||
mgr, err := New(store, meta, scanMgr, nil, Config{Now: clock.Now, CleanupInterval: 24 * time.Hour, ScanWaitTimeout: 200 * time.Millisecond})
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { _ = mgr.Close() })
|
||||
scanMgr.SetFileSource(mgr.ScanFile)
|
||||
|
||||
entry, err := mgr.Get(context.Background(), "npm", "left-pad", "1.3.0", func(context.Context) (*FetchResult, error) {
|
||||
return &FetchResult{Data: io.NopCloser(strings.NewReader("tarball-bytes"))}, nil
|
||||
})
|
||||
require.NoError(t, err)
|
||||
_, _ = io.Copy(io.Discard, entry.Data)
|
||||
_ = entry.Data.Close()
|
||||
|
||||
for attempt := 1; attempt <= 2; attempt++ {
|
||||
select {
|
||||
case got := <-fs.seen:
|
||||
require.Equal(t, "tarball-bytes", got, "scan attempt %d must read the blob", attempt)
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatalf("scan attempt %d never ran", attempt)
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
+38
@@ -0,0 +1,38 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func (h *idleHarness) getFrom(t *testing.T, registry, name, version string) *CacheEntry {
|
||||
t.Helper()
|
||||
entry, err := h.mgr.Get(context.Background(), registry, name, version, func(context.Context) (*FetchResult, error) {
|
||||
return &FetchResult{Data: io.NopCloser(strings.NewReader("payload-" + name)), UpstreamURL: "https://upstream/" + name}, nil
|
||||
})
|
||||
require.NoError(t, err)
|
||||
_ = entry.Data.Close()
|
||||
return entry
|
||||
}
|
||||
|
||||
func TestMetadataTTLOverridesApplyPerRegistry(t *testing.T) {
|
||||
h := newIdleHarness(t, Config{
|
||||
DefaultTTL: 6 * time.Hour,
|
||||
TTLOverrides: map[string]time.Duration{"npm": time.Hour, "go": 12 * time.Hour},
|
||||
})
|
||||
|
||||
require.Equal(t, time.Hour, h.getFrom(t, "npm", "left-pad", "metadata").Package.ExpiresAt.Sub(h.clock.Now()))
|
||||
require.Equal(t, 12*time.Hour, h.getFrom(t, "go", "example.com/m/@v/list", "list").Package.ExpiresAt.Sub(h.clock.Now()))
|
||||
require.Equal(t, 6*time.Hour, h.getFrom(t, "pypi", "left-pad", "metadata").Package.ExpiresAt.Sub(h.clock.Now()), "registry without override keeps default_ttl")
|
||||
}
|
||||
|
||||
func TestMetadataTTLOverridesSkipArtifacts(t *testing.T) {
|
||||
h := newIdleHarness(t, Config{TTLOverrides: map[string]time.Duration{"npm": time.Hour}})
|
||||
|
||||
require.Nil(t, h.getFrom(t, "npm", "left-pad", artifactVer).Package.ExpiresAt, "artifacts have no age expiry")
|
||||
}
|
||||
+69
-28
@@ -35,6 +35,7 @@ type ServerConfig struct {
|
||||
ReadTimeout time.Duration `mapstructure:"read_timeout" json:"read_timeout"`
|
||||
WriteTimeout time.Duration `mapstructure:"write_timeout" json:"write_timeout"`
|
||||
IdleTimeout time.Duration `mapstructure:"idle_timeout" json:"idle_timeout"`
|
||||
ReadBufferSize int `mapstructure:"read_buffer_size" json:"read_buffer_size"` // bytes; caps the request line plus headers
|
||||
}
|
||||
|
||||
// TLSConfig contains TLS/HTTPS configuration
|
||||
@@ -133,32 +134,61 @@ type MySQLConfig struct {
|
||||
ParseTime bool `mapstructure:"parse_time" json:"parse_time"`
|
||||
}
|
||||
|
||||
// DefaultMetadataTTL is the freshness window for metadata pages. It stays below the 72h
|
||||
// release-age gate clients apply, so a cached page never hides the entries the gate reads.
|
||||
const DefaultMetadataTTL = 24 * time.Hour
|
||||
|
||||
// DefaultReadBufferSize is the HTTP server read buffer. Fiber's own 8192 rejects browsers
|
||||
// that send OIDC session cookies plus a long Referer or URL with 431.
|
||||
const DefaultReadBufferSize = 16384
|
||||
|
||||
// ttlOverrideRegistries maps each accepted cache.ttl_overrides key to its registry name.
|
||||
var ttlOverrideRegistries = map[string]string{"npm": "npm", "pypi": "pypi", "pip": "pypi", "go": "go"}
|
||||
|
||||
// MetadataTTLOverrides returns the per-registry metadata freshness TTLs keyed by registry name.
|
||||
func (c CacheConfig) MetadataTTLOverrides() map[string]time.Duration {
|
||||
out := make(map[string]time.Duration, len(c.TTLOverrides))
|
||||
for key, ttl := range c.TTLOverrides {
|
||||
out[ttlOverrideRegistries[key]] = ttl
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// DefaultIdleTTL is how long a cached item can go unrequested before cleanup removes it.
|
||||
const DefaultIdleTTL = 7 * 24 * time.Hour
|
||||
|
||||
// DefaultDeletedRetention is how long a soft-deleted package row is kept before cleanup purges it.
|
||||
const DefaultDeletedRetention = 30 * 24 * time.Hour
|
||||
|
||||
// CacheConfig contains cache management configuration
|
||||
type CacheConfig struct {
|
||||
TTLOverrides map[string]time.Duration `mapstructure:"ttl_overrides" json:"ttl_overrides"`
|
||||
DefaultTTL time.Duration `mapstructure:"default_ttl" json:"default_ttl"`
|
||||
CleanupInterval time.Duration `mapstructure:"cleanup_interval" json:"cleanup_interval"`
|
||||
IdleTTL time.Duration `mapstructure:"idle_ttl" json:"idle_ttl"` // 0 disables idle eviction
|
||||
MaxSizeBytes int64 `mapstructure:"max_size_bytes" json:"max_size_bytes"`
|
||||
PerProjectQuota int64 `mapstructure:"per_project_quota" json:"per_project_quota"`
|
||||
// DeletedRetention is how long soft-deleted package rows stay before cleanup purges them; 0 keeps them forever.
|
||||
DeletedRetention time.Duration `mapstructure:"deleted_retention" json:"deleted_retention"`
|
||||
MaxSizeBytes int64 `mapstructure:"max_size_bytes" json:"max_size_bytes"`
|
||||
PerProjectQuota int64 `mapstructure:"per_project_quota" json:"per_project_quota"`
|
||||
}
|
||||
|
||||
// SecurityConfig contains security scanning configuration
|
||||
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
|
||||
@@ -330,11 +360,12 @@ type PyPIHandlerConfig struct {
|
||||
func Default() *Config {
|
||||
return &Config{
|
||||
Server: ServerConfig{
|
||||
Host: "0.0.0.0",
|
||||
Port: 8080,
|
||||
ReadTimeout: 5 * time.Minute,
|
||||
WriteTimeout: 5 * time.Minute,
|
||||
IdleTimeout: 2 * time.Minute,
|
||||
Host: "0.0.0.0",
|
||||
Port: 8080,
|
||||
ReadTimeout: 5 * time.Minute,
|
||||
WriteTimeout: 5 * time.Minute,
|
||||
IdleTimeout: 2 * time.Minute,
|
||||
ReadBufferSize: DefaultReadBufferSize,
|
||||
TLS: TLSConfig{
|
||||
Enabled: false,
|
||||
},
|
||||
@@ -355,16 +386,12 @@ func Default() *Config {
|
||||
},
|
||||
},
|
||||
Cache: CacheConfig{
|
||||
DefaultTTL: 7 * 24 * time.Hour,
|
||||
CleanupInterval: 1 * time.Hour,
|
||||
IdleTTL: DefaultIdleTTL,
|
||||
MaxSizeBytes: 500 * 1024 * 1024 * 1024, // 500GB
|
||||
PerProjectQuota: 50 * 1024 * 1024 * 1024, // 50GB
|
||||
TTLOverrides: map[string]time.Duration{
|
||||
"npm": 7 * 24 * time.Hour,
|
||||
"pip": 7 * 24 * time.Hour,
|
||||
"go": 7 * 24 * time.Hour,
|
||||
},
|
||||
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,
|
||||
@@ -507,12 +534,26 @@ func (c *Config) Validate() error {
|
||||
}
|
||||
|
||||
// Validate cache
|
||||
if c.Server.ReadBufferSize < 0 {
|
||||
return fmt.Errorf("server.read_buffer_size cannot be negative")
|
||||
}
|
||||
if c.Cache.DefaultTTL < 0 {
|
||||
return fmt.Errorf("cache.default_ttl cannot be negative")
|
||||
}
|
||||
if c.Cache.IdleTTL < 0 {
|
||||
return fmt.Errorf("cache.idle_ttl cannot be negative")
|
||||
}
|
||||
for key, ttl := range c.Cache.TTLOverrides {
|
||||
if _, ok := ttlOverrideRegistries[key]; !ok {
|
||||
return fmt.Errorf("cache.ttl_overrides: unknown registry %q (want npm, pypi or go)", key)
|
||||
}
|
||||
if ttl <= 0 {
|
||||
return fmt.Errorf("cache.ttl_overrides.%s must be positive, got %s", key, ttl)
|
||||
}
|
||||
}
|
||||
if c.Cache.DeletedRetention < 0 {
|
||||
return fmt.Errorf("cache.deleted_retention cannot be negative")
|
||||
}
|
||||
if c.Cache.MaxSizeBytes < 0 {
|
||||
return fmt.Errorf("cache.max_size_bytes cannot be negative")
|
||||
}
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestDefaultMetadataTTL(t *testing.T) {
|
||||
require.Equal(t, 24*time.Hour, Default().Cache.DefaultTTL)
|
||||
for registry, ttl := range Default().Cache.TTLOverrides {
|
||||
require.LessOrEqual(t, ttl, 72*time.Hour, "override %s outlives the 72h release-age gate", registry)
|
||||
}
|
||||
}
|
||||
|
||||
// The shipped examples must not teach a metadata TTL longer than the release-age gate.
|
||||
func TestShippedExamplesKeepMetadataTTLWithinGate(t *testing.T) {
|
||||
for file, key := range map[string]string{
|
||||
"../../config.yaml.example": `default_ttl`,
|
||||
"../../helm/gohoarder/values.yaml": `defaultTTL`,
|
||||
} {
|
||||
raw, err := os.ReadFile(file)
|
||||
require.NoError(t, err)
|
||||
m := regexp.MustCompile(`(?m)^\s*` + key + `:\s*"?(\d+h)"?`).FindSubmatch(raw)
|
||||
require.NotNil(t, m, "%s has no %s", file, key)
|
||||
ttl, err := time.ParseDuration(string(m[1]))
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 24*time.Hour, ttl, file)
|
||||
|
||||
for _, o := range regexp.MustCompile(`(?m)^\s+(?:npm|pip|go):\s*"(\d+h)"`).FindAllSubmatch(raw, -1) {
|
||||
d, err := time.ParseDuration(string(o[1]))
|
||||
require.NoError(t, err)
|
||||
require.LessOrEqual(t, d, 72*time.Hour, "%s: override %s", file, o[0])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestTTLOverridesValidation(t *testing.T) {
|
||||
for name, tc := range map[string]struct {
|
||||
overrides map[string]time.Duration
|
||||
wantErr string
|
||||
}{
|
||||
"known registries": {map[string]time.Duration{"npm": time.Hour, "pypi": time.Hour, "go": time.Hour}, ""},
|
||||
"pip alias": {map[string]time.Duration{"pip": time.Hour}, ""},
|
||||
"unknown registry": {map[string]time.Duration{"cargo": time.Hour}, "cache.ttl_overrides"},
|
||||
"zero": {map[string]time.Duration{"npm": 0}, "cache.ttl_overrides"},
|
||||
"negative": {map[string]time.Duration{"go": -time.Hour}, "cache.ttl_overrides"},
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
c := Default()
|
||||
c.Cache.TTLOverrides = tc.overrides
|
||||
err := c.Validate()
|
||||
if tc.wantErr == "" {
|
||||
require.NoError(t, err)
|
||||
return
|
||||
}
|
||||
require.ErrorContains(t, err, tc.wantErr)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestMetadataTTLOverridesNormalisesPip(t *testing.T) {
|
||||
c := CacheConfig{TTLOverrides: map[string]time.Duration{"pip": time.Hour, "npm": 2 * time.Hour}}
|
||||
require.Equal(t, map[string]time.Duration{"pypi": time.Hour, "npm": 2 * time.Hour}, c.MetadataTTLOverrides())
|
||||
}
|
||||
|
||||
func TestDefaultsKeepNoTTLOverrides(t *testing.T) {
|
||||
require.Empty(t, Default().Cache.TTLOverrides, "an unset override must not shadow default_ttl")
|
||||
}
|
||||
|
||||
func TestLoadReadsTTLOverridesFromYAML(t *testing.T) {
|
||||
write := func(body string) string {
|
||||
path := filepath.Join(t.TempDir(), "config.yaml")
|
||||
require.NoError(t, os.WriteFile(path, []byte(body), 0o600))
|
||||
return path
|
||||
}
|
||||
|
||||
cfg, err := Load(write("cache:\n ttl_overrides:\n npm: 2h\n pip: 30m\n"))
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, map[string]time.Duration{"npm": 2 * time.Hour, "pypi": 30 * time.Minute}, cfg.Cache.MetadataTTLOverrides())
|
||||
|
||||
_, err = Load(write("cache:\n ttl_overrides:\n cargo: 2h\n"))
|
||||
require.ErrorContains(t, err, "cache.ttl_overrides")
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestDeletedRetentionDefaultsToThirtyDays(t *testing.T) {
|
||||
require.Equal(t, 30*24*time.Hour, Default().Cache.DeletedRetention)
|
||||
|
||||
cfg, err := loadCacheYAML(t, "cache:\n default_ttl: 24h\n")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 30*24*time.Hour, cfg.Cache.DeletedRetention, "an unset key keeps the default")
|
||||
}
|
||||
|
||||
func TestDeletedRetentionParse(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
yaml string
|
||||
want time.Duration
|
||||
wantErr bool
|
||||
}{
|
||||
{name: "duration string", yaml: "cache:\n deleted_retention: 48h\n", want: 48 * time.Hour},
|
||||
{name: "zero keeps rows", yaml: "cache:\n deleted_retention: 0\n", want: 0},
|
||||
{name: "quoted duration", yaml: "cache:\n deleted_retention: \"720h\"\n", want: 720 * time.Hour},
|
||||
{name: "negative rejected", yaml: "cache:\n deleted_retention: -1h\n", wantErr: true},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
cfg, err := loadCacheYAML(t, tt.yaml)
|
||||
if tt.wantErr {
|
||||
require.ErrorContains(t, err, "cache.deleted_retention")
|
||||
return
|
||||
}
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, tt.want, cfg.Cache.DeletedRetention)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
package file
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
)
|
||||
|
||||
// packageKey identifies a file-store record, which has no numeric id.
|
||||
func packageKey(p *metadata.Package) string {
|
||||
return p.Registry + "/" + p.Name + "@" + p.Version
|
||||
}
|
||||
|
||||
// listRecords returns package records only: the store's walk also yields scan result files.
|
||||
func (s *Store) listRecords(ctx context.Context) ([]*metadata.Package, error) {
|
||||
all, err := s.ListPackages(ctx, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := all[:0]
|
||||
for _, p := range all {
|
||||
if p.Registry != "" && p.Name != "" {
|
||||
out = append(out, p)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// ListPackageGroups pages groups in memory.
|
||||
func (s *Store) ListPackageGroups(ctx context.Context, opts metadata.GroupListOptions) (*metadata.GroupPage, error) {
|
||||
all, err := s.listRecords(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, p := range all {
|
||||
if p.ID == "" {
|
||||
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)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
want := make(map[string]struct{}, len(packageIDs))
|
||||
for _, id := range packageIDs {
|
||||
want[id] = struct{}{}
|
||||
}
|
||||
var out []*metadata.ScanSummary
|
||||
for _, p := range all {
|
||||
id := p.ID
|
||||
if id == "" {
|
||||
id = packageKey(p)
|
||||
}
|
||||
if _, ok := want[id]; packageIDs != nil && !ok || !p.SecurityScanned {
|
||||
continue
|
||||
}
|
||||
sum := &metadata.ScanSummary{
|
||||
Registry: p.Registry, PackageID: id, Name: p.Name, Version: p.Version, ReleaseVersion: p.ReleaseVersion,
|
||||
}
|
||||
res, err := s.GetScanResult(ctx, p.Registry, p.Name, p.Version)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if res != nil {
|
||||
sum.HasScan = true
|
||||
sum.Status = res.Status
|
||||
sum.ScannedAt = res.ScannedAt
|
||||
sum.Total = res.VulnerabilityCount
|
||||
sum.Details = res.Details
|
||||
for _, v := range res.Vulnerabilities {
|
||||
switch metadata.NormalizeSeverity(v.Severity) {
|
||||
case "CRITICAL":
|
||||
sum.Critical++
|
||||
case "HIGH":
|
||||
sum.High++
|
||||
case "MODERATE":
|
||||
sum.Moderate++
|
||||
default:
|
||||
sum.Low++
|
||||
}
|
||||
}
|
||||
if withDetails {
|
||||
sum.Vulnerabilities = res.Vulnerabilities
|
||||
}
|
||||
}
|
||||
out = append(out, sum)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// GetRegistryStats totals artifacts per registry.
|
||||
func (s *Store) GetRegistryStats(ctx context.Context) ([]metadata.RegistryStat, error) {
|
||||
all, err := s.listRecords(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
byRegistry := map[string]*metadata.RegistryStat{}
|
||||
var order []string
|
||||
for _, p := range all {
|
||||
if metadata.IsMetadataVersion(p.Version) {
|
||||
continue
|
||||
}
|
||||
st, ok := byRegistry[p.Registry]
|
||||
if !ok {
|
||||
st = &metadata.RegistryStat{Registry: p.Registry}
|
||||
byRegistry[p.Registry] = st
|
||||
order = append(order, p.Registry)
|
||||
}
|
||||
st.Count++
|
||||
st.Size += p.Size
|
||||
st.Downloads += p.DownloadCount
|
||||
}
|
||||
out := make([]metadata.RegistryStat, 0, len(order))
|
||||
for _, r := range order {
|
||||
out = append(out, *byRegistry[r])
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -147,9 +147,9 @@ func (s *Store) ListPackages(ctx context.Context, opts *metadata.ListOptions) ([
|
||||
return []*metadata.Package{}, nil
|
||||
}
|
||||
|
||||
end := opts.Offset + opts.Limit
|
||||
if end > len(packages) {
|
||||
end = len(packages)
|
||||
end := len(packages)
|
||||
if opts.Limit > 0 && opts.Offset+opts.Limit < end {
|
||||
end = opts.Offset + opts.Limit
|
||||
}
|
||||
|
||||
return packages[opts.Offset:end], nil
|
||||
@@ -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)
|
||||
|
||||
@@ -82,3 +82,57 @@ func TestCleanupExpiredBypasses_DoesNotFollowSymlinkOutsideStore(t *testing.T) {
|
||||
require.Error(t, err, "escaping symlink must be refused, not read")
|
||||
require.FileExists(t, target)
|
||||
}
|
||||
|
||||
func TestListPackagesZeroLimitMeansNoLimit(t *testing.T) {
|
||||
store, err := New(Config{Path: t.TempDir()})
|
||||
require.NoError(t, err)
|
||||
ctx := context.Background()
|
||||
for _, v := range []string{"1", "2", "3"} {
|
||||
require.NoError(t, store.SavePackage(ctx, &metadata.Package{Registry: "npm", Name: "p", Version: v}))
|
||||
}
|
||||
got, err := store.ListPackages(ctx, &metadata.ListOptions{Offset: 1})
|
||||
require.NoError(t, err)
|
||||
require.Len(t, got, 2)
|
||||
}
|
||||
|
||||
func TestFileStoreDashboardQueries(t *testing.T) {
|
||||
store, err := New(Config{Path: t.TempDir()})
|
||||
require.NoError(t, err)
|
||||
ctx := context.Background()
|
||||
now := time.Now()
|
||||
for _, p := range []*metadata.Package{
|
||||
{Registry: "npm", Name: "a", Version: "1", Size: 10, DownloadCount: 2, SecurityScanned: true, CachedAt: now},
|
||||
{Registry: "npm", Name: "a", Version: "list", Size: 1, CachedAt: now},
|
||||
{Registry: "go", Name: "m", Version: "v1", Size: 30, DownloadCount: 1, CachedAt: now},
|
||||
} {
|
||||
require.NoError(t, store.SavePackage(ctx, p))
|
||||
}
|
||||
require.NoError(t, store.SaveScanResult(ctx, &metadata.ScanResult{
|
||||
Registry: "npm", PackageName: "a", PackageVersion: "1", Scanner: "t", Status: metadata.ScanStatusVulnerable, ScannedAt: now,
|
||||
VulnerabilityCount: 1, Vulnerabilities: []metadata.Vulnerability{{ID: "CVE-1", Severity: "high"}},
|
||||
}))
|
||||
|
||||
page, err := store.ListPackageGroups(ctx, metadata.GroupListOptions{Page: 1, PageSize: 10})
|
||||
require.NoError(t, err)
|
||||
require.EqualValues(t, 2, page.TotalGroups)
|
||||
require.Len(t, page.Packages, 2)
|
||||
|
||||
sums, err := store.GetScanSummaries(ctx, nil, true)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, sums, 1)
|
||||
require.True(t, sums[0].HasScan)
|
||||
require.Equal(t, 1, sums[0].High)
|
||||
require.Len(t, sums[0].Vulnerabilities, 1)
|
||||
|
||||
byID, err := store.GetScanSummaries(ctx, []string{sums[0].PackageID}, false)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, byID, 1)
|
||||
require.Nil(t, byID[0].Vulnerabilities)
|
||||
|
||||
stats, err := store.GetRegistryStats(ctx)
|
||||
require.NoError(t, err)
|
||||
require.ElementsMatch(t, []metadata.RegistryStat{
|
||||
{Registry: "npm", Count: 1, Size: 10, Downloads: 2},
|
||||
{Registry: "go", Count: 1, Size: 30, Downloads: 1},
|
||||
}, stats)
|
||||
}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package gormstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/rs/zerolog/log"
|
||||
@@ -17,6 +19,10 @@ type AggregationWorker struct {
|
||||
stopChan chan struct{}
|
||||
ticker *time.Ticker
|
||||
now func() time.Time // nil means time.Now
|
||||
blocked func(context.Context) (int64, error)
|
||||
wg sync.WaitGroup
|
||||
stopOnce sync.Once
|
||||
mu sync.Mutex // guards blocked
|
||||
}
|
||||
|
||||
// NewAggregationWorker creates a new aggregation worker
|
||||
@@ -36,6 +42,15 @@ func (w *AggregationWorker) clock() time.Time {
|
||||
return time.Now()
|
||||
}
|
||||
|
||||
// StartAsync runs Start in a goroutine that Stop waits for.
|
||||
func (w *AggregationWorker) StartAsync() {
|
||||
w.wg.Add(1)
|
||||
go func() {
|
||||
defer w.wg.Done()
|
||||
w.Start()
|
||||
}()
|
||||
}
|
||||
|
||||
// Start begins the aggregation worker
|
||||
func (w *AggregationWorker) Start() {
|
||||
log.Info().Msg("Starting aggregation worker")
|
||||
@@ -68,9 +83,10 @@ func (w *AggregationWorker) Start() {
|
||||
}
|
||||
}
|
||||
|
||||
// Stop stops the aggregation worker
|
||||
// Stop stops the aggregation worker and waits for a started one to exit. Safe to call repeatedly.
|
||||
func (w *AggregationWorker) Stop() {
|
||||
close(w.stopChan)
|
||||
w.stopOnce.Do(func() { close(w.stopChan) })
|
||||
w.wg.Wait()
|
||||
}
|
||||
|
||||
// AggregateHourly aggregates download events into hourly stats
|
||||
@@ -139,7 +155,7 @@ func (w *AggregationWorker) AggregateHourly() error {
|
||||
// SQLite: Use strftime for time bucketing
|
||||
// Note: SQLite doesn't support UPSERT as elegantly, need to handle separately
|
||||
aggregateSQL = `
|
||||
INSERT OR REPLACE INTO download_stats_hourly (registry_id, package_id, time_bucket, download_count, unique_ips, auth_downloads, created_at, updated_at)
|
||||
INSERT INTO download_stats_hourly (registry_id, package_id, time_bucket, download_count, unique_ips, auth_downloads, created_at, updated_at)
|
||||
SELECT
|
||||
de.registry_id,
|
||||
de.package_id,
|
||||
@@ -152,6 +168,12 @@ func (w *AggregationWorker) AggregateHourly() error {
|
||||
FROM download_events de
|
||||
WHERE de.downloaded_at < ?
|
||||
GROUP BY de.registry_id, de.package_id, time_bucket
|
||||
ON CONFLICT (registry_id, COALESCE(package_id, 0), time_bucket)
|
||||
DO UPDATE SET
|
||||
download_count = download_stats_hourly.download_count + excluded.download_count,
|
||||
unique_ips = MAX(download_stats_hourly.unique_ips, excluded.unique_ips),
|
||||
auth_downloads = download_stats_hourly.auth_downloads + excluded.auth_downloads,
|
||||
updated_at = datetime('now')
|
||||
`
|
||||
}
|
||||
|
||||
@@ -221,7 +243,7 @@ func (w *AggregationWorker) AggregateHourly() error {
|
||||
default:
|
||||
// SQLite
|
||||
registryAggSQL = `
|
||||
INSERT OR REPLACE INTO download_stats_hourly (registry_id, package_id, time_bucket, download_count, unique_ips, auth_downloads, created_at, updated_at)
|
||||
INSERT INTO download_stats_hourly (registry_id, package_id, time_bucket, download_count, unique_ips, auth_downloads, created_at, updated_at)
|
||||
SELECT
|
||||
registry_id,
|
||||
NULL as package_id,
|
||||
@@ -234,6 +256,12 @@ func (w *AggregationWorker) AggregateHourly() error {
|
||||
FROM download_stats_hourly
|
||||
WHERE package_id IS NOT NULL
|
||||
GROUP BY registry_id, time_bucket
|
||||
ON CONFLICT (registry_id, COALESCE(package_id, 0), time_bucket)
|
||||
DO UPDATE SET
|
||||
download_count = excluded.download_count,
|
||||
unique_ips = excluded.unique_ips,
|
||||
auth_downloads = excluded.auth_downloads,
|
||||
updated_at = datetime('now')
|
||||
`
|
||||
}
|
||||
|
||||
@@ -264,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 {
|
||||
@@ -317,7 +345,7 @@ func (w *AggregationWorker) AggregateDaily() error {
|
||||
|
||||
default: // SQLite
|
||||
aggregateSQL = `
|
||||
INSERT OR REPLACE INTO download_stats_daily (registry_id, package_id, time_bucket, download_count, unique_ips, auth_downloads, top_user_agents, created_at, updated_at)
|
||||
INSERT INTO download_stats_daily (registry_id, package_id, time_bucket, download_count, unique_ips, auth_downloads, top_user_agents, created_at, updated_at)
|
||||
SELECT
|
||||
registry_id,
|
||||
package_id,
|
||||
@@ -331,6 +359,12 @@ func (w *AggregationWorker) AggregateDaily() error {
|
||||
FROM download_stats_hourly
|
||||
WHERE time_bucket >= ? AND time_bucket < ?
|
||||
GROUP BY registry_id, package_id, date(time_bucket)
|
||||
ON CONFLICT (registry_id, COALESCE(package_id, 0), time_bucket)
|
||||
DO UPDATE SET
|
||||
download_count = excluded.download_count,
|
||||
unique_ips = excluded.unique_ips,
|
||||
auth_downloads = excluded.auth_downloads,
|
||||
updated_at = datetime('now')
|
||||
`
|
||||
}
|
||||
|
||||
@@ -353,6 +387,15 @@ func (w *AggregationWorker) AggregateDaily() error {
|
||||
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// The snapshot is not part of the rollup: a failure here must not undo it.
|
||||
if err := w.SnapshotStats(context.Background()); err != nil {
|
||||
log.Error().Err(err).Msg("Failed to record stats snapshot")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// UpdatePackageAccessCounts synchronizes package access_count from download stats
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
package gormstore
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestCloseIsIdempotent(t *testing.T) {
|
||||
store := openFileStore(t, true)
|
||||
if err := store.Close(); err != nil {
|
||||
t.Fatalf("first Close: %v", err)
|
||||
}
|
||||
if err := store.Close(); err != nil {
|
||||
t.Fatalf("second Close: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,405 @@
|
||||
package gormstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
stderrors "errors"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/errors"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// likeEscape is the ESCAPE character for search patterns; unlike a backslash it
|
||||
// means the same thing on SQLite, PostgreSQL and MySQL.
|
||||
const likeEscape = "!"
|
||||
|
||||
// scanErrorStatus marks a failed scan whose details decide whether it blocks.
|
||||
const scanErrorStatus = string(metadata.ScanStatusError)
|
||||
|
||||
// baseNameExpr is the SQL that strips the Go "/@v/<file>" suffix from a package name.
|
||||
func (s *GORMStoreV2) baseNameExpr() string {
|
||||
switch s.db.Name() {
|
||||
case "postgres":
|
||||
return "split_part(name, '/@v/', 1)"
|
||||
case "mysql":
|
||||
return "SUBSTRING_INDEX(name, '/@v/', 1)"
|
||||
default:
|
||||
return "CASE WHEN instr(name, '/@v/') > 0 THEN substr(name, 1, instr(name, '/@v/') - 1) ELSE name END"
|
||||
}
|
||||
}
|
||||
|
||||
func escapeLike(q string) string {
|
||||
r := strings.NewReplacer(likeEscape, likeEscape+likeEscape, "%", likeEscape+"%", "_", likeEscape+"_")
|
||||
return "%" + r.Replace(strings.ToLower(q)) + "%"
|
||||
}
|
||||
|
||||
// registryNames snapshots the id to name mapping.
|
||||
func (s *GORMStoreV2) registryNames() map[int32]string {
|
||||
s.registryCacheMu.RLock()
|
||||
defer s.registryCacheMu.RUnlock()
|
||||
names := make(map[int32]string, len(s.registryCache))
|
||||
for name, id := range s.registryCache {
|
||||
names[id] = name
|
||||
}
|
||||
return names
|
||||
}
|
||||
|
||||
// groupFilter builds the WHERE clause shared by the group count, the group page and the row fetch.
|
||||
func (s *GORMStoreV2) groupFilter(opts metadata.GroupListOptions) (clause string, args []interface{}, empty bool, err error) {
|
||||
clause = "version NOT IN ?"
|
||||
args = []interface{}{metadata.MetadataVersions}
|
||||
if opts.Registry != "" {
|
||||
id, idErr := s.getRegistryID(opts.Registry)
|
||||
if idErr != nil {
|
||||
var hErr *errors.Error
|
||||
if stderrors.As(idErr, &hErr) && hErr.Code == errors.ErrCodeNotFound {
|
||||
return "", nil, true, nil
|
||||
}
|
||||
return "", nil, false, idErr
|
||||
}
|
||||
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 + "'" +
|
||||
" OR LOWER(version) LIKE ? ESCAPE '" + likeEscape + "'" +
|
||||
" OR LOWER(release_version) LIKE ? ESCAPE '" + likeEscape + "')"
|
||||
args = append(args, like, like, like)
|
||||
}
|
||||
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 {
|
||||
dir := "ASC"
|
||||
if opts.SortDesc {
|
||||
dir = "DESC"
|
||||
}
|
||||
var lead string
|
||||
switch opts.SortBy {
|
||||
case metadata.GroupSortCachedAt:
|
||||
lead = "last_cached " + dir + ", "
|
||||
case metadata.GroupSortDownloads:
|
||||
lead = "downloads " + dir + ", "
|
||||
case metadata.GroupSortSize:
|
||||
lead = "total_size " + dir + ", "
|
||||
}
|
||||
nameDir := "ASC"
|
||||
if lead == "" && opts.SortDesc {
|
||||
nameDir = "DESC"
|
||||
}
|
||||
return lead + "LOWER(base_name) " + nameDir + ", base_name " + nameDir + ", registry_id ASC"
|
||||
}
|
||||
|
||||
type groupKey struct {
|
||||
name string
|
||||
registryID int32
|
||||
}
|
||||
|
||||
// ListPackageGroups returns one page of groups with all their version rows in four statements at most.
|
||||
func (s *GORMStoreV2) ListPackageGroups(ctx context.Context, opts metadata.GroupListOptions) (*metadata.GroupPage, error) {
|
||||
page := &metadata.GroupPage{}
|
||||
clause, args, empty, err := s.groupFilter(opts)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if empty {
|
||||
return page, nil
|
||||
}
|
||||
base := s.baseNameExpr()
|
||||
matching := func() *gorm.DB {
|
||||
return s.db.WithContext(ctx).Model(&PackageModel{}).Where(clause, args...)
|
||||
}
|
||||
|
||||
var rows []PackageModel
|
||||
if opts.PageSize <= 0 {
|
||||
// Everything is wanted, so order the groups in memory with the reference implementation.
|
||||
if err := matching().Find(&rows).Error; err != nil {
|
||||
return nil, errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to list packages")
|
||||
}
|
||||
opts.Registry, opts.Query = "", ""
|
||||
return metadata.PageGroups(s.modelsToPackages(rows), opts), nil
|
||||
}
|
||||
|
||||
distinct := matching().
|
||||
Select("registry_id, " + base + " AS base_name, MAX(cached_at) AS last_cached, SUM(access_count) AS downloads, SUM(size) AS total_size").
|
||||
Group("registry_id, " + base)
|
||||
if err := s.db.WithContext(ctx).Table("(?) AS g", distinct).Select("COUNT(*)").Scan(&page.TotalGroups).Error; err != nil {
|
||||
return nil, errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to count package groups")
|
||||
}
|
||||
if page.TotalGroups == 0 {
|
||||
return page, nil
|
||||
}
|
||||
|
||||
pageNo := opts.Page
|
||||
if pageNo < 1 {
|
||||
pageNo = 1
|
||||
}
|
||||
var keys []struct {
|
||||
BaseName string
|
||||
RegistryID int32
|
||||
}
|
||||
if err := s.db.WithContext(ctx).Table("(?) AS g", distinct).Select("registry_id, base_name").
|
||||
Order(groupOrder(opts)).
|
||||
Limit(opts.PageSize).Offset((pageNo - 1) * opts.PageSize).
|
||||
Scan(&keys).Error; err != nil {
|
||||
return nil, errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to page package groups")
|
||||
}
|
||||
if len(keys) == 0 {
|
||||
return page, nil
|
||||
}
|
||||
order := make([]groupKey, len(keys))
|
||||
registryIDs := make([]int32, 0, len(keys))
|
||||
names := make([]string, 0, len(keys))
|
||||
for i, k := range keys {
|
||||
order[i] = groupKey{name: k.BaseName, registryID: k.RegistryID}
|
||||
registryIDs = append(registryIDs, k.RegistryID)
|
||||
names = append(names, k.BaseName)
|
||||
}
|
||||
|
||||
if err := matching().
|
||||
Where("registry_id IN ? AND "+base+" IN ?", registryIDs, names).
|
||||
Order("cached_at DESC").Find(&rows).Error; err != nil {
|
||||
return nil, errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to list group packages")
|
||||
}
|
||||
return s.orderGroupRows(page, rows, order), nil
|
||||
}
|
||||
|
||||
// orderGroupRows converts rows, dedupes Go file variants and sorts them into the page's group order.
|
||||
func (s *GORMStoreV2) orderGroupRows(page *metadata.GroupPage, rows []PackageModel, order []groupKey) *metadata.GroupPage {
|
||||
names := s.registryNames()
|
||||
rank := make(map[string]int, len(order))
|
||||
for i, k := range order {
|
||||
rank[names[k.registryID]+"\x00"+k.name] = i
|
||||
}
|
||||
var kept []*metadata.Package
|
||||
for _, p := range metadata.DedupeVersions(s.modelsToPackages(rows)) {
|
||||
if _, ok := rank[p.Registry+"\x00"+p.Name]; ok {
|
||||
kept = append(kept, p)
|
||||
}
|
||||
}
|
||||
sort.SliceStable(kept, func(i, j int) bool {
|
||||
return rank[kept[i].Registry+"\x00"+kept[i].Name] < rank[kept[j].Registry+"\x00"+kept[j].Name]
|
||||
})
|
||||
page.Packages = kept
|
||||
return page
|
||||
}
|
||||
|
||||
// GetScanSummaries returns the latest scan per package in two statements (three when a scan failed and details are lazily loaded).
|
||||
func (s *GORMStoreV2) GetScanSummaries(ctx context.Context, packageIDs []string, withDetails bool) ([]*metadata.ScanSummary, error) {
|
||||
var ids []int64
|
||||
for _, raw := range packageIDs {
|
||||
id, err := strconv.ParseInt(raw, 10, 64)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
ids = append(ids, id)
|
||||
}
|
||||
if packageIDs != nil && len(ids) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
pkgQuery := s.db.WithContext(ctx).Model(&PackageModel{}).
|
||||
Select("id, registry_id, name, version, release_version").
|
||||
Where("security_scanned = ?", true)
|
||||
if packageIDs != nil {
|
||||
pkgQuery = pkgQuery.Where("id IN ?", ids)
|
||||
}
|
||||
var pkgs []PackageModel
|
||||
if err := pkgQuery.Order("id").Find(&pkgs).Error; err != nil {
|
||||
return nil, errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to load scanned packages")
|
||||
}
|
||||
if len(pkgs) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
columns := "id, package_id, status, scanned_at, vuln_count, critical_count, high_count, medium_count, low_count"
|
||||
if withDetails {
|
||||
columns += ", details"
|
||||
}
|
||||
scanQuery := s.db.WithContext(ctx).Model(&ScanResultModel{}).Select(columns).
|
||||
Where("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)")
|
||||
if packageIDs != nil {
|
||||
scanQuery = scanQuery.Where("package_id IN ?", ids)
|
||||
} else {
|
||||
scanQuery = scanQuery.Where("package_id IN (SELECT id FROM packages WHERE security_scanned = ? AND deleted_at IS NULL)", true)
|
||||
}
|
||||
var scans []ScanResultModel
|
||||
if err := scanQuery.Find(&scans).Error; err != nil {
|
||||
return nil, errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to load scan results")
|
||||
}
|
||||
latest := make(map[int64]*ScanResultModel, len(scans))
|
||||
for i := range scans {
|
||||
// Equal timestamps return two rows; the newer insert wins.
|
||||
if cur, ok := latest[scans[i].PackageID]; !ok || scans[i].ID > cur.ID {
|
||||
latest[scans[i].PackageID] = &scans[i]
|
||||
}
|
||||
}
|
||||
|
||||
if !withDetails {
|
||||
if err := s.loadFailedScanDetails(ctx, latest); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
names := s.registryNames()
|
||||
out := make([]*metadata.ScanSummary, 0, len(pkgs))
|
||||
for i := range pkgs {
|
||||
p := &pkgs[i]
|
||||
sum := &metadata.ScanSummary{
|
||||
Registry: names[p.RegistryID],
|
||||
PackageID: strconv.FormatInt(p.ID, 10),
|
||||
Name: p.Name,
|
||||
Version: p.Version,
|
||||
ReleaseVersion: p.ReleaseVersion,
|
||||
}
|
||||
if scan, ok := latest[p.ID]; ok {
|
||||
sum.HasScan = true
|
||||
sum.Status = metadata.ScanStatus(scan.Status)
|
||||
sum.ScannedAt = scan.ScannedAt
|
||||
sum.Total = scan.VulnCount
|
||||
sum.Critical = scan.CriticalCount
|
||||
sum.High = scan.HighCount
|
||||
sum.Moderate = scan.MediumCount
|
||||
sum.Low = scan.LowCount
|
||||
if withDetails {
|
||||
sum.Vulnerabilities = vulnerabilitiesFromDetails(scan.Details)
|
||||
}
|
||||
if scan.Status == scanErrorStatus || withDetails {
|
||||
sum.Details = map[string]interface{}(scan.Details)
|
||||
}
|
||||
}
|
||||
out = append(out, sum)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// loadFailedScanDetails fills Details for failed scans, which carry the infrastructure-error flag.
|
||||
func (s *GORMStoreV2) loadFailedScanDetails(ctx context.Context, latest map[int64]*ScanResultModel) error {
|
||||
var failed []int64
|
||||
for _, scan := range latest {
|
||||
if scan.Status == scanErrorStatus {
|
||||
failed = append(failed, scan.ID)
|
||||
}
|
||||
}
|
||||
if len(failed) == 0 {
|
||||
return nil
|
||||
}
|
||||
var rows []ScanResultModel
|
||||
if err := s.db.WithContext(ctx).Model(&ScanResultModel{}).
|
||||
Select("id, details").Where("id IN ?", failed).Find(&rows).Error; err != nil {
|
||||
return errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to load failed scan details")
|
||||
}
|
||||
details := make(map[int64]JSONBField, len(rows))
|
||||
for _, r := range rows {
|
||||
details[r.ID] = r.Details
|
||||
}
|
||||
for _, scan := range latest {
|
||||
if scan.Status == scanErrorStatus {
|
||||
scan.Details = details[scan.ID]
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetRegistryStats groups cache artifacts by registry in one statement.
|
||||
func (s *GORMStoreV2) GetRegistryStats(ctx context.Context) ([]metadata.RegistryStat, error) {
|
||||
var rows []struct {
|
||||
RegistryID int32
|
||||
Count int64
|
||||
Size int64
|
||||
Downloads int64
|
||||
}
|
||||
if err := s.db.WithContext(ctx).Model(&PackageModel{}).
|
||||
Select("registry_id, COUNT(*) AS count, COALESCE(SUM(size), 0) AS size, COALESCE(SUM(access_count), 0) AS downloads").
|
||||
Where("version NOT IN ?", metadata.MetadataVersions).
|
||||
Group("registry_id").Order("registry_id").
|
||||
Scan(&rows).Error; err != nil {
|
||||
return nil, errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to aggregate registry stats")
|
||||
}
|
||||
names := s.registryNames()
|
||||
out := make([]metadata.RegistryStat, 0, len(rows))
|
||||
for _, r := range rows {
|
||||
out = append(out, metadata.RegistryStat{Registry: names[r.RegistryID], Count: r.Count, Size: r.Size, Downloads: r.Downloads})
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// vulnerabilitiesFromDetails decodes the vulnerability list stored in a scan's details.
|
||||
func vulnerabilitiesFromDetails(details JSONBField) []metadata.Vulnerability {
|
||||
var vulnerabilities []metadata.Vulnerability
|
||||
vulnArray, ok := details["vulnerabilities"].([]interface{})
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
for _, v := range vulnArray {
|
||||
vulnMap, ok := v.(map[string]interface{})
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
vuln := metadata.Vulnerability{
|
||||
ID: getStringFromMap(vulnMap, "id"),
|
||||
Severity: getStringFromMap(vulnMap, "severity"),
|
||||
Title: getStringFromMap(vulnMap, "title"),
|
||||
Description: getStringFromMap(vulnMap, "description"),
|
||||
FixedIn: getStringFromMap(vulnMap, "fixed_in"),
|
||||
}
|
||||
if refs, ok := vulnMap["references"].([]interface{}); ok {
|
||||
for _, ref := range refs {
|
||||
if refStr, ok := ref.(string); ok {
|
||||
vuln.References = append(vuln.References, refStr)
|
||||
}
|
||||
}
|
||||
}
|
||||
if detectedBy, ok := vulnMap["detected_by"].([]interface{}); ok {
|
||||
for _, d := range detectedBy {
|
||||
if dStr, ok := d.(string); ok {
|
||||
vuln.DetectedBy = append(vuln.DetectedBy, dStr)
|
||||
}
|
||||
}
|
||||
}
|
||||
vulnerabilities = append(vulnerabilities, vuln)
|
||||
}
|
||||
return vulnerabilities
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
//go:build pgintegration
|
||||
|
||||
package gormstore
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func TestPostgresDashboardQueries(t *testing.T) {
|
||||
store, _ := newPostgresStore(t)
|
||||
|
||||
reset := func(t *testing.T) {
|
||||
t.Helper()
|
||||
require.NoError(t, store.db.Exec("TRUNCATE packages RESTART IDENTITY CASCADE").Error)
|
||||
}
|
||||
for name, check := range map[string]func(*testing.T, *GORMStoreV2){
|
||||
"groups match the reference": checkListPackageGroupsMatchesReference,
|
||||
"group behaviour": checkListPackageGroupsBehaviour,
|
||||
"statement count is constant": checkDashboardStatementsAreConstant,
|
||||
"scan summaries": checkScanSummaries,
|
||||
"registry stats": checkRegistryStats,
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
reset(t)
|
||||
check(t, store)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// With sequential scans disabled the latest-scan lookup must run on the new index.
|
||||
func TestPostgresLatestScanLookupUsesIndex(t *testing.T) {
|
||||
store, _ := newPostgresStore(t)
|
||||
seedScanned(t, store, 0, 20)
|
||||
|
||||
var plan []string
|
||||
require.NoError(t, store.db.Connection(func(tx *gorm.DB) error {
|
||||
if err := tx.Exec("SET enable_seqscan = off").Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Raw(`EXPLAIN SELECT id, package_id FROM scan_results
|
||||
WHERE package_id IN (1, 2, 3)
|
||||
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 deleted_at IS NULL`).Scan(&plan).Error
|
||||
}))
|
||||
require.Contains(t, strings.Join(plan, "\n"), scanPackageScannedAtIndex)
|
||||
}
|
||||
@@ -0,0 +1,348 @@
|
||||
package gormstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/internal/dbcount"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
var dashboardEpoch = time.Date(2026, 11, 1, 12, 0, 0, 0, time.UTC)
|
||||
|
||||
type seedRow struct {
|
||||
registry, name, version, release string
|
||||
size int64
|
||||
downloads int
|
||||
}
|
||||
|
||||
// seedDashboard stores rows with distinct, increasing cache times so orderings are unambiguous.
|
||||
func seedDashboard(t *testing.T, store *GORMStoreV2, rows []seedRow) {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
for i, r := range rows {
|
||||
at := dashboardEpoch.Add(time.Duration(i) * time.Minute)
|
||||
require.NoError(t, store.SavePackage(ctx, &metadata.Package{
|
||||
Registry: r.registry, Name: r.name, Version: r.version, ReleaseVersion: r.release,
|
||||
StorageKey: fmt.Sprintf("%s/%s/%s", r.registry, r.name, r.version),
|
||||
Size: r.size, CachedAt: at, LastAccessed: at,
|
||||
}))
|
||||
for d := 0; d < r.downloads; d++ {
|
||||
require.NoError(t, store.UpdateDownloadCount(ctx, r.registry, r.name, r.version))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func dashboardFixture() []seedRow {
|
||||
return []seedRow{
|
||||
{"npm", "left-pad", "1.0.0", "", 100, 3},
|
||||
{"npm", "left-pad", "1.1.0", "", 110, 1},
|
||||
{"npm", "left-pad", "list", "", 5, 0}, // metadata page, never a row
|
||||
{"npm", "@scope/pkg", "2.0.0", "", 300, 0},
|
||||
{"npm", "react", "18.0.0", "", 900, 7},
|
||||
{"npm", "a_b", "1.0.0", "", 10, 0},
|
||||
{"npm", "axb", "1.0.0", "", 20, 0},
|
||||
{"go", "github.com/a/b/@v/v1.0.0.zip", "v1.0.0", "", 500, 2},
|
||||
{"go", "github.com/a/b/@v/v1.0.0.mod", "v1.0.0", "", 10, 0},
|
||||
{"go", "github.com/a/b/@v/v1.0.0.info", "v1.0.0", "", 5, 0},
|
||||
{"go", "github.com/a/b/@v/v1.1.0.zip", "v1.1.0", "", 520, 0},
|
||||
{"go", "github.com/c/d/@v/v0.1.0.zip", "v0.1.0", "", 40, 1},
|
||||
{"pypi", "six", "six-1.17.0.tar.gz", "1.17.0", 60, 4},
|
||||
{"pypi", "six", "six-1.17.0-py2.py3-none-any.whl", "1.17.0", 20, 0},
|
||||
}
|
||||
}
|
||||
|
||||
func rowKeys(pkgs []*metadata.Package) []string {
|
||||
out := make([]string, len(pkgs))
|
||||
for i, p := range pkgs {
|
||||
out[i] = p.Registry + "/" + p.Name + "@" + p.Version
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// checkListPackageGroupsMatchesReference compares the SQL paging with the in-memory reference for many option sets.
|
||||
func checkListPackageGroupsMatchesReference(t *testing.T, store *GORMStoreV2) {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
seedDashboard(t, store, dashboardFixture())
|
||||
all, err := store.ListPackages(ctx, nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
var cases []metadata.GroupListOptions
|
||||
for _, sortBy := range []string{"", metadata.GroupSortName, metadata.GroupSortCachedAt, metadata.GroupSortDownloads, metadata.GroupSortSize} {
|
||||
for _, desc := range []bool{false, true} {
|
||||
for _, filter := range []struct{ registry, q string }{
|
||||
{"", ""}, {"go", ""}, {"npm", ""}, {"nowhere", ""}, {"", "LEFT"}, {"", "1.17"}, {"", "a_b"}, {"", "github.com/a"}, {"", "no-such"},
|
||||
} {
|
||||
for _, size := range []int{0, 2, 3} {
|
||||
for page := 1; page <= 3; page++ {
|
||||
cases = append(cases, metadata.GroupListOptions{
|
||||
Registry: filter.registry, Query: filter.q, SortBy: sortBy, SortDesc: desc, Page: page, PageSize: size,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, opts := range cases {
|
||||
got, err := store.ListPackageGroups(ctx, opts)
|
||||
require.NoError(t, err, "%+v", opts)
|
||||
want := metadata.PageGroups(all, opts)
|
||||
require.Equal(t, want.TotalGroups, got.TotalGroups, "total groups %+v", opts)
|
||||
require.Equal(t, rowKeys(want.Packages), rowKeys(got.Packages), "rows %+v", opts)
|
||||
}
|
||||
}
|
||||
|
||||
func checkListPackageGroupsBehaviour(t *testing.T, store *GORMStoreV2) {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
seedDashboard(t, store, dashboardFixture())
|
||||
|
||||
t.Run("metadata pages are not rows and Go variants collapse to the largest", func(t *testing.T) {
|
||||
page, err := store.ListPackageGroups(ctx, metadata.GroupListOptions{Registry: "go"})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, int64(2), page.TotalGroups)
|
||||
require.ElementsMatch(t, []string{
|
||||
"go/github.com/a/[email protected]", "go/github.com/a/[email protected]", "go/github.com/c/[email protected]",
|
||||
}, rowKeys(page.Packages))
|
||||
for _, p := range page.Packages {
|
||||
if p.Version == "v1.0.0" && p.Name == "github.com/a/b" {
|
||||
require.EqualValues(t, 500, p.Size, "the .zip outranks .mod and .info")
|
||||
}
|
||||
}
|
||||
npm, err := store.ListPackageGroups(ctx, metadata.GroupListOptions{Registry: "npm", Query: "left"})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []string{"npm/[email protected]", "npm/[email protected]"}, rowKeys(npm.Packages), "newest first, no list page")
|
||||
})
|
||||
|
||||
t.Run("a page holds whole groups and total_groups counts all groups", func(t *testing.T) {
|
||||
page, err := store.ListPackageGroups(ctx, metadata.GroupListOptions{Page: 1, PageSize: 2})
|
||||
require.NoError(t, err)
|
||||
require.EqualValues(t, 8, page.TotalGroups)
|
||||
groups := map[string]bool{}
|
||||
for _, p := range page.Packages {
|
||||
groups[p.Registry+"/"+p.Name] = true
|
||||
}
|
||||
require.Len(t, groups, 2)
|
||||
require.Equal(t, "@scope/pkg", page.Packages[0].Name)
|
||||
})
|
||||
|
||||
t.Run("search treats LIKE wildcards literally", func(t *testing.T) {
|
||||
page, err := store.ListPackageGroups(ctx, metadata.GroupListOptions{Query: "a_b"})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []string{"npm/[email protected]"}, rowKeys(page.Packages))
|
||||
})
|
||||
|
||||
t.Run("search finds a release version", func(t *testing.T) {
|
||||
page, err := store.ListPackageGroups(ctx, metadata.GroupListOptions{Query: "1.17.0"})
|
||||
require.NoError(t, err)
|
||||
require.Len(t, page.Packages, 2)
|
||||
})
|
||||
|
||||
t.Run("an unknown registry is an empty page, not an error", func(t *testing.T) {
|
||||
page, err := store.ListPackageGroups(ctx, metadata.GroupListOptions{Registry: "nowhere", PageSize: 5})
|
||||
require.NoError(t, err)
|
||||
require.Zero(t, page.TotalGroups)
|
||||
require.Empty(t, page.Packages)
|
||||
})
|
||||
|
||||
t.Run("recent groups come first by cached_at", func(t *testing.T) {
|
||||
page, err := store.ListPackageGroups(ctx, metadata.GroupListOptions{SortBy: metadata.GroupSortCachedAt, SortDesc: true, Page: 1, PageSize: 1})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "six", page.Packages[0].Name)
|
||||
})
|
||||
}
|
||||
|
||||
// checkDashboardStatementsAreConstant proves the statement count does not follow the row count.
|
||||
func checkDashboardStatementsAreConstant(t *testing.T, store *GORMStoreV2) {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
var counter *dbcount.Counter
|
||||
store.WrapDB(func(db *gorm.DB) *gorm.DB {
|
||||
counted, c := dbcount.Attach(db)
|
||||
counter = c
|
||||
return counted
|
||||
})
|
||||
|
||||
measure := func() map[string]int {
|
||||
out := map[string]int{}
|
||||
counter.Reset()
|
||||
_, err := store.ListPackageGroups(ctx, metadata.GroupListOptions{Page: 1, PageSize: 25, Query: "pkg"})
|
||||
require.NoError(t, err)
|
||||
out["groups"] = counter.Count()
|
||||
counter.Reset()
|
||||
_, err = store.ListPackageGroups(ctx, metadata.GroupListOptions{})
|
||||
require.NoError(t, err)
|
||||
out["all"] = counter.Count()
|
||||
counter.Reset()
|
||||
_, err = store.GetScanSummaries(ctx, nil, false)
|
||||
require.NoError(t, err)
|
||||
out["summaries"] = counter.Count()
|
||||
counter.Reset()
|
||||
_, err = store.GetRegistryStats(ctx)
|
||||
require.NoError(t, err)
|
||||
out["registry stats"] = 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["groups"], 3, "count, keys, rows")
|
||||
require.LessOrEqual(t, large["summaries"], 2)
|
||||
}
|
||||
|
||||
// seedScanned stores n scanned packages, each with two scans so the latest-scan pick is exercised.
|
||||
func seedScanned(t *testing.T, store *GORMStoreV2, from, n int) {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
for i := from; i < from+n; i++ {
|
||||
name := fmt.Sprintf("pkg-%03d", i)
|
||||
at := dashboardEpoch.Add(time.Duration(i) * time.Minute)
|
||||
require.NoError(t, store.SavePackage(ctx, &metadata.Package{
|
||||
Registry: "npm", Name: name, Version: "1.0.0", StorageKey: "npm/" + name,
|
||||
Size: 10, CachedAt: at, LastAccessed: at,
|
||||
}))
|
||||
for _, scanner := range []string{"old", "new"} {
|
||||
scan := &metadata.ScanResult{
|
||||
Registry: "npm", PackageName: name, PackageVersion: "1.0.0", Scanner: scanner,
|
||||
Status: metadata.ScanStatusClean, ScannedAt: at,
|
||||
}
|
||||
if scanner == "new" {
|
||||
scan.ScannedAt = at.Add(time.Hour)
|
||||
}
|
||||
require.NoError(t, store.SaveScanResult(ctx, scan))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func checkScanSummaries(t *testing.T, store *GORMStoreV2) {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
seedDashboard(t, store, []seedRow{
|
||||
{"npm", "clean", "1.0.0", "", 1, 0},
|
||||
{"npm", "bad", "1.0.0", "", 1, 0},
|
||||
{"npm", "broken", "1.0.0", "", 1, 0},
|
||||
{"npm", "lost", "1.0.0", "", 1, 0},
|
||||
{"npm", "unscanned", "1.0.0", "", 1, 0},
|
||||
})
|
||||
save := func(name string, res *metadata.ScanResult) {
|
||||
res.Registry, res.PackageName, res.PackageVersion = "npm", name, "1.0.0"
|
||||
require.NoError(t, store.SaveScanResult(ctx, res))
|
||||
}
|
||||
save("clean", &metadata.ScanResult{Scanner: "a", Status: metadata.ScanStatusVulnerable, ScannedAt: dashboardEpoch,
|
||||
VulnerabilityCount: 1, Vulnerabilities: []metadata.Vulnerability{{ID: "CVE-1", Severity: "low"}}})
|
||||
save("clean", &metadata.ScanResult{Scanner: "b", Status: metadata.ScanStatusClean, ScannedAt: dashboardEpoch.Add(time.Hour)})
|
||||
save("bad", &metadata.ScanResult{Scanner: "a", Status: metadata.ScanStatusVulnerable, ScannedAt: dashboardEpoch, VulnerabilityCount: 3,
|
||||
Vulnerabilities: []metadata.Vulnerability{
|
||||
{ID: "CVE-2", Severity: "critical"}, {ID: "CVE-3", Severity: "HIGH"}, {ID: "CVE-4", Severity: "medium"},
|
||||
}})
|
||||
save("broken", &metadata.ScanResult{Scanner: "a", Status: metadata.ScanStatusError, ScannedAt: dashboardEpoch,
|
||||
Details: map[string]interface{}{"infrastructure_error": true}})
|
||||
require.NoError(t, store.db.Model(&PackageModel{}).Where("name = ?", "lost").Update("security_scanned", true).Error)
|
||||
|
||||
byName := func(sums []*metadata.ScanSummary) map[string]*metadata.ScanSummary {
|
||||
m := map[string]*metadata.ScanSummary{}
|
||||
for _, s := range sums {
|
||||
m[s.Name] = s
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
all, err := store.GetScanSummaries(ctx, nil, false)
|
||||
require.NoError(t, err)
|
||||
sums := byName(all)
|
||||
require.Len(t, sums, 4, "the unscanned package has no summary")
|
||||
|
||||
require.Equal(t, metadata.ScanStatusClean, sums["clean"].Status, "the later scan wins")
|
||||
require.Zero(t, sums["clean"].Total)
|
||||
require.Equal(t, "npm", sums["clean"].Registry)
|
||||
|
||||
bad := sums["bad"]
|
||||
require.Equal(t, 3, bad.Total)
|
||||
require.Equal(t, [4]int{1, 1, 1, 0}, [4]int{bad.Critical, bad.High, bad.Moderate, bad.Low})
|
||||
require.Nil(t, bad.Vulnerabilities, "the list is loaded only on request")
|
||||
|
||||
require.Equal(t, metadata.ScanStatusError, sums["broken"].Status)
|
||||
require.Equal(t, true, sums["broken"].Details["infrastructure_error"], "failed scans always carry their details")
|
||||
|
||||
require.False(t, sums["lost"].HasScan)
|
||||
|
||||
withList, err := store.GetScanSummaries(ctx, []string{sums["bad"].PackageID, sums["clean"].PackageID}, true)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, withList, 2)
|
||||
require.Len(t, byName(withList)["bad"].Vulnerabilities, 3)
|
||||
require.Equal(t, "CVE-2", byName(withList)["bad"].Vulnerabilities[0].ID)
|
||||
|
||||
none, err := store.GetScanSummaries(ctx, []string{}, false)
|
||||
require.NoError(t, err)
|
||||
require.Empty(t, none)
|
||||
}
|
||||
|
||||
func checkRegistryStats(t *testing.T, store *GORMStoreV2) {
|
||||
t.Helper()
|
||||
seedDashboard(t, store, dashboardFixture())
|
||||
stats, err := store.GetRegistryStats(context.Background())
|
||||
require.NoError(t, err)
|
||||
got := map[string]metadata.RegistryStat{}
|
||||
for _, s := range stats {
|
||||
got[s.Registry] = s
|
||||
}
|
||||
require.Equal(t, metadata.RegistryStat{Registry: "npm", Count: 6, Size: 100 + 110 + 300 + 900 + 10 + 20, Downloads: 3 + 1 + 7}, got["npm"], "the list page is excluded")
|
||||
require.Equal(t, metadata.RegistryStat{Registry: "go", Count: 5, Size: 500 + 10 + 5 + 520 + 40, Downloads: 3}, got["go"])
|
||||
require.Equal(t, metadata.RegistryStat{Registry: "pypi", Count: 2, Size: 80, Downloads: 4}, got["pypi"])
|
||||
}
|
||||
|
||||
func TestListPackageGroupsMatchesReference(t *testing.T) {
|
||||
checkListPackageGroupsMatchesReference(t, newTimeSeriesStore(t))
|
||||
}
|
||||
func TestListPackageGroupsBehaviour(t *testing.T) {
|
||||
checkListPackageGroupsBehaviour(t, newTimeSeriesStore(t))
|
||||
}
|
||||
func TestDashboardStatementsAreConstant(t *testing.T) {
|
||||
checkDashboardStatementsAreConstant(t, newTimeSeriesStore(t))
|
||||
}
|
||||
func TestScanSummaries(t *testing.T) { checkScanSummaries(t, newTimeSeriesStore(t)) }
|
||||
func TestRegistryStats(t *testing.T) { checkRegistryStats(t, newTimeSeriesStore(t)) }
|
||||
|
||||
// checkScanIndexMigration drops the index and proves the migration restores it, twice over.
|
||||
func checkScanIndexMigration(t *testing.T, store *GORMStoreV2) {
|
||||
t.Helper()
|
||||
m := store.db.Migrator()
|
||||
require.True(t, m.HasIndex(&ScanResultModel{}, scanPackageScannedAtIndex), "a fresh schema carries the index")
|
||||
require.NoError(t, m.DropIndex(&ScanResultModel{}, scanPackageScannedAtIndex))
|
||||
require.False(t, m.HasIndex(&ScanResultModel{}, scanPackageScannedAtIndex))
|
||||
|
||||
for _, migration := range GetMigrations() {
|
||||
if migration.ID != "202611240001" {
|
||||
continue
|
||||
}
|
||||
require.NoError(t, migration.Migrate(store.db))
|
||||
require.NoError(t, migration.Migrate(store.db), "rerun must be a no-op")
|
||||
require.True(t, m.HasIndex(&ScanResultModel{}, scanPackageScannedAtIndex))
|
||||
return
|
||||
}
|
||||
t.Fatal("migration 202611240001 is not registered")
|
||||
}
|
||||
|
||||
func TestScanIndexMigration(t *testing.T) { checkScanIndexMigration(t, newTimeSeriesStore(t)) }
|
||||
|
||||
func (s *GORMStoreV2TestSuite) Test_V2_ListPackageGroupsMatchesReference() {
|
||||
checkListPackageGroupsMatchesReference(s.T(), s.store)
|
||||
}
|
||||
func (s *GORMStoreV2TestSuite) Test_V2_ListPackageGroupsBehaviour() {
|
||||
checkListPackageGroupsBehaviour(s.T(), s.store)
|
||||
}
|
||||
func (s *GORMStoreV2TestSuite) Test_V2_DashboardStatementsAreConstant() {
|
||||
checkDashboardStatementsAreConstant(s.T(), s.store)
|
||||
}
|
||||
func (s *GORMStoreV2TestSuite) Test_V2_ScanSummaries() { checkScanSummaries(s.T(), s.store) }
|
||||
func (s *GORMStoreV2TestSuite) Test_V2_RegistryStats() { checkRegistryStats(s.T(), s.store) }
|
||||
func (s *GORMStoreV2TestSuite) Test_V2_ScanIndexMigration() { checkScanIndexMigration(s.T(), s.store) }
|
||||
@@ -103,6 +103,12 @@ func NewV2(cfg Config) (*GORMStoreV2, error) {
|
||||
}
|
||||
}
|
||||
|
||||
if cfg.Driver == "sqlite" {
|
||||
if err := ensureSQLiteStatsIndexes(db); err != nil {
|
||||
return nil, errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to create stats indexes")
|
||||
}
|
||||
}
|
||||
|
||||
if err := dropEmptyTable(db, legacyDownloadEventsTable); err != nil {
|
||||
log.Warn().Err(err).Str("table", legacyDownloadEventsTable).Msg("Failed to drop empty legacy table")
|
||||
}
|
||||
@@ -119,10 +125,17 @@ func NewV2(cfg Config) (*GORMStoreV2, error) {
|
||||
}
|
||||
}
|
||||
|
||||
// History must exist before the worker writes today's snapshot.
|
||||
if days, err := BackfillStatsSnapshots(context.Background(), db, time.Now()); err != nil {
|
||||
log.Warn().Err(err).Msg("Failed to backfill stats snapshots")
|
||||
} else if days > 0 {
|
||||
log.Info().Int("days", days).Msg("Backfilled stats snapshots")
|
||||
}
|
||||
|
||||
// Start aggregation worker (skip for in-memory databases used in tests)
|
||||
if !strings.Contains(cfg.DSN, ":memory:") {
|
||||
store.aggregationWorker = NewAggregationWorker(db)
|
||||
go store.aggregationWorker.Start()
|
||||
store.aggregationWorker.StartAsync()
|
||||
} else {
|
||||
// For tests: create worker but don't start it
|
||||
store.aggregationWorker = NewAggregationWorker(db)
|
||||
@@ -673,6 +686,12 @@ func (s *GORMStoreV2) GetStats(ctx context.Context, registry string) (*metadata.
|
||||
return stats, nil
|
||||
}
|
||||
|
||||
// DB exposes the GORM handle for tests.
|
||||
func (s *GORMStoreV2) DB() *gorm.DB { return s.db }
|
||||
|
||||
// WrapDB replaces the handle with wrap(handle). Tests use it to count statements; call it before concurrent use.
|
||||
func (s *GORMStoreV2) WrapDB(wrap func(*gorm.DB) *gorm.DB) { s.db = wrap(s.db) }
|
||||
|
||||
// Health checks database connectivity
|
||||
func (s *GORMStoreV2) Health(ctx context.Context) error {
|
||||
sqlDB, err := s.db.DB()
|
||||
@@ -969,41 +988,7 @@ func (s *GORMStoreV2) GetScanResult(ctx context.Context, registry, name, version
|
||||
return nil, errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to retrieve scan result")
|
||||
}
|
||||
|
||||
// Extract vulnerabilities from Details
|
||||
var vulnerabilities []metadata.Vulnerability
|
||||
if vulnData, ok := scanModel.Details["vulnerabilities"]; ok {
|
||||
// The vulnerabilities are stored as []interface{} after JSON unmarshaling
|
||||
if vulnArray, ok := vulnData.([]interface{}); ok {
|
||||
for _, v := range vulnArray {
|
||||
if vulnMap, ok := v.(map[string]interface{}); ok {
|
||||
vuln := metadata.Vulnerability{
|
||||
ID: getStringFromMap(vulnMap, "id"),
|
||||
Severity: getStringFromMap(vulnMap, "severity"),
|
||||
Title: getStringFromMap(vulnMap, "title"),
|
||||
Description: getStringFromMap(vulnMap, "description"),
|
||||
FixedIn: getStringFromMap(vulnMap, "fixed_in"),
|
||||
}
|
||||
// Extract references array
|
||||
if refs, ok := vulnMap["references"].([]interface{}); ok {
|
||||
for _, ref := range refs {
|
||||
if refStr, ok := ref.(string); ok {
|
||||
vuln.References = append(vuln.References, refStr)
|
||||
}
|
||||
}
|
||||
}
|
||||
// Extract detected_by array
|
||||
if detectedBy, ok := vulnMap["detected_by"].([]interface{}); ok {
|
||||
for _, db := range detectedBy {
|
||||
if dbStr, ok := db.(string); ok {
|
||||
vuln.DetectedBy = append(vuln.DetectedBy, dbStr)
|
||||
}
|
||||
}
|
||||
}
|
||||
vulnerabilities = append(vulnerabilities, vuln)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
vulnerabilities := vulnerabilitiesFromDetails(scanModel.Details)
|
||||
|
||||
// Convert to metadata.ScanResult
|
||||
result := &metadata.ScanResult{
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package gormstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
@@ -88,9 +89,44 @@ func GetMigrations() []*gormigrate.Migration {
|
||||
},
|
||||
Rollback: func(tx *gorm.DB) error { return nil },
|
||||
},
|
||||
{
|
||||
// Serves the latest-scan-per-package lookup behind the dashboard lists.
|
||||
ID: "202611240001",
|
||||
Migrate: func(tx *gorm.DB) error {
|
||||
return createIndexIfMissing(tx, &ScanResultModel{}, scanPackageScannedAtIndex)
|
||||
},
|
||||
Rollback: func(tx *gorm.DB) error {
|
||||
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{})
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// scanPackageScannedAtIndex is scan_results (package_id, scanned_at).
|
||||
const scanPackageScannedAtIndex = "idx_scan_package_scanned_at"
|
||||
|
||||
// createIndexIfMissing creates a tag-declared index; MySQL has no CREATE INDEX IF NOT EXISTS.
|
||||
func createIndexIfMissing(db *gorm.DB, model interface{}, name string) error {
|
||||
if db.Migrator().HasIndex(model, name) {
|
||||
return nil
|
||||
}
|
||||
return db.Migrator().CreateIndex(model, name)
|
||||
}
|
||||
|
||||
// legacyDownloadEventsTable is what the partition manager renames the plain
|
||||
// download_events table to before it creates the partitioned one.
|
||||
const legacyDownloadEventsTable = "download_events_old"
|
||||
@@ -271,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",
|
||||
|
||||
@@ -114,7 +114,7 @@ func (PackageMetadataModel) TableName() string {
|
||||
|
||||
// ScanResultModel represents security scan results (optimized)
|
||||
type ScanResultModel struct {
|
||||
ScannedAt time.Time `gorm:"not null;index:idx_scan_scanned_at"`
|
||||
ScannedAt time.Time `gorm:"not null;index:idx_scan_scanned_at;index:idx_scan_package_scanned_at,priority:2"`
|
||||
Details JSONBField // Scanner-specific details
|
||||
BaseModel
|
||||
|
||||
@@ -123,7 +123,7 @@ type ScanResultModel struct {
|
||||
|
||||
Package PackageModel `gorm:"foreignKey:PackageID;constraint:OnUpdate:CASCADE,OnDelete:CASCADE"`
|
||||
ID int64 `gorm:"primaryKey;autoIncrement"`
|
||||
PackageID int64 `gorm:"not null;index:idx_scan_package_scanner,priority:1"` // Foreign key
|
||||
PackageID int64 `gorm:"not null;index:idx_scan_package_scanner,priority:1;index:idx_scan_package_scanned_at,priority:1"` // Foreign key
|
||||
VulnCount int `gorm:"not null;default:0;index:idx_scan_vuln_count"`
|
||||
CriticalCount int `gorm:"not null;default:0"`
|
||||
HighCount int `gorm:"not null;default:0"`
|
||||
@@ -351,6 +351,27 @@ func (a *PostgresArray) Scan(value interface{}) error {
|
||||
return json.Unmarshal(bytes, a)
|
||||
}
|
||||
|
||||
// StatsSnapshotModel is the cache state at the end of one UTC day. It has no
|
||||
// foreign key to packages, so purging package rows never touches history. A nil
|
||||
// count is unknown, not zero.
|
||||
type StatsSnapshotModel struct {
|
||||
CreatedAt time.Time `gorm:"not null"`
|
||||
UpdatedAt time.Time `gorm:"not null"`
|
||||
VulnerablePackages *int64
|
||||
Critical *int64 // packages whose highest severity is critical
|
||||
High *int64
|
||||
Moderate *int64
|
||||
Low *int64
|
||||
Blocked *int64
|
||||
Day string `gorm:"primaryKey;size:10"` // YYYY-MM-DD, UTC
|
||||
TotalPackages int64 `gorm:"not null;default:0"`
|
||||
TotalSize int64 `gorm:"not null;default:0"`
|
||||
}
|
||||
|
||||
func (StatsSnapshotModel) TableName() string {
|
||||
return "stats_snapshots"
|
||||
}
|
||||
|
||||
// GetAllModels returns all models for GORM auto-migration
|
||||
func GetAllModels() []interface{} {
|
||||
return []interface{}{
|
||||
@@ -366,5 +387,6 @@ func GetAllModels() []interface{} {
|
||||
&DownloadStatsDailyModel{},
|
||||
&AuditLogModel{},
|
||||
&APIKeyModel{},
|
||||
&StatsSnapshotModel{},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
package gormstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/errors"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// PurgeDeletedPackages hard-deletes up to limit soft-deleted packages deleted
|
||||
// before deletedBefore, oldest id first, with the rows that reference them.
|
||||
// Download history and stats snapshots hold no reference and stay.
|
||||
func (s *GORMStoreV2) PurgeDeletedPackages(ctx context.Context, deletedBefore time.Time, limit int) (int64, error) {
|
||||
if limit <= 0 {
|
||||
limit = metadata.DefaultBatchSize
|
||||
}
|
||||
var purged int64
|
||||
err := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
var ids []int64
|
||||
if err := tx.Unscoped().Model(&PackageModel{}).
|
||||
Where("deleted_at IS NOT NULL AND deleted_at < ?", deletedBefore).
|
||||
Order("id").Limit(limit).Pluck("id", &ids).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if len(ids) == 0 {
|
||||
return nil
|
||||
}
|
||||
// The foreign keys cascade on PostgreSQL and MySQL; SQLite enforces them only when asked.
|
||||
for _, child := range []interface{}{&PackageVulnerabilityModel{}, &ScanResultModel{}, &PackageMetadataModel{}} {
|
||||
if err := tx.Unscoped().Where("package_id IN ?", ids).Delete(child).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
res := tx.Unscoped().Where("id IN ?", ids).Delete(&PackageModel{})
|
||||
purged = res.RowsAffected
|
||||
return res.Error
|
||||
})
|
||||
if err != nil {
|
||||
return 0, errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to purge deleted packages")
|
||||
}
|
||||
return purged, nil
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
//go:build pgintegration
|
||||
|
||||
package gormstore
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestPostgresPurgeDeletedPackages(t *testing.T) {
|
||||
store, _ := newPostgresStore(t)
|
||||
require.NoError(t, store.db.Exec("TRUNCATE packages, stats_snapshots, download_stats_daily RESTART IDENTITY CASCADE").Error)
|
||||
|
||||
checkPurgeDeletedPackages(t, store)
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package gormstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func checkPurgeDeletedPackages(t *testing.T, store *GORMStoreV2) {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
for i := 0; i < 5; i++ {
|
||||
name := fmt.Sprintf("gone-%d", i)
|
||||
seedAt(t, store, name, "1.0.0", 10, daysAgo(60))
|
||||
scanAt(t, store, name, "1.0.0", daysAgo(59), "high")
|
||||
require.NoError(t, store.db.Create(&PackageMetadataModel{PackageID: packageID(t, store, name)}).Error)
|
||||
}
|
||||
seedAt(t, store, "live", "1.0.0", 10, daysAgo(60))
|
||||
scanAt(t, store, "live", "1.0.0", daysAgo(59), "high")
|
||||
seedAt(t, store, "recent", "1.0.0", 10, daysAgo(60))
|
||||
softDeleteAt(t, store, "recent", "1.0.0", daysAgo(5))
|
||||
for i := 0; i < 5; i++ {
|
||||
softDeleteAt(t, store, fmt.Sprintf("gone-%d", i), "1.0.0", daysAgo(40-i))
|
||||
}
|
||||
|
||||
// History survives the purge: snapshots and download rows hold their own counts.
|
||||
days, err := BackfillStatsSnapshots(ctx, store.db, time.Now())
|
||||
require.NoError(t, err)
|
||||
require.Positive(t, days)
|
||||
snapshotsBefore := trendByDay(t, store, daysAgo(100))
|
||||
require.NoError(t, store.db.Create(&DownloadStatsDailyModel{
|
||||
TimeBucket: daysAgo(45), RegistryID: 1, PackageID: ptr(packageIDUnscoped(t, store, "gone-0")), DownloadCount: 9,
|
||||
}).Error)
|
||||
|
||||
cutoff := today().AddDate(0, 0, -30)
|
||||
n, err := store.PurgeDeletedPackages(ctx, cutoff, 2)
|
||||
require.NoError(t, err)
|
||||
require.EqualValues(t, 2, n, "bounded by the batch limit")
|
||||
require.EqualValues(t, 3, countRows(t, store, "gone-%", true), "oldest deletions go first")
|
||||
|
||||
n, err = store.PurgeDeletedPackages(ctx, cutoff, 100)
|
||||
require.NoError(t, err)
|
||||
require.EqualValues(t, 3, n)
|
||||
n, err = store.PurgeDeletedPackages(ctx, cutoff, 100)
|
||||
require.NoError(t, err)
|
||||
require.Zero(t, n, "nothing left past the retention")
|
||||
|
||||
require.Zero(t, countRows(t, store, "gone-%", true))
|
||||
require.EqualValues(t, 1, countRows(t, store, "recent", true), "a deletion inside the retention stays")
|
||||
require.EqualValues(t, 1, countRows(t, store, "live", false), "an active package is never purged")
|
||||
|
||||
var children int64
|
||||
for _, table := range []string{"scan_results", "package_vulnerabilities", "package_metadata"} {
|
||||
var rows int64
|
||||
require.NoError(t, store.db.Table(table).Count(&rows).Error)
|
||||
children += rows
|
||||
}
|
||||
require.EqualValues(t, 1, children, "only the live package keeps its scan row; vulnerability and metadata rows left with their packages")
|
||||
|
||||
var scans int64
|
||||
require.NoError(t, store.db.Model(&ScanResultModel{}).Count(&scans).Error)
|
||||
require.EqualValues(t, 1, scans)
|
||||
|
||||
require.Equal(t, snapshotsBefore, trendByDay(t, store, daysAgo(100)), "snapshots are untouched")
|
||||
var daily int64
|
||||
require.NoError(t, store.db.Model(&DownloadStatsDailyModel{}).Count(&daily).Error)
|
||||
require.EqualValues(t, 1, daily, "download history is untouched")
|
||||
|
||||
again, err := BackfillStatsSnapshots(ctx, store.db, time.Now())
|
||||
require.NoError(t, err)
|
||||
require.Zero(t, again, "the backfill never rewrites history after a purge")
|
||||
}
|
||||
|
||||
func packageID(t *testing.T, store *GORMStoreV2, name string) int64 {
|
||||
t.Helper()
|
||||
var id int64
|
||||
require.NoError(t, store.db.Model(&PackageModel{}).Where("name = ?", name).Pluck("id", &id).Error)
|
||||
return id
|
||||
}
|
||||
|
||||
func packageIDUnscoped(t *testing.T, store *GORMStoreV2, name string) int64 {
|
||||
t.Helper()
|
||||
var id int64
|
||||
require.NoError(t, store.db.Unscoped().Model(&PackageModel{}).Where("name = ?", name).Pluck("id", &id).Error)
|
||||
return id
|
||||
}
|
||||
|
||||
func countRows(t *testing.T, store *GORMStoreV2, namePattern string, deleted bool) int64 {
|
||||
t.Helper()
|
||||
q := store.db.Unscoped().Model(&PackageModel{}).Where("name LIKE ?", namePattern)
|
||||
if deleted {
|
||||
q = q.Where("deleted_at IS NOT NULL")
|
||||
} else {
|
||||
q = q.Where("deleted_at IS NULL")
|
||||
}
|
||||
var n int64
|
||||
require.NoError(t, q.Count(&n).Error)
|
||||
return n
|
||||
}
|
||||
|
||||
func TestBackfillStatsSnapshots(t *testing.T) { checkBackfillStatsSnapshots(t, newTimeSeriesStore(t)) }
|
||||
func TestBackfillWithoutScans(t *testing.T) { checkBackfillWithoutScans(t, newTimeSeriesStore(t)) }
|
||||
func TestSnapshotStats(t *testing.T) { checkSnapshotStats(t, newTimeSeriesStore(t)) }
|
||||
func TestTrendWindow(t *testing.T) { checkTrendWindow(t, newTimeSeriesStore(t)) }
|
||||
func TestTrendStatementsAreConstant(t *testing.T) {
|
||||
checkTrendStatementsAreConstant(t, newTimeSeriesStore(t))
|
||||
}
|
||||
func TestPurgeDeletedPackages(t *testing.T) { checkPurgeDeletedPackages(t, newTimeSeriesStore(t)) }
|
||||
@@ -0,0 +1,23 @@
|
||||
//go:build pgintegration
|
||||
|
||||
package gormstore
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestPostgresSeverityFilter(t *testing.T) {
|
||||
store, _ := newPostgresStore(t)
|
||||
|
||||
for name, check := range map[string]func(*testing.T, *GORMStoreV2){
|
||||
"severity filter": checkSeverityFilter,
|
||||
"severity statements constant": checkSeverityFilterStatementsAreConstant,
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
require.NoError(t, store.db.Exec("TRUNCATE packages RESTART IDENTITY CASCADE").Error)
|
||||
check(t, store)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
package gormstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func checkSeverityFilter(t *testing.T, store *GORMStoreV2) {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
for _, n := range []string{"crit", "high", "mod", "low", "clean", "fixed", "multi", "unscanned"} {
|
||||
seedAt(t, store, n, "1.0.0", 1, daysAgo(3))
|
||||
}
|
||||
scanAt(t, store, "crit", "1.0.0", daysAgo(2), "critical")
|
||||
scanAt(t, store, "high", "1.0.0", daysAgo(2), "high")
|
||||
scanAt(t, store, "mod", "1.0.0", daysAgo(2), "moderate")
|
||||
scanAt(t, store, "low", "1.0.0", daysAgo(2), "low")
|
||||
scanAt(t, store, "clean", "1.0.0", daysAgo(2))
|
||||
scanAt(t, store, "fixed", "1.0.0", daysAgo(2), "critical")
|
||||
scanAt(t, store, "fixed", "1.0.0", daysAgo(1)) // the newest scan decides
|
||||
scanAt(t, store, "multi", "1.0.0", daysAgo(2), "high", "low")
|
||||
|
||||
pick := func(opts metadata.GroupListOptions) []string {
|
||||
page, err := store.ListPackageGroups(ctx, opts)
|
||||
require.NoError(t, err)
|
||||
out := names(page.Packages)
|
||||
for i := range out {
|
||||
for j := i + 1; j < len(out); j++ {
|
||||
if out[j] < out[i] {
|
||||
out[i], out[j] = out[j], out[i]
|
||||
}
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
require.Equal(t, []string{"crit"}, pick(metadata.GroupListOptions{Severities: []string{"critical"}}))
|
||||
require.Equal(t, []string{"high", "multi"}, pick(metadata.GroupListOptions{Severities: []string{"high"}}))
|
||||
require.Equal(t, []string{"crit", "mod"}, pick(metadata.GroupListOptions{Severities: []string{"critical", "moderate"}}), "OR across severities")
|
||||
require.Equal(t, []string{"low", "multi"}, pick(metadata.GroupListOptions{Severities: []string{"low"}}))
|
||||
require.Equal(t, []string{"crit", "high", "low", "mod", "multi"},
|
||||
pick(metadata.GroupListOptions{Severities: metadata.Severities}), "every severity = every vulnerable package")
|
||||
require.Len(t, pick(metadata.GroupListOptions{}), 8, "no filter keeps everything")
|
||||
|
||||
paged, err := store.ListPackageGroups(ctx, metadata.GroupListOptions{Severities: []string{"high", "low"}, Page: 1, PageSize: 2})
|
||||
require.NoError(t, err)
|
||||
require.EqualValues(t, 3, paged.TotalGroups, "paging counts the filtered groups")
|
||||
require.Len(t, paged.Packages, 2)
|
||||
|
||||
require.Equal(t, []string{"crit"}, pick(metadata.GroupListOptions{Severities: []string{"critical"}, Query: "cr"}), "composes with search")
|
||||
require.Empty(t, pick(metadata.GroupListOptions{Severities: []string{"critical"}, Query: "high"}))
|
||||
|
||||
// The trend snapshot counts a package under every severity it holds, exactly as the filter selects it.
|
||||
snap, err := liveSnapshot(ctx, store.db, time.Now(), nil)
|
||||
require.NoError(t, err)
|
||||
for sev, got := range map[string]*int64{
|
||||
metadata.SeverityCritical: snap.Critical, metadata.SeverityHigh: snap.High,
|
||||
metadata.SeverityModerate: snap.Moderate, metadata.SeverityLow: snap.Low,
|
||||
} {
|
||||
require.EqualValues(t, len(pick(metadata.GroupListOptions{Severities: []string{sev}})), *got, sev)
|
||||
}
|
||||
require.EqualValues(t, 5, *snap.VulnerablePackages)
|
||||
require.EqualValues(t, len(pick(metadata.GroupListOptions{Severities: metadata.Severities})), *snap.VulnerablePackages)
|
||||
require.EqualValues(t, [4]int64{1, 2, 1, 2}, [4]int64{*snap.Critical, *snap.High, *snap.Moderate, *snap.Low}, "multi counts under high and low")
|
||||
}
|
||||
|
||||
func checkSeverityFilterStatementsAreConstant(t *testing.T, store *GORMStoreV2) {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
counter := attachCounter(store)
|
||||
measure := func() [2]int {
|
||||
var out [2]int
|
||||
counter.Reset()
|
||||
_, err := store.ListPackageGroups(ctx, metadata.GroupListOptions{Severities: []string{"critical", "high"}})
|
||||
require.NoError(t, err)
|
||||
out[0] = counter.Count()
|
||||
counter.Reset()
|
||||
_, err = store.ListPackageGroups(ctx, metadata.GroupListOptions{Severities: []string{"low"}, Page: 1, PageSize: 25})
|
||||
require.NoError(t, err)
|
||||
out[1] = counter.Count()
|
||||
return out
|
||||
}
|
||||
seedScanned(t, store, 0, 10)
|
||||
small := measure()
|
||||
seedScanned(t, store, 10, 90)
|
||||
large := measure()
|
||||
t.Logf("statements for 10 rows %v, for 100 rows %v", small, large)
|
||||
require.Equal(t, small, large)
|
||||
require.LessOrEqual(t, large[0], 1, "the filter is a subquery of the one list read")
|
||||
require.LessOrEqual(t, large[1], 3)
|
||||
}
|
||||
|
||||
func TestSeverityFilter(t *testing.T) { checkSeverityFilter(t, newTimeSeriesStore(t)) }
|
||||
func TestSeverityFilterStatementsAreConstant(t *testing.T) {
|
||||
checkSeverityFilterStatementsAreConstant(t, newTimeSeriesStore(t))
|
||||
}
|
||||
@@ -0,0 +1,389 @@
|
||||
package gormstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sort"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/errors"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/rs/zerolog/log"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
const (
|
||||
day = 24 * time.Hour
|
||||
snapshotBatch = 500
|
||||
)
|
||||
|
||||
// artifactPackages limits a query on packages to cache artifacts: no metadata
|
||||
// pages and no Go .mod/.info files, as GetStats counts them.
|
||||
func artifactPackages(db *gorm.DB) *gorm.DB {
|
||||
return db.Where("version NOT IN ?", metadata.MetadataVersions).
|
||||
Where("name NOT LIKE ?", "%.mod").Where("name NOT LIKE ?", "%.info")
|
||||
}
|
||||
|
||||
func dayString(t time.Time) string { return t.UTC().Format(metadata.StatsSnapshotDateLayout) }
|
||||
|
||||
func ptr(v int64) *int64 { return &v }
|
||||
|
||||
// liveSnapshot reads the current cache state in one statement. blocked may be nil.
|
||||
func liveSnapshot(ctx context.Context, db *gorm.DB, at time.Time, blocked *int64) (*StatsSnapshotModel, error) {
|
||||
var r struct {
|
||||
Total int64
|
||||
Size int64
|
||||
Vulnerable int64
|
||||
Critical int64
|
||||
High int64
|
||||
Moderate int64
|
||||
Low int64
|
||||
}
|
||||
// A package counts under every severity its latest scan holds, as the severity filter selects it.
|
||||
scanned := func(col string) string {
|
||||
return "COALESCE(SUM(CASE WHEN security_scanned = ? AND id IN (" + latestScanWith(col+" > 0") + ") THEN 1 ELSE 0 END), 0)"
|
||||
}
|
||||
err := artifactPackages(db.WithContext(ctx).Model(&PackageModel{})).Select(`
|
||||
COUNT(*) AS total,
|
||||
COALESCE(SUM(size), 0) AS size,
|
||||
`+scanned("vuln_count")+` AS vulnerable,
|
||||
`+scanned(severityColumns[metadata.SeverityCritical])+` AS critical,
|
||||
`+scanned(severityColumns[metadata.SeverityHigh])+` AS high,
|
||||
`+scanned(severityColumns[metadata.SeverityModerate])+` AS moderate,
|
||||
`+scanned(severityColumns[metadata.SeverityLow])+` AS low`, true, true, true, true, true).
|
||||
Scan(&r).Error
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to read stats for snapshot")
|
||||
}
|
||||
return &StatsSnapshotModel{
|
||||
Day: dayString(at),
|
||||
TotalPackages: r.Total,
|
||||
TotalSize: r.Size,
|
||||
VulnerablePackages: ptr(r.Vulnerable),
|
||||
Critical: ptr(r.Critical),
|
||||
High: ptr(r.High),
|
||||
Moderate: ptr(r.Moderate),
|
||||
Low: ptr(r.Low),
|
||||
Blocked: blocked,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// snapshotColumns are overwritten when a day's snapshot is written again.
|
||||
var snapshotColumns = []string{
|
||||
"total_packages", "total_size", "vulnerable_packages", "critical", "high", "moderate", "low", "blocked", "updated_at",
|
||||
}
|
||||
|
||||
// upsertSnapshot writes the day's row, replacing an earlier write of the same day.
|
||||
// A nil blocked keeps the stored value so a run without a blocking policy never erases it.
|
||||
func upsertSnapshot(ctx context.Context, db *gorm.DB, snap *StatsSnapshotModel) error {
|
||||
cols := snapshotColumns
|
||||
if snap.Blocked == nil {
|
||||
cols = make([]string, 0, len(snapshotColumns))
|
||||
for _, c := range snapshotColumns {
|
||||
if c != "blocked" {
|
||||
cols = append(cols, c)
|
||||
}
|
||||
}
|
||||
}
|
||||
err := db.WithContext(ctx).Clauses(clause.OnConflict{
|
||||
Columns: []clause.Column{{Name: "day"}},
|
||||
DoUpdates: clause.AssignmentColumns(cols),
|
||||
}).Create(snap).Error
|
||||
if err != nil {
|
||||
return errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to save stats snapshot")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// SnapshotStats records today's (UTC) cache state. Running it again the same
|
||||
// day overwrites that day's row, so the last run of a day is its closing state.
|
||||
func (w *AggregationWorker) SnapshotStats(ctx context.Context) error {
|
||||
now := w.clock()
|
||||
var blocked *int64
|
||||
if count := w.blockedCounter(); count != nil {
|
||||
n, err := count(ctx)
|
||||
if err != nil {
|
||||
log.Warn().Err(err).Msg("Failed to count blocked packages for the stats snapshot")
|
||||
} else {
|
||||
blocked = ptr(n)
|
||||
}
|
||||
}
|
||||
snap, err := liveSnapshot(ctx, w.db, now, blocked)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := upsertSnapshot(ctx, w.db, snap); err != nil {
|
||||
return err
|
||||
}
|
||||
log.Info().Str("day", snap.Day).Int64("packages", snap.TotalPackages).Msg("Recorded stats snapshot")
|
||||
return nil
|
||||
}
|
||||
|
||||
// SetBlockedCounter sets how the snapshot counts blocked packages, which needs the scan policy the store lacks.
|
||||
func (w *AggregationWorker) SetBlockedCounter(count func(context.Context) (int64, error)) {
|
||||
w.mu.Lock()
|
||||
w.blocked = count
|
||||
w.mu.Unlock()
|
||||
}
|
||||
|
||||
func (w *AggregationWorker) blockedCounter() func(context.Context) (int64, error) {
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
return w.blocked
|
||||
}
|
||||
|
||||
// SetBlockedCounter sets how daily snapshots count blocked packages.
|
||||
func (s *GORMStoreV2) SetBlockedCounter(count func(context.Context) (int64, error)) {
|
||||
if s.aggregationWorker != nil {
|
||||
s.aggregationWorker.SetBlockedCounter(count)
|
||||
}
|
||||
}
|
||||
|
||||
// GetStatsTrend returns the daily snapshots from the UTC day of since, oldest first, in one statement.
|
||||
func (s *GORMStoreV2) GetStatsTrend(ctx context.Context, since time.Time) ([]*metadata.StatsSnapshot, error) {
|
||||
var rows []StatsSnapshotModel
|
||||
if err := s.db.WithContext(ctx).Where("day >= ?", dayString(since)).Order("day").Find(&rows).Error; err != nil {
|
||||
return nil, errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to read stats snapshots")
|
||||
}
|
||||
out := make([]*metadata.StatsSnapshot, len(rows))
|
||||
for i, r := range rows {
|
||||
out[i] = &metadata.StatsSnapshot{
|
||||
Date: r.Day,
|
||||
TotalPackages: r.TotalPackages,
|
||||
TotalSize: r.TotalSize,
|
||||
VulnerablePackages: r.VulnerablePackages,
|
||||
Critical: r.Critical,
|
||||
High: r.High,
|
||||
Moderate: r.Moderate,
|
||||
Low: r.Low,
|
||||
Blocked: r.Blocked,
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// dayState is one package's contribution to a day's totals.
|
||||
type dayState struct {
|
||||
size, vulnerable, critical, high, moderate, low int64
|
||||
alive int64
|
||||
}
|
||||
|
||||
func (a dayState) minus(b dayState) dayState {
|
||||
return dayState{
|
||||
alive: a.alive - b.alive, size: a.size - b.size, vulnerable: a.vulnerable - b.vulnerable,
|
||||
critical: a.critical - b.critical, high: a.high - b.high, moderate: a.moderate - b.moderate, low: a.low - b.low,
|
||||
}
|
||||
}
|
||||
|
||||
func (a *dayState) add(b dayState) {
|
||||
a.alive += b.alive
|
||||
a.size += b.size
|
||||
a.vulnerable += b.vulnerable
|
||||
a.critical += b.critical
|
||||
a.high += b.high
|
||||
a.moderate += b.moderate
|
||||
a.low += b.low
|
||||
}
|
||||
|
||||
// backfillScan is one scan result reduced to what the history needs.
|
||||
type backfillScan struct {
|
||||
at time.Time
|
||||
vulns, critical, high, moderate, lowCounts int
|
||||
id int64
|
||||
}
|
||||
|
||||
// backfillPackage is one package's lifetime: alive from cachedAt up to deletedAt.
|
||||
type backfillPackage struct {
|
||||
cachedAt time.Time
|
||||
deletedAt *time.Time
|
||||
size int64
|
||||
}
|
||||
|
||||
// stateAtDayEnd is the package's contribution at the end of the UTC day whose
|
||||
// midnight-after is end. withScans is false for days before any scan exists.
|
||||
func (p backfillPackage) stateAtDayEnd(end time.Time, scans []backfillScan, withScans bool) dayState {
|
||||
if !p.cachedAt.Before(end) || (p.deletedAt != nil && p.deletedAt.Before(end)) {
|
||||
return dayState{}
|
||||
}
|
||||
st := dayState{alive: 1, size: p.size}
|
||||
if !withScans {
|
||||
return st
|
||||
}
|
||||
// scans is sorted by (at, id); the last one before end is the latest.
|
||||
i := sort.Search(len(scans), func(i int) bool { return !scans[i].at.Before(end) })
|
||||
if i == 0 {
|
||||
return st
|
||||
}
|
||||
sc := scans[i-1]
|
||||
if sc.vulns > 0 {
|
||||
st.vulnerable = 1
|
||||
}
|
||||
// Every severity the scan holds counts, as in liveSnapshot.
|
||||
if sc.critical > 0 {
|
||||
st.critical = 1
|
||||
}
|
||||
if sc.high > 0 {
|
||||
st.high = 1
|
||||
}
|
||||
if sc.moderate > 0 {
|
||||
st.moderate = 1
|
||||
}
|
||||
if sc.lowCounts > 0 {
|
||||
st.low = 1
|
||||
}
|
||||
return st
|
||||
}
|
||||
|
||||
// BackfillStatsSnapshots writes one snapshot per past UTC day, from the first
|
||||
// package to the day before today, when no snapshot of a past day exists yet. Package counts
|
||||
// come from cached_at and deleted_at. Vulnerability counts come from the
|
||||
// append-only scan results and start at the first scan; earlier days leave
|
||||
// them nil, as blocked is always nil (the policy at the time is not stored).
|
||||
// It returns the number of days written.
|
||||
func BackfillStatsSnapshots(ctx context.Context, db *gorm.DB, now time.Time) (int, error) {
|
||||
today := now.UTC().Truncate(day)
|
||||
var existing int64
|
||||
if err := db.WithContext(ctx).Model(&StatsSnapshotModel{}).Where("day < ?", dayString(today)).Count(&existing).Error; err != nil {
|
||||
return 0, errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to count stats snapshots")
|
||||
}
|
||||
if existing > 0 {
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
pkgs, err := loadBackfillPackages(ctx, db)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if len(pkgs) == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
scans, firstScan, err := loadBackfillScans(ctx, db, pkgs)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
deltas := map[int64]dayState{}
|
||||
first := today
|
||||
for id, p := range pkgs {
|
||||
if d := p.cachedAt.UTC().Truncate(day); d.Before(first) {
|
||||
first = d
|
||||
}
|
||||
prev := dayState{}
|
||||
for _, d := range candidateDays(p, scans[id], today) {
|
||||
cur := p.stateAtDayEnd(d.Add(day), scans[id], !firstScan.IsZero() && !d.Before(firstScan))
|
||||
if delta := cur.minus(prev); delta != (dayState{}) {
|
||||
acc := deltas[d.Unix()]
|
||||
acc.add(delta)
|
||||
deltas[d.Unix()] = acc
|
||||
}
|
||||
prev = cur
|
||||
}
|
||||
}
|
||||
|
||||
var rows []StatsSnapshotModel
|
||||
var total dayState
|
||||
for d := first; d.Before(today); d = d.Add(day) {
|
||||
total.add(deltas[d.Unix()])
|
||||
row := StatsSnapshotModel{Day: dayString(d), TotalPackages: total.alive, TotalSize: total.size}
|
||||
if !firstScan.IsZero() && !d.Before(firstScan) {
|
||||
row.VulnerablePackages, row.Critical, row.High = ptr(total.vulnerable), ptr(total.critical), ptr(total.high)
|
||||
row.Moderate, row.Low = ptr(total.moderate), ptr(total.low)
|
||||
}
|
||||
rows = append(rows, row)
|
||||
}
|
||||
if len(rows) == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
err = db.WithContext(ctx).Clauses(clause.OnConflict{DoNothing: true}).CreateInBatches(rows, snapshotBatch).Error
|
||||
if err != nil {
|
||||
return 0, errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to backfill stats snapshots")
|
||||
}
|
||||
return len(rows), nil
|
||||
}
|
||||
|
||||
// candidateDays lists, sorted, the days before today on which a package's
|
||||
// end-of-day state can change: when it was cached, deleted or scanned.
|
||||
func candidateDays(p backfillPackage, scans []backfillScan, today time.Time) []time.Time {
|
||||
set := map[int64]struct{}{}
|
||||
mark := func(t time.Time) {
|
||||
if d := t.UTC().Truncate(day); d.Before(today) {
|
||||
set[d.Unix()] = struct{}{}
|
||||
}
|
||||
}
|
||||
mark(p.cachedAt)
|
||||
if p.deletedAt != nil {
|
||||
mark(*p.deletedAt)
|
||||
}
|
||||
for _, s := range scans {
|
||||
mark(s.at)
|
||||
}
|
||||
days := make([]time.Time, 0, len(set))
|
||||
for unix := range set {
|
||||
days = append(days, time.Unix(unix, 0).UTC())
|
||||
}
|
||||
sort.Slice(days, func(i, j int) bool { return days[i].Before(days[j]) })
|
||||
return days
|
||||
}
|
||||
|
||||
func loadBackfillPackages(ctx context.Context, db *gorm.DB) (map[int64]backfillPackage, error) {
|
||||
var rows []struct {
|
||||
CachedAt time.Time
|
||||
DeletedAt *time.Time
|
||||
ID int64
|
||||
Size int64
|
||||
}
|
||||
err := artifactPackages(db.WithContext(ctx).Unscoped().Model(&PackageModel{})).
|
||||
Select("id, cached_at, deleted_at, size").Scan(&rows).Error
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to read packages for backfill")
|
||||
}
|
||||
pkgs := make(map[int64]backfillPackage, len(rows))
|
||||
for _, r := range rows {
|
||||
pkgs[r.ID] = backfillPackage{cachedAt: r.CachedAt, deletedAt: r.DeletedAt, size: r.Size}
|
||||
}
|
||||
return pkgs, nil
|
||||
}
|
||||
|
||||
// loadBackfillScans groups the scan results of the given packages and returns
|
||||
// the UTC day of the first scan (zero when there is none).
|
||||
func loadBackfillScans(ctx context.Context, db *gorm.DB, pkgs map[int64]backfillPackage) (map[int64][]backfillScan, time.Time, error) {
|
||||
var rows []struct {
|
||||
ScannedAt time.Time
|
||||
ID int64
|
||||
PackageID int64
|
||||
VulnCount int
|
||||
CriticalCount int
|
||||
HighCount int
|
||||
MediumCount int
|
||||
LowCount int
|
||||
}
|
||||
err := db.WithContext(ctx).Model(&ScanResultModel{}).
|
||||
Select("id, package_id, scanned_at, vuln_count, critical_count, high_count, medium_count, low_count").
|
||||
Scan(&rows).Error
|
||||
if err != nil {
|
||||
return nil, time.Time{}, errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to read scans for backfill")
|
||||
}
|
||||
scans := map[int64][]backfillScan{}
|
||||
var firstScan time.Time
|
||||
for _, r := range rows {
|
||||
if _, ok := pkgs[r.PackageID]; !ok {
|
||||
continue
|
||||
}
|
||||
scans[r.PackageID] = append(scans[r.PackageID], backfillScan{
|
||||
id: r.ID, at: r.ScannedAt, vulns: r.VulnCount,
|
||||
critical: r.CriticalCount, high: r.HighCount, moderate: r.MediumCount, lowCounts: r.LowCount,
|
||||
})
|
||||
if d := r.ScannedAt.UTC().Truncate(day); firstScan.IsZero() || d.Before(firstScan) {
|
||||
firstScan = d
|
||||
}
|
||||
}
|
||||
for _, list := range scans {
|
||||
sort.Slice(list, func(i, j int) bool {
|
||||
if list[i].at.Equal(list[j].at) {
|
||||
return list[i].id < list[j].id
|
||||
}
|
||||
return list[i].at.Before(list[j].at)
|
||||
})
|
||||
}
|
||||
return scans, firstScan, nil
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
//go:build pgintegration
|
||||
|
||||
package gormstore
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestPostgresTrendSeverityAndPurge(t *testing.T) {
|
||||
store, _ := newPostgresStore(t)
|
||||
|
||||
reset := func(t *testing.T) {
|
||||
t.Helper()
|
||||
require.NoError(t, store.db.Exec(
|
||||
"TRUNCATE packages, stats_snapshots, download_stats_daily RESTART IDENTITY CASCADE").Error)
|
||||
}
|
||||
for name, check := range map[string]func(*testing.T, *GORMStoreV2){
|
||||
"backfill": checkBackfillStatsSnapshots,
|
||||
"backfill without scans": checkBackfillWithoutScans,
|
||||
"snapshot": checkSnapshotStats,
|
||||
"trend window": checkTrendWindow,
|
||||
"trend statements constant": checkTrendStatementsAreConstant,
|
||||
"severity filter": checkSeverityFilter,
|
||||
"severity statements constant": checkSeverityFilterStatementsAreConstant,
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
reset(t)
|
||||
check(t, store)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPostgresStatsSnapshotsHaveNoPackageForeignKey(t *testing.T) {
|
||||
store, _ := newPostgresStore(t)
|
||||
|
||||
var referencing []string
|
||||
require.NoError(t, store.db.Raw(
|
||||
"SELECT conrelid::regclass::text FROM pg_constraint WHERE contype = 'f' AND confrelid = 'packages'::regclass",
|
||||
).Scan(&referencing).Error)
|
||||
require.NotContains(t, referencing, "stats_snapshots", "a package purge must not cascade over history")
|
||||
}
|
||||
@@ -0,0 +1,257 @@
|
||||
package gormstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/internal/dbcount"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func today() time.Time { return time.Now().UTC().Truncate(day) }
|
||||
|
||||
// daysAgo is noon UTC, n days before today.
|
||||
func daysAgo(n int) time.Time { return today().AddDate(0, 0, -n).Add(12 * time.Hour) }
|
||||
|
||||
func seedAt(t *testing.T, store *GORMStoreV2, name, version string, size int64, cachedAt time.Time) {
|
||||
t.Helper()
|
||||
require.NoError(t, store.SavePackage(context.Background(), &metadata.Package{
|
||||
Registry: "npm", Name: name, Version: version, StorageKey: fmt.Sprintf("npm/%s/%s", name, version),
|
||||
Size: size, CachedAt: cachedAt, LastAccessed: cachedAt,
|
||||
}))
|
||||
}
|
||||
|
||||
func scanAt(t *testing.T, store *GORMStoreV2, name, version string, at time.Time, severities ...string) {
|
||||
t.Helper()
|
||||
res := &metadata.ScanResult{
|
||||
Registry: "npm", PackageName: name, PackageVersion: version, Scanner: "test", ScannedAt: at,
|
||||
Status: metadata.ScanStatusClean,
|
||||
}
|
||||
for i, sev := range severities {
|
||||
res.Status = metadata.ScanStatusVulnerable
|
||||
res.Vulnerabilities = append(res.Vulnerabilities, metadata.Vulnerability{ID: fmt.Sprintf("CVE-%d", i), Severity: sev})
|
||||
}
|
||||
res.VulnerabilityCount = len(severities)
|
||||
require.NoError(t, store.SaveScanResult(context.Background(), res))
|
||||
}
|
||||
|
||||
// softDeleteAt deletes the package and backdates the deletion.
|
||||
func softDeleteAt(t *testing.T, store *GORMStoreV2, name, version string, at time.Time) {
|
||||
t.Helper()
|
||||
require.NoError(t, store.DeletePackage(context.Background(), "npm", name, version))
|
||||
require.NoError(t, store.db.Unscoped().Model(&PackageModel{}).
|
||||
Where("name = ? AND version = ?", name, version).Update("deleted_at", at).Error)
|
||||
}
|
||||
|
||||
func trendByDay(t *testing.T, store *GORMStoreV2, since time.Time) map[string]*metadata.StatsSnapshot {
|
||||
t.Helper()
|
||||
pts, err := store.GetStatsTrend(context.Background(), since)
|
||||
require.NoError(t, err)
|
||||
out := map[string]*metadata.StatsSnapshot{}
|
||||
for _, p := range pts {
|
||||
out[p.Date] = p
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func vulns(p *metadata.StatsSnapshot) [5]int64 {
|
||||
get := func(v *int64) int64 {
|
||||
if v == nil {
|
||||
return -1
|
||||
}
|
||||
return *v
|
||||
}
|
||||
return [5]int64{get(p.VulnerablePackages), get(p.Critical), get(p.High), get(p.Moderate), get(p.Low)}
|
||||
}
|
||||
|
||||
// checkBackfillStatsSnapshots seeds a five-day history and proves the reconstruction day by day.
|
||||
func checkBackfillStatsSnapshots(t *testing.T, store *GORMStoreV2) {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
|
||||
seedAt(t, store, "a", "1.0.0", 10, daysAgo(5))
|
||||
seedAt(t, store, "b", "1.0.0", 20, daysAgo(4))
|
||||
seedAt(t, store, "a", "list", 5, daysAgo(5)) // metadata page: never counted
|
||||
seedAt(t, store, "mod/@v/v1.mod", "v1", 7, daysAgo(5)) // Go .mod file: never counted
|
||||
seedAt(t, store, "early", "1.0.0", 40, daysAgo(2)) // cached and deleted the same day
|
||||
scanAt(t, store, "b", "1.0.0", daysAgo(4), "high") // first scan: vulnerability history starts here
|
||||
scanAt(t, store, "a", "1.0.0", daysAgo(3), "critical", "low") // critical wins over low
|
||||
scanAt(t, store, "a", "1.0.0", daysAgo(1)) // clean rescan
|
||||
softDeleteAt(t, store, "b", "1.0.0", daysAgo(2))
|
||||
softDeleteAt(t, store, "early", "1.0.0", daysAgo(2).Add(time.Hour))
|
||||
|
||||
days, err := BackfillStatsSnapshots(ctx, store.db, time.Now())
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 5, days, "day -5 to day -1; today belongs to the live snapshot")
|
||||
|
||||
got := trendByDay(t, store, daysAgo(10))
|
||||
require.Len(t, got, 5)
|
||||
day := func(n int) *metadata.StatsSnapshot {
|
||||
p, ok := got[dayString(daysAgo(n))]
|
||||
require.True(t, ok, "day -%d", n)
|
||||
return p
|
||||
}
|
||||
|
||||
require.EqualValues(t, 1, day(5).TotalPackages)
|
||||
require.EqualValues(t, 10, day(5).TotalSize)
|
||||
require.Equal(t, [5]int64{-1, -1, -1, -1, -1}, vulns(day(5)), "no scan existed yet: unknown, not zero")
|
||||
|
||||
require.EqualValues(t, 2, day(4).TotalPackages)
|
||||
require.EqualValues(t, 30, day(4).TotalSize)
|
||||
require.Equal(t, [5]int64{1, 0, 1, 0, 0}, vulns(day(4)))
|
||||
|
||||
require.EqualValues(t, 2, day(3).TotalPackages)
|
||||
require.Equal(t, [5]int64{2, 1, 1, 0, 1}, vulns(day(3)), "a counts under critical and low")
|
||||
|
||||
require.EqualValues(t, 1, day(2).TotalPackages, "b was deleted on day -2; early lived and died within it")
|
||||
require.EqualValues(t, 10, day(2).TotalSize)
|
||||
require.Equal(t, [5]int64{1, 1, 0, 0, 1}, vulns(day(2)))
|
||||
|
||||
require.EqualValues(t, 1, day(1).TotalPackages)
|
||||
require.Equal(t, [5]int64{0, 0, 0, 0, 0}, vulns(day(1)), "the clean rescan clears the vulnerability")
|
||||
require.Nil(t, day(1).Blocked, "the policy of a past day is not reconstructable")
|
||||
|
||||
again, err := BackfillStatsSnapshots(ctx, store.db, time.Now())
|
||||
require.NoError(t, err)
|
||||
require.Zero(t, again, "a second run is a no-op")
|
||||
require.Len(t, trendByDay(t, store, daysAgo(10)), 5)
|
||||
}
|
||||
|
||||
// checkBackfillWithoutScans proves that without scan history only package counts are written.
|
||||
func checkBackfillWithoutScans(t *testing.T, store *GORMStoreV2) {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
days, err := BackfillStatsSnapshots(ctx, store.db, time.Now())
|
||||
require.NoError(t, err)
|
||||
require.Zero(t, days, "no packages, no history")
|
||||
|
||||
seedAt(t, store, "a", "1.0.0", 10, daysAgo(2))
|
||||
days, err = BackfillStatsSnapshots(ctx, store.db, time.Now())
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 2, days)
|
||||
for _, p := range trendByDay(t, store, daysAgo(10)) {
|
||||
require.EqualValues(t, 1, p.TotalPackages)
|
||||
require.Equal(t, [5]int64{-1, -1, -1, -1, -1}, vulns(p))
|
||||
}
|
||||
}
|
||||
|
||||
func checkSnapshotStats(t *testing.T, store *GORMStoreV2) {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
seedAt(t, store, "a", "1.0.0", 10, daysAgo(1))
|
||||
seedAt(t, store, "b", "1.0.0", 20, daysAgo(1))
|
||||
seedAt(t, store, "c", "1.0.0", 30, daysAgo(1))
|
||||
scanAt(t, store, "a", "1.0.0", daysAgo(1), "critical")
|
||||
scanAt(t, store, "b", "1.0.0", daysAgo(1), "moderate")
|
||||
|
||||
// An in-memory database has no running worker; this one is the test's own.
|
||||
worker := store.aggregationWorker
|
||||
store.SetBlockedCounter(func(context.Context) (int64, error) { return 1, nil })
|
||||
require.NoError(t, worker.SnapshotStats(ctx))
|
||||
require.NoError(t, worker.SnapshotStats(ctx), "the same day twice writes one row")
|
||||
|
||||
rows := trendByDay(t, store, today())
|
||||
require.Len(t, rows, 1)
|
||||
snap := rows[dayString(time.Now())]
|
||||
require.NotNil(t, snap)
|
||||
require.EqualValues(t, 3, snap.TotalPackages)
|
||||
require.EqualValues(t, 60, snap.TotalSize)
|
||||
require.Equal(t, [5]int64{2, 1, 0, 1, 0}, vulns(snap))
|
||||
require.EqualValues(t, 1, *snap.Blocked)
|
||||
|
||||
// The next run of the day replaces the counts.
|
||||
scanAt(t, store, "a", "1.0.0", daysAgo(0).Add(-time.Hour), "high")
|
||||
store.SetBlockedCounter(nil)
|
||||
require.NoError(t, worker.SnapshotStats(ctx))
|
||||
snap = trendByDay(t, store, today())[dayString(time.Now())]
|
||||
require.Equal(t, [5]int64{2, 0, 1, 1, 0}, vulns(snap))
|
||||
require.EqualValues(t, 1, *snap.Blocked, "a run without a blocking policy keeps the earlier count")
|
||||
|
||||
store.SetBlockedCounter(func(context.Context) (int64, error) { return 0, errors.New("scanner down") })
|
||||
require.NoError(t, worker.SnapshotStats(ctx), "a failed blocked count must not lose the snapshot")
|
||||
}
|
||||
|
||||
func checkTrendWindow(t *testing.T, store *GORMStoreV2) {
|
||||
t.Helper()
|
||||
for i := 0; i < 5; i++ {
|
||||
require.NoError(t, store.db.Create(&StatsSnapshotModel{Day: dayString(daysAgo(i)), TotalPackages: int64(i)}).Error)
|
||||
}
|
||||
pts, err := store.GetStatsTrend(context.Background(), daysAgo(2))
|
||||
require.NoError(t, err)
|
||||
require.Len(t, pts, 3)
|
||||
require.Equal(t, dayString(daysAgo(2)), pts[0].Date, "oldest first, from the since day inclusive")
|
||||
require.Equal(t, dayString(daysAgo(0)), pts[2].Date)
|
||||
require.Nil(t, pts[0].VulnerablePackages)
|
||||
|
||||
none, err := store.GetStatsTrend(context.Background(), today().AddDate(0, 0, 1))
|
||||
require.NoError(t, err)
|
||||
require.Empty(t, none)
|
||||
}
|
||||
|
||||
// attachCounter counts the statements of the store and of its worker, which holds its own handle.
|
||||
func attachCounter(store *GORMStoreV2) *dbcount.Counter {
|
||||
var counter *dbcount.Counter
|
||||
store.aggregationWorker.Stop() // its handle is swapped below; a running loop would race
|
||||
store.WrapDB(func(db *gorm.DB) *gorm.DB {
|
||||
counted, c := dbcount.Attach(db)
|
||||
counter = c
|
||||
return counted
|
||||
})
|
||||
store.aggregationWorker.db = store.db
|
||||
return counter
|
||||
}
|
||||
|
||||
func checkTrendStatementsAreConstant(t *testing.T, store *GORMStoreV2) {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
counter := attachCounter(store)
|
||||
|
||||
measure := func() map[string]int {
|
||||
out := map[string]int{}
|
||||
counter.Reset()
|
||||
_, err := store.GetStatsTrend(ctx, daysAgo(365))
|
||||
require.NoError(t, err)
|
||||
out["trend"] = counter.Count()
|
||||
counter.Reset()
|
||||
require.NoError(t, store.aggregationWorker.SnapshotStats(ctx))
|
||||
out["snapshot"] = counter.Count()
|
||||
require.NoError(t, store.db.Exec("DELETE FROM stats_snapshots").Error)
|
||||
counter.Reset()
|
||||
_, err = BackfillStatsSnapshots(ctx, store.db, time.Now().AddDate(0, 0, 400))
|
||||
require.NoError(t, err)
|
||||
out["backfill"] = counter.Count()
|
||||
return out
|
||||
}
|
||||
|
||||
seedScanned(t, store, 0, 10)
|
||||
small := measure()
|
||||
seedScanned(t, store, 10, 90)
|
||||
large := measure()
|
||||
t.Logf("statements for 10 packages %v, for 100 packages %v", small, large)
|
||||
require.Equal(t, small, large)
|
||||
require.Equal(t, 1, large["trend"])
|
||||
require.Equal(t, 2, large["snapshot"], "one aggregate read, one upsert")
|
||||
require.LessOrEqual(t, large["backfill"], 4, "count, packages, scans, one insert batch")
|
||||
require.Positive(t, large["backfill"])
|
||||
}
|
||||
|
||||
func TestStatsSnapshotMigration(t *testing.T) {
|
||||
store := newTimeSeriesStore(t)
|
||||
seedAt(t, store, "a", "1.0.0", 10, daysAgo(2))
|
||||
require.NoError(t, store.db.Migrator().DropTable(&StatsSnapshotModel{}))
|
||||
for _, migration := range GetMigrations() {
|
||||
if migration.ID != "202611250001" {
|
||||
continue
|
||||
}
|
||||
require.NoError(t, migration.Migrate(store.db))
|
||||
require.NoError(t, migration.Migrate(store.db), "rerun must be a no-op")
|
||||
require.Len(t, trendByDay(t, store, daysAgo(10)), 2, "the migration seeds the history")
|
||||
return
|
||||
}
|
||||
t.Fatal("migration 202611250001 is not registered")
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package gormstore
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// ensureSQLiteStatsIndexes gives SQLite the unique indexes PostgreSQL gets from
|
||||
// the partition manager, merging duplicate rows written before they existed.
|
||||
func ensureSQLiteStatsIndexes(db *gorm.DB) error {
|
||||
var present int64
|
||||
if err := db.Raw("SELECT COUNT(*) FROM sqlite_master WHERE type = 'index' AND name IN ('idx_stats_hourly_upsert', 'idx_stats_daily_upsert')").Scan(&present).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if present == int64(len(statsUpsertIndexes)) {
|
||||
return nil
|
||||
}
|
||||
|
||||
return db.Transaction(func(tx *gorm.DB) error {
|
||||
// Hourly package rows come from passes over disjoint events, so they add up.
|
||||
// Registry rows (NULL package) and daily rows are derived and recomputed by the
|
||||
// next pass; one copy of each is enough.
|
||||
const group = "d.registry_id = download_stats_hourly.registry_id AND d.package_id = download_stats_hourly.package_id AND d.time_bucket = download_stats_hourly.time_bucket"
|
||||
merge := `UPDATE download_stats_hourly SET
|
||||
download_count = (SELECT SUM(d.download_count) FROM download_stats_hourly d WHERE ` + group + `),
|
||||
auth_downloads = (SELECT SUM(d.auth_downloads) FROM download_stats_hourly d WHERE ` + group + `),
|
||||
unique_ips = (SELECT MAX(d.unique_ips) FROM download_stats_hourly d WHERE ` + group + `)
|
||||
WHERE package_id IS NOT NULL AND id = (SELECT MIN(d.id) FROM download_stats_hourly d WHERE ` + group + `)`
|
||||
if err := tx.Exec(merge).Error; err != nil {
|
||||
return fmt.Errorf("merge duplicate hourly stats rows: %w", err)
|
||||
}
|
||||
for _, table := range []string{"download_stats_hourly", "download_stats_daily"} {
|
||||
dedupe := fmt.Sprintf("DELETE FROM %[1]s WHERE id NOT IN (SELECT MIN(id) FROM %[1]s GROUP BY registry_id, COALESCE(package_id, 0), time_bucket)", table)
|
||||
if err := tx.Exec(dedupe).Error; err != nil {
|
||||
return fmt.Errorf("delete duplicate %s rows: %w", table, err)
|
||||
}
|
||||
}
|
||||
for _, stmt := range statsUpsertIndexes {
|
||||
if err := tx.Exec(stmt).Error; err != nil {
|
||||
return fmt.Errorf("create stats upsert index: %w", err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
//go:build pgintegration
|
||||
|
||||
package gormstore
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// The same scenario the SQLite test runs: both dialects must report the same totals.
|
||||
func TestPostgresHourlyTotalsMatchSQLite(t *testing.T) {
|
||||
store, _ := newPostgresStore(t)
|
||||
require.Equal(t, wantHourlyScenario(), runHourlyScenario(t, store))
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
package gormstore
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// statsScenario drives the same hourly passes on any dialect and returns the
|
||||
// observable totals, so SQLite and PostgreSQL can be held to one expectation.
|
||||
type statsScenario struct {
|
||||
packageRows, registryRows int64
|
||||
packageCount, registryCnt int64
|
||||
chartTotal int64
|
||||
}
|
||||
|
||||
func runHourlyScenario(t *testing.T, store *GORMStoreV2) statsScenario {
|
||||
t.Helper()
|
||||
hour := time.Now().UTC().Truncate(time.Hour).Add(-3 * time.Hour)
|
||||
|
||||
seedEventsAt(t, store, hour.Add(10*time.Minute), hour.Add(20*time.Minute))
|
||||
tick(t, store, hour.Add(2*time.Hour), false)
|
||||
tick(t, store, hour.Add(2*time.Hour+5*time.Minute), false) // nothing new: must change nothing
|
||||
|
||||
seedEventsAt(t, store, hour.Add(50*time.Minute)) // a late download for the same bucket
|
||||
tick(t, store, hour.Add(3*time.Hour), false)
|
||||
|
||||
var s statsScenario
|
||||
db := store.db.Table("download_stats_hourly")
|
||||
require.NoError(t, db.Where("package_id IS NOT NULL").Count(&s.packageRows).Error)
|
||||
require.NoError(t, store.db.Table("download_stats_hourly").Where("package_id IS NULL").Count(&s.registryRows).Error)
|
||||
require.NoError(t, store.db.Table("download_stats_hourly").Where("package_id IS NOT NULL").Select("COALESCE(SUM(download_count),0)").Scan(&s.packageCount).Error)
|
||||
require.NoError(t, store.db.Table("download_stats_hourly").Where("package_id IS NULL").Select("COALESCE(SUM(download_count),0)").Scan(&s.registryCnt).Error)
|
||||
s.chartTotal = totalAt(t, store, hour.Add(3*time.Hour+10*time.Minute), "24hour")
|
||||
return s
|
||||
}
|
||||
|
||||
func wantHourlyScenario() statsScenario {
|
||||
return statsScenario{packageRows: 1, registryRows: 1, packageCount: 3, registryCnt: 3, chartTotal: 3}
|
||||
}
|
||||
|
||||
// SQLite carried no unique index, so INSERT OR REPLACE inserted a new row every pass.
|
||||
func TestSQLiteHourlyTotalsMatchPostgresSemantics(t *testing.T) {
|
||||
store := newTimeSeriesStore(t)
|
||||
require.Equal(t, wantHourlyScenario(), runHourlyScenario(t, store))
|
||||
}
|
||||
|
||||
func TestSQLiteDailyRollupIsIdempotent(t *testing.T) {
|
||||
store := newTimeSeriesStore(t)
|
||||
day := time.Date(2026, 3, 10, 0, 0, 0, 0, time.UTC)
|
||||
seedEventsAt(t, store, day.Add(5*time.Hour), day.Add(6*time.Hour))
|
||||
tick(t, store, day.Add(24*time.Hour+30*time.Minute), false)
|
||||
for i := 0; i < 3; i++ {
|
||||
store.aggregationWorker.now = func() time.Time { return day.Add(25 * time.Hour) }
|
||||
require.NoError(t, store.aggregationWorker.AggregateDaily())
|
||||
}
|
||||
|
||||
var rows, total int64
|
||||
require.NoError(t, store.db.Table("download_stats_daily").Where("package_id IS NOT NULL").Count(&rows).Error)
|
||||
require.NoError(t, store.db.Table("download_stats_daily").Where("package_id IS NOT NULL").Select("COALESCE(SUM(download_count),0)").Scan(&total).Error)
|
||||
require.EqualValues(t, 1, rows)
|
||||
require.EqualValues(t, 2, total)
|
||||
}
|
||||
|
||||
// Databases written by the old code hold duplicate rows; the migration merges them.
|
||||
func TestSQLiteStatsDedupeMigration(t *testing.T) {
|
||||
store := newTimeSeriesStore(t)
|
||||
for _, name := range []string{"idx_stats_hourly_upsert", "idx_stats_daily_upsert"} {
|
||||
require.NoError(t, store.db.Exec("DROP INDEX IF EXISTS "+name).Error)
|
||||
}
|
||||
bucket := "2026-03-10 05:00:00"
|
||||
insert := func(table string, pkg any, n int) {
|
||||
require.NoError(t, store.db.Exec(
|
||||
"INSERT INTO "+table+" (registry_id, package_id, time_bucket, download_count, unique_ips, auth_downloads, created_at, updated_at) VALUES (1, ?, ?, ?, 1, 0, datetime('now'), datetime('now'))",
|
||||
pkg, bucket, n).Error)
|
||||
}
|
||||
// Package rows from separate passes hold disjoint events: they add up.
|
||||
insert("download_stats_hourly", 7, 2)
|
||||
insert("download_stats_hourly", 7, 3)
|
||||
// Registry rows are derived copies: one survives.
|
||||
insert("download_stats_hourly", nil, 5)
|
||||
insert("download_stats_hourly", nil, 5)
|
||||
insert("download_stats_daily", nil, 5)
|
||||
insert("download_stats_daily", nil, 5)
|
||||
|
||||
require.NoError(t, ensureSQLiteStatsIndexes(store.db))
|
||||
|
||||
count := func(table, where string) (rows, total int64) {
|
||||
require.NoError(t, store.db.Table(table).Where(where).Count(&rows).Error)
|
||||
require.NoError(t, store.db.Table(table).Where(where).Select("COALESCE(SUM(download_count),0)").Scan(&total).Error)
|
||||
return
|
||||
}
|
||||
rows, total := count("download_stats_hourly", "package_id = 7")
|
||||
require.EqualValues(t, 1, rows)
|
||||
require.EqualValues(t, 5, total)
|
||||
rows, total = count("download_stats_hourly", "package_id IS NULL")
|
||||
require.EqualValues(t, 1, rows)
|
||||
require.EqualValues(t, 5, total)
|
||||
rows, _ = count("download_stats_daily", "package_id IS NULL")
|
||||
require.EqualValues(t, 1, rows)
|
||||
|
||||
require.Error(t, store.db.Exec(
|
||||
"INSERT INTO download_stats_hourly (registry_id, package_id, time_bucket, download_count, unique_ips, auth_downloads, created_at, updated_at) VALUES (1, NULL, ?, 1, 1, 0, datetime('now'), datetime('now'))", bucket).Error,
|
||||
"unique index must reject a duplicate registry row")
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
package metadata
|
||||
|
||||
import (
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// IsMetadataVersion reports whether version names a metadata page rather than an artifact.
|
||||
func IsMetadataVersion(version string) bool {
|
||||
for _, v := range MetadataVersions {
|
||||
if version == v {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// MatchesQuery reports whether a package matches a case-insensitive search on name, version or release version.
|
||||
func MatchesQuery(p *Package, query string) bool {
|
||||
q := strings.ToLower(strings.TrimSpace(query))
|
||||
if q == "" {
|
||||
return true
|
||||
}
|
||||
return strings.Contains(strings.ToLower(p.Name), q) ||
|
||||
strings.Contains(strings.ToLower(p.Version), q) ||
|
||||
strings.Contains(strings.ToLower(p.ReleaseVersion), q)
|
||||
}
|
||||
|
||||
type groupAgg struct {
|
||||
registry, name string
|
||||
rows []*Package
|
||||
last int64
|
||||
size, dl int64
|
||||
}
|
||||
|
||||
// PageGroups filters, groups, sorts and pages rows in memory. It is the reference
|
||||
// behaviour that SQL backends of ListPackageGroups must match.
|
||||
func PageGroups(all []*Package, opts GroupListOptions) *GroupPage {
|
||||
groups := map[string]*groupAgg{}
|
||||
for _, p := range all {
|
||||
if IsMetadataVersion(p.Version) || (opts.Registry != "" && p.Registry != opts.Registry) || !MatchesQuery(p, opts.Query) {
|
||||
continue
|
||||
}
|
||||
name := CleanName(p.Name)
|
||||
key := p.Registry + "\x00" + name
|
||||
g, ok := groups[key]
|
||||
if !ok {
|
||||
g = &groupAgg{registry: p.Registry, name: name}
|
||||
groups[key] = g
|
||||
}
|
||||
if ts := p.CachedAt.UnixNano(); ts > g.last {
|
||||
g.last = ts
|
||||
}
|
||||
g.size += p.Size
|
||||
g.dl += p.DownloadCount
|
||||
g.rows = append(g.rows, p)
|
||||
}
|
||||
|
||||
ordered := make([]*groupAgg, 0, len(groups))
|
||||
for _, g := range groups {
|
||||
ordered = append(ordered, g)
|
||||
}
|
||||
sort.Slice(ordered, func(i, j int) bool {
|
||||
a, b := ordered[i], ordered[j]
|
||||
var cmp int
|
||||
switch opts.SortBy {
|
||||
case GroupSortCachedAt:
|
||||
cmp = compareInt(a.last, b.last)
|
||||
case GroupSortDownloads:
|
||||
cmp = compareInt(a.dl, b.dl)
|
||||
case GroupSortSize:
|
||||
cmp = compareInt(a.size, b.size)
|
||||
}
|
||||
if cmp != 0 {
|
||||
if opts.SortDesc {
|
||||
return cmp > 0
|
||||
}
|
||||
return cmp < 0
|
||||
}
|
||||
if c := strings.Compare(strings.ToLower(a.name), strings.ToLower(b.name)); c != 0 {
|
||||
if opts.SortBy == "" || opts.SortBy == GroupSortName {
|
||||
if opts.SortDesc {
|
||||
return c > 0
|
||||
}
|
||||
}
|
||||
return c < 0
|
||||
}
|
||||
return a.registry < b.registry
|
||||
})
|
||||
|
||||
page := &GroupPage{TotalGroups: int64(len(ordered))}
|
||||
if opts.PageSize > 0 {
|
||||
pageNo := opts.Page
|
||||
if pageNo < 1 {
|
||||
pageNo = 1
|
||||
}
|
||||
start := (pageNo - 1) * opts.PageSize
|
||||
if start >= len(ordered) {
|
||||
return page
|
||||
}
|
||||
end := start + opts.PageSize
|
||||
if end > len(ordered) {
|
||||
end = len(ordered)
|
||||
}
|
||||
ordered = ordered[start:end]
|
||||
}
|
||||
for _, g := range ordered {
|
||||
sort.SliceStable(g.rows, func(i, j int) bool { return g.rows[i].CachedAt.After(g.rows[j].CachedAt) })
|
||||
page.Packages = append(page.Packages, DedupeVersions(g.rows)...)
|
||||
}
|
||||
return page
|
||||
}
|
||||
|
||||
func compareInt(a, b int64) int {
|
||||
switch {
|
||||
case a < b:
|
||||
return -1
|
||||
case a > b:
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package metadata
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestCleanName(t *testing.T) {
|
||||
require.Equal(t, "github.com/a/b", CleanName("github.com/a/b/@v/v1.0.0.zip"))
|
||||
require.Equal(t, "left-pad", CleanName("left-pad"))
|
||||
require.Equal(t, "@scope/pkg", CleanName("@scope/pkg"))
|
||||
}
|
||||
|
||||
func TestDedupeVersionsKeepsLargestAndRenames(t *testing.T) {
|
||||
rows := []*Package{
|
||||
{Registry: "go", Name: "m/@v/v1.zip", Version: "v1", Size: 5},
|
||||
{Registry: "go", Name: "m/@v/v1.mod", Version: "v1", Size: 50},
|
||||
{Registry: "go", Name: "m/@v/v1.info", Version: "v1", Size: 1},
|
||||
{Registry: "npm", Name: "m", Version: "v1", Size: 9},
|
||||
}
|
||||
got := DedupeVersions(rows)
|
||||
require.Len(t, got, 2, "the same name in another registry is a different package")
|
||||
require.Equal(t, "m", got[0].Name)
|
||||
require.EqualValues(t, 50, got[0].Size)
|
||||
require.Equal(t, "m/@v/v1.zip", rows[0].Name, "input rows stay untouched")
|
||||
}
|
||||
|
||||
func TestPageGroupsPagesWholeGroups(t *testing.T) {
|
||||
at := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)
|
||||
rows := []*Package{
|
||||
{Registry: "npm", Name: "b", Version: "1", CachedAt: at.Add(1 * time.Hour)},
|
||||
{Registry: "npm", Name: "b", Version: "2", CachedAt: at.Add(5 * time.Hour)},
|
||||
{Registry: "npm", Name: "a", Version: "1", CachedAt: at.Add(2 * time.Hour)},
|
||||
{Registry: "npm", Name: "c", Version: "list", CachedAt: at},
|
||||
}
|
||||
page := PageGroups(rows, GroupListOptions{Page: 1, PageSize: 1})
|
||||
require.EqualValues(t, 2, page.TotalGroups, "the list page forms no group")
|
||||
require.Len(t, page.Packages, 1)
|
||||
require.Equal(t, "a", page.Packages[0].Name)
|
||||
|
||||
recent := PageGroups(rows, GroupListOptions{SortBy: GroupSortCachedAt, SortDesc: true, Page: 1, PageSize: 1})
|
||||
require.Equal(t, []string{"2", "1"}, []string{recent.Packages[0].Version, recent.Packages[1].Version}, "group b, newest version first")
|
||||
|
||||
require.Empty(t, PageGroups(rows, GroupListOptions{Page: 9, PageSize: 1}).Packages)
|
||||
require.Len(t, PageGroups(rows, GroupListOptions{Query: "B"}).Packages, 2)
|
||||
}
|
||||
@@ -63,6 +63,18 @@ type MetadataStore interface {
|
||||
// ListPackages lists packages with optional filtering
|
||||
ListPackages(ctx context.Context, opts *ListOptions) ([]*Package, error)
|
||||
|
||||
// ListPackageGroups returns one page of (registry, name) groups with every
|
||||
// version row of each group. It costs a constant number of statements.
|
||||
ListPackageGroups(ctx context.Context, opts GroupListOptions) (*GroupPage, error)
|
||||
|
||||
// GetScanSummaries returns the latest scan of each scanned package in one
|
||||
// round trip. A nil packageIDs means every scanned package. Vulnerability
|
||||
// lists are loaded only when withDetails is set.
|
||||
GetScanSummaries(ctx context.Context, packageIDs []string, withDetails bool) ([]*ScanSummary, error)
|
||||
|
||||
// GetRegistryStats returns per-registry totals over cache artifacts.
|
||||
GetRegistryStats(ctx context.Context) ([]RegistryStat, error)
|
||||
|
||||
// UpdateDownloadCount increments download counter and stamps last_accessed
|
||||
UpdateDownloadCount(ctx context.Context, registry, name, version string) error
|
||||
|
||||
@@ -74,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)
|
||||
@@ -305,3 +326,119 @@ type ListOptions struct {
|
||||
ScannedOnly bool
|
||||
SortDesc bool
|
||||
}
|
||||
|
||||
// Group sort keys for GroupListOptions.SortBy.
|
||||
const (
|
||||
GroupSortName = "name"
|
||||
GroupSortCachedAt = "cached_at"
|
||||
GroupSortDownloads = "downloads"
|
||||
GroupSortSize = "size"
|
||||
)
|
||||
|
||||
// GroupListOptions selects one page of package groups. A group is one
|
||||
// (registry, cleaned name) pair; metadata pages never form a group.
|
||||
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
|
||||
// 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
|
||||
// order and newest first within a group. Name is the cleaned group name.
|
||||
Packages []*Package
|
||||
// TotalGroups counts the groups matching the filters, across all pages.
|
||||
TotalGroups int64
|
||||
}
|
||||
|
||||
// ScanSummary is the latest scan of one package, without the heavy details.
|
||||
type ScanSummary struct {
|
||||
ScannedAt time.Time
|
||||
Details map[string]interface{} // set only for failed scans
|
||||
Registry string
|
||||
PackageID string
|
||||
Name string // the cache row name, including any Go /@v/ suffix
|
||||
Version string
|
||||
ReleaseVersion string
|
||||
Status ScanStatus
|
||||
Vulnerabilities []Vulnerability // set only when requested
|
||||
Total int
|
||||
Critical int
|
||||
High int
|
||||
Moderate int
|
||||
Low int
|
||||
HasScan bool // false when the package is flagged scanned but has no scan row
|
||||
}
|
||||
|
||||
// RegistryStat holds the totals of one registry.
|
||||
type RegistryStat struct {
|
||||
Registry string
|
||||
Count int64
|
||||
Size int64
|
||||
Downloads int64
|
||||
}
|
||||
|
||||
// CleanName strips the Go "/@v/<file>" suffix so every file of a module version shares one name.
|
||||
func CleanName(name string) string {
|
||||
if idx := strings.Index(name, "/@v/"); idx != -1 {
|
||||
return name[:idx]
|
||||
}
|
||||
return name
|
||||
}
|
||||
|
||||
// DedupeVersions keeps one row per (cleaned name, version), preferring the largest
|
||||
// (the Go .zip over its .mod and .info), and renames the rows to the cleaned name.
|
||||
// Output order follows the first appearance of each key.
|
||||
func DedupeVersions(rows []*Package) []*Package {
|
||||
index := make(map[string]int, len(rows))
|
||||
out := make([]*Package, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
clean := *row
|
||||
clean.Name = CleanName(row.Name)
|
||||
key := clean.Registry + "\x00" + clean.Name + "\x00" + clean.Version
|
||||
if i, ok := index[key]; ok {
|
||||
if clean.Size > out[i].Size {
|
||||
out[i] = &clean
|
||||
}
|
||||
continue
|
||||
}
|
||||
index[key] = len(out)
|
||||
out = append(out, &clean)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
+114
-7
@@ -6,8 +6,11 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/errors"
|
||||
@@ -19,6 +22,7 @@ import (
|
||||
// Client is an HTTP client with resilience features
|
||||
type Client struct {
|
||||
client *http.Client
|
||||
hopClient *http.Client
|
||||
rateLimiter *rate.Limiter
|
||||
circuitBreaker *CircuitBreaker
|
||||
retryConfig RetryConfig
|
||||
@@ -34,6 +38,9 @@ type Config struct {
|
||||
RateLimit float64
|
||||
RateBurst int
|
||||
MaxConnsPerHost int
|
||||
// AllowPrivateRedirects lets a redirect to another host reach private, loopback or
|
||||
// link-local addresses. Off by default; it exists for tests and private mirrors.
|
||||
AllowPrivateRedirects bool
|
||||
}
|
||||
|
||||
// RetryConfig holds retry configuration
|
||||
@@ -105,8 +112,19 @@ func NewClient(config Config) *Client {
|
||||
}
|
||||
|
||||
httpClient := &http.Client{
|
||||
Timeout: config.Timeout,
|
||||
Transport: transport,
|
||||
Timeout: config.Timeout,
|
||||
Transport: transport,
|
||||
CheckRedirect: noAutoRedirect,
|
||||
}
|
||||
|
||||
hopTransport := transport.Clone()
|
||||
if !config.AllowPrivateRedirects {
|
||||
hopTransport.DialContext = (&net.Dialer{Timeout: 30 * time.Second, Control: refusePrivateAddress}).DialContext
|
||||
}
|
||||
hopClient := &http.Client{
|
||||
Timeout: config.Timeout,
|
||||
Transport: hopTransport,
|
||||
CheckRedirect: noAutoRedirect,
|
||||
}
|
||||
|
||||
var rateLimiter *rate.Limiter
|
||||
@@ -140,6 +158,7 @@ func NewClient(config Config) *Client {
|
||||
|
||||
return &Client{
|
||||
client: httpClient,
|
||||
hopClient: hopClient,
|
||||
rateLimiter: rateLimiter,
|
||||
circuitBreaker: cb,
|
||||
retryConfig: RetryConfig{
|
||||
@@ -154,8 +173,15 @@ func NewClient(config Config) *Client {
|
||||
}
|
||||
|
||||
// Get performs a GET request with resilience features
|
||||
func (c *Client) Get(ctx context.Context, url string, headers map[string]string) (io.ReadCloser, int, error) {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
|
||||
func (c *Client) Get(ctx context.Context, rawURL string, headers map[string]string) (io.ReadCloser, int, error) {
|
||||
return c.GetWithRedirectCheck(ctx, rawURL, headers, nil)
|
||||
}
|
||||
|
||||
// GetWithRedirectCheck is Get with a policy that every redirect target must pass.
|
||||
// Redirects are always capped, limited to http(s), and refused when they reach a
|
||||
// private address on another host; check adds an allowlist on top.
|
||||
func (c *Client) GetWithRedirectCheck(ctx context.Context, rawURL string, headers map[string]string, check RedirectCheck) (io.ReadCloser, int, error) {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil)
|
||||
if err != nil {
|
||||
return nil, 0, errors.Wrap(err, errors.ErrCodeUpstreamError, "failed to create request")
|
||||
}
|
||||
@@ -164,7 +190,7 @@ func (c *Client) Get(ctx context.Context, url string, headers map[string]string)
|
||||
req.Header.Set(key, value)
|
||||
}
|
||||
|
||||
resp, err := c.do(ctx, req)
|
||||
resp, err := c.do(ctx, req, check)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
@@ -173,7 +199,7 @@ func (c *Client) Get(ctx context.Context, url string, headers map[string]string)
|
||||
}
|
||||
|
||||
// do executes an HTTP request with retries and circuit breaker
|
||||
func (c *Client) do(ctx context.Context, req *http.Request) (*http.Response, error) {
|
||||
func (c *Client) do(ctx context.Context, req *http.Request, check RedirectCheck) (*http.Response, error) {
|
||||
// Check circuit breaker
|
||||
if c.circuitBreaker != nil {
|
||||
if !c.circuitBreaker.AllowRequest() {
|
||||
@@ -226,7 +252,7 @@ func (c *Client) do(ctx context.Context, req *http.Request) (*http.Response, err
|
||||
Msg("Retrying request")
|
||||
}
|
||||
|
||||
resp, err := c.client.Do(req)
|
||||
resp, err := c.send(req, check)
|
||||
if err != nil {
|
||||
lastErr = err
|
||||
continue
|
||||
@@ -353,3 +379,84 @@ func (cb *CircuitBreaker) GetState() CircuitBreakerState {
|
||||
defer cb.mu.RUnlock()
|
||||
return cb.state
|
||||
}
|
||||
|
||||
// MaxRedirects caps the hops one request may follow.
|
||||
const MaxRedirects = 10
|
||||
|
||||
// RedirectCheck vets a redirect target before it is fetched.
|
||||
type RedirectCheck func(*url.URL) error
|
||||
|
||||
var errRedirectNotAllowed = errors.New(errors.ErrCodeUpstreamError, "redirect refused")
|
||||
|
||||
func noAutoRedirect(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
|
||||
|
||||
// send performs req and follows redirects itself, so each hop is vetted and, once the
|
||||
// host changes, dialed through the guard that refuses private addresses.
|
||||
func (c *Client) send(req *http.Request, check RedirectCheck) (*http.Response, error) {
|
||||
origin := req.URL.Host
|
||||
cur := req
|
||||
httpClient := c.client
|
||||
for hop := 0; ; hop++ {
|
||||
resp, err := httpClient.Do(cur)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
loc := resp.Header.Get("Location")
|
||||
if !isRedirectStatus(resp.StatusCode) || loc == "" {
|
||||
return resp, nil
|
||||
}
|
||||
_ = resp.Body.Close() // #nosec G104 -- Cleanup, error not critical
|
||||
if hop >= MaxRedirects {
|
||||
return nil, errors.Wrap(errRedirectNotAllowed, errors.ErrCodeUpstreamError, "too many redirects")
|
||||
}
|
||||
next, err := cur.URL.Parse(loc)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, errors.ErrCodeUpstreamError, "invalid redirect location")
|
||||
}
|
||||
if next.Scheme != "http" && next.Scheme != "https" {
|
||||
return nil, errors.Wrap(errRedirectNotAllowed, errors.ErrCodeUpstreamError, "redirect to non-http scheme")
|
||||
}
|
||||
if check != nil {
|
||||
if err := check(next); err != nil {
|
||||
return nil, errors.Wrap(err, errors.ErrCodeUpstreamError, "redirect target not allowed")
|
||||
}
|
||||
}
|
||||
clone := cur.Clone(cur.Context())
|
||||
clone.URL = next
|
||||
clone.Host = ""
|
||||
if next.Host != cur.URL.Host {
|
||||
clone.Header.Del("Authorization")
|
||||
clone.Header.Del("Cookie")
|
||||
}
|
||||
cur = clone
|
||||
if next.Host != origin {
|
||||
httpClient = c.hopClient
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func isRedirectStatus(code int) bool {
|
||||
switch code {
|
||||
case http.StatusMovedPermanently, http.StatusFound, http.StatusSeeOther,
|
||||
http.StatusTemporaryRedirect, http.StatusPermanentRedirect:
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// carrierGradeNAT is 100.64.0.0/10, which net.IP.IsPrivate does not cover.
|
||||
var carrierGradeNAT = &net.IPNet{IP: net.IPv4(100, 64, 0, 0), Mask: net.CIDRMask(10, 32)}
|
||||
|
||||
// refusePrivateAddress runs after DNS resolution, so a name cannot rebind to an internal address.
|
||||
func refusePrivateAddress(_, address string, _ syscall.RawConn) error {
|
||||
host, _, err := net.SplitHostPort(address)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ip := net.ParseIP(host)
|
||||
if ip == nil || ip.IsLoopback() || ip.IsPrivate() || ip.IsUnspecified() || ip.IsLinkLocalUnicast() ||
|
||||
ip.IsLinkLocalMulticast() || ip.IsInterfaceLocalMulticast() || ip.IsMulticast() || carrierGradeNAT.Contains(ip) {
|
||||
return fmt.Errorf("refusing to connect to non-public address %s", host)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
package network_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/network"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func redirectClient(allowPrivate bool) *network.Client {
|
||||
return network.NewClient(network.Config{
|
||||
Timeout: 5 * time.Second,
|
||||
MaxRetries: 1,
|
||||
AllowPrivateRedirects: allowPrivate,
|
||||
})
|
||||
}
|
||||
|
||||
// hostPolicy allows only the listed hostnames (port ignored).
|
||||
func hostPolicy(hosts ...string) func(*url.URL) error {
|
||||
return func(u *url.URL) error {
|
||||
for _, h := range hosts {
|
||||
if u.Hostname() == h {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("host %q not allowed", u.Hostname())
|
||||
}
|
||||
}
|
||||
|
||||
func okServer(hit *atomic.Int32) *httptest.Server {
|
||||
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
hit.Add(1)
|
||||
_, _ = w.Write([]byte("secret"))
|
||||
}))
|
||||
}
|
||||
|
||||
func TestRedirectToDisallowedHostRefused(t *testing.T) {
|
||||
var hit atomic.Int32
|
||||
target := okServer(&hit)
|
||||
defer target.Close()
|
||||
// Same loopback server under a different hostname: allowed host redirects to a disallowed one.
|
||||
redirectTo := strings.Replace(target.URL, "127.0.0.1", "localhost", 1)
|
||||
origin := httptest.NewServer(http.RedirectHandler(redirectTo, http.StatusFound))
|
||||
defer origin.Close()
|
||||
|
||||
_, _, err := redirectClient(true).GetWithRedirectCheck(context.Background(), origin.URL, nil, hostPolicy("127.0.0.1"))
|
||||
require.Error(t, err)
|
||||
assert.Zero(t, hit.Load(), "disallowed hop must not be fetched")
|
||||
}
|
||||
|
||||
func TestRedirectToLoopbackRefused(t *testing.T) {
|
||||
var hit atomic.Int32
|
||||
target := okServer(&hit)
|
||||
defer target.Close()
|
||||
// Allowed by name, but resolves to loopback on a different host:port than the origin.
|
||||
origin := httptest.NewServer(http.RedirectHandler(strings.Replace(target.URL, "127.0.0.1", "localhost", 1), http.StatusFound))
|
||||
defer origin.Close()
|
||||
|
||||
_, _, err := redirectClient(false).GetWithRedirectCheck(context.Background(), origin.URL, nil, hostPolicy("127.0.0.1", "localhost"))
|
||||
require.Error(t, err)
|
||||
assert.Zero(t, hit.Load(), "loopback hop must not be fetched")
|
||||
}
|
||||
|
||||
func TestRedirectToPrivateLiteralRefused(t *testing.T) {
|
||||
for _, loc := range []string{"http://10.1.2.3/x", "http://169.254.169.254/latest/meta-data", "http://[::1]/x", "http://192.168.0.1/x"} {
|
||||
origin := httptest.NewServer(http.RedirectHandler(loc, http.StatusFound))
|
||||
_, _, err := redirectClient(false).Get(context.Background(), origin.URL, nil)
|
||||
origin.Close()
|
||||
require.Error(t, err, loc)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRedirectAllowedToAllowedWorks(t *testing.T) {
|
||||
var hit atomic.Int32
|
||||
target := okServer(&hit)
|
||||
defer target.Close()
|
||||
origin := httptest.NewServer(http.RedirectHandler(strings.Replace(target.URL, "127.0.0.1", "localhost", 1), http.StatusFound))
|
||||
defer origin.Close()
|
||||
|
||||
body, status, err := redirectClient(true).GetWithRedirectCheck(context.Background(), origin.URL, nil, hostPolicy("127.0.0.1", "localhost"))
|
||||
require.NoError(t, err)
|
||||
defer func() { _ = body.Close() }()
|
||||
data, _ := io.ReadAll(body)
|
||||
assert.Equal(t, http.StatusOK, status)
|
||||
assert.Equal(t, "secret", string(data))
|
||||
}
|
||||
|
||||
func TestRedirectHopsCapped(t *testing.T) {
|
||||
var hits atomic.Int32
|
||||
var srv *httptest.Server
|
||||
srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
hits.Add(1)
|
||||
http.Redirect(w, r, srv.URL+"/loop", http.StatusFound)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
_, _, err := redirectClient(true).Get(context.Background(), srv.URL, nil)
|
||||
require.Error(t, err)
|
||||
assert.LessOrEqual(t, int(hits.Load()), 11)
|
||||
}
|
||||
|
||||
func TestRedirectToNonHTTPSchemeRefused(t *testing.T) {
|
||||
origin := httptest.NewServer(http.RedirectHandler("file:///etc/passwd", http.StatusFound))
|
||||
defer origin.Close()
|
||||
_, _, err := redirectClient(true).Get(context.Background(), origin.URL, nil)
|
||||
require.Error(t, err)
|
||||
}
|
||||
|
||||
func TestRedirectDropsAuthorizationAcrossHosts(t *testing.T) {
|
||||
var got atomic.Value
|
||||
got.Store("unset")
|
||||
target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
got.Store(r.Header.Get("Authorization"))
|
||||
}))
|
||||
defer target.Close()
|
||||
origin := httptest.NewServer(http.RedirectHandler(strings.Replace(target.URL, "127.0.0.1", "localhost", 1), http.StatusFound))
|
||||
defer origin.Close()
|
||||
|
||||
body, _, err := redirectClient(true).Get(context.Background(), origin.URL, map[string]string{"Authorization": "Bearer x"})
|
||||
require.NoError(t, err)
|
||||
_ = body.Close()
|
||||
assert.Equal(t, "", got.Load())
|
||||
}
|
||||
|
||||
func TestSameHostRedirectToLoopbackStillWorks(t *testing.T) {
|
||||
// A private index redirecting within itself is operator-trusted.
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/a", func(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, "/b", http.StatusFound) })
|
||||
mux.HandleFunc("/b", func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write([]byte("ok")) })
|
||||
srv := httptest.NewServer(mux)
|
||||
defer srv.Close()
|
||||
|
||||
body, status, err := redirectClient(false).Get(context.Background(), srv.URL+"/a", nil)
|
||||
require.NoError(t, err)
|
||||
_ = body.Close()
|
||||
assert.Equal(t, http.StatusOK, status)
|
||||
}
|
||||
@@ -0,0 +1,266 @@
|
||||
package prewarming
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"html"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"path"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/proxy/pypi"
|
||||
)
|
||||
|
||||
const (
|
||||
registryNPM = "npm"
|
||||
registryPyPI = "pypi"
|
||||
registryGo = "go"
|
||||
|
||||
// proxyHost is only a placeholder: the handlers are called in-process and never dial it.
|
||||
proxyHost = "gohoarder.invalid"
|
||||
maxMetadataBytes = 64 << 20
|
||||
)
|
||||
|
||||
var (
|
||||
hrefPattern = regexp.MustCompile(`href="([^"]+)"`)
|
||||
numericSemVer = regexp.MustCompile(`^\d+(\.\d+)*$`)
|
||||
distSuffixes = []string{".whl", ".tar.gz", ".zip", ".egg"}
|
||||
)
|
||||
|
||||
// ProxyFetcher pre-warms through the registry handlers in-process, so artifacts are cached,
|
||||
// scanned and policy-checked exactly like a client request.
|
||||
type ProxyFetcher struct {
|
||||
handlers map[string]http.Handler
|
||||
}
|
||||
|
||||
// NewProxyFetcher returns a fetcher with no registries mounted.
|
||||
func NewProxyFetcher() *ProxyFetcher {
|
||||
return &ProxyFetcher{handlers: make(map[string]http.Handler)}
|
||||
}
|
||||
|
||||
// Mount registers the handler serving a registry; it must already strip the "/<registry>" prefix
|
||||
// the way the HTTP server mounts it. Mount before the worker starts.
|
||||
func (f *ProxyFetcher) Mount(registry string, h http.Handler) {
|
||||
f.handlers[registry] = h
|
||||
}
|
||||
|
||||
// Fetch resolves the version when it is empty or LatestVersion, then downloads the artifact.
|
||||
func (f *ProxyFetcher) Fetch(ctx context.Context, pkg PackageInfo) error {
|
||||
h, ok := f.handlers[pkg.Registry]
|
||||
if !ok {
|
||||
return fmt.Errorf("registry %q is not mounted", pkg.Registry)
|
||||
}
|
||||
if !safeName(pkg.Name) {
|
||||
return fmt.Errorf("unsafe package name %q", pkg.Name)
|
||||
}
|
||||
latest := pkg.Version == "" || pkg.Version == LatestVersion
|
||||
switch pkg.Registry {
|
||||
case registryNPM:
|
||||
return f.fetchNPM(ctx, h, pkg.Name, pkg.Version, latest)
|
||||
case registryGo:
|
||||
return f.fetchGo(ctx, h, pkg.Name, pkg.Version, latest)
|
||||
case registryPyPI:
|
||||
return f.fetchPyPI(ctx, h, pkg.Name, pkg.Version, latest)
|
||||
default:
|
||||
return fmt.Errorf("unsupported registry %q", pkg.Registry)
|
||||
}
|
||||
}
|
||||
|
||||
func safeName(name string) bool {
|
||||
return name != "" && !strings.ContainsAny(name, "?#\\") && !strings.Contains(name, "..") && !strings.HasPrefix(name, "/")
|
||||
}
|
||||
|
||||
func (f *ProxyFetcher) fetchNPM(ctx context.Context, h http.Handler, name, version string, latest bool) error {
|
||||
if latest {
|
||||
body, err := call(ctx, h, "/npm/"+name, "", true)
|
||||
if err != nil {
|
||||
return fmt.Errorf("npm metadata: %w", err)
|
||||
}
|
||||
var meta struct {
|
||||
DistTags map[string]string `json:"dist-tags"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &meta); err != nil {
|
||||
return fmt.Errorf("npm metadata: %w", err)
|
||||
}
|
||||
if version = meta.DistTags["latest"]; version == "" {
|
||||
return fmt.Errorf("npm %s has no latest dist-tag", name)
|
||||
}
|
||||
}
|
||||
bare := name[strings.LastIndex(name, "/")+1:]
|
||||
_, err := call(ctx, h, "/npm/"+name+"/-/"+bare+"-"+version+".tgz", "", false)
|
||||
return err
|
||||
}
|
||||
|
||||
func (f *ProxyFetcher) fetchGo(ctx context.Context, h http.Handler, name, version string, latest bool) error {
|
||||
if latest {
|
||||
body, err := call(ctx, h, "/go/"+name+"/@latest", "", true)
|
||||
if err != nil {
|
||||
return fmt.Errorf("go latest: %w", err)
|
||||
}
|
||||
var info struct{ Version string }
|
||||
if err := json.Unmarshal(body, &info); err != nil {
|
||||
return fmt.Errorf("go latest: %w", err)
|
||||
}
|
||||
if version = info.Version; version == "" {
|
||||
return fmt.Errorf("go %s has no latest version", name)
|
||||
}
|
||||
}
|
||||
_, err := call(ctx, h, "/go/"+name+"/@v/"+version+".zip", "", false)
|
||||
return err
|
||||
}
|
||||
|
||||
func (f *ProxyFetcher) fetchPyPI(ctx context.Context, h http.Handler, name, version string, latest bool) error {
|
||||
page, err := call(ctx, h, "/pypi/simple/"+name+"/", "text/html", true)
|
||||
if err != nil {
|
||||
return fmt.Errorf("pypi package page: %w", err)
|
||||
}
|
||||
link, err := pickPyPIFile(page, version, latest)
|
||||
if err != nil {
|
||||
return fmt.Errorf("pypi %s: %w", name, err)
|
||||
}
|
||||
if !strings.HasPrefix(link.Path, "/pypi/") {
|
||||
return fmt.Errorf("pypi %s: link %q is not a proxy path", name, link.Path)
|
||||
}
|
||||
_, err = call(ctx, h, link.Path, "", false, link.RawQuery)
|
||||
return err
|
||||
}
|
||||
|
||||
type distFile struct {
|
||||
link *url.URL
|
||||
version string
|
||||
}
|
||||
|
||||
// pickPyPIFile chooses one distribution: the wanted version or the highest plain release,
|
||||
// preferring a wheel over an sdist.
|
||||
func pickPyPIFile(page []byte, version string, latest bool) (*url.URL, error) {
|
||||
var wheel, sdist *distFile
|
||||
for _, m := range hrefPattern.FindAllSubmatch(page, -1) {
|
||||
u, err := url.Parse(html.UnescapeString(string(m[1])))
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
file := path.Base(u.Path)
|
||||
if !hasDistSuffix(file) {
|
||||
continue
|
||||
}
|
||||
cand := &distFile{link: u, version: pypi.ReleaseVersion(file)}
|
||||
if latest {
|
||||
if !numericSemVer.MatchString(cand.version) {
|
||||
continue
|
||||
}
|
||||
} else if cand.version != version {
|
||||
continue
|
||||
}
|
||||
if strings.HasSuffix(file, ".whl") {
|
||||
wheel = better(wheel, cand, latest)
|
||||
} else {
|
||||
sdist = better(sdist, cand, latest)
|
||||
}
|
||||
}
|
||||
for _, c := range []*distFile{wheel, sdist} {
|
||||
if c != nil {
|
||||
return c.link, nil
|
||||
}
|
||||
}
|
||||
if latest {
|
||||
return nil, fmt.Errorf("no plain release file listed")
|
||||
}
|
||||
return nil, fmt.Errorf("no file listed for version %q", version)
|
||||
}
|
||||
|
||||
func better(cur, cand *distFile, latest bool) *distFile {
|
||||
if cur == nil || (latest && compareVersions(cand.version, cur.version) > 0) {
|
||||
return cand
|
||||
}
|
||||
return cur
|
||||
}
|
||||
|
||||
func hasDistSuffix(file string) bool {
|
||||
for _, s := range distSuffixes {
|
||||
if strings.HasSuffix(file, s) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func compareVersions(a, b string) int {
|
||||
as, bs := strings.Split(a, "."), strings.Split(b, ".")
|
||||
for i := 0; i < len(as) || i < len(bs); i++ {
|
||||
var x, y int
|
||||
if i < len(as) {
|
||||
x, _ = strconv.Atoi(as[i])
|
||||
}
|
||||
if i < len(bs) {
|
||||
y, _ = strconv.Atoi(bs[i])
|
||||
}
|
||||
if x != y {
|
||||
if x > y {
|
||||
return 1
|
||||
}
|
||||
return -1
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// call serves a GET through h. It keeps the body only when capture is set and fails on non-200.
|
||||
func call(ctx context.Context, h http.Handler, p, accept string, capture bool, rawQuery ...string) ([]byte, error) {
|
||||
u := url.URL{Scheme: "http", Host: proxyHost, Path: p}
|
||||
if len(rawQuery) > 0 {
|
||||
u.RawQuery = rawQuery[0]
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if accept != "" {
|
||||
req.Header.Set("Accept", accept)
|
||||
}
|
||||
w := &sink{header: make(http.Header), capture: capture}
|
||||
h.ServeHTTP(w, req)
|
||||
if w.status == 0 {
|
||||
w.status = http.StatusOK
|
||||
}
|
||||
if w.status != http.StatusOK {
|
||||
return nil, fmt.Errorf("GET %s: status %d", p, w.status)
|
||||
}
|
||||
if w.overflow {
|
||||
return nil, fmt.Errorf("GET %s: response over %d bytes", p, maxMetadataBytes)
|
||||
}
|
||||
return w.buf.Bytes(), nil
|
||||
}
|
||||
|
||||
// sink is a ResponseWriter that discards artifact bytes so a pre-warm never holds one in memory.
|
||||
type sink struct {
|
||||
header http.Header
|
||||
buf bytes.Buffer
|
||||
status int
|
||||
capture bool
|
||||
overflow bool
|
||||
}
|
||||
|
||||
func (s *sink) Header() http.Header { return s.header }
|
||||
|
||||
func (s *sink) WriteHeader(code int) {
|
||||
if s.status == 0 {
|
||||
s.status = code
|
||||
}
|
||||
}
|
||||
|
||||
func (s *sink) Write(b []byte) (int, error) {
|
||||
s.WriteHeader(http.StatusOK)
|
||||
if s.capture {
|
||||
if s.buf.Len()+len(b) > maxMetadataBytes {
|
||||
s.overflow = true
|
||||
} else {
|
||||
s.buf.Write(b)
|
||||
}
|
||||
}
|
||||
return len(b), nil
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user