mirror of
https://github.com/lukaszraczylo/gohoarder.git
synced 2026-11-29 06:55:23 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
536f35ab55 | ||
|
|
5a9d104b37 | ||
|
|
f2049383cb | ||
|
|
549d56e0a1 | ||
|
|
31db940014 | ||
|
|
f46e079cee | ||
|
|
ae5167ffa9 | ||
|
|
787c757827 | ||
|
|
ac4f39322c | ||
|
|
db5ca2539f |
@@ -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;
|
||||
|
||||
@@ -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
|
||||
@@ -252,7 +253,7 @@ 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.
|
||||
|
||||
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 +888,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 +940,10 @@ GET /api/packages/:registry/:name/:version
|
||||
}
|
||||
}
|
||||
],
|
||||
"total": 42
|
||||
"total": 1,
|
||||
"total_groups": 42,
|
||||
"page": 1,
|
||||
"page_size": 25
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
+9
-4
@@ -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,15 +94,15 @@ 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
|
||||
max_size_bytes: 536870912000 # 500GB
|
||||
per_project_quota: 53687091200 # 50GB
|
||||
ttl_overrides:
|
||||
npm: "168h"
|
||||
pip: "168h"
|
||||
go: "168h"
|
||||
npm: "24h"
|
||||
pip: "24h"
|
||||
go: "24h"
|
||||
|
||||
security:
|
||||
enabled: false
|
||||
|
||||
@@ -12,7 +12,7 @@ describe('Dashboard.vue', () => {
|
||||
// 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 +127,7 @@ describe('Dashboard.vue', () => {
|
||||
const store = usePackageStore()
|
||||
|
||||
store.loading = false
|
||||
store.packages = [
|
||||
store.recentPackages = [
|
||||
{
|
||||
id: '1',
|
||||
registry: 'npm',
|
||||
@@ -144,22 +144,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 +160,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')
|
||||
|
||||
@@ -75,7 +75,7 @@
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<EmptyState
|
||||
v-if="packages.length === 0"
|
||||
v-if="recentPackages.length === 0"
|
||||
size="sm"
|
||||
:icon="faBoxOpen"
|
||||
title="No packages cached yet"
|
||||
@@ -140,7 +140,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 +259,7 @@ const packageColumns: DataTableColumn<Package>[] = [
|
||||
|
||||
function refresh() {
|
||||
void store.fetchStats()
|
||||
void store.fetchPackages()
|
||||
void store.fetchRecentPackages()
|
||||
}
|
||||
|
||||
function getChartLabel(index: number): string {
|
||||
@@ -291,14 +291,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 +301,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) {
|
||||
|
||||
@@ -208,7 +208,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,120 @@
|
||||
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('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()
|
||||
})
|
||||
})
|
||||
@@ -44,16 +44,60 @@ 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. */
|
||||
async function fetchPackages() {
|
||||
begin()
|
||||
try {
|
||||
const response = await axios.get('/api/packages')
|
||||
// Only update packages if we got valid data
|
||||
@@ -68,13 +112,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 +190,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,
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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,15 @@ 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
|
||||
maxSizeBytes: 536870912000 # 500GB
|
||||
perProjectQuota: 53687091200 # 50GB
|
||||
ttlOverrides:
|
||||
npm: "168h"
|
||||
pip: "168h"
|
||||
go: "168h"
|
||||
npm: "24h"
|
||||
pip: "24h"
|
||||
go: "24h"
|
||||
|
||||
# Security scanning configuration
|
||||
security:
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
+31
-6
@@ -20,6 +20,13 @@ 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` | this change |
|
||||
|
||||
### Exploit paths and reach
|
||||
|
||||
@@ -30,9 +37,33 @@ 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` has no consumer in the Go code (`grep TTLOverrides pkg cmd`: the field and its compiled default
|
||||
only). The per-registry keys are kept and now default to 24h; they change nothing until something reads them.
|
||||
- **GH-18.** New keys read `ghk_<id>.<secret>`; the hash covers the secret and one lookup selects the stored key. A miss
|
||||
compares a dummy hash. Keys minted before are accepted through a legacy path capped at 4 concurrent bcrypt compares. They
|
||||
cannot be migrated: the raw key holds no id and the stored hash covers the whole raw key. Re-issue them to leave the
|
||||
legacy path. Production holds none.
|
||||
- **GH-20.** SQLite startup merges old duplicate rows (package rows add up, derived rows keep one) and creates the unique indexes.
|
||||
- **GH-21.** `RescanWorker` still skips remote storage ("No local file path available"); that is a separate, unchanged behaviour.
|
||||
- **GH-22.** Frontend nginx dropped the `Cookie` header on `/api/` and `/ws` (the backend reads none; keys travel in `Authorization` / `X-API-Key`).
|
||||
The server read buffer is `server.read_buffer_size`, default 16384 (Fiber's default is 8192): a long Referer or `Authorization` no longer gets 431.
|
||||
- **GH-17 cleanup.** The per-handler `Access-Control-Allow-Origin: *` lines in `pkg/app/handlers*.go` are now overridden by the
|
||||
guard and are dead; remove them once the API performance work lands.
|
||||
|
||||
## Not fixed
|
||||
|
||||
| id | area | claim | verdict | why |
|
||||
@@ -42,13 +73,7 @@ Currency: `sh lean4/scripts/check_currency.sh origin/main`.
|
||||
| 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-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.
|
||||
-/
|
||||
|
||||
@@ -125,15 +125,64 @@ 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. -/
|
||||
|
||||
@@ -47,12 +47,12 @@ 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⟩
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -87,4 +87,24 @@ 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]
|
||||
|
||||
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;
|
||||
|
||||
+12
-7
@@ -308,6 +308,8 @@ 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")
|
||||
@@ -389,10 +391,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 +414,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()))
|
||||
@@ -888,13 +893,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 +930,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()
|
||||
|
||||
// Handlers set a wildcard grant; replace it with the allowlist decision.
|
||||
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)
|
||||
}
|
||||
+141
-164
@@ -1,12 +1,14 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/lukaszraczylo/gohoarder/internal/version"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/websocket"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
@@ -56,156 +58,141 @@ 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
|
||||
}
|
||||
|
||||
// parseListParams reads page, page_size, registry, q, sort and order. Without
|
||||
// page or page_size the list is unpaginated, as it was before paging existed.
|
||||
func parseListParams(c fiber.Ctx) listParams {
|
||||
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
|
||||
}
|
||||
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
|
||||
}
|
||||
|
||||
// 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 := parseListParams(c)
|
||||
|
||||
// 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 +223,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")
|
||||
@@ -363,39 +351,28 @@ 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{})
|
||||
// Blocked packages need the blocking policy, so judge every scanned package in one batch.
|
||||
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
|
||||
if a.config.Security.Enabled && a.scanManager != nil {
|
||||
decisions, err := a.scanManager.ScanDecisions(ctx, nil)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Failed to judge scanned packages")
|
||||
}
|
||||
|
||||
// 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 {
|
||||
for _, d := range decisions {
|
||||
if d.Blocked && !metadata.IsMetadataVersion(d.Summary.Version) {
|
||||
blockedCount++
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
+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
|
||||
}
|
||||
|
||||
@@ -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
+35
-1
@@ -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"
|
||||
@@ -172,7 +173,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 {
|
||||
@@ -693,6 +694,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)
|
||||
|
||||
Vendored
+25
-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)
|
||||
@@ -346,7 +370,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
+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)
|
||||
}
|
||||
}
|
||||
}
|
||||
+22
-9
@@ -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,6 +134,14 @@ 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
|
||||
|
||||
// DefaultIdleTTL is how long a cached item can go unrequested before cleanup removes it.
|
||||
const DefaultIdleTTL = 7 * 24 * time.Hour
|
||||
|
||||
@@ -330,11 +339,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,15 +365,15 @@ func Default() *Config {
|
||||
},
|
||||
},
|
||||
Cache: CacheConfig{
|
||||
DefaultTTL: 7 * 24 * time.Hour,
|
||||
DefaultTTL: DefaultMetadataTTL,
|
||||
CleanupInterval: 1 * time.Hour,
|
||||
IdleTTL: DefaultIdleTTL,
|
||||
MaxSizeBytes: 500 * 1024 * 1024 * 1024, // 500GB
|
||||
PerProjectQuota: 50 * 1024 * 1024 * 1024, // 50GB
|
||||
TTLOverrides: map[string]time.Duration{
|
||||
"npm": 7 * 24 * time.Hour,
|
||||
"pip": 7 * 24 * time.Hour,
|
||||
"go": 7 * 24 * time.Hour,
|
||||
"npm": DefaultMetadataTTL,
|
||||
"pip": DefaultMetadataTTL,
|
||||
"go": DefaultMetadataTTL,
|
||||
},
|
||||
},
|
||||
Security: SecurityConfig{
|
||||
@@ -507,6 +517,9 @@ 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")
|
||||
}
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"os"
|
||||
"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])
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
return metadata.PageGroups(all, opts), 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
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -139,7 +139,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 +152,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 +227,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 +240,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')
|
||||
`
|
||||
}
|
||||
|
||||
@@ -317,7 +329,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 +343,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')
|
||||
`
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,369 @@
|
||||
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 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
|
||||
}
|
||||
|
||||
// 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")
|
||||
}
|
||||
@@ -673,6 +679,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 +981,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{
|
||||
|
||||
@@ -88,9 +88,30 @@ 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)
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// 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"
|
||||
|
||||
@@ -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"`
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -305,3 +317,88 @@ 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
|
||||
SortDesc bool
|
||||
Page int // 1-based
|
||||
PageSize int // 0 = every group, unpaginated
|
||||
}
|
||||
|
||||
// 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)
|
||||
}
|
||||
+14
-4
@@ -51,6 +51,16 @@ func isAllowedPyPIHost(host string, allowed []string) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// get fetches from upstream; every redirect hop must be on the allowlist, as for original_url.
|
||||
func (h *Handler) get(ctx context.Context, rawURL string, headers map[string]string) (io.ReadCloser, int, error) {
|
||||
return h.client.GetWithRedirectCheck(ctx, rawURL, headers, func(u *url.URL) error {
|
||||
if !isAllowedPyPIHost(u.Host, h.allowedHosts) {
|
||||
return fmt.Errorf("redirect host %q not on allowlist", u.Hostname())
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// Handler implements the PyPI Simple API (PEP 503)
|
||||
type Handler struct {
|
||||
cache *cache.Manager
|
||||
@@ -130,7 +140,7 @@ func (h *Handler) handleIndex(ctx context.Context, w http.ResponseWriter, r *htt
|
||||
url := h.upstream + "/"
|
||||
|
||||
entry, err := h.cache.Get(ctx, "pypi", "index", "latest", func(ctx context.Context) (*cache.FetchResult, error) {
|
||||
body, statusCode, err := h.client.Get(ctx, url, nil)
|
||||
body, statusCode, err := h.get(ctx, url, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -178,7 +188,7 @@ func (h *Handler) handlePackagePage(ctx context.Context, w http.ResponseWriter,
|
||||
}
|
||||
|
||||
entry, err := h.cache.Get(ctx, "pypi", packageName, cacheVersion, func(ctx context.Context) (*cache.FetchResult, error) {
|
||||
body, statusCode, err := h.client.Get(ctx, url, upstreamHeaders)
|
||||
body, statusCode, err := h.get(ctx, url, upstreamHeaders)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -323,7 +333,7 @@ func (h *Handler) handlePackageFile(ctx context.Context, w http.ResponseWriter,
|
||||
headers["Authorization"] = credentials
|
||||
}
|
||||
|
||||
body, statusCode, err := h.client.Get(ctx, originalURL, headers)
|
||||
body, statusCode, err := h.get(ctx, originalURL, headers)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -454,7 +464,7 @@ func (h *Handler) serveMetadataSidecar(ctx context.Context, w http.ResponseWrite
|
||||
if credentials != "" {
|
||||
headers["Authorization"] = credentials
|
||||
}
|
||||
body, status, err := h.client.Get(ctx, upstreamURL, headers)
|
||||
body, status, err := h.get(ctx, upstreamURL, headers)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Str("url", upstreamURL).Msg("Failed to fetch PEP 658 metadata")
|
||||
http.Error(w, "Failed to fetch package metadata", http.StatusBadGateway)
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
package pypi
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/network"
|
||||
)
|
||||
|
||||
// A PEP 658 sidecar fetched from an allowed host must not follow a redirect off the allowlist.
|
||||
func TestSidecarRedirectOffAllowlistRefused(t *testing.T) {
|
||||
var hit atomic.Int32
|
||||
internal := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
hit.Add(1)
|
||||
_, _ = w.Write([]byte("internal-secret"))
|
||||
}))
|
||||
defer internal.Close()
|
||||
allowed := httptest.NewServer(http.RedirectHandler(strings.Replace(internal.URL, "127.0.0.1", "localhost", 1)+"/example-1.0.0-py3-none-any.whl.metadata", http.StatusFound))
|
||||
defer allowed.Close()
|
||||
|
||||
client := network.NewClient(network.Config{Timeout: 5 * time.Second, MaxRetries: 1, AllowPrivateRedirects: true})
|
||||
h := &Handler{client: client, allowedHosts: []string{"127.0.0.1"}}
|
||||
|
||||
const path = "/example/example-1.0.0-py3-none-any.whl.metadata"
|
||||
q := url.Values{"original_url": {allowed.URL + "/files/example-1.0.0-py3-none-any.whl"}}
|
||||
req := httptest.NewRequest(http.MethodGet, path+"?"+q.Encode(), nil)
|
||||
w := httptest.NewRecorder()
|
||||
h.handlePackageFile(req.Context(), w, req, path)
|
||||
|
||||
if w.Code != http.StatusBadGateway {
|
||||
t.Errorf("code=%d want 502 body=%q", w.Code, w.Body.String())
|
||||
}
|
||||
if hit.Load() != 0 || strings.Contains(w.Body.String(), "internal-secret") {
|
||||
t.Errorf("redirect target was fetched (hits=%d)", hit.Load())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
package scanner
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/config"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata/gormstore"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
type decisionFixture struct {
|
||||
scan *metadata.ScanResult
|
||||
name, registry, pkg, version, release string
|
||||
scannedWithoutRow bool
|
||||
}
|
||||
|
||||
func vuln(id, severity string) metadata.Vulnerability {
|
||||
return metadata.Vulnerability{ID: id, Severity: severity}
|
||||
}
|
||||
|
||||
func decisionFixtures() []decisionFixture {
|
||||
scan := func(status metadata.ScanStatus, details map[string]interface{}, vulns ...metadata.Vulnerability) *metadata.ScanResult {
|
||||
return &metadata.ScanResult{Scanner: "t", Status: status, ScannedAt: time.Now(), Details: details, Vulnerabilities: vulns, VulnerabilityCount: len(vulns)}
|
||||
}
|
||||
return []decisionFixture{
|
||||
{name: "clean", registry: "npm", pkg: "clean", version: "1.0.0", scan: scan(metadata.ScanStatusClean, nil)},
|
||||
{name: "critical", registry: "npm", pkg: "crit", version: "1.0.0", scan: scan(metadata.ScanStatusVulnerable, nil, vuln("CVE-1", "critical"))},
|
||||
{name: "high+moderate", registry: "npm", pkg: "mix", version: "1.0.0", scan: scan(metadata.ScanStatusVulnerable, nil, vuln("CVE-2", "high"), vuln("CVE-3", "medium"))},
|
||||
{name: "low only", registry: "npm", pkg: "low", version: "1.0.0", scan: scan(metadata.ScanStatusVulnerable, nil, vuln("CVE-4", "low"), vuln("CVE-5", "weird"))},
|
||||
{name: "infra error", registry: "npm", pkg: "infra", version: "1.0.0", scan: scan(metadata.ScanStatusError, map[string]interface{}{DetailInfrastructureError: true})},
|
||||
{name: "scan error", registry: "npm", pkg: "err", version: "1.0.0", scan: scan(metadata.ScanStatusError, nil)},
|
||||
{name: "scanned without row", registry: "npm", pkg: "lost", version: "1.0.0", scannedWithoutRow: true},
|
||||
{name: "go zip", registry: "go", pkg: "github.com/a/b/@v/v1.0.0.zip", version: "v1.0.0", scan: scan(metadata.ScanStatusVulnerable, nil, vuln("CVE-6", "high"))},
|
||||
{name: "pypi release", registry: "pypi", pkg: "six", version: "six-1.0.tar.gz", release: "1.0", scan: scan(metadata.ScanStatusVulnerable, nil, vuln("CVE-7", "critical"))},
|
||||
}
|
||||
}
|
||||
|
||||
func seedDecisions(t *testing.T, store *gormstore.GORMStoreV2) map[string]string {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
ids := map[string]string{}
|
||||
for _, f := range decisionFixtures() {
|
||||
now := time.Now()
|
||||
require.NoError(t, store.SavePackage(ctx, &metadata.Package{
|
||||
Registry: f.registry, Name: f.pkg, Version: f.version, ReleaseVersion: f.release,
|
||||
StorageKey: fmt.Sprintf("%s/%s/%s", f.registry, f.pkg, f.version), Size: 1, CachedAt: now, LastAccessed: now,
|
||||
}))
|
||||
if f.scan != nil {
|
||||
res := *f.scan
|
||||
res.Registry, res.PackageName, res.PackageVersion = f.registry, f.pkg, f.version
|
||||
require.NoError(t, store.SaveScanResult(ctx, &res))
|
||||
}
|
||||
if f.scannedWithoutRow {
|
||||
require.NoError(t, store.DB().Exec("UPDATE packages SET security_scanned = ? WHERE name = ?", true, f.pkg).Error)
|
||||
}
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
func addBypass(t *testing.T, store *gormstore.GORMStoreV2, kind metadata.BypassType, target string) {
|
||||
t.Helper()
|
||||
require.NoError(t, store.SaveCVEBypass(context.Background(), &metadata.CVEBypass{
|
||||
Type: kind, Target: target, Reason: "test", CreatedBy: "test", Active: true, ExpiresAt: time.Now().Add(time.Hour),
|
||||
}))
|
||||
}
|
||||
|
||||
// ScanDecisions must reach the same verdict as CheckVulnerabilities for every policy and bypass combination.
|
||||
func TestScanDecisionsMatchCheckVulnerabilities(t *testing.T) {
|
||||
policies := map[string]config.SecurityConfig{
|
||||
"block on high": {Enabled: true, BlockOnSeverity: "high", BlockThresholds: config.VulnerabilityThresholds{Critical: -1, High: -1, Medium: -1, Low: -1}},
|
||||
"block on critical": {Enabled: true, BlockOnSeverity: "critical", BlockThresholds: config.VulnerabilityThresholds{Critical: -1, High: -1, Medium: -1, Low: -1}},
|
||||
"block on moderate": {Enabled: true, BlockOnSeverity: "moderate", BlockThresholds: config.VulnerabilityThresholds{Critical: -1, High: -1, Medium: -1, Low: -1}},
|
||||
"block on low": {Enabled: true, BlockOnSeverity: "low", BlockThresholds: config.VulnerabilityThresholds{Critical: -1, High: -1, Medium: -1, Low: -1}},
|
||||
"thresholds": {Enabled: true, BlockOnSeverity: "none", BlockThresholds: config.VulnerabilityThresholds{Critical: 0, High: 1, Medium: 0, Low: 1}},
|
||||
"fail closed": {Enabled: true, FailClosed: true, BlockOnSeverity: "none", BlockThresholds: config.VulnerabilityThresholds{Critical: -1, High: -1, Medium: -1, Low: -1}},
|
||||
"block on low, closed": {Enabled: true, FailClosed: true, BlockOnSeverity: "low", BlockThresholds: config.VulnerabilityThresholds{Critical: -1, High: -1, Medium: -1, Low: -1}},
|
||||
"disabled scanner mgr": {Enabled: false, BlockOnSeverity: "low"},
|
||||
"thresholds, high only": {Enabled: true, BlockOnSeverity: "none", BlockThresholds: config.VulnerabilityThresholds{Critical: -1, High: 0, Medium: -1, Low: -1}},
|
||||
}
|
||||
bypassSets := map[string]func(*testing.T, *gormstore.GORMStoreV2){
|
||||
"no bypass": func(*testing.T, *gormstore.GORMStoreV2) {},
|
||||
"cve bypass": func(t *testing.T, s *gormstore.GORMStoreV2) { addBypass(t, s, metadata.BypassTypeCVE, "cve-1") },
|
||||
"cve high": func(t *testing.T, s *gormstore.GORMStoreV2) { addBypass(t, s, metadata.BypassTypeCVE, "CVE-2") },
|
||||
"package bypass": func(t *testing.T, s *gormstore.GORMStoreV2) { addBypass(t, s, metadata.BypassTypePackage, "npm/crit") },
|
||||
"go bypass": func(t *testing.T, s *gormstore.GORMStoreV2) {
|
||||
addBypass(t, s, metadata.BypassTypePackage, "go/github.com/a/[email protected]")
|
||||
},
|
||||
"release bypass": func(t *testing.T, s *gormstore.GORMStoreV2) {
|
||||
addBypass(t, s, metadata.BypassTypePackage, "pypi/[email protected]")
|
||||
},
|
||||
"both kinds": func(t *testing.T, s *gormstore.GORMStoreV2) {
|
||||
addBypass(t, s, metadata.BypassTypeCVE, "CVE-3")
|
||||
addBypass(t, s, metadata.BypassTypePackage, "npm/mix")
|
||||
},
|
||||
}
|
||||
|
||||
for bypassName, setBypasses := range bypassSets {
|
||||
store, err := gormstore.NewV2(gormstore.Config{
|
||||
Driver: "sqlite", DSN: fmt.Sprintf("file:dec_%d?mode=memory&cache=shared", time.Now().UnixNano()),
|
||||
MaxOpenConns: 1, MaxIdleConns: 1, LogLevel: "silent",
|
||||
})
|
||||
require.NoError(t, err)
|
||||
seedDecisions(t, store)
|
||||
setBypasses(t, store)
|
||||
|
||||
for policyName, cfg := range policies {
|
||||
t.Run(bypassName+"/"+policyName, func(t *testing.T) {
|
||||
mgr, err := New(cfg, store)
|
||||
require.NoError(t, err)
|
||||
ctx := context.Background()
|
||||
|
||||
decisions, err := mgr.ScanDecisions(ctx, nil)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, decisions, len(decisionFixtures()))
|
||||
for _, d := range decisions {
|
||||
s := d.Summary
|
||||
wantBlocked, wantReason, checkErr := mgr.CheckVulnerabilities(ctx, s.Registry, s.Name, s.Version)
|
||||
require.NoError(t, checkErr)
|
||||
require.Equal(t, wantBlocked, d.Blocked, "%s/%s@%s", s.Registry, s.Name, s.Version)
|
||||
if wantBlocked && len(wantReason) > 0 && wantReason[0] != 'P' {
|
||||
// Count-based reasons carry numbers that differ only under CVE bypasses; the
|
||||
// fixed fail-closed reasons must match exactly.
|
||||
require.Equal(t, wantReason, d.Reason)
|
||||
}
|
||||
}
|
||||
|
||||
ids := make([]string, 0, 3)
|
||||
for _, d := range decisions[:3] {
|
||||
ids = append(ids, d.Summary.PackageID)
|
||||
}
|
||||
subset, err := mgr.ScanDecisions(ctx, ids)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, subset, 3)
|
||||
})
|
||||
}
|
||||
require.NoError(t, store.Close())
|
||||
}
|
||||
}
|
||||
|
||||
func TestScanDecisionsVerdicts(t *testing.T) {
|
||||
store, err := gormstore.NewV2(gormstore.Config{
|
||||
Driver: "sqlite", DSN: fmt.Sprintf("file:decv_%d?mode=memory&cache=shared", time.Now().UnixNano()),
|
||||
MaxOpenConns: 1, MaxIdleConns: 1, LogLevel: "silent",
|
||||
})
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { _ = store.Close() })
|
||||
seedDecisions(t, store)
|
||||
addBypass(t, store, metadata.BypassTypeCVE, "CVE-3")
|
||||
mgr, err := New(config.SecurityConfig{
|
||||
Enabled: true, BlockOnSeverity: "high",
|
||||
BlockThresholds: config.VulnerabilityThresholds{Critical: -1, High: -1, Medium: -1, Low: -1},
|
||||
}, store)
|
||||
require.NoError(t, err)
|
||||
|
||||
decisions, err := mgr.ScanDecisions(context.Background(), nil)
|
||||
require.NoError(t, err)
|
||||
blocked := map[string]bool{}
|
||||
for _, d := range decisions {
|
||||
blocked[d.Summary.Name] = d.Blocked
|
||||
}
|
||||
require.Equal(t, map[string]bool{
|
||||
"clean": false, "crit": true, "mix": true, "low": false,
|
||||
"infra": false, // infrastructure failure serves the package unless fail_closed
|
||||
"err": true, "lost": true,
|
||||
"github.com/a/b/@v/v1.0.0.zip": true, "six": true,
|
||||
}, blocked)
|
||||
}
|
||||
+170
-38
@@ -6,6 +6,7 @@ import (
|
||||
"context"
|
||||
stderrors "errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
@@ -53,11 +54,23 @@ const (
|
||||
maxScanRetries = 6
|
||||
)
|
||||
|
||||
// FileSource returns a readable local copy of a stored package for a retry, plus its cleanup.
|
||||
type FileSource func(ctx context.Context, registry, packageName, version string) (path string, cleanup func(), err error)
|
||||
|
||||
// SetFileSource lets a retry re-read the stored blob when the file its first scan used is gone,
|
||||
// as with remote storage whose scan source is a temp file removed after the first attempt.
|
||||
func (m *Manager) SetFileSource(fs FileSource) {
|
||||
m.stateMu.Lock()
|
||||
m.fileSource = fs
|
||||
m.stateMu.Unlock()
|
||||
}
|
||||
|
||||
// Manager manages multiple security scanners
|
||||
type Manager struct {
|
||||
metadataStore metadata.MetadataStore
|
||||
broadcaster events.Broadcaster
|
||||
retryTimers map[string]*time.Timer
|
||||
fileSource FileSource
|
||||
inflight map[string]int
|
||||
scanners []Scanner
|
||||
config config.SecurityConfig
|
||||
@@ -121,8 +134,21 @@ func (m *Manager) scheduleRetry(registry, packageName, version, filePath string,
|
||||
m.retryTimers[key] = time.AfterFunc(interval, func() {
|
||||
m.stateMu.Lock()
|
||||
delete(m.retryTimers, key)
|
||||
source := m.fileSource
|
||||
m.stateMu.Unlock()
|
||||
if err := m.scan(context.Background(), registry, packageName, version, filePath, attempt); err != nil {
|
||||
|
||||
ctx := context.Background()
|
||||
path := filePath
|
||||
if _, statErr := os.Stat(filePath); statErr != nil && source != nil {
|
||||
fresh, cleanup, err := source(ctx, registry, packageName, version)
|
||||
if err != nil {
|
||||
log.Warn().Err(err).Str("package", packageName).Int("attempt", attempt).Msg("Scan retry could not re-read package")
|
||||
return
|
||||
}
|
||||
defer cleanup()
|
||||
path = fresh
|
||||
}
|
||||
if err := m.scan(ctx, registry, packageName, version, path, attempt); err != nil {
|
||||
log.Warn().Err(err).Str("package", packageName).Int("attempt", attempt).Msg("Scan retry failed")
|
||||
}
|
||||
})
|
||||
@@ -564,24 +590,10 @@ func (m *Manager) CheckVulnerabilities(ctx context.Context, registry, packageNam
|
||||
bypasses = []*metadata.CVEBypass{} // Continue without bypasses
|
||||
}
|
||||
|
||||
// Check if entire package is bypassed
|
||||
bypassName := normalizeBypassPackageName(registry, packageName)
|
||||
packageKey := fmt.Sprintf("%s/%s@%s", registry, bypassName, version)
|
||||
packageKeyNoVersion := fmt.Sprintf("%s/%s", registry, bypassName)
|
||||
releaseKey := m.releaseVersionKey(ctx, registry, packageName, version, bypassName)
|
||||
|
||||
for _, bypass := range bypasses {
|
||||
if bypass.Type == metadata.BypassTypePackage && bypass.Active {
|
||||
if bypass.Target == packageKey || bypass.Target == packageKeyNoVersion || (releaseKey != "" && bypass.Target == releaseKey) {
|
||||
log.Info().
|
||||
Str("package", packageKey).
|
||||
Str("bypass_id", bypass.ID).
|
||||
Str("reason", bypass.Reason).
|
||||
Time("expires_at", bypass.ExpiresAt).
|
||||
Msg("Package bypassed by admin")
|
||||
return false, "", nil
|
||||
}
|
||||
}
|
||||
if packageBypassed(registry, bypassName, version, releaseKey, bypasses) {
|
||||
return false, "", nil
|
||||
}
|
||||
|
||||
// Get latest scan result.
|
||||
@@ -596,10 +608,7 @@ func (m *Manager) CheckVulnerabilities(ctx context.Context, registry, packageNam
|
||||
if err != nil {
|
||||
var hErr *hoardererrors.Error
|
||||
if stderrors.As(err, &hErr) && hErr.Code == hoardererrors.ErrCodeNotFound {
|
||||
if !m.config.FailClosed && m.isInflight(scanKey(registry, packageName, version)) {
|
||||
return false, "", nil
|
||||
}
|
||||
return true, "no scan available - fail closed", nil
|
||||
return m.missingScanDecision(registry, packageName, version)
|
||||
}
|
||||
// Real backend error (DB transient, etc.) — also block.
|
||||
log.Warn().
|
||||
@@ -613,17 +622,70 @@ func (m *Manager) CheckVulnerabilities(ctx context.Context, registry, packageNam
|
||||
return true, "no scan available - fail closed", nil
|
||||
}
|
||||
|
||||
infra, _ := result.Details[DetailInfrastructureError].(bool)
|
||||
return m.evaluateScan(registry, packageName, version, releaseKey, bypasses, scanFacts{
|
||||
status: result.Status,
|
||||
infra: infra,
|
||||
vulns: result.Vulnerabilities,
|
||||
hasList: true,
|
||||
})
|
||||
}
|
||||
|
||||
// missingScanDecision is the verdict for a package flagged scanned that has no scan record.
|
||||
func (m *Manager) missingScanDecision(registry, packageName, version string) (bool, string, error) {
|
||||
if !m.config.FailClosed && m.isInflight(scanKey(registry, packageName, version)) {
|
||||
return false, "", nil
|
||||
}
|
||||
return true, "no scan available - fail closed", nil
|
||||
}
|
||||
|
||||
// packageBypassed reports whether an active admin bypass covers the whole package.
|
||||
func packageBypassed(registry, bypassName, version, releaseKey string, bypasses []*metadata.CVEBypass) bool {
|
||||
packageKey := fmt.Sprintf("%s/%s@%s", registry, bypassName, version)
|
||||
packageKeyNoVersion := fmt.Sprintf("%s/%s", registry, bypassName)
|
||||
for _, bypass := range bypasses {
|
||||
if bypass.Type == metadata.BypassTypePackage && bypass.Active {
|
||||
if bypass.Target == packageKey || bypass.Target == packageKeyNoVersion || (releaseKey != "" && bypass.Target == releaseKey) {
|
||||
log.Info().
|
||||
Str("package", packageKey).
|
||||
Str("bypass_id", bypass.ID).
|
||||
Str("reason", bypass.Reason).
|
||||
Time("expires_at", bypass.ExpiresAt).
|
||||
Msg("Package bypassed by admin")
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// scanFacts is what the blocking policy needs to know about one scan.
|
||||
type scanFacts struct {
|
||||
counts map[string]int // per-severity counts, used when hasList is false
|
||||
status metadata.ScanStatus
|
||||
vulns []metadata.Vulnerability
|
||||
total int // findings when the list is not loaded
|
||||
infra bool // the scan failed on infrastructure, not on the package
|
||||
hasList bool // vulns is the full list, so CVE bypasses can be applied
|
||||
}
|
||||
|
||||
// evaluateScan applies bypasses and thresholds to one scan.
|
||||
func (m *Manager) evaluateScan(registry, packageName, version, releaseKey string, bypasses []*metadata.CVEBypass, f scanFacts) (bool, string, error) {
|
||||
// If the scan itself errored (all scanners failed for this package),
|
||||
// block. A scan-error record means we don't actually know whether the
|
||||
// package is safe.
|
||||
if result.Status == metadata.ScanStatusError {
|
||||
if infra, _ := result.Details[DetailInfrastructureError].(bool); infra && !m.config.FailClosed {
|
||||
if f.status == metadata.ScanStatusError {
|
||||
if f.infra && !m.config.FailClosed {
|
||||
log.Warn().Str("package", packageName).Msg("Scan failed on infrastructure, serving package; scan will be retried")
|
||||
return false, "", nil
|
||||
}
|
||||
return true, "scan failed - fail closed", nil
|
||||
}
|
||||
|
||||
bypassName := normalizeBypassPackageName(registry, packageName)
|
||||
packageKey := fmt.Sprintf("%s/%s@%s", registry, bypassName, version)
|
||||
packageKeyNoVersion := fmt.Sprintf("%s/%s", registry, bypassName)
|
||||
|
||||
// Build set of bypassed CVEs for fast lookup
|
||||
bypassedCVEs := make(map[string]*metadata.CVEBypass)
|
||||
for _, bypass := range bypasses {
|
||||
@@ -637,22 +699,26 @@ func (m *Manager) CheckVulnerabilities(ctx context.Context, registry, packageNam
|
||||
}
|
||||
|
||||
// Count vulnerabilities by severity, excluding bypassed CVEs
|
||||
severityCounts := make(map[string]int)
|
||||
remaining := 0
|
||||
for _, vuln := range result.Vulnerabilities {
|
||||
// Check if this CVE is bypassed
|
||||
if bypass, ok := bypassedCVEs[strings.ToUpper(vuln.ID)]; ok {
|
||||
log.Debug().
|
||||
Str("cve", vuln.ID).
|
||||
Str("package", packageName).
|
||||
Str("bypass_id", bypass.ID).
|
||||
Str("reason", bypass.Reason).
|
||||
Time("expires_at", bypass.ExpiresAt).
|
||||
Msg("CVE bypassed by admin")
|
||||
continue
|
||||
severityCounts := f.counts
|
||||
remaining := f.total
|
||||
if f.hasList {
|
||||
severityCounts = make(map[string]int)
|
||||
remaining = 0
|
||||
for _, vuln := range f.vulns {
|
||||
// Check if this CVE is bypassed
|
||||
if bypass, ok := bypassedCVEs[strings.ToUpper(vuln.ID)]; ok {
|
||||
log.Debug().
|
||||
Str("cve", vuln.ID).
|
||||
Str("package", packageName).
|
||||
Str("bypass_id", bypass.ID).
|
||||
Str("reason", bypass.Reason).
|
||||
Time("expires_at", bypass.ExpiresAt).
|
||||
Msg("CVE bypassed by admin")
|
||||
continue
|
||||
}
|
||||
severityCounts[metadata.NormalizeSeverity(vuln.Severity)]++
|
||||
remaining++
|
||||
}
|
||||
severityCounts[metadata.NormalizeSeverity(vuln.Severity)]++
|
||||
remaining++
|
||||
}
|
||||
|
||||
// Check against thresholds
|
||||
@@ -712,6 +778,72 @@ func (m *Manager) CheckVulnerabilities(ctx context.Context, registry, packageNam
|
||||
return false, "", nil
|
||||
}
|
||||
|
||||
// ScanDecision pairs a package's latest scan with the blocking verdict.
|
||||
type ScanDecision struct {
|
||||
Summary *metadata.ScanSummary
|
||||
Reason string
|
||||
Blocked bool
|
||||
}
|
||||
|
||||
// ScanDecisions judges scanned packages in a constant number of statements. A nil
|
||||
// packageIDs judges every scanned package. The verdicts equal CheckVulnerabilities.
|
||||
func (m *Manager) ScanDecisions(ctx context.Context, packageIDs []string) ([]ScanDecision, error) {
|
||||
var bypasses []*metadata.CVEBypass
|
||||
if m.enabled {
|
||||
var err error
|
||||
if bypasses, err = m.metadataStore.GetActiveCVEBypasses(ctx); err != nil {
|
||||
log.Warn().Err(err).Msg("Failed to get CVE bypasses, continuing without bypasses")
|
||||
bypasses = nil
|
||||
}
|
||||
}
|
||||
// Per-CVE bypasses need the vulnerability ids; counts alone decide otherwise.
|
||||
withList := false
|
||||
for _, b := range bypasses {
|
||||
if b.Type == metadata.BypassTypeCVE && b.Active {
|
||||
withList = true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
summaries, err := m.metadataStore.GetScanSummaries(ctx, packageIDs, withList)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
decisions := make([]ScanDecision, 0, len(summaries))
|
||||
for _, sum := range summaries {
|
||||
d := ScanDecision{Summary: sum}
|
||||
if m.enabled {
|
||||
d.Blocked, d.Reason = m.judgeSummary(sum, bypasses, withList)
|
||||
}
|
||||
decisions = append(decisions, d)
|
||||
}
|
||||
return decisions, nil
|
||||
}
|
||||
|
||||
func (m *Manager) judgeSummary(sum *metadata.ScanSummary, bypasses []*metadata.CVEBypass, withList bool) (bool, string) {
|
||||
bypassName := normalizeBypassPackageName(sum.Registry, sum.Name)
|
||||
releaseKey := ""
|
||||
if sum.ReleaseVersion != "" {
|
||||
releaseKey = fmt.Sprintf("%s/%s@%s", sum.Registry, bypassName, sum.ReleaseVersion)
|
||||
}
|
||||
if packageBypassed(sum.Registry, bypassName, sum.Version, releaseKey, bypasses) {
|
||||
return false, ""
|
||||
}
|
||||
if !sum.HasScan {
|
||||
blocked, reason, _ := m.missingScanDecision(sum.Registry, sum.Name, sum.Version)
|
||||
return blocked, reason
|
||||
}
|
||||
infra, _ := sum.Details[DetailInfrastructureError].(bool)
|
||||
facts := scanFacts{status: sum.Status, infra: infra, total: sum.Total, hasList: withList, vulns: sum.Vulnerabilities}
|
||||
if !withList {
|
||||
facts.counts = map[string]int{
|
||||
"CRITICAL": sum.Critical, "HIGH": sum.High, "MODERATE": sum.Moderate, "LOW": sum.Low,
|
||||
}
|
||||
}
|
||||
blocked, reason, _ := m.evaluateScan(sum.Registry, sum.Name, sum.Version, releaseKey, bypasses, facts)
|
||||
return blocked, reason
|
||||
}
|
||||
|
||||
// UpdateDatabases updates vulnerability databases for all scanners
|
||||
func (m *Manager) UpdateDatabases(ctx context.Context) error {
|
||||
if !m.enabled {
|
||||
|
||||
@@ -89,6 +89,15 @@ func (m *stubMetadataStore) DeletePackage(context.Context, string, string, strin
|
||||
func (m *stubMetadataStore) ListPackages(context.Context, *metadata.ListOptions) ([]*metadata.Package, error) {
|
||||
return nil, nil
|
||||
}
|
||||
func (m *stubMetadataStore) ListPackageGroups(context.Context, metadata.GroupListOptions) (*metadata.GroupPage, error) {
|
||||
return nil, nil
|
||||
}
|
||||
func (m *stubMetadataStore) GetScanSummaries(context.Context, []string, bool) ([]*metadata.ScanSummary, error) {
|
||||
return nil, nil
|
||||
}
|
||||
func (m *stubMetadataStore) GetRegistryStats(context.Context) ([]metadata.RegistryStat, error) {
|
||||
return nil, nil
|
||||
}
|
||||
func (m *stubMetadataStore) UpdateDownloadCount(context.Context, string, string, string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
Executable
+57
@@ -0,0 +1,57 @@
|
||||
#!/bin/sh
|
||||
# Builds the frontend image from a Dockerfile and checks that /api and /ws do not forward the
|
||||
# browser's Cookie header to the backend. Usage: scripts/check_frontend_cookie_strip.sh [Dockerfile]
|
||||
set -eu
|
||||
|
||||
dockerfile="${1:-Dockerfile.frontend}"
|
||||
root="$(git rev-parse --show-toplevel)"
|
||||
work="$(mktemp -d)"
|
||||
tag="gohoarder-frontend-cookie-check:$$"
|
||||
net="gohoarder-cookie-check-$$"
|
||||
stub="$net-backend"
|
||||
front="$net-frontend"
|
||||
|
||||
cleanup() {
|
||||
docker rm -f "$front" "$stub" >/dev/null 2>&1 || true
|
||||
docker network rm "$net" >/dev/null 2>&1 || true
|
||||
docker rmi "$tag" >/dev/null 2>&1 || true
|
||||
rm -rf "$work"
|
||||
}
|
||||
trap cleanup EXIT
|
||||
|
||||
mkdir -p "$work/frontend/dist"
|
||||
echo '<html></html>' >"$work/frontend/dist/index.html"
|
||||
cp "$root/$dockerfile" "$work/Dockerfile"
|
||||
docker build -q --load -t "$tag" "$work" >/dev/null
|
||||
|
||||
cat >"$work/stub.conf" <<'CONF'
|
||||
server {
|
||||
listen 8080;
|
||||
location / { default_type text/plain; return 200 "cookie=[$http_cookie]"; }
|
||||
}
|
||||
CONF
|
||||
|
||||
docker network create "$net" >/dev/null
|
||||
docker run -d --name "$stub" --network "$net" -v "$work/stub.conf:/etc/nginx/conf.d/default.conf:ro" nginx:alpine >/dev/null
|
||||
docker run -d --name "$front" --network "$net" -e BACKEND_HOST="$stub" -e BACKEND_PORT=8080 "$tag" >/dev/null
|
||||
|
||||
cookie="session=$(head -c 8000 /dev/zero | tr '\0' 'a')"
|
||||
status=0
|
||||
for path in /api/packages /ws; do
|
||||
ok=no
|
||||
for _ in 1 2 3 4 5 6 7 8 9 10; do
|
||||
body="$(docker exec "$front" wget -qO- --header "Cookie: $cookie" "http://127.0.0.1$path" 2>/dev/null || true)"
|
||||
[ -n "$body" ] && ok=yes && break
|
||||
sleep 1
|
||||
done
|
||||
if [ "$ok" = no ]; then
|
||||
echo "FAIL: $path returned no body"
|
||||
status=1
|
||||
elif [ "$body" = "cookie=[]" ]; then
|
||||
echo "ok: $path forwards no Cookie"
|
||||
else
|
||||
echo "FAIL: $path forwarded a Cookie header ($(printf '%s' "$body" | wc -c) bytes)"
|
||||
status=1
|
||||
fi
|
||||
done
|
||||
exit "$status"
|
||||
Reference in New Issue
Block a user