mirror of
https://github.com/lukaszraczylo/gohoarder.git
synced 2026-11-27 06:46:01 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1432c7176b | ||
|
|
426225bd14 | ||
|
|
518d836c7b | ||
|
|
1e99b53d51 | ||
|
|
9c0420161e | ||
|
|
c685131865 | ||
|
|
e80489e55c | ||
|
|
5f4bdbed80 | ||
|
|
1b00236749 | ||
|
|
9ff6de2414 | ||
|
|
3bfc367898 | ||
|
|
6715cefd25 | ||
|
|
5518d02599 | ||
|
|
547f41677a | ||
|
|
7b8ff467b8 | ||
|
|
48bd654839 | ||
|
|
80160eeb56 | ||
|
|
a685b71c7f | ||
|
|
798fadb4bb | ||
|
|
4b2ec7c45c | ||
|
|
8b6f1ae4ac | ||
|
|
bc56b97677 | ||
|
|
7470c41560 | ||
|
|
8b4d4746df | ||
|
|
43e075baf3 | ||
|
|
64793f9c7e | ||
|
|
55c60cb8e4 | ||
|
|
ad8295455d | ||
|
|
6e8ac5265c | ||
|
|
671bb0625b | ||
|
|
45aa4bcace | ||
|
|
b248bfed31 | ||
|
|
a511544d7a | ||
|
|
6ddc382d5b | ||
|
|
2b6f3bd892 | ||
|
|
916e2b0aa5 | ||
|
|
30ebfaae3e | ||
|
|
3a7ffab4d5 | ||
|
|
22f2a8dfb9 |
@@ -32,6 +32,10 @@ data:
|
||||
severity_threshold: medium
|
||||
block_on_vulnerability: false
|
||||
rescan_interval: 24h
|
||||
rescan_active_window: 0s
|
||||
rescan_concurrency: 1
|
||||
rescan_on_access: false
|
||||
scan_wait_timeout: 30s
|
||||
|
||||
handlers:
|
||||
npm:
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
"@fontsource/ibm-plex-mono": "5.3.0",
|
||||
"@fontsource/ibm-plex-sans": "5.3.0",
|
||||
"@fortawesome/free-solid-svg-icons": "7.3.1",
|
||||
"@perfect-design/ui": "0.3.10",
|
||||
"@perfect-design/ui": "0.3.11",
|
||||
"axios": "^1.20.0",
|
||||
"pinia": "^4.0.0",
|
||||
"vue": "^3.5.26",
|
||||
@@ -23,7 +23,7 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tailwindcss/vite": "^4.3.3",
|
||||
"@testing-library/jest-dom": "^7.0.0",
|
||||
"@testing-library/jest-dom": "^8.0.0",
|
||||
"@testing-library/vue": "^8.1.0",
|
||||
"@vitejs/plugin-vue": "^6.0.3",
|
||||
"@vue/test-utils": "^2.4.6",
|
||||
|
||||
Generated
+12
-12
@@ -23,8 +23,8 @@ importers:
|
||||
specifier: 7.3.1
|
||||
version: 7.3.1
|
||||
'@perfect-design/ui':
|
||||
specifier: 0.3.10
|
||||
version: 0.3.10([email protected](@vue/[email protected])([email protected])([email protected]([email protected])))([email protected])([email protected]([email protected]))
|
||||
specifier: 0.3.11
|
||||
version: 0.3.11([email protected](@vue/[email protected])([email protected])([email protected]([email protected])))([email protected])([email protected]([email protected]))
|
||||
axios:
|
||||
specifier: ^1.20.0
|
||||
version: 1.21.1([email protected]([email protected]))([email protected])
|
||||
@@ -42,8 +42,8 @@ importers:
|
||||
specifier: ^4.3.3
|
||||
version: 4.3.5([email protected]([email protected])([email protected]))
|
||||
'@testing-library/jest-dom':
|
||||
specifier: ^7.0.0
|
||||
version: 7.0.1(@testing-library/[email protected])([email protected]([email protected])([email protected]([email protected])([email protected])))
|
||||
specifier: ^8.0.0
|
||||
version: 8.0.0(@testing-library/[email protected])([email protected]([email protected])([email protected]([email protected])([email protected])))
|
||||
'@testing-library/vue':
|
||||
specifier: ^8.1.0
|
||||
version: 8.1.0(@vue/[email protected])(@vue/[email protected])(@vue/[email protected])([email protected]([email protected]))
|
||||
@@ -353,8 +353,8 @@ packages:
|
||||
'@oxc-project/[email protected]':
|
||||
resolution: {integrity: sha512-1Duyg48TdJNdyhEB8Xn1L36bT9Pv6GUtlKjHxOys8xkaF/rQq3XJE+bAurSK/AgIz5mGFsb77cn9Pb20+WCScw==}
|
||||
|
||||
'@perfect-design/[email protected]0':
|
||||
resolution: {integrity: sha512-nFpY8dK6braHsRPVdX3bUCrkPNfwiUj2KfvUfLdFRFlfBRaqrkNGx2QkmNu/L0rdNe6JQj6Mvdrb+LnC/sFg8Q==}
|
||||
'@perfect-design/[email protected]1':
|
||||
resolution: {integrity: sha512-vu7liBjd6ZndJWio3gt1EHmOVi1VAcPQ/v+8xQRLvrIH9Bd43ZYsgsh+JITpBRmagYyAxPjo1zFU7ma/I6lVmg==}
|
||||
peerDependencies:
|
||||
pinia: ^3.0.0 || ^4.0.0
|
||||
tailwindcss: ^4.1.0
|
||||
@@ -561,12 +561,12 @@ packages:
|
||||
resolution: {integrity: sha512-FlS4ZWlp97iiNWig0Muq8p+3rVDjRiYE+YKGbAqXOu9nwJFFOdL00kFpz42M+4huzYi86vAK1sOOfyOG45muIQ==}
|
||||
engines: {node: '>=14'}
|
||||
|
||||
'@testing-library/jest-dom@7.0.1':
|
||||
resolution: {integrity: sha512-oMDTC3oA+6CXSO2JZnvOI7CA6oVub6kij5ggk9ohwye5slmkwxYDXcPOVxgMw/RQlticjtO0C1RZkR97HgrWMw==}
|
||||
'@testing-library/jest-dom@8.0.0':
|
||||
resolution: {integrity: sha512-Nu45KEeFgP/ydCMipnisMblq6YHViqEFi3fKN0a40s+zdKDDD7vEPCEavS0i7i4RxmclcEIL8q2o42pu+WgNgg==}
|
||||
engines: {node: '>=22', npm: '>=6', yarn: '>=1'}
|
||||
peerDependencies:
|
||||
'@testing-library/dom': '>=10 <11'
|
||||
vitest: '>= 0.32'
|
||||
vitest: '>=5 <6'
|
||||
peerDependenciesMeta:
|
||||
vitest:
|
||||
optional: true
|
||||
@@ -1967,7 +1967,7 @@ snapshots:
|
||||
|
||||
'@oxc-project/[email protected]': {}
|
||||
|
||||
'@perfect-design/[email protected]0([email protected](@vue/[email protected])([email protected])([email protected]([email protected])))([email protected])([email protected]([email protected]))':
|
||||
'@perfect-design/[email protected]1([email protected](@vue/[email protected])([email protected])([email protected]([email protected])))([email protected])([email protected]([email protected]))':
|
||||
dependencies:
|
||||
pinia: 4.1.0(@vue/[email protected])([email protected])([email protected]([email protected]))
|
||||
reka-ui: 2.11.0([email protected]([email protected]))
|
||||
@@ -2123,11 +2123,11 @@ snapshots:
|
||||
lz-string: 1.5.0
|
||||
pretty-format: 27.5.1
|
||||
|
||||
'@testing-library/jest-dom@7.0.1(@testing-library/[email protected])([email protected]([email protected])([email protected]([email protected])([email protected])))':
|
||||
'@testing-library/jest-dom@8.0.0(@testing-library/[email protected])([email protected]([email protected])([email protected]([email protected])([email protected])))':
|
||||
dependencies:
|
||||
'@adobe/css-tools': 4.4.4
|
||||
'@testing-library/dom': 10.4.2
|
||||
aria-query: 5.1.3
|
||||
aria-query: 5.3.0
|
||||
css.escape: 1.5.1
|
||||
dom-accessibility-api: 0.6.3
|
||||
picocolors: 1.1.1
|
||||
|
||||
@@ -27,7 +27,7 @@ onMounted(() => {
|
||||
<template #brand>
|
||||
<Icon :icon="faBoxOpen" size="lg" class="text-primary" />
|
||||
<p class="m-0 text-lg font-semibold">GoHoarder</p>
|
||||
<p class="m-0 hidden text-sm text-muted-foreground sm:block">Package cache manager</p>
|
||||
<p class="m-0 hidden text-sm text-muted-foreground sm:block">Package checkpoint</p>
|
||||
</template>
|
||||
<template #actions><ThemeToggle /></template>
|
||||
<template #mobile><AppNav sheet /></template>
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
<template>
|
||||
<div class="flex flex-col gap-6">
|
||||
<PageHeader
|
||||
title="CVE bypass management"
|
||||
description="Manage temporary security bypasses for packages and CVEs."
|
||||
title="Bypasses"
|
||||
description="A bypass lets a package or an advisory through the block policy until it expires. Each one is kept for the audit trail."
|
||||
>
|
||||
<template #actions>
|
||||
<Button :icon-start="faPlus" @click="showCreateModal = true">Create bypass</Button>
|
||||
@@ -33,7 +33,7 @@
|
||||
v-if="filteredBypasses.length === 0"
|
||||
:icon="faShieldHalved"
|
||||
title="No bypasses found"
|
||||
description="Create a bypass to allow packages with known vulnerabilities."
|
||||
description="Create a bypass to serve a package that the policy holds."
|
||||
/>
|
||||
<DataTable
|
||||
v-else
|
||||
@@ -44,7 +44,7 @@
|
||||
:rows="filteredBypasses"
|
||||
>
|
||||
<template #cell-type="{ row }">
|
||||
<Badge :variant="row.type === 'cve' ? 'default' : 'outline'">{{ row.type === 'cve' ? 'CVE' : 'Package' }}</Badge>
|
||||
<Badge :variant="row.type === 'cve' ? 'secondary' : 'outline'">{{ row.type === 'cve' ? 'CVE' : 'Package' }}</Badge>
|
||||
</template>
|
||||
<template #cell-status="{ row }">
|
||||
<span class="flex flex-wrap gap-1">
|
||||
@@ -55,6 +55,13 @@
|
||||
<StatusBadge v-if="isExpired(row.expires_at)" status="expired" :tones="{ expired: 'danger' }" />
|
||||
</span>
|
||||
</template>
|
||||
<template #cell-created_at="{ row }"><RelativeTime :datetime="row.created_at" /></template>
|
||||
<template #cell-expires_at="{ row }">
|
||||
<span class="block">{{ formatDate(row.expires_at) }}</span>
|
||||
<span class="block text-xs text-muted-foreground">
|
||||
<RelativeTime :datetime="row.expires_at" />
|
||||
</span>
|
||||
</template>
|
||||
<template #cell-actions="{ row }">
|
||||
<span class="flex gap-1">
|
||||
<IconButton :icon="faPen" :label="`Edit bypass for ${row.target}`" @click="editBypass(row)" />
|
||||
@@ -84,7 +91,7 @@
|
||||
:label="bypassForm.type === 'cve' ? 'CVE ID' : 'Package'"
|
||||
:hint="
|
||||
bypassForm.type === 'cve'
|
||||
? 'Enter the CVE ID, for example CVE-2021-23337.'
|
||||
? 'Enter a CVE or GHSA id, for example CVE-2021-23337. It also covers findings that carry it as an alias.'
|
||||
: 'Enter a package, for example npm/[email protected], or npm/lodash for all versions. PyPI packages use the release version, for example pypi/[email protected].'
|
||||
"
|
||||
required
|
||||
@@ -170,6 +177,7 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, computed, onMounted, watch } from 'vue'
|
||||
import axios from 'axios'
|
||||
import { useRoute } from 'vue-router'
|
||||
import {
|
||||
Badge,
|
||||
Button,
|
||||
@@ -191,28 +199,18 @@ import {
|
||||
Input,
|
||||
LoadingState,
|
||||
PageHeader,
|
||||
RelativeTime,
|
||||
SegmentedControl,
|
||||
StatusBadge,
|
||||
Textarea,
|
||||
useToastStore,
|
||||
type DataTableColumn,
|
||||
} from '@perfect-design/ui'
|
||||
import { useAdminKey } from '@/lib/adminKey'
|
||||
import { isExpired, type Bypass } from '@/lib/bypass'
|
||||
import { formatDate } from '@/lib/format'
|
||||
import { faPen, faPlus, faRotateRight, faShieldHalved, faTrash } from '@/lib/icons'
|
||||
|
||||
interface Bypass {
|
||||
id: string
|
||||
type: 'cve' | 'package'
|
||||
target: string
|
||||
reason: string
|
||||
created_by: string
|
||||
created_at: string
|
||||
expires_at: string
|
||||
applies_to?: string
|
||||
notify_on_expiry: boolean
|
||||
active: boolean
|
||||
}
|
||||
|
||||
const loading = ref(false)
|
||||
const error = ref<string | null>(null)
|
||||
const toasts = useToastStore()
|
||||
@@ -220,6 +218,7 @@ const bypasses = ref<Bypass[]>([])
|
||||
const activeFilter = ref<'all' | 'active' | 'expired'>('all')
|
||||
const typeFilter = ref<'all' | 'cve' | 'package'>('all')
|
||||
|
||||
const route = useRoute()
|
||||
const showCreateModal = ref(false)
|
||||
const showDeleteModal = ref(false)
|
||||
const editingBypass = ref<Bypass | null>(null)
|
||||
@@ -238,8 +237,8 @@ const EMPTY_FORM = {
|
||||
|
||||
const bypassForm = ref({ ...EMPTY_FORM })
|
||||
|
||||
// Get API key from localStorage or prompt user
|
||||
const apiKey = ref<string>('')
|
||||
const adminKey = useAdminKey()
|
||||
const apiKey = adminKey.key
|
||||
const keyInput = ref('')
|
||||
const showKeyDialog = ref(false)
|
||||
|
||||
@@ -274,8 +273,8 @@ const isFormValid = computed(() => {
|
||||
})
|
||||
|
||||
onMounted(() => {
|
||||
// Try to get API key from localStorage
|
||||
apiKey.value = localStorage.getItem('admin_api_key') || ''
|
||||
adminKey.load()
|
||||
prefillFromQuery()
|
||||
if (!apiKey.value) {
|
||||
promptForApiKey()
|
||||
} else {
|
||||
@@ -283,6 +282,14 @@ onMounted(() => {
|
||||
}
|
||||
})
|
||||
|
||||
// A package page links here with the package to cover.
|
||||
function prefillFromQuery() {
|
||||
const { type, target } = route.query
|
||||
if (typeof target !== 'string' || target === '') return
|
||||
bypassForm.value = { ...EMPTY_FORM, type: type === 'cve' ? 'cve' : 'package', target }
|
||||
showCreateModal.value = true
|
||||
}
|
||||
|
||||
function promptForApiKey() {
|
||||
keyInput.value = ''
|
||||
showKeyDialog.value = true
|
||||
@@ -291,8 +298,7 @@ function promptForApiKey() {
|
||||
function submitApiKey() {
|
||||
const key = keyInput.value.trim()
|
||||
if (!key) return
|
||||
apiKey.value = key
|
||||
localStorage.setItem('admin_api_key', key)
|
||||
adminKey.save(key)
|
||||
showKeyDialog.value = false
|
||||
fetchBypasses()
|
||||
}
|
||||
@@ -330,8 +336,7 @@ async function fetchBypasses() {
|
||||
console.error('Failed to fetch bypasses:', err)
|
||||
if (err.response?.status === 401) {
|
||||
error.value = 'Invalid API key. Please check your credentials.'
|
||||
localStorage.removeItem('admin_api_key')
|
||||
apiKey.value = ''
|
||||
adminKey.clear()
|
||||
} else {
|
||||
error.value = err.response?.data?.error?.message || err.message || 'Failed to load bypasses'
|
||||
}
|
||||
@@ -449,10 +454,6 @@ async function deleteBypass() {
|
||||
}
|
||||
}
|
||||
|
||||
function isExpired(expiresAt: string): boolean {
|
||||
return new Date(expiresAt) < new Date()
|
||||
}
|
||||
|
||||
const FILTER_OPTIONS = [
|
||||
{ value: 'all', label: 'All' },
|
||||
{ value: 'active', label: 'Active' },
|
||||
@@ -471,13 +472,13 @@ const BYPASS_TYPE_OPTIONS = [
|
||||
]
|
||||
|
||||
const bypassColumns: DataTableColumn<Bypass>[] = [
|
||||
{ key: 'target', header: 'Target', rowHeader: true },
|
||||
{ key: 'target', header: 'Target', sortable: true, rowHeader: true },
|
||||
{ key: 'type', header: 'Type' },
|
||||
{ key: 'status', header: 'Status', accessor: (b) => (b.active ? 'active' : 'inactive') },
|
||||
{ key: 'reason', header: 'Reason' },
|
||||
{ key: 'created_by', header: 'Created by' },
|
||||
{ key: 'created_at', header: 'Created', accessor: (b) => formatDate(b.created_at) },
|
||||
{ key: 'expires_at', header: 'Expires', accessor: (b) => formatDate(b.expires_at) },
|
||||
{ key: 'created_at', header: 'Created', sortable: true, accessor: (b) => Date.parse(b.created_at) },
|
||||
{ key: 'expires_at', header: 'Expires', sortable: true, accessor: (b) => Date.parse(b.expires_at) },
|
||||
{ key: 'applies_to', header: 'Applies to' },
|
||||
{ key: 'actions', header: 'Actions', actions: true, accessor: () => '' },
|
||||
]
|
||||
|
||||
@@ -1,246 +0,0 @@
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest'
|
||||
import { mount as mountWith } from '@vue/test-utils'
|
||||
import { createPinia, setActivePinia } from 'pinia'
|
||||
import Dashboard from './Dashboard.vue'
|
||||
import { usePackageStore } from '../stores/packages'
|
||||
import { useRealtimeStore, __resetRealtimeSingleton } from '../stores/realtime'
|
||||
import { createTestRouter } from '@/test/router'
|
||||
|
||||
describe('Dashboard.vue', () => {
|
||||
let router: Awaited<ReturnType<typeof createTestRouter>>
|
||||
const mount = (component: typeof Dashboard) => mountWith(component, { global: { plugins: [router] } })
|
||||
|
||||
beforeEach(async () => {
|
||||
router = await createTestRouter('/')
|
||||
setActivePinia(createPinia())
|
||||
__resetRealtimeSingleton()
|
||||
// Mock the fetch functions to prevent actual API calls
|
||||
const store = usePackageStore()
|
||||
vi.spyOn(store, 'fetchStats').mockResolvedValue()
|
||||
vi.spyOn(store, 'fetchRecentPackages').mockResolvedValue()
|
||||
})
|
||||
|
||||
it('renders dashboard component', () => {
|
||||
const wrapper = mount(Dashboard)
|
||||
expect(wrapper.find('h1').text()).toBe('Dashboard')
|
||||
})
|
||||
|
||||
it('displays error message when error occurs', async () => {
|
||||
const wrapper = mount(Dashboard)
|
||||
const store = usePackageStore()
|
||||
|
||||
store.error = 'Failed to load dashboard'
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
expect(wrapper.text()).toContain('Failed to load dashboard')
|
||||
})
|
||||
|
||||
it('displays loading state when loading', async () => {
|
||||
const wrapper = mount(Dashboard)
|
||||
const store = usePackageStore()
|
||||
|
||||
store.loading = true
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
expect(wrapper.text()).toContain('Loading statistics...')
|
||||
})
|
||||
|
||||
it('displays overview stats cards', async () => {
|
||||
const wrapper = mount(Dashboard)
|
||||
const store = usePackageStore()
|
||||
|
||||
store.loading = false
|
||||
store.stats = {
|
||||
registry: '',
|
||||
total_packages: 2,
|
||||
total_size: 3072,
|
||||
max_cache_size: 10737418240,
|
||||
total_downloads: 30,
|
||||
scanned_packages: 2,
|
||||
vulnerable_packages: 0,
|
||||
blocked_packages: 0,
|
||||
}
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
expect(wrapper.text()).toContain('Total packages')
|
||||
expect(wrapper.text()).toContain('Total size')
|
||||
expect(wrapper.text()).toContain('Total downloads')
|
||||
})
|
||||
|
||||
it('displays total packages from stats', async () => {
|
||||
const wrapper = mount(Dashboard)
|
||||
const store = usePackageStore()
|
||||
|
||||
store.loading = false
|
||||
store.stats = {
|
||||
registry: '',
|
||||
total_packages: 100,
|
||||
total_size: 0,
|
||||
max_cache_size: 10737418240,
|
||||
total_downloads: 0,
|
||||
scanned_packages: 0,
|
||||
vulnerable_packages: 0,
|
||||
blocked_packages: 0,
|
||||
}
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
expect(wrapper.text()).toContain('100')
|
||||
})
|
||||
|
||||
it('displays total downloads from stats', async () => {
|
||||
const wrapper = mount(Dashboard)
|
||||
const store = usePackageStore()
|
||||
|
||||
store.loading = false
|
||||
store.stats = {
|
||||
registry: '',
|
||||
total_packages: 0,
|
||||
total_size: 0,
|
||||
max_cache_size: 10737418240,
|
||||
total_downloads: 500,
|
||||
scanned_packages: 0,
|
||||
vulnerable_packages: 0,
|
||||
blocked_packages: 0,
|
||||
}
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
expect(wrapper.text()).toContain('500')
|
||||
})
|
||||
|
||||
it('displays total size from stats', async () => {
|
||||
const wrapper = mount(Dashboard)
|
||||
const store = usePackageStore()
|
||||
|
||||
store.loading = false
|
||||
store.stats = {
|
||||
registry: '',
|
||||
total_packages: 0,
|
||||
total_size: 1048576, // 1 MB
|
||||
max_cache_size: 10737418240,
|
||||
total_downloads: 0,
|
||||
scanned_packages: 0,
|
||||
vulnerable_packages: 0,
|
||||
blocked_packages: 0,
|
||||
}
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
expect(wrapper.text()).toContain('1 MB')
|
||||
})
|
||||
|
||||
it('displays recent packages section', async () => {
|
||||
const wrapper = mount(Dashboard)
|
||||
const store = usePackageStore()
|
||||
|
||||
store.loading = false
|
||||
store.recentPackages = [
|
||||
{
|
||||
id: '1',
|
||||
registry: 'npm',
|
||||
name: 'test-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()
|
||||
|
||||
expect(wrapper.text()).toContain('Recent packages')
|
||||
})
|
||||
|
||||
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.recentPackages = [
|
||||
{
|
||||
id: '2',
|
||||
registry: 'npm',
|
||||
name: 'new-package',
|
||||
version: '1.0.0',
|
||||
size: 1024,
|
||||
cached_at: '2025-01-02T00:00:00Z',
|
||||
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]
|
||||
|
||||
// The store sorts by cached_at; the view keeps that order
|
||||
expect(recentPackagesSection.indexOf('new-package')).toBeLessThan(
|
||||
recentPackagesSection.indexOf('old-package')
|
||||
)
|
||||
})
|
||||
|
||||
it('handles empty packages array', async () => {
|
||||
const wrapper = mount(Dashboard)
|
||||
const store = usePackageStore()
|
||||
|
||||
store.loading = false
|
||||
store.recentPackages = []
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
expect(wrapper.text()).toContain('0')
|
||||
expect(wrapper.text()).toContain('0 B')
|
||||
})
|
||||
|
||||
it('renders realtime lastStats over polled stats when present', async () => {
|
||||
const wrapper = mount(Dashboard)
|
||||
const store = usePackageStore()
|
||||
const rt = useRealtimeStore()
|
||||
|
||||
store.loading = false
|
||||
store.stats = {
|
||||
registry: '',
|
||||
total_packages: 10,
|
||||
total_size: 1024,
|
||||
max_cache_size: 10737418240,
|
||||
total_downloads: 5,
|
||||
scanned_packages: 0,
|
||||
vulnerable_packages: 0,
|
||||
blocked_packages: 0,
|
||||
}
|
||||
rt.lastStats = {
|
||||
total_packages: 999,
|
||||
total_size: 2048,
|
||||
total_downloads: 777,
|
||||
scanned_packages: 0,
|
||||
}
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
// Realtime values should be visible (override polled values).
|
||||
expect(wrapper.text()).toContain('999')
|
||||
expect(wrapper.text()).toContain('777')
|
||||
})
|
||||
|
||||
it('shows a neutral "Live updates paused" badge while the socket is down', async () => {
|
||||
const wrapper = mount(Dashboard)
|
||||
const badge = wrapper.find('[data-testid="ws-live-indicator"]')
|
||||
expect(badge.text()).toBe('Live updates paused')
|
||||
expect(badge.text()).not.toMatch(/offline/i)
|
||||
expect(badge.attributes('data-tone')).toBe('neutral')
|
||||
})
|
||||
|
||||
it('shows a "Live" badge once the socket is connected', async () => {
|
||||
const wrapper = mount(Dashboard)
|
||||
useRealtimeStore().connected = true
|
||||
await wrapper.vm.$nextTick()
|
||||
const badge = wrapper.find('[data-testid="ws-live-indicator"]')
|
||||
expect(badge.text()).toBe('Live')
|
||||
expect(badge.attributes('data-tone')).toBe('success')
|
||||
})
|
||||
})
|
||||
@@ -1,311 +0,0 @@
|
||||
<template>
|
||||
<div class="flex flex-col gap-6">
|
||||
<PageHeader title="Dashboard" description="What the cache holds and what is moving through it.">
|
||||
<template #actions>
|
||||
<StatusBadge
|
||||
:status="rt.connected ? 'live' : 'paused'"
|
||||
:label="rt.connected ? 'Live' : 'Live updates paused'"
|
||||
:tones="{ live: 'success', paused: 'neutral' }"
|
||||
:pulse="rt.connected"
|
||||
data-testid="ws-live-indicator"
|
||||
/>
|
||||
</template>
|
||||
</PageHeader>
|
||||
|
||||
<LoadingState v-if="loading" variant="kpi-grid" :columns="4" label="Loading statistics..." />
|
||||
|
||||
<ErrorState
|
||||
v-else-if="error"
|
||||
variant="card"
|
||||
title="Could not load statistics"
|
||||
:message="error"
|
||||
@retry="refresh"
|
||||
/>
|
||||
|
||||
<template v-else>
|
||||
<StatGroup :columns="4" aria-label="Cache totals">
|
||||
<KpiTile label="Total packages" :value="displayStats?.total_packages || 0" :icon="faBoxesStacked" />
|
||||
<KpiTile label="Total size" :value="formatBytes(displayStats?.total_size || 0)" :icon="faHardDrive" />
|
||||
<KpiTile label="Total downloads" :value="displayStats?.total_downloads || 0" :icon="faDownload" />
|
||||
<KpiTile label="Scanned packages" :value="displayStats?.scanned_packages || 0" :icon="faShieldHalved" />
|
||||
</StatGroup>
|
||||
|
||||
<Card v-if="recentRealtimeEvents.length > 0" data-testid="ws-event-feed">
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">Live activity</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<ActivityFeed :events="feedEvents" variant="compact" label="Live activity" />
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<div class="grid gap-6 lg:grid-cols-2">
|
||||
<Card class="min-w-0">
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">Download activity</CardTitle>
|
||||
<CardAction>
|
||||
<SegmentedControl v-model="selectedPeriod" :options="chartPeriods" aria-label="Period" />
|
||||
</CardAction>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<LoadingState
|
||||
v-if="chartLoading && chartData.length === 0"
|
||||
layout="inline"
|
||||
label="Loading chart data..."
|
||||
/>
|
||||
<ErrorState
|
||||
v-else-if="chartError"
|
||||
variant="inline"
|
||||
title="Could not load download activity"
|
||||
:message="chartError"
|
||||
@retry="fetchTimeSeriesData"
|
||||
/>
|
||||
<BarChart
|
||||
v-else
|
||||
:labels="chartLabels"
|
||||
:series="[{ name: 'Downloads', data: chartData }]"
|
||||
label="Downloads over the selected period"
|
||||
empty-text="No download activity in this period"
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<TrendChart compact class="min-w-0" />
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">Recent packages</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<EmptyState
|
||||
v-if="recentPackages.length === 0"
|
||||
size="sm"
|
||||
:icon="faBoxOpen"
|
||||
title="No packages cached yet"
|
||||
description="Packages appear here once they are downloaded through the proxy."
|
||||
/>
|
||||
<DataTable
|
||||
v-else
|
||||
label="Recent packages"
|
||||
layout="cards"
|
||||
:columns="packageColumns"
|
||||
:rows="recentPackages"
|
||||
>
|
||||
<template #cell-registry="{ row }">
|
||||
<Badge variant="outline">{{ row.registry }}</Badge>
|
||||
</template>
|
||||
</DataTable>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import { storeToRefs } from 'pinia'
|
||||
import axios from 'axios'
|
||||
import {
|
||||
ActivityFeed,
|
||||
BarChart,
|
||||
Badge,
|
||||
Card,
|
||||
CardAction,
|
||||
CardContent,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
DataTable,
|
||||
EmptyState,
|
||||
ErrorState,
|
||||
KpiTile,
|
||||
LoadingState,
|
||||
PageHeader,
|
||||
SegmentedControl,
|
||||
StatGroup,
|
||||
StatusBadge,
|
||||
type ActivityEvent,
|
||||
type DataTableColumn,
|
||||
} from '@perfect-design/ui'
|
||||
import type { IconDefinition } from '@perfect-design/ui/lib/icons-tools'
|
||||
import TrendChart from './TrendChart.vue'
|
||||
import { usePackageStore, type Package } from '../stores/packages'
|
||||
import { useRealtimeStore } from '../stores/realtime'
|
||||
import type { EventType, RealtimeEvent } from '@/lib/ws'
|
||||
import { displayVersion, formatBytes, formatNumber, withVersionPrefix } from '@/lib/format'
|
||||
import {
|
||||
faBox,
|
||||
faBoxOpen,
|
||||
faBoxesStacked,
|
||||
faChartLine,
|
||||
faDownload,
|
||||
faHardDrive,
|
||||
faShieldHalved,
|
||||
faTrash,
|
||||
} from '@/lib/icons'
|
||||
|
||||
const store = usePackageStore()
|
||||
const { recentPackages, stats, loading, error } = storeToRefs(store)
|
||||
|
||||
const rt = useRealtimeStore()
|
||||
const { lastStats, events: rtEvents } = storeToRefs(rt)
|
||||
|
||||
// Realtime stats override polled stats when available; otherwise fall back.
|
||||
const displayStats = computed(() => lastStats.value ?? stats.value)
|
||||
|
||||
const recentRealtimeEvents = computed<RealtimeEvent[]>(() => {
|
||||
const list = rtEvents.value
|
||||
return list.slice(Math.max(list.length - 5, 0)).reverse()
|
||||
})
|
||||
|
||||
const EVENT_LABELS: Record<EventType, string> = {
|
||||
package_cached: 'Cached',
|
||||
package_deleted: 'Deleted',
|
||||
package_downloaded: 'Downloaded',
|
||||
scan_complete: 'Scan complete',
|
||||
stats_update: 'Stats update',
|
||||
}
|
||||
|
||||
const EVENT_ICONS: Record<EventType, IconDefinition> = {
|
||||
package_cached: faBox,
|
||||
package_deleted: faTrash,
|
||||
package_downloaded: faDownload,
|
||||
scan_complete: faShieldHalved,
|
||||
stats_update: faChartLine,
|
||||
}
|
||||
|
||||
function iconForEvent(type: EventType): IconDefinition {
|
||||
return EVENT_ICONS[type] ?? faChartLine
|
||||
}
|
||||
|
||||
const feedEvents = computed<ActivityEvent[]>(() =>
|
||||
recentRealtimeEvents.value.map((evt, idx) => ({
|
||||
id: `${evt.timestamp}-${idx}`,
|
||||
action: labelForEvent(evt.type),
|
||||
target: describeEvent(evt) || undefined,
|
||||
time: evt.timestamp,
|
||||
icon: iconForEvent(evt.type),
|
||||
})),
|
||||
)
|
||||
|
||||
function labelForEvent(type: EventType): string {
|
||||
return EVENT_LABELS[type] ?? type
|
||||
}
|
||||
|
||||
function describeEvent(evt: RealtimeEvent): string {
|
||||
const p = evt.payload
|
||||
const name = typeof p.name === 'string' ? p.name : ''
|
||||
const shown = typeof p.release_version === 'string' && p.release_version ? p.release_version : p.version
|
||||
const version = typeof shown === 'string' ? `@${shown}` : ''
|
||||
const registry = typeof p.registry === 'string' ? `[${p.registry}] ` : ''
|
||||
if (evt.type === 'stats_update') return ''
|
||||
if (name) return `${registry}${name}${version}`
|
||||
return ''
|
||||
}
|
||||
|
||||
// Chart periods and data
|
||||
const selectedPeriod = ref<string>('1day')
|
||||
const chartPeriods = [
|
||||
{ value: '1h', label: '1 hour' },
|
||||
{ value: '1day', label: '24 hours' },
|
||||
{ value: '7day', label: '7 days' },
|
||||
{ value: '30day', label: '30 days' },
|
||||
]
|
||||
|
||||
// Time-series data from API
|
||||
interface TimeSeriesDataPoint {
|
||||
timestamp: string
|
||||
value: number
|
||||
}
|
||||
|
||||
interface TimeSeriesStats {
|
||||
period: string
|
||||
registry: string
|
||||
data_points: TimeSeriesDataPoint[]
|
||||
}
|
||||
|
||||
const timeSeriesData = ref<TimeSeriesStats | null>(null)
|
||||
const chartLoading = ref(false)
|
||||
const chartError = ref<string | null>(null)
|
||||
|
||||
// Fetch time-series data from API
|
||||
async function fetchTimeSeriesData() {
|
||||
chartLoading.value = true
|
||||
chartError.value = null
|
||||
try {
|
||||
const response = await axios.get(`/api/stats/timeseries?period=${selectedPeriod.value}`)
|
||||
timeSeriesData.value = response.data
|
||||
} catch (err) {
|
||||
console.error('Failed to fetch time-series data:', err)
|
||||
timeSeriesData.value = null
|
||||
chartError.value = err instanceof Error ? err.message : 'Failed to load download activity'
|
||||
} finally {
|
||||
chartLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// Extract chart values from time-series data
|
||||
const chartData = computed(() => {
|
||||
if (!timeSeriesData.value || !timeSeriesData.value.data_points) {
|
||||
return []
|
||||
}
|
||||
return timeSeriesData.value.data_points.map(point => point.value)
|
||||
})
|
||||
|
||||
const chartLabels = computed(() => chartData.value.map((_, index) => getChartLabel(index)))
|
||||
|
||||
const packageColumns: DataTableColumn<Package>[] = [
|
||||
{ key: 'name', header: 'Package', rowHeader: true },
|
||||
{ key: 'version', header: 'Version', accessor: (pkg) => withVersionPrefix(displayVersion(pkg)) },
|
||||
{ key: 'registry', header: 'Registry' },
|
||||
{ key: 'size', header: 'Size', numeric: true, accessor: (pkg) => formatBytes(pkg.size) },
|
||||
{ key: 'download_count', header: 'Downloads', numeric: true, accessor: (pkg) => formatNumber(pkg.download_count) },
|
||||
]
|
||||
|
||||
function refresh() {
|
||||
void store.fetchStats()
|
||||
void store.fetchRecentPackages()
|
||||
}
|
||||
|
||||
function getChartLabel(index: number): string {
|
||||
// Use timestamp from data if available
|
||||
if (timeSeriesData.value && timeSeriesData.value.data_points[index]) {
|
||||
const date = new Date(timeSeriesData.value.data_points[index].timestamp)
|
||||
|
||||
switch (selectedPeriod.value) {
|
||||
case '1h':
|
||||
return date.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' })
|
||||
case '1day':
|
||||
return date.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' })
|
||||
case '7day':
|
||||
return date.toLocaleDateString('en-US', { weekday: 'short' })
|
||||
case '30day':
|
||||
return date.toLocaleDateString('en-US', { day: 'numeric' })
|
||||
default:
|
||||
return `${index}`
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback to index-based labels
|
||||
const labels: Record<string, (i: number) => string> = {
|
||||
'1h': (i) => `${i * 5}m`,
|
||||
'1day': (i) => `${i}:00`,
|
||||
'7day': (i) => ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'][i] || `Day ${i + 1}`,
|
||||
'30day': (i) => `${i + 1}`,
|
||||
}
|
||||
return labels[selectedPeriod.value]?.(index) || `${index}`
|
||||
}
|
||||
|
||||
// Watch for period changes and fetch new data
|
||||
watch(selectedPeriod, () => {
|
||||
fetchTimeSeriesData()
|
||||
})
|
||||
|
||||
onMounted(async () => {
|
||||
// Connect to realtime stream first so we can pick up live events while
|
||||
// initial polling resolves. Singleton survives navigation, so we
|
||||
// intentionally do not disconnect on unmount.
|
||||
rt.connect()
|
||||
await Promise.all([store.fetchStats(), store.fetchRecentPackages(), fetchTimeSeriesData()])
|
||||
})
|
||||
|
||||
</script>
|
||||
@@ -0,0 +1,77 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { createPinia, setActivePinia } from 'pinia'
|
||||
import axios from 'axios'
|
||||
import { flushPromises } from '@vue/test-utils'
|
||||
import Insights from './Insights.vue'
|
||||
import { REGISTRIES, STATS, TIMESERIES, TREND } from '@/test/fixtures'
|
||||
import { mountStrict } from '@/test/mountStrict'
|
||||
import { createTestRouter } from '@/test/router'
|
||||
|
||||
vi.mock('axios')
|
||||
|
||||
let restore: (() => void) | undefined
|
||||
|
||||
afterEach(() => {
|
||||
restore?.()
|
||||
restore = undefined
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
async function open(stats = STATS, timeseries: unknown = TIMESERIES) {
|
||||
vi.mocked(axios.get).mockImplementation(async (url: string) => {
|
||||
if (url.startsWith('/api/stats/timeseries')) return { data: timeseries } as never
|
||||
if (url.startsWith('/api/stats/trend')) return { data: TREND } as never
|
||||
return { data: { stats, registries: REGISTRIES } } as never
|
||||
})
|
||||
const router = await createTestRouter('/stats')
|
||||
const pinia = createPinia()
|
||||
setActivePinia(pinia)
|
||||
const mounted = await mountStrict(Insights, { global: { plugins: [pinia, router] } })
|
||||
restore = mounted.restore
|
||||
await flushPromises()
|
||||
return mounted
|
||||
}
|
||||
|
||||
beforeEach(() => setActivePinia(createPinia()))
|
||||
|
||||
describe('Insights', () => {
|
||||
it('lists packages and downloads per registry', async () => {
|
||||
const { wrapper, problems } = await open()
|
||||
expect(problems).toEqual([])
|
||||
const table = wrapper.get('[data-testid="registry-breakdown"] table')
|
||||
expect(table.text()).toContain('npm280')
|
||||
expect(table.text()).toContain('go110')
|
||||
expect(table.text()).toContain('pypi130')
|
||||
})
|
||||
|
||||
it('reports scan coverage and the four outcomes', async () => {
|
||||
const { wrapper } = await open()
|
||||
const coverage = wrapper.get('[data-testid="scan-coverage"]').text()
|
||||
expect(coverage).toContain('3 of 4')
|
||||
for (const word of ['Cleared', 'Held', 'Bypassed', 'Awaiting scan']) expect(coverage).toContain(word)
|
||||
})
|
||||
|
||||
it('shades a day when there were downloads', async () => {
|
||||
const { wrapper } = await open()
|
||||
expect(wrapper.get('[data-testid="daily-downloads"]').find('[role="img"]').exists()).toBe(true)
|
||||
})
|
||||
|
||||
it('summarises the heatmap period next to the grid', async () => {
|
||||
const { wrapper } = await open()
|
||||
const summary = wrapper.get('[data-testid="heatmap-summary"]').text()
|
||||
expect(summary).toContain('Total')
|
||||
expect(summary).toContain(`of ${TIMESERIES.data_points.length}`)
|
||||
expect(summary).toContain('Busiest day')
|
||||
})
|
||||
|
||||
it('does not draw an empty heatmap for a month with no downloads', async () => {
|
||||
const quiet = { ...TIMESERIES, data_points: TIMESERIES.data_points.map((p) => ({ ...p, value: 0 })) }
|
||||
const { wrapper } = await open(STATS, quiet)
|
||||
expect(wrapper.get('[data-testid="daily-downloads"]').text()).toContain('No downloads yet')
|
||||
})
|
||||
|
||||
it('never shows a hit rate or evictions, which the server does not track', async () => {
|
||||
const { wrapper } = await open()
|
||||
expect(wrapper.text()).not.toMatch(/hit rate|evict/i)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,211 @@
|
||||
<template>
|
||||
<div class="flex flex-col gap-6">
|
||||
<PageHeader title="Insights" description="How the cache grows, what each registry holds, and how much of it the scanners have covered.">
|
||||
<template #actions>
|
||||
<Button variant="outline" :icon-start="faRotateRight" @click="refresh">Refresh</Button>
|
||||
</template>
|
||||
</PageHeader>
|
||||
|
||||
<LoadingState v-if="loading && !stats" variant="kpi-grid" :columns="3" label="Loading statistics..." />
|
||||
|
||||
<ErrorState v-else-if="error && !stats" variant="card" title="Could not load statistics" :message="error" @retry="refresh" />
|
||||
|
||||
<template v-else>
|
||||
<Callout v-if="idleTtl > 0" type="note" size="sm">
|
||||
Cached items not requested for {{ formatDuration(idleTtl) }} are removed.
|
||||
</Callout>
|
||||
|
||||
<Card data-testid="registry-breakdown">
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">By registry</CardTitle>
|
||||
<CardDescription>Packages, disk and traffic for each upstream.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent class="flex flex-col gap-6">
|
||||
<EmptyState v-if="registryRows.length === 0" size="sm" title="No registry data yet" description="Each registry appears after its first download." />
|
||||
<template v-else>
|
||||
<BarChart
|
||||
:labels="registryRows.map((r) => r.registry)"
|
||||
:series="[
|
||||
{ name: 'Packages', data: registryRows.map((r) => r.count) },
|
||||
{ name: 'Downloads', data: registryRows.map((r) => r.downloads) },
|
||||
]"
|
||||
label="Packages and downloads by registry"
|
||||
/>
|
||||
<DataTable label="Registry breakdown" layout="cards" row-key="registry" :columns="registryColumns" :rows="registryRows">
|
||||
<template #cell-registry="{ row }"><Badge variant="outline">{{ row.registry }}</Badge></template>
|
||||
<template #cell-share="{ row }">
|
||||
<StatBar label="Share of disk" hide-label :value="row.size" :max="Math.max(totalSize, 1)" :value-text="sharePercent(row.size)" />
|
||||
</template>
|
||||
</DataTable>
|
||||
</template>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card data-testid="scan-coverage">
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">Scan coverage</CardTitle>
|
||||
<CardDescription>Share of cached package files with a scan result.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent class="flex flex-col gap-6">
|
||||
<StatBar
|
||||
label="Scanned"
|
||||
:value="stats?.scanned_packages ?? 0"
|
||||
:max="Math.max(stats?.total_packages ?? 0, 1)"
|
||||
:value-text="`${stats?.scanned_packages ?? 0} of ${stats?.total_packages ?? 0}`"
|
||||
/>
|
||||
<StatGroup :columns="4" aria-label="Scan outcomes">
|
||||
<KpiTile v-for="tile in outcomeTiles" :key="tile.verdict" :as="RouterLink" :to="tile.to" variant="interactive" :label="tile.label" :value="tile.value" />
|
||||
</StatGroup>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<TrendChart />
|
||||
|
||||
<Card data-testid="daily-downloads">
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">Daily downloads</CardTitle>
|
||||
<CardDescription>The last 30 days. A stronger colour is a busier day.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<LoadingState v-if="heatLoading && heatData.length === 0" layout="inline" label="Loading daily downloads..." />
|
||||
<ErrorState v-else-if="heatError" variant="inline" title="Could not load daily downloads" :message="heatError" @retry="loadHeatmap" />
|
||||
<EmptyState v-else-if="heatData.length === 0" size="sm" title="No downloads yet" description="Days fill in as clients request packages." />
|
||||
<div v-else class="flex flex-wrap items-start gap-x-12 gap-y-6">
|
||||
<CalendarHeatmap
|
||||
:data="heatData"
|
||||
:start="heatStart"
|
||||
:end="heatEnd"
|
||||
label="Downloads per day over the last 30 days"
|
||||
:cell-title="(date: string, value: number | null) => `${date}: ${value ?? 0} downloads`"
|
||||
/>
|
||||
<DescriptionList variant="grid" :columns="3" class="min-w-64 flex-1" data-testid="heatmap-summary">
|
||||
<DescriptionItem term="Total">{{ formatNumber(heatSummary.total) }}</DescriptionItem>
|
||||
<DescriptionItem term="Active days">{{ heatSummary.activeDays }} of {{ heatData.length }}</DescriptionItem>
|
||||
<DescriptionItem term="Busiest day">{{ heatSummary.busiest }}</DescriptionItem>
|
||||
</DescriptionList>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { storeToRefs } from 'pinia'
|
||||
import axios from 'axios'
|
||||
import { RouterLink } from 'vue-router'
|
||||
import {
|
||||
Badge,
|
||||
BarChart,
|
||||
Button,
|
||||
CalendarHeatmap,
|
||||
DescriptionItem,
|
||||
DescriptionList,
|
||||
Callout,
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
DataTable,
|
||||
EmptyState,
|
||||
ErrorState,
|
||||
KpiTile,
|
||||
LoadingState,
|
||||
PageHeader,
|
||||
StatBar,
|
||||
StatGroup,
|
||||
type DataTableColumn,
|
||||
} from '@perfect-design/ui'
|
||||
import TrendChart from './TrendChart.vue'
|
||||
import { usePackageStore } from '../stores/packages'
|
||||
import { formatBytes, formatDuration, formatNumber } from '@/lib/format'
|
||||
import { faRotateRight } from '@/lib/icons'
|
||||
import { isoDay, type TimeSeries } from '@/lib/timeseries'
|
||||
|
||||
interface RegistryRow {
|
||||
registry: string
|
||||
count: number
|
||||
size: number
|
||||
downloads: number
|
||||
}
|
||||
|
||||
const store = usePackageStore()
|
||||
const { stats, registries, loading, error } = storeToRefs(store)
|
||||
|
||||
const idleTtl = computed(() => stats.value?.idle_ttl ?? 0)
|
||||
const totalSize = computed(() => stats.value?.total_size ?? 0)
|
||||
|
||||
const registryRows = computed<RegistryRow[]>(() =>
|
||||
Object.entries(registries.value)
|
||||
.map(([registry, r]) => ({ registry, count: r.count ?? 0, size: r.size ?? 0, downloads: r.downloads ?? 0 }))
|
||||
.sort((a, b) => b.size - a.size),
|
||||
)
|
||||
|
||||
function sharePercent(size: number): string {
|
||||
return totalSize.value > 0 ? `${Math.round((size / totalSize.value) * 100)}%` : '0%'
|
||||
}
|
||||
|
||||
const registryColumns: DataTableColumn<RegistryRow>[] = [
|
||||
{ key: 'registry', header: 'Registry', rowHeader: true },
|
||||
{ key: 'count', header: 'Packages', numeric: true, accessor: (r) => formatNumber(r.count) },
|
||||
{ key: 'size', header: 'Disk', numeric: true, accessor: (r) => formatBytes(r.size) },
|
||||
{ key: 'downloads', header: 'Downloads', numeric: true, accessor: (r) => formatNumber(r.downloads) },
|
||||
{ key: 'share', header: 'Share of disk', accessor: (r) => r.size },
|
||||
]
|
||||
|
||||
const outcomeTiles = computed(() => {
|
||||
const s = stats.value
|
||||
const total = s?.total_packages ?? 0
|
||||
const scanned = s?.scanned_packages ?? 0
|
||||
const held = s?.blocked_packages ?? 0
|
||||
const bypassed = s?.bypassed_packages ?? 0
|
||||
return [
|
||||
{ verdict: 'cleared', label: 'Cleared', value: Math.max(scanned - held - bypassed, 0), to: '/packages?verdict=cleared' },
|
||||
{ verdict: 'held', label: 'Held', value: held, to: '/security?tab=held' },
|
||||
{ verdict: 'bypassed', label: 'Bypassed', value: bypassed, to: '/security?tab=bypassed' },
|
||||
{ verdict: 'pending', label: 'Awaiting scan', value: Math.max(total - scanned, 0), to: '/packages?verdict=pending' },
|
||||
]
|
||||
})
|
||||
|
||||
const heatPoints = ref<TimeSeries['data_points']>([])
|
||||
const heatLoading = ref(false)
|
||||
const heatError = ref<string | null>(null)
|
||||
|
||||
// An all-zero month has nothing to shade, so it reads as empty.
|
||||
const heatData = computed(() =>
|
||||
heatPoints.value.some((p) => p.value > 0) ? heatPoints.value.map((p) => ({ date: isoDay(p.timestamp), value: p.value })) : [],
|
||||
)
|
||||
const heatSummary = computed(() => {
|
||||
const days = heatData.value
|
||||
const busiest = days.reduce((max, d) => (d.value > max.value ? d : max), days[0] ?? { date: '', value: 0 })
|
||||
return {
|
||||
total: days.reduce((sum, d) => sum + d.value, 0),
|
||||
activeDays: days.filter((d) => d.value > 0).length,
|
||||
busiest: busiest.value > 0 ? `${busiest.date}, ${formatNumber(busiest.value)}` : 'None',
|
||||
}
|
||||
})
|
||||
const heatStart = computed(() => heatData.value[0]?.date ?? '')
|
||||
const heatEnd = computed(() => heatData.value[heatData.value.length - 1]?.date ?? '')
|
||||
|
||||
async function loadHeatmap() {
|
||||
heatLoading.value = true
|
||||
heatError.value = null
|
||||
try {
|
||||
const response = await axios.get<TimeSeries>('/api/stats/timeseries?period=30day')
|
||||
heatPoints.value = response.data.data_points ?? []
|
||||
} catch (err) {
|
||||
heatError.value = err instanceof Error ? err.message : 'Failed to load daily downloads'
|
||||
} finally {
|
||||
heatLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function refresh() {
|
||||
void store.fetchStats()
|
||||
void loadHeatmap()
|
||||
}
|
||||
|
||||
onMounted(refresh)
|
||||
</script>
|
||||
@@ -10,7 +10,7 @@
|
||||
>
|
||||
<template #action>
|
||||
<Button as-child>
|
||||
<RouterLink to="/">Back to the dashboard</RouterLink>
|
||||
<RouterLink to="/">Back to the overview</RouterLink>
|
||||
</Button>
|
||||
</template>
|
||||
</EmptyState>
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { createPinia, setActivePinia } from 'pinia'
|
||||
import axios from 'axios'
|
||||
import { flushPromises } from '@vue/test-utils'
|
||||
import Overview from './Overview.vue'
|
||||
import { usePackageStore } from '../stores/packages'
|
||||
import { useRealtimeStore, __resetRealtimeSingleton } from '../stores/realtime'
|
||||
import { __resetSystem } from '@/lib/system'
|
||||
import { PACKAGES, REGISTRIES, STATS, SYSTEM, TIMESERIES, TOP_PACKAGES } from '@/test/fixtures'
|
||||
import { serveRows } from '@/test/rowsServer'
|
||||
import { mountStrict } from '@/test/mountStrict'
|
||||
import { createTestRouter } from '@/test/router'
|
||||
|
||||
vi.mock('axios')
|
||||
|
||||
let restore: (() => void) | undefined
|
||||
|
||||
beforeEach(() => {
|
||||
setActivePinia(createPinia())
|
||||
__resetRealtimeSingleton()
|
||||
__resetSystem()
|
||||
vi.mocked(axios.get).mockImplementation(async (url: string) => {
|
||||
if (url.startsWith('/api/system')) return { data: SYSTEM } as never
|
||||
if (url.includes('layout=rows')) return { data: serveRows(url, PACKAGES) } as never
|
||||
if (url.startsWith('/api/analytics/')) return { data: TOP_PACKAGES } as never
|
||||
if (url.startsWith('/api/stats/timeseries')) return { data: TIMESERIES } as never
|
||||
return { data: { stats: STATS, registries: REGISTRIES } } as never
|
||||
})
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
restore?.()
|
||||
restore = undefined
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
async function open() {
|
||||
const router = await createTestRouter('/')
|
||||
const pinia = createPinia()
|
||||
setActivePinia(pinia)
|
||||
vi.spyOn(useRealtimeStore(), 'connect').mockImplementation(() => {})
|
||||
const mounted = await mountStrict(Overview, { global: { plugins: [pinia, router] } })
|
||||
restore = mounted.restore
|
||||
await flushPromises()
|
||||
return mounted
|
||||
}
|
||||
|
||||
describe('Overview', () => {
|
||||
it('fetches each panel once while the stats load', async () => {
|
||||
await open()
|
||||
const urls = vi.mocked(axios.get).mock.calls.map(([url]) => String(url))
|
||||
const count = (prefix: string) => urls.filter((u) => u.startsWith(prefix)).length
|
||||
expect(count('/api/stats/timeseries')).toBe(1)
|
||||
expect(count('/api/analytics/trending')).toBe(1)
|
||||
expect(urls.filter((u) => u.includes('layout=rows')).length).toBe(1)
|
||||
})
|
||||
|
||||
it('counts each verdict from the stats', async () => {
|
||||
const { wrapper, problems } = await open()
|
||||
expect(problems).toEqual([])
|
||||
const count = (verdict: string) => wrapper.get(`[data-verdict="${verdict}"]`).text()
|
||||
// 4 cached, 3 scanned, 1 held, 1 bypassed.
|
||||
expect(count('cleared')).toMatch(/Cleared\s*1/)
|
||||
expect(count('held')).toMatch(/Held\s*1/)
|
||||
expect(count('bypassed')).toMatch(/Bypassed\s*1/)
|
||||
expect(count('pending')).toMatch(/Awaiting scan\s*1/)
|
||||
})
|
||||
|
||||
it('links each verdict to the page that lists it', async () => {
|
||||
const { wrapper } = await open()
|
||||
const href = (verdict: string) => wrapper.get(`[data-verdict="${verdict}"]`).attributes('href')
|
||||
expect(href('held')).toBe('/security?tab=held')
|
||||
expect(href('bypassed')).toBe('/security?tab=bypassed')
|
||||
expect(href('pending')).toBe('/packages?verdict=pending')
|
||||
})
|
||||
|
||||
it('never shows a hit rate or evictions, which the server does not track', async () => {
|
||||
const { wrapper } = await open()
|
||||
expect(wrapper.text()).not.toMatch(/hit rate|evict/i)
|
||||
})
|
||||
|
||||
it('lets a live stats frame override polled counters without losing the rest', async () => {
|
||||
const { wrapper } = await open()
|
||||
useRealtimeStore().lastStats = { blocked_packages: 5 }
|
||||
await flushPromises()
|
||||
expect(wrapper.get('[data-verdict="held"]').text()).toMatch(/Held\s*5/)
|
||||
expect(wrapper.get('[data-verdict="bypassed"]').text()).toMatch(/Bypassed\s*1/)
|
||||
})
|
||||
|
||||
it('shows loading while statistics are in flight', async () => {
|
||||
const router = await createTestRouter('/')
|
||||
const pinia = createPinia()
|
||||
setActivePinia(pinia)
|
||||
usePackageStore().loading = true
|
||||
vi.spyOn(usePackageStore(), 'fetchStats').mockResolvedValue()
|
||||
vi.spyOn(useRealtimeStore(), 'connect').mockImplementation(() => {})
|
||||
const mounted = await mountStrict(Overview, { global: { plugins: [pinia, router] } })
|
||||
restore = mounted.restore
|
||||
expect(mounted.wrapper.text()).toContain('Loading statistics...')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,210 @@
|
||||
<template>
|
||||
<div class="flex flex-col gap-6">
|
||||
<PageHeader title="Overview" description="Packages arrive at the proxy, the scanners inspect them, and each is cleared, held or waved through.">
|
||||
<template #actions>
|
||||
<StatusBadge
|
||||
:status="rt.connected ? 'live' : 'paused'"
|
||||
:label="rt.connected ? 'Live' : 'Live updates paused'"
|
||||
:tones="{ live: 'success', paused: 'neutral' }"
|
||||
:pulse="rt.connected"
|
||||
data-testid="ws-live-indicator"
|
||||
/>
|
||||
</template>
|
||||
</PageHeader>
|
||||
|
||||
<PolicyLine />
|
||||
|
||||
<LoadingState v-if="loading && !displayStats" variant="kpi-grid" :columns="4" label="Loading statistics..." />
|
||||
|
||||
<ErrorState
|
||||
v-else-if="error && !displayStats"
|
||||
variant="card"
|
||||
title="Could not load statistics"
|
||||
:message="error"
|
||||
@retry="refresh"
|
||||
/>
|
||||
|
||||
<template v-else>
|
||||
<StatGroup :columns="4" aria-label="Verdicts" data-testid="verdict-strip">
|
||||
<KpiTile
|
||||
v-for="tile in verdictTiles"
|
||||
:key="tile.verdict"
|
||||
:as="RouterLink"
|
||||
:to="tile.to"
|
||||
variant="interactive"
|
||||
:label="VERDICT_LABELS[tile.verdict]"
|
||||
:value="tile.value"
|
||||
:hint="tile.hint"
|
||||
:data-verdict="tile.verdict"
|
||||
>
|
||||
<template #icon><Icon :icon="tile.icon" :class="VERDICT_TEXT[tile.verdict]" /></template>
|
||||
</KpiTile>
|
||||
</StatGroup>
|
||||
</template>
|
||||
|
||||
<!-- Outside the stats loading chain: a stats refresh must not remount these and refetch their data. -->
|
||||
<div class="grid items-start gap-6 xl:grid-cols-3">
|
||||
<CacheCapacity
|
||||
v-if="displayStats"
|
||||
:used="displayStats.total_size ?? 0"
|
||||
:max-size="displayStats.max_cache_size ?? 0"
|
||||
:registries="registries"
|
||||
/>
|
||||
<LoadingState v-else-if="loading" variant="card" label="Loading cache capacity..." />
|
||||
<DownloadTrend class="xl:col-span-2" />
|
||||
</div>
|
||||
|
||||
<TopPackages />
|
||||
|
||||
<div class="grid gap-6 lg:grid-cols-2">
|
||||
<ScannerHealth />
|
||||
<Card v-if="!(error && !displayStats)" class="min-w-0" data-testid="ws-event-feed">
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">Live activity</CardTitle>
|
||||
<CardDescription>What the proxy just did.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<EmptyState
|
||||
v-if="feedEvents.length === 0"
|
||||
size="sm"
|
||||
:icon="faBoxOpen"
|
||||
title="Quiet at the desk"
|
||||
description="Cached, downloaded and scanned packages appear here as they happen."
|
||||
/>
|
||||
<ActivityFeed v-else :events="feedEvents" variant="compact" label="Live activity" />
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted } from 'vue'
|
||||
import { storeToRefs } from 'pinia'
|
||||
import { RouterLink } from 'vue-router'
|
||||
import {
|
||||
ActivityFeed,
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
EmptyState,
|
||||
ErrorState,
|
||||
Icon,
|
||||
KpiTile,
|
||||
LoadingState,
|
||||
PageHeader,
|
||||
StatGroup,
|
||||
StatusBadge,
|
||||
type ActivityEvent,
|
||||
} from '@perfect-design/ui'
|
||||
import type { IconDefinition } from '@perfect-design/ui/lib/icons-tools'
|
||||
import CacheCapacity from './parts/CacheCapacity.vue'
|
||||
import DownloadTrend from './parts/DownloadTrend.vue'
|
||||
import PolicyLine from './parts/PolicyLine.vue'
|
||||
import ScannerHealth from './parts/ScannerHealth.vue'
|
||||
import TopPackages from './parts/TopPackages.vue'
|
||||
import { usePackageStore, type Stats } from '../stores/packages'
|
||||
import { useRealtimeStore } from '../stores/realtime'
|
||||
import type { EventType, RealtimeEvent } from '@/lib/ws'
|
||||
import { VERDICT_LABELS, VERDICT_TEXT, type Verdict } from '@/lib/verdict'
|
||||
import {
|
||||
faBan,
|
||||
faBox,
|
||||
faBoxOpen,
|
||||
faChartLine,
|
||||
faCircleCheck,
|
||||
faDownload,
|
||||
faHourglassHalf,
|
||||
faShieldHalved,
|
||||
faTrash,
|
||||
faUnlockKeyhole,
|
||||
} from '@/lib/icons'
|
||||
|
||||
const store = usePackageStore()
|
||||
const { stats, registries, loading, error } = storeToRefs(store)
|
||||
|
||||
const rt = useRealtimeStore()
|
||||
const { lastStats, events: rtEvents } = storeToRefs(rt)
|
||||
|
||||
// A live stats frame can lack counters the polled response carries, so it overlays rather than replaces.
|
||||
const displayStats = computed<Stats | null>(() => {
|
||||
if (!stats.value && !lastStats.value) return null
|
||||
return { ...stats.value, ...lastStats.value } as Stats
|
||||
})
|
||||
|
||||
interface VerdictTile {
|
||||
verdict: Verdict
|
||||
value: number
|
||||
hint: string
|
||||
to: string
|
||||
icon: IconDefinition
|
||||
}
|
||||
|
||||
const verdictTiles = computed<VerdictTile[]>(() => {
|
||||
const s = displayStats.value
|
||||
const total = s?.total_packages ?? 0
|
||||
const scanned = s?.scanned_packages ?? 0
|
||||
const held = s?.blocked_packages ?? 0
|
||||
const bypassed = s?.bypassed_packages ?? 0
|
||||
const tiles: Array<[Verdict, number, string, string, IconDefinition]> = [
|
||||
['cleared', Math.max(scanned - held - bypassed, 0), 'Scanned and served', '/packages?verdict=cleared', faCircleCheck],
|
||||
['held', held, 'Blocked with a 403', '/security?tab=held', faBan],
|
||||
['bypassed', bypassed, 'Served under an admin bypass', '/security?tab=bypassed', faUnlockKeyhole],
|
||||
['pending', Math.max(total - scanned, 0), 'No scan result yet', '/packages?verdict=pending', faHourglassHalf],
|
||||
]
|
||||
return tiles.map(([verdict, value, hint, to, icon]) => ({ verdict, value, hint, to, icon }))
|
||||
})
|
||||
|
||||
const EVENT_LABELS: Record<EventType, string> = {
|
||||
package_cached: 'Cached',
|
||||
package_deleted: 'Deleted',
|
||||
package_downloaded: 'Downloaded',
|
||||
scan_complete: 'Scan complete',
|
||||
stats_update: 'Stats update',
|
||||
}
|
||||
|
||||
const EVENT_ICONS: Record<EventType, IconDefinition> = {
|
||||
package_cached: faBox,
|
||||
package_deleted: faTrash,
|
||||
package_downloaded: faDownload,
|
||||
scan_complete: faShieldHalved,
|
||||
stats_update: faChartLine,
|
||||
}
|
||||
|
||||
const FEED_LENGTH = 6
|
||||
|
||||
const feedEvents = computed<ActivityEvent[]>(() =>
|
||||
rtEvents.value
|
||||
.filter((evt) => evt.type !== 'stats_update')
|
||||
.slice(-FEED_LENGTH)
|
||||
.reverse()
|
||||
.map((evt, idx) => ({
|
||||
id: `${evt.timestamp}-${idx}`,
|
||||
action: EVENT_LABELS[evt.type] ?? evt.type,
|
||||
target: describeEvent(evt) || undefined,
|
||||
time: evt.timestamp,
|
||||
icon: EVENT_ICONS[evt.type] ?? faChartLine,
|
||||
})),
|
||||
)
|
||||
|
||||
function describeEvent(evt: RealtimeEvent): string {
|
||||
const p = evt.payload
|
||||
const name = typeof p.name === 'string' ? p.name : ''
|
||||
const shown = typeof p.release_version === 'string' && p.release_version ? p.release_version : p.version
|
||||
const version = typeof shown === 'string' ? `@${shown}` : ''
|
||||
const registry = typeof p.registry === 'string' ? `[${p.registry}] ` : ''
|
||||
return name ? `${registry}${name}${version}` : ''
|
||||
}
|
||||
|
||||
function refresh() {
|
||||
void store.fetchStats()
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
// The realtime client is a singleton that outlives this view, so it is never disconnected here.
|
||||
rt.connect()
|
||||
refresh()
|
||||
})
|
||||
</script>
|
||||
@@ -1,167 +1,112 @@
|
||||
<template>
|
||||
<div class="flex flex-col gap-6">
|
||||
<PageHeader :title="packageName">
|
||||
<template #back>
|
||||
<Button variant="ghost" size="sm" :icon-start="faArrowLeft" @click="goBack">Back to packages</Button>
|
||||
</template>
|
||||
<PageHeader :title="packageName" back-href="/packages" back-label="Back to packages">
|
||||
<template #description>
|
||||
<span class="flex flex-wrap items-center gap-2">
|
||||
<Badge variant="outline">{{ registry }}</Badge>
|
||||
<Badge variant="outline" class="font-mono">{{ withVersionPrefix(shownVersion) }}</Badge>
|
||||
<VerdictBadge v-if="report" :verdict="verdict" />
|
||||
</span>
|
||||
</template>
|
||||
</PageHeader>
|
||||
|
||||
<LoadingState v-if="loading" variant="card" label="Loading vulnerability details..." />
|
||||
<LoadingState v-if="loading" variant="card" label="Loading package details..." />
|
||||
|
||||
<ErrorState
|
||||
v-else-if="error"
|
||||
variant="card"
|
||||
title="Could not load vulnerability details"
|
||||
title="Could not load this package"
|
||||
:message="error"
|
||||
@retry="fetchVulnerabilities"
|
||||
@retry="load"
|
||||
/>
|
||||
|
||||
<template v-else-if="vulnerabilities">
|
||||
<template v-else-if="report">
|
||||
<Callout v-if="banner" :type="banner.type" :title="banner.title" data-testid="verdict-banner">{{ banner.body }}</Callout>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">Security scan summary</CardTitle>
|
||||
<CardTitle as="h2">Details</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent class="flex flex-col gap-4">
|
||||
<SeveritySummary :counts="severityCounts" label="Vulnerabilities by severity" />
|
||||
<DescriptionList variant="inline" divided>
|
||||
<DescriptionItem term="Scanned">{{ formatDate(vulnerabilities.scanned_at) }}</DescriptionItem>
|
||||
<DescriptionItem term="Scanners">
|
||||
<span class="flex flex-wrap gap-1">
|
||||
<Badge v-for="scanner in scannerList" :key="scanner" variant="secondary">{{ scanner }}</Badge>
|
||||
</span>
|
||||
</DescriptionItem>
|
||||
<DescriptionItem v-if="bypassedCount > 0" term="Bypassed">
|
||||
<StatusBadge status="bypassed" :label="`${bypassedCount} bypassed`" :tones="{ bypassed: 'success' }" />
|
||||
</DescriptionItem>
|
||||
</DescriptionList>
|
||||
<CardContent>
|
||||
<div class="flex flex-col gap-6" data-testid="package-meta">
|
||||
<DescriptionList variant="grid" :columns="3" class="items-start">
|
||||
<DescriptionItem term="Size">{{ row ? formatBytes(row.size) : 'Unknown' }}</DescriptionItem>
|
||||
<DescriptionItem term="Downloads">{{ row ? formatNumber(row.download_count) : 'Unknown' }}</DescriptionItem>
|
||||
<DescriptionItem term="Upstream">{{ upstream }}</DescriptionItem>
|
||||
<DescriptionItem term="Cached">
|
||||
<RelativeTime v-if="row" :datetime="row.cached_at" />
|
||||
<template v-else>Unknown</template>
|
||||
</DescriptionItem>
|
||||
<DescriptionItem term="Last accessed">
|
||||
<RelativeTime v-if="row" :datetime="row.last_accessed" />
|
||||
<template v-else>Unknown</template>
|
||||
</DescriptionItem>
|
||||
<DescriptionItem term="Last scanned">
|
||||
<RelativeTime v-if="report.scanned_at" :datetime="report.scanned_at" />
|
||||
<template v-else>Never</template>
|
||||
</DescriptionItem>
|
||||
</DescriptionList>
|
||||
<DescriptionList variant="grid" :columns="1" class="items-start">
|
||||
<DescriptionItem term="Checksum (SHA-256)" :copyable="Boolean(row?.checksum_sha256)" :copy-text="row?.checksum_sha256">
|
||||
<span class="break-all font-mono text-xs">{{ row?.checksum_sha256 || 'Not recorded' }}</span>
|
||||
</DescriptionItem>
|
||||
<DescriptionItem term="Expiry">{{ expiry }}</DescriptionItem>
|
||||
</DescriptionList>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card v-if="vulnerabilityList.length === 0">
|
||||
<CardContent>
|
||||
<EmptyState
|
||||
tone="success"
|
||||
:icon="faCircleCheck"
|
||||
title="No vulnerabilities found"
|
||||
description="The scanners reported nothing for this package version."
|
||||
<Tabs v-model="tab">
|
||||
<TabsList aria-label="Package sections">
|
||||
<TabsTrigger value="vulnerabilities">Vulnerabilities ({{ report.vulnerability_count }})</TabsTrigger>
|
||||
<TabsTrigger value="inspectors">Inspectors</TabsTrigger>
|
||||
<TabsTrigger value="downloads">Downloads</TabsTrigger>
|
||||
<TabsTrigger value="bypass">Bypass</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<TabsContent value="vulnerabilities" class="pt-4">
|
||||
<div class="flex flex-col gap-4">
|
||||
<SeveritySummary :counts="severityCounts" label="Findings by severity" />
|
||||
<EmptyState
|
||||
v-if="report.vulnerabilities.length === 0"
|
||||
tone="success"
|
||||
:icon="faCircleCheck"
|
||||
:title="report.scanned ? 'No vulnerabilities found' : 'Not scanned yet'"
|
||||
:description="report.scanned ? 'The scanners reported nothing for this package version.' : 'Findings appear here once a scan completes.'"
|
||||
/>
|
||||
<VulnerabilityTable v-else :vulnerabilities="report.vulnerabilities" />
|
||||
</div>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="inspectors" class="pt-4">
|
||||
<InspectorMatrix :registry="registry" :results="report.scanners" :configured="configured" />
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="downloads" class="pt-4">
|
||||
<DownloadsPanel :registry="registry" :name="packageName" :download-count="row?.download_count ?? 0" />
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="bypass" class="pt-4">
|
||||
<BypassPanel
|
||||
:applied="report.decision.bypass"
|
||||
:registry="registry"
|
||||
:name="packageName"
|
||||
:version="version"
|
||||
:release-version="report.package?.release_version"
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card v-else>
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">Detected vulnerabilities ({{ vulnerabilityList.length }})</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Table label="Detected vulnerabilities" layout="cards">
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Severity</TableHead>
|
||||
<TableHead>CVE ID</TableHead>
|
||||
<TableHead>Description</TableHead>
|
||||
<TableHead>Fix version</TableHead>
|
||||
<TableHead align="center">Details</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
<template v-for="(vuln, index) in vulnerabilityList" :key="vuln.id">
|
||||
<TableRow class="cursor-pointer" :selected="expandedRows.has(index)" @click="toggleRow(index)">
|
||||
<TableCell label="Severity">
|
||||
<span class="flex flex-wrap items-center gap-2">
|
||||
<StatusBadge
|
||||
:status="vuln.severity"
|
||||
:tones="SEVERITY_TONES"
|
||||
:label="formatSeverityName(vuln.severity)"
|
||||
/>
|
||||
<StatusBadge
|
||||
v-if="vuln.bypassed"
|
||||
status="bypassed"
|
||||
label="Bypassed"
|
||||
:tones="{ bypassed: 'success' }"
|
||||
/>
|
||||
</span>
|
||||
</TableCell>
|
||||
<TableCell label="CVE ID" class="font-mono font-medium">{{ vuln.id }}</TableCell>
|
||||
<TableCell label="Description">
|
||||
<p class="m-0 line-clamp-2 break-words">{{ vuln.title || vuln.description }}</p>
|
||||
</TableCell>
|
||||
<TableCell label="Fix version">
|
||||
<span v-if="vuln.fixed_in">v{{ vuln.fixed_in }}</span>
|
||||
<span v-else class="text-muted-foreground">-</span>
|
||||
</TableCell>
|
||||
<TableCell label="Details" align="center">
|
||||
<IconButton
|
||||
size="icon-sm"
|
||||
:icon="expandedRows.has(index) ? faChevronUp : faChevronDown"
|
||||
:label="`${expandedRows.has(index) ? 'Hide' : 'Show'} details for ${vuln.id}`"
|
||||
:aria-expanded="expandedRows.has(index)"
|
||||
@click.stop="toggleRow(index)"
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
|
||||
<TableRow v-if="expandedRows.has(index)" :hoverable="false">
|
||||
<TableCell :colspan="5">
|
||||
<div class="flex flex-col gap-4 py-2">
|
||||
<section>
|
||||
<h3 class="mb-2 text-sm font-semibold">Description</h3>
|
||||
<Markdown :source="vuln.description" :heading-offset="3" />
|
||||
</section>
|
||||
|
||||
<Alert v-if="vuln.bypassed && vuln.bypass" variant="success">
|
||||
<AlertTitle>Bypass active</AlertTitle>
|
||||
<AlertDescription>
|
||||
<DescriptionList variant="grid" :columns="3" size="sm">
|
||||
<DescriptionItem term="Reason">{{ vuln.bypass.reason }}</DescriptionItem>
|
||||
<DescriptionItem term="By">{{ vuln.bypass.created_by }}</DescriptionItem>
|
||||
<DescriptionItem term="Expires">{{ formatDate(vuln.bypass.expires_at) }}</DescriptionItem>
|
||||
</DescriptionList>
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
|
||||
<Alert v-if="vuln.fixed_in" variant="info">
|
||||
<AlertTitle>Fix available</AlertTitle>
|
||||
<AlertDescription>
|
||||
Upgrade to version <strong>{{ vuln.fixed_in }}</strong> or later.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
|
||||
<section v-if="vuln.references && vuln.references.length > 0">
|
||||
<h3 class="mb-2 text-sm font-semibold">References ({{ vuln.references.length }})</h3>
|
||||
<ul class="m-0 flex list-none flex-col gap-1 p-0 text-sm">
|
||||
<li v-for="(ref, refIndex) in vuln.references" :key="refIndex" class="break-all">
|
||||
<Link :href="ref" external>{{ ref }}</Link>
|
||||
</li>
|
||||
</ul>
|
||||
</section>
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
</template>
|
||||
</TableBody>
|
||||
</Table>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, computed, onMounted } from 'vue'
|
||||
import { useRouter, useRoute } from 'vue-router'
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import axios from 'axios'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import {
|
||||
Alert,
|
||||
AlertDescription,
|
||||
AlertTitle,
|
||||
Badge,
|
||||
Button,
|
||||
Callout,
|
||||
Card,
|
||||
CardContent,
|
||||
CardHeader,
|
||||
@@ -170,129 +115,95 @@ import {
|
||||
DescriptionList,
|
||||
EmptyState,
|
||||
ErrorState,
|
||||
IconButton,
|
||||
Link,
|
||||
LoadingState,
|
||||
Markdown,
|
||||
PageHeader,
|
||||
StatusBadge,
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
RelativeTime,
|
||||
Tabs,
|
||||
TabsContent,
|
||||
TabsList,
|
||||
TabsTrigger,
|
||||
} from '@perfect-design/ui'
|
||||
import SeveritySummary from './SeveritySummary.vue'
|
||||
import { formatDate, withVersionPrefix } from '@/lib/format'
|
||||
import { faArrowLeft, faChevronDown, faChevronUp, faCircleCheck } from '@/lib/icons'
|
||||
import { NO_VULNERABILITIES, SEVERITY_TONES, formatSeverityName, severityRank } from '@/lib/severity'
|
||||
import BypassPanel from './parts/BypassPanel.vue'
|
||||
import DownloadsPanel from './parts/DownloadsPanel.vue'
|
||||
import InspectorMatrix from './parts/InspectorMatrix.vue'
|
||||
import VerdictBadge from './parts/VerdictBadge.vue'
|
||||
import VulnerabilityTable from './parts/VulnerabilityTable.vue'
|
||||
import type { Package } from '../stores/packages'
|
||||
import { formatBytes, formatDate, formatNumber, formatDuration, withVersionPrefix } from '@/lib/format'
|
||||
import { faCircleCheck } from '@/lib/icons'
|
||||
import type { PackageReport } from '@/lib/report'
|
||||
import { NO_VULNERABILITIES } from '@/lib/severity'
|
||||
import { describePolicy, useSystem } from '@/lib/system'
|
||||
import type { Verdict } from '@/lib/verdict'
|
||||
import { verdictBanner } from '@/lib/verdictBanner'
|
||||
|
||||
const TABS = ['vulnerabilities', 'inspectors', 'downloads', 'bypass'] as const
|
||||
type TabName = (typeof TABS)[number]
|
||||
|
||||
const router = useRouter()
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
const system = useSystem()
|
||||
|
||||
const registry = computed(() => route.params.registry as string)
|
||||
// Names with slashes (scoped npm, Go modules) arrive as segments.
|
||||
const packageName = computed(() => {
|
||||
// Handle package names with slashes (e.g., Go packages like github.com/user/repo)
|
||||
const nameParam = route.params.name
|
||||
if (Array.isArray(nameParam)) {
|
||||
return nameParam.join('/')
|
||||
}
|
||||
return nameParam as string
|
||||
const name = route.params.name
|
||||
return Array.isArray(name) ? name.join('/') : (name as string)
|
||||
})
|
||||
const version = computed(() => route.params.version as string)
|
||||
const shownVersion = computed(() => vulnerabilities.value?.package?.release_version || version.value)
|
||||
|
||||
interface BypassInfo {
|
||||
id: string
|
||||
reason: string
|
||||
created_by: string
|
||||
expires_at: string
|
||||
}
|
||||
|
||||
interface Vulnerability {
|
||||
id: string
|
||||
severity: string
|
||||
title: string
|
||||
description: string
|
||||
references: string[]
|
||||
fixed_in: string
|
||||
bypassed: boolean
|
||||
bypass?: BypassInfo
|
||||
}
|
||||
|
||||
interface VulnerabilityResponse {
|
||||
package?: { release_version?: string }
|
||||
scanned: boolean
|
||||
scanner: string
|
||||
scanned_at: string
|
||||
status: string
|
||||
vulnerabilities: Vulnerability[]
|
||||
vulnerability_count: number
|
||||
severity_counts: {
|
||||
critical: number
|
||||
high: number
|
||||
moderate: number
|
||||
low: number
|
||||
}
|
||||
bypassed_count: number
|
||||
}
|
||||
const shownVersion = computed(() => report.value?.package?.release_version || version.value)
|
||||
|
||||
const loading = ref(false)
|
||||
const error = ref<string | null>(null)
|
||||
const vulnerabilities = ref<VulnerabilityResponse | null>(null)
|
||||
const expandedRows = ref<Set<number>>(new Set())
|
||||
const report = ref<PackageReport | null>(null)
|
||||
const row = ref<Package | null>(null)
|
||||
|
||||
const vulnerabilityList = computed(() => {
|
||||
const vulns = vulnerabilities.value?.vulnerabilities || []
|
||||
// Sort by severity (most severe first)
|
||||
return [...vulns].sort((a, b) => {
|
||||
return severityRank(b.severity) - severityRank(a.severity)
|
||||
})
|
||||
const tab = ref<TabName>(TABS.find((t) => t === route.query.tab) ?? 'vulnerabilities')
|
||||
watch(tab, (value) => void router.replace({ query: { ...route.query, tab: value === 'vulnerabilities' ? undefined : value } }))
|
||||
|
||||
const severityCounts = computed(() => report.value?.severity_counts ?? NO_VULNERABILITIES)
|
||||
const configured = computed(() => system.info.value?.security.scanners ?? [])
|
||||
const verdict = computed<Verdict>(() => report.value?.decision.verdict ?? 'unscanned')
|
||||
|
||||
const banner = computed(() => {
|
||||
if (!report.value) return null
|
||||
const sec = system.info.value?.security
|
||||
return verdictBanner(report.value, sec ? describePolicy(sec) : '', sec?.fail_closed ?? false)
|
||||
})
|
||||
|
||||
const severityCounts = computed(() => vulnerabilities.value?.severity_counts || NO_VULNERABILITIES)
|
||||
const bypassedCount = computed(() => vulnerabilities.value?.bypassed_count || 0)
|
||||
const upstream = computed(() => system.info.value?.upstreams[registry.value] || 'Not reported')
|
||||
|
||||
// Parse scanner string into array of scanner names
|
||||
const scannerList = computed(() => {
|
||||
if (!vulnerabilities.value?.scanner) return []
|
||||
return vulnerabilities.value.scanner.split('+').map((s: string) => s.trim())
|
||||
// Idle eviction is the only expiry the server enforces on a cached package.
|
||||
const expiry = computed(() => {
|
||||
const idle = system.info.value?.cache.idle_ttl
|
||||
if (idle === undefined) return 'Not reported'
|
||||
if (idle === 0) return 'Never. Idle eviction is off.'
|
||||
const last = row.value ? Date.parse(row.value.last_accessed) : Number.NaN
|
||||
const after = `Removed after ${formatDuration(idle)} without a request`
|
||||
return Number.isNaN(last) ? after : `${after}, on ${formatDate(new Date(last + idle * 1000).toISOString())} if unused`
|
||||
})
|
||||
|
||||
onMounted(() => {
|
||||
fetchVulnerabilities()
|
||||
})
|
||||
|
||||
async function fetchVulnerabilities() {
|
||||
async function load() {
|
||||
loading.value = true
|
||||
error.value = null
|
||||
vulnerabilities.value = null
|
||||
|
||||
report.value = null
|
||||
try {
|
||||
const response = await axios.get(
|
||||
`/api/packages/${registry.value}/${packageName.value}/${version.value}/vulnerabilities`
|
||||
)
|
||||
// Store the response data
|
||||
vulnerabilities.value = response.data
|
||||
} catch (err: any) {
|
||||
console.error('Failed to fetch vulnerabilities:', err)
|
||||
error.value = err.response?.data?.error || err.message || 'Failed to load vulnerability details'
|
||||
const encoded = `${registry.value}/${packageName.value}/${version.value}`
|
||||
const [details, single] = await Promise.all([
|
||||
axios.get<PackageReport>(`/api/packages/${encoded}/vulnerabilities`),
|
||||
axios.get<Package>(`/api/packages/${encoded}`).catch(() => null),
|
||||
system.load(),
|
||||
])
|
||||
report.value = details.data
|
||||
row.value = single?.data ?? null
|
||||
} catch (err: unknown) {
|
||||
const e = err as { response?: { data?: { error?: string } }; message?: string }
|
||||
error.value = e.response?.data?.error || e.message || 'Failed to load package details'
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function goBack() {
|
||||
router.push('/packages')
|
||||
}
|
||||
|
||||
function toggleRow(index: number) {
|
||||
if (expandedRows.value.has(index)) {
|
||||
expandedRows.value.delete(index)
|
||||
} else {
|
||||
expandedRows.value.add(index)
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(load)
|
||||
</script>
|
||||
|
||||
@@ -1,325 +1,145 @@
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
|
||||
import { mount } from '@vue/test-utils'
|
||||
import { afterEach, beforeEach, describe, it, expect, vi } from 'vitest'
|
||||
import { createPinia, setActivePinia } from 'pinia'
|
||||
import { createRouter, createMemoryHistory, type Router } from 'vue-router'
|
||||
import { defineComponent, h } from 'vue'
|
||||
import axios from 'axios'
|
||||
import { flushPromises, mount } from '@vue/test-utils'
|
||||
import PackageList from './PackageList.vue'
|
||||
import { usePackageStore } from '../stores/packages'
|
||||
import type { Package } from '../stores/packages'
|
||||
import { PACKAGES } from '@/test/fixtures'
|
||||
import { serveRows } from '@/test/rowsServer'
|
||||
import { createTestRouter } from '@/test/router'
|
||||
|
||||
type Row = ReturnType<typeof usePackageStore>['packagePage']['packages'][number]
|
||||
vi.mock('axios')
|
||||
|
||||
// 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 lastUrl = () => new URL(String(vi.mocked(axios.get).mock.calls[vi.mocked(axios.get).mock.calls.length - 1]![0]), 'http://x').searchParams
|
||||
|
||||
function serve(rows: Package[]) {
|
||||
vi.mocked(axios.get).mockImplementation(async (url: string) => ({ data: serveRows(url, rows) }) as never)
|
||||
}
|
||||
|
||||
const Stub = defineComponent({ render: () => h('div') })
|
||||
|
||||
function createTestRouter(): Router {
|
||||
return createRouter({
|
||||
history: createMemoryHistory(),
|
||||
routes: [
|
||||
{ path: '/', name: 'dashboard', component: Stub },
|
||||
{ path: '/packages/:registry?', name: 'packages', component: Stub, props: true },
|
||||
{
|
||||
path: '/package/:registry/:name+/:version',
|
||||
name: 'package-details',
|
||||
component: Stub,
|
||||
props: true,
|
||||
},
|
||||
],
|
||||
})
|
||||
}
|
||||
|
||||
async function mountWithRouter() {
|
||||
const router = createTestRouter()
|
||||
router.push('/packages')
|
||||
await router.isReady()
|
||||
return mount(PackageList, {
|
||||
global: {
|
||||
plugins: [router],
|
||||
},
|
||||
})
|
||||
async function open(path = '/packages', rows: Package[] = PACKAGES) {
|
||||
serve(rows)
|
||||
const router = await createTestRouter(path)
|
||||
const pinia = createPinia()
|
||||
setActivePinia(pinia)
|
||||
const wrapper = mount(PackageList, { props: { registry: router.currentRoute.value.params.registry as string | undefined }, global: { plugins: [pinia, router] } })
|
||||
await flushPromises()
|
||||
return { wrapper, router }
|
||||
}
|
||||
|
||||
describe('PackageList.vue', () => {
|
||||
beforeEach(() => {
|
||||
// Create a fresh pinia instance before each test
|
||||
setActivePinia(createPinia())
|
||||
// Prevent real network calls from store actions on mount
|
||||
const store = usePackageStore()
|
||||
vi.spyOn(store, 'fetchPackagePage').mockResolvedValue()
|
||||
vi.useFakeTimers({ shouldAdvanceTime: true })
|
||||
})
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('renders package list component', async () => {
|
||||
const wrapper = await mountWithRouter()
|
||||
it('renders the page heading', async () => {
|
||||
const { wrapper } = await open()
|
||||
expect(wrapper.find('h1').text()).toBe('Packages')
|
||||
})
|
||||
|
||||
it('displays loading state when loading', async () => {
|
||||
const wrapper = await mountWithRouter()
|
||||
const store = usePackageStore()
|
||||
|
||||
store.loading = true
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
expect(wrapper.text()).toContain('Loading packages...')
|
||||
it('asks the server for the first page of rows, not for every package', async () => {
|
||||
await open()
|
||||
const calls = vi.mocked(axios.get).mock.calls.filter((c) => String(c[0]).startsWith('/api/packages'))
|
||||
expect(calls).toHaveLength(1)
|
||||
expect(Object.fromEntries(lastUrl())).toEqual({ layout: 'rows', page: '1', page_size: '25' })
|
||||
})
|
||||
|
||||
it('displays error message when error occurs', async () => {
|
||||
const wrapper = await mountWithRouter()
|
||||
const store = usePackageStore()
|
||||
|
||||
store.error = 'Failed to fetch packages'
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
it('displays the error message when the load fails', async () => {
|
||||
vi.mocked(axios.get).mockRejectedValue(new Error('Failed to fetch packages'))
|
||||
const router = await createTestRouter('/packages')
|
||||
const wrapper = mount(PackageList, { global: { plugins: [createPinia(), router] } })
|
||||
await flushPromises()
|
||||
expect(wrapper.text()).toContain('Failed to fetch packages')
|
||||
})
|
||||
|
||||
it('displays empty state when no packages', async () => {
|
||||
const wrapper = await mountWithRouter()
|
||||
const store = usePackageStore()
|
||||
|
||||
store.loading = false
|
||||
setRows(store, [])
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
it('displays an empty state when nothing is cached', async () => {
|
||||
const { wrapper } = await open('/packages', [])
|
||||
expect(wrapper.text()).toContain('No packages cached yet')
|
||||
})
|
||||
|
||||
it('displays package accordion when packages exist', async () => {
|
||||
const wrapper = await mountWithRouter()
|
||||
const store = usePackageStore()
|
||||
|
||||
store.loading = false
|
||||
setRows(store, [
|
||||
{
|
||||
id: '1',
|
||||
registry: 'npm',
|
||||
name: 'test-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()
|
||||
|
||||
expect(wrapper.text()).toContain('test-package')
|
||||
expect(wrapper.text()).toContain('1 version')
|
||||
it('shows one row per version with its size, downloads and verdict word', async () => {
|
||||
const { wrapper } = await open()
|
||||
expect(wrapper.findAll('tbody tr')).toHaveLength(PACKAGES.length)
|
||||
const text = wrapper.text()
|
||||
expect(text).toContain('2 KB')
|
||||
expect(text).toContain('Held')
|
||||
expect(text).toContain('Awaiting scan')
|
||||
})
|
||||
|
||||
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.fetchPackagePage as ReturnType<typeof vi.spyOn>
|
||||
fetchSpy.mockClear()
|
||||
it('debounces the search box into one request', async () => {
|
||||
const { wrapper } = await open()
|
||||
vi.mocked(axios.get).mockClear()
|
||||
const input = wrapper.get('input[aria-label="Search packages"]')
|
||||
|
||||
await mountWithRouter()
|
||||
await input.setValue('r')
|
||||
await input.setValue('re')
|
||||
await input.setValue('requests')
|
||||
await vi.advanceTimersByTimeAsync(100)
|
||||
expect(axios.get).not.toHaveBeenCalled()
|
||||
|
||||
expect(fetchSpy).toHaveBeenCalled()
|
||||
await vi.advanceTimersByTimeAsync(400)
|
||||
await flushPromises()
|
||||
expect(axios.get).toHaveBeenCalledTimes(1)
|
||||
expect(lastUrl().get('q')).toBe('requests')
|
||||
expect(wrapper.findAll('tbody tr')).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('groups packages and displays version counts', async () => {
|
||||
const wrapper = await mountWithRouter()
|
||||
const store = usePackageStore()
|
||||
|
||||
store.loading = false
|
||||
setRows(store, [
|
||||
{
|
||||
id: '1',
|
||||
registry: 'npm',
|
||||
name: 'test-package',
|
||||
version: '1.0.0',
|
||||
size: 1024,
|
||||
cached_at: '2025-01-01T00:00:00Z',
|
||||
last_accessed: '2025-01-01T00:00:00Z',
|
||||
download_count: 10,
|
||||
},
|
||||
{
|
||||
id: '2',
|
||||
registry: 'npm',
|
||||
name: 'test-package',
|
||||
version: '2.0.0',
|
||||
size: 2048,
|
||||
cached_at: '2025-01-02T00:00:00Z',
|
||||
last_accessed: '2025-01-02T00:00:00Z',
|
||||
download_count: 20,
|
||||
},
|
||||
])
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
expect(wrapper.text()).toContain('test-package')
|
||||
expect(wrapper.text()).toContain('2 versions')
|
||||
it('says nothing matches when the server returns no rows for a search', async () => {
|
||||
const { wrapper } = await open()
|
||||
await wrapper.get('input[aria-label="Search packages"]').setValue('nothing-like-this')
|
||||
await vi.advanceTimersByTimeAsync(400)
|
||||
await flushPromises()
|
||||
expect(wrapper.text()).toContain('No packages match')
|
||||
})
|
||||
|
||||
it('formats bytes correctly', async () => {
|
||||
const wrapper = await mountWithRouter()
|
||||
const store = usePackageStore()
|
||||
|
||||
store.loading = false
|
||||
setRows(store, [
|
||||
{
|
||||
id: '1',
|
||||
registry: 'npm',
|
||||
name: 'test-package',
|
||||
version: '1.0.0',
|
||||
size: 1048576, // 1 MB
|
||||
cached_at: '2025-01-01T00:00:00Z',
|
||||
last_accessed: '2025-01-01T00:00:00Z',
|
||||
download_count: 10,
|
||||
},
|
||||
])
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
expect(wrapper.text()).toContain('1 MB')
|
||||
it('writes the search to the URL so a reload restores it', async () => {
|
||||
const { wrapper, router } = await open()
|
||||
await wrapper.get('input[aria-label="Search packages"]').setValue('left')
|
||||
await vi.advanceTimersByTimeAsync(400)
|
||||
await flushPromises()
|
||||
expect(router.currentRoute.value.query.q).toBe('left')
|
||||
})
|
||||
|
||||
it('prints every registry as a badge with its name', async () => {
|
||||
const wrapper = await mountWithRouter()
|
||||
const store = usePackageStore()
|
||||
|
||||
store.loading = false
|
||||
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',
|
||||
name: 'npm-package',
|
||||
version: '1.0.0',
|
||||
size: 1024,
|
||||
cached_at: '2025-01-01T00:00:00Z',
|
||||
last_accessed: '2025-01-01T00:00:00Z',
|
||||
download_count: 10,
|
||||
},
|
||||
{
|
||||
id: '2',
|
||||
registry: 'pypi',
|
||||
name: 'python-package',
|
||||
version: '1.0.0',
|
||||
size: 1024,
|
||||
cached_at: '2025-01-01T00:00:00Z',
|
||||
last_accessed: '2025-01-01T00:00:00Z',
|
||||
download_count: 5,
|
||||
},
|
||||
])
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
// Verify that all registry badges are displayed
|
||||
// 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')
|
||||
|
||||
// Each registry is printed as text in an outline badge, never as colour alone.
|
||||
const badges = wrapper.findAll('[data-slot="badge"]').map((badge) => badge.text())
|
||||
expect(badges).toEqual(['go', 'npm', 'pypi'])
|
||||
it('treats the registry path segment as a registry filter sent to the server', async () => {
|
||||
const { wrapper } = await open('/packages/pypi')
|
||||
expect(lastUrl().get('registry')).toBe('pypi')
|
||||
expect(wrapper.findAll('tbody tr')).toHaveLength(1)
|
||||
expect(wrapper.text()).toContain('requests')
|
||||
})
|
||||
|
||||
it('shows the release version for a PyPI file row, not the file name', async () => {
|
||||
const wrapper = await mountWithRouter()
|
||||
const store = usePackageStore()
|
||||
it('sends the verdict from the URL', async () => {
|
||||
const { wrapper } = await open('/packages?verdict=held')
|
||||
expect(lastUrl().get('verdict')).toBe('held')
|
||||
expect(wrapper.get('[data-testid="package-count"]').text()).toContain('1 of 1 package version')
|
||||
})
|
||||
|
||||
setRows(store, [
|
||||
{
|
||||
id: '1',
|
||||
registry: 'pypi',
|
||||
name: 'six',
|
||||
version: 'six-1.17.0-py2.py3-none-any.whl',
|
||||
release_version: '1.17.0',
|
||||
size: 1,
|
||||
cached_at: '2026-11-23T00:00:00Z',
|
||||
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()
|
||||
it('pages through the server and shows the range', async () => {
|
||||
const many = Array.from({ length: 60 }, (_, i) => ({ ...PACKAGES[0]!, id: `p${i}`, name: `pkg-${String(i).padStart(2, '0')}` }))
|
||||
const { wrapper } = await open('/packages', many)
|
||||
expect(wrapper.findAll('tbody tr')).toHaveLength(25)
|
||||
expect(wrapper.get('[data-testid="package-count"]').text()).toContain('1–25 of 60 package versions')
|
||||
|
||||
await wrapper.get('nav[aria-label="Package pages"] button[aria-label*="ext"]').trigger('click')
|
||||
await flushPromises()
|
||||
expect(lastUrl().get('page')).toBe('2')
|
||||
expect(wrapper.get('[data-testid="package-count"]').text()).toContain('26–50 of 60')
|
||||
})
|
||||
|
||||
it('sends a column sort to the server and returns to page 1', async () => {
|
||||
const { wrapper } = await open()
|
||||
await wrapper.get('thead button[aria-label*="Size"], thead th button').trigger('click')
|
||||
await flushPromises()
|
||||
expect(lastUrl().get('page')).toBe('1')
|
||||
expect(lastUrl().get('sort')).not.toBeNull()
|
||||
})
|
||||
|
||||
it('shows the release version of a PyPI file row, not the file name', async () => {
|
||||
const six = { ...PACKAGES[2], version: 'six-1.17.0-py2.py3-none-any.whl', release_version: '1.17.0' } as Package
|
||||
const { wrapper } = await open('/packages', [six])
|
||||
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')
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,133 +1,83 @@
|
||||
<template>
|
||||
<div class="flex flex-col gap-6">
|
||||
<PageHeader title="Packages" description="Everything the proxy has cached, grouped by package.">
|
||||
<PageHeader title="Packages" description="Everything the proxy has cached and the verdict each package received.">
|
||||
<template #actions>
|
||||
<Button variant="outline" :icon-start="faRotateRight" @click="load()">Refresh</Button>
|
||||
</template>
|
||||
</PageHeader>
|
||||
|
||||
<div class="flex flex-col gap-4 sm:flex-row sm:items-center">
|
||||
<SegmentedControl
|
||||
:model-value="selectedRegistry"
|
||||
:options="REGISTRY_OPTIONS"
|
||||
aria-label="Filter by registry"
|
||||
@update:model-value="changeRegistryFilter"
|
||||
/>
|
||||
<SearchInput v-model="searchTerm" aria-label="Search packages" placeholder="Search packages..." class="w-full sm:ms-auto sm:w-64" />
|
||||
<div class="flex flex-col gap-3">
|
||||
<SearchInput v-model="query" aria-label="Search packages" placeholder="Search by name or version..." class="w-full sm:max-w-md" />
|
||||
<FilterBar v-model="filterItems" :fields="filterFields" variant="compact" />
|
||||
</div>
|
||||
|
||||
<LoadingState v-if="loading" variant="table" label="Loading packages..." />
|
||||
<LoadingState v-if="loading && !loaded" variant="table" label="Loading packages..." />
|
||||
|
||||
<ErrorState
|
||||
v-else-if="error"
|
||||
variant="card"
|
||||
title="Could not load packages"
|
||||
:message="error"
|
||||
@retry="load()"
|
||||
/>
|
||||
<ErrorState v-else-if="error" variant="card" title="Could not load packages" :message="error" @retry="load()" />
|
||||
|
||||
<Card v-else>
|
||||
<CardContent>
|
||||
<EmptyState
|
||||
v-if="totalGroups === 0 && !filtersActive"
|
||||
v-if="total === 0 && !filtered"
|
||||
:icon="faBoxOpen"
|
||||
title="No packages cached yet"
|
||||
description="Packages will appear here once they are downloaded through the proxy."
|
||||
/>
|
||||
<EmptyState
|
||||
v-else-if="groups.length === 0"
|
||||
v-else-if="total === 0"
|
||||
:icon="faMagnifyingGlass"
|
||||
title="No packages match"
|
||||
description="Change the registry filter or the search text."
|
||||
description="Change the search text or remove a filter."
|
||||
/>
|
||||
<Accordion v-else type="multiple" class="w-full">
|
||||
<AccordionItem
|
||||
v-for="group in groups"
|
||||
:key="`${group.registry}:${group.name}`"
|
||||
:value="`${group.registry}:${group.name}`"
|
||||
>
|
||||
<AccordionTrigger :heading-level="2">
|
||||
<!-- Stacked below sm: a side-by-side row leaves the name ~90px at 320px and breaks scoped names mid-word. -->
|
||||
<span class="flex w-full min-w-0 flex-col items-start gap-2 sm:flex-row sm:items-center sm:justify-between sm:gap-4">
|
||||
<span class="w-full min-w-0 text-start sm:w-auto">
|
||||
<span class="block break-words font-semibold">{{ group.name }}</span>
|
||||
<span class="block text-sm text-muted-foreground">
|
||||
{{ group.versions.length }} version{{ group.versions.length > 1 ? 's' : '' }}
|
||||
</span>
|
||||
</span>
|
||||
<span class="flex shrink-0 items-center gap-4">
|
||||
<Badge variant="outline">{{ group.registry }}</Badge>
|
||||
<span class="text-end tabular-nums">
|
||||
<span class="block text-sm font-medium">{{ formatBytes(group.totalSize) }}</span>
|
||||
<span class="block text-xs text-muted-foreground">{{ formatNumber(group.totalDownloads) }} downloads</span>
|
||||
</span>
|
||||
</span>
|
||||
</span>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent>
|
||||
<Table :label="`Versions of ${group.name}`" layout="cards">
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Version</TableHead>
|
||||
<TableHead align="right">Downloads</TableHead>
|
||||
<TableHead align="right">Size</TableHead>
|
||||
<TableHead>Cached</TableHead>
|
||||
<TableHead>Vulnerabilities</TableHead>
|
||||
<TableHead align="right">Actions</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
<TableRow v-for="version in group.versions" :key="version.id">
|
||||
<TableCell label="Version" class="font-medium">{{ withVersionPrefix(displayVersion(version)) }}</TableCell>
|
||||
<TableCell label="Downloads" numeric>{{ formatNumber(version.download_count) }}</TableCell>
|
||||
<TableCell label="Size" numeric>{{ formatBytes(version.size) }}</TableCell>
|
||||
<TableCell label="Cached">{{ formatDate(version.cached_at) }}</TableCell>
|
||||
<TableCell label="Vulnerabilities">
|
||||
<VulnerabilityBadge
|
||||
v-if="version.vulnerabilities"
|
||||
:scanned="version.vulnerabilities.scanned"
|
||||
:status="version.vulnerabilities.status"
|
||||
:counts="version.vulnerabilities.counts"
|
||||
:total="version.vulnerabilities.total"
|
||||
:scannedAt="version.vulnerabilities.scannedAt"
|
||||
:isBlocked="version.vulnerabilities.isBlocked"
|
||||
@click="showVulnerabilityDetails(group.registry, group.name, version.version)"
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell label="Actions" align="right">
|
||||
<IconButton
|
||||
:icon="faTrash"
|
||||
:label="`Delete ${group.name} ${version.version}`"
|
||||
@click="confirmDelete(version)"
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
</TableBody>
|
||||
</Table>
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
|
||||
<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 }} ({{ totalGroups }} total packages)
|
||||
<template v-else>
|
||||
<p class="m-0 mb-3 text-sm text-muted-foreground" data-testid="package-count">
|
||||
{{ rangeStart }}–{{ rangeEnd }} of {{ plural(total, 'package version') }}
|
||||
</p>
|
||||
<DataTable
|
||||
v-model:sort="sort"
|
||||
label="Cached packages"
|
||||
layout="cards"
|
||||
density="compact"
|
||||
row-clickable
|
||||
:loading="loading"
|
||||
:columns="columns"
|
||||
:rows="rows"
|
||||
@row-click="(row: Package) => (selected = row)"
|
||||
>
|
||||
<template #cell-name="{ row }">
|
||||
<RouterLink :to="packageRoute(row)" class="break-words font-medium text-foreground underline-offset-4 hover:underline">
|
||||
{{ row.name }}
|
||||
</RouterLink>
|
||||
</template>
|
||||
<template #cell-registry="{ row }"><Badge variant="outline">{{ row.registry }}</Badge></template>
|
||||
<template #cell-size="{ row }">{{ formatBytes(row.size) }}</template>
|
||||
<template #cell-download_count="{ row }">{{ formatNumber(row.download_count) }}</template>
|
||||
<template #cell-last_accessed="{ row }"><RelativeTime :datetime="row.last_accessed" /></template>
|
||||
<template #cell-verdict="{ row }"><VerdictBadge :verdict="verdictOf(row)" /></template>
|
||||
<template #cell-scanned="{ row }">
|
||||
<RelativeTime v-if="row.vulnerabilities?.scannedAt" :datetime="row.vulnerabilities.scannedAt" />
|
||||
<span v-else class="text-muted-foreground">Never</span>
|
||||
</template>
|
||||
</DataTable>
|
||||
<Pagination
|
||||
:page="currentPage"
|
||||
:total="totalGroups"
|
||||
v-if="total > PAGE_SIZE"
|
||||
v-model:page="page"
|
||||
class="mt-4"
|
||||
:total="total"
|
||||
:page-size="PAGE_SIZE"
|
||||
:show-edges="false"
|
||||
@update:page="changePage"
|
||||
aria-label="Package pages"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<PackageQuickView :pkg="selected" @close="selected = null" @delete="confirmDelete" />
|
||||
|
||||
<ConfirmDialog
|
||||
v-model:open="showDeleteModal"
|
||||
title="Delete package version?"
|
||||
:description="`Delete ${packageToDelete?.name}@${packageToDelete?.version}? This action cannot be undone.`"
|
||||
confirm-label="Delete version"
|
||||
title="Remove package version?"
|
||||
:description="`Remove ${packageToDelete?.name}@${packageToDelete?.version} from the cache? Clients can fetch it again from upstream.`"
|
||||
confirm-label="Remove version"
|
||||
tone="danger"
|
||||
destructive
|
||||
@confirm="deletePackage"
|
||||
@@ -136,130 +86,155 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
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'
|
||||
import { computed, onMounted, onUnmounted, ref, watch } from 'vue'
|
||||
import { RouterLink, useRoute, useRouter } from 'vue-router'
|
||||
import {
|
||||
Accordion,
|
||||
AccordionContent,
|
||||
AccordionItem,
|
||||
AccordionTrigger,
|
||||
Badge,
|
||||
Button,
|
||||
Card,
|
||||
CardContent,
|
||||
ConfirmDialog,
|
||||
DataTable,
|
||||
EmptyState,
|
||||
ErrorState,
|
||||
IconButton,
|
||||
FilterBar,
|
||||
LoadingState,
|
||||
PageHeader,
|
||||
Pagination,
|
||||
RelativeTime,
|
||||
SearchInput,
|
||||
SegmentedControl,
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
useToastStore,
|
||||
type DataTableColumn,
|
||||
type FilterField,
|
||||
type FilterItem,
|
||||
type SortState,
|
||||
} from '@perfect-design/ui'
|
||||
import VulnerabilityBadge from './VulnerabilityBadge.vue'
|
||||
import { formatBytes, formatDate, formatNumber, displayVersion, withVersionPrefix } from '@/lib/format'
|
||||
import { faBoxOpen, faMagnifyingGlass, faRotateRight, faTrash } from '@/lib/icons'
|
||||
import PackageQuickView from './parts/PackageQuickView.vue'
|
||||
import VerdictBadge from './parts/VerdictBadge.vue'
|
||||
import { usePackageStore, type ApiVerdict, type Package } from '../stores/packages'
|
||||
import { plural } from '@/lib/reason'
|
||||
import { displayVersion, formatBytes, formatNumber, withVersionPrefix } from '@/lib/format'
|
||||
import { packageRoute } from '@/lib/packages'
|
||||
import { usePackageRows, type RowQuery, type RowSort } from '@/lib/packageRows'
|
||||
import { faBoxOpen, faMagnifyingGlass, faRotateRight } from '@/lib/icons'
|
||||
import { VERDICT_OPTIONS, verdictOf } from '@/lib/verdict'
|
||||
|
||||
// Props from router
|
||||
const props = defineProps<{
|
||||
registry?: string
|
||||
}>()
|
||||
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
const store = usePackageStore()
|
||||
const toasts = useToastStore()
|
||||
const { packagePage, loading, error } = storeToRefs(store)
|
||||
|
||||
const showDeleteModal = ref(false)
|
||||
const packageToDelete = ref<Package | null>(null)
|
||||
const REGISTRY_OPTIONS = [
|
||||
{ value: 'all', label: 'All' },
|
||||
{ value: 'npm', label: 'npm' },
|
||||
{ value: 'pypi', label: 'PyPI' },
|
||||
{ value: 'go', label: 'Go' },
|
||||
]
|
||||
const props = defineProps<{ registry?: string }>()
|
||||
|
||||
const PAGE_SIZE = 25
|
||||
const SEARCH_DEBOUNCE_MS = 300
|
||||
const KNOWN_REGISTRIES = ['npm', 'go', 'pypi']
|
||||
|
||||
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 store = usePackageStore()
|
||||
const toasts = useToastStore()
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
const { rows, total, loading, error, load: loadRows } = usePackageRows()
|
||||
|
||||
const totalGroups = computed(() => packagePage.value.totalGroups)
|
||||
const totalPages = computed(() => Math.ceil(totalGroups.value / PAGE_SIZE))
|
||||
const filtersActive = computed(() => selectedRegistry.value !== 'all' || activeQuery.value.trim() !== '')
|
||||
const loaded = ref(false)
|
||||
const selected = ref<Package | null>(null)
|
||||
const showDeleteModal = ref(false)
|
||||
const packageToDelete = ref<Package | null>(null)
|
||||
const sort = ref<SortState | null>(null)
|
||||
const page = ref(1)
|
||||
|
||||
// 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),
|
||||
}))
|
||||
function queryText(key: string): string {
|
||||
const raw = route.query[key]
|
||||
return typeof raw === 'string' ? raw : ''
|
||||
}
|
||||
|
||||
const query = ref(queryText('q'))
|
||||
const searchTerm = ref(query.value)
|
||||
let searchTimer: ReturnType<typeof setTimeout> | undefined
|
||||
watch(query, (value) => {
|
||||
clearTimeout(searchTimer)
|
||||
searchTimer = setTimeout(() => (searchTerm.value = value), SEARCH_DEBOUNCE_MS)
|
||||
})
|
||||
onUnmounted(() => clearTimeout(searchTimer))
|
||||
|
||||
let nextFilterId = 0
|
||||
function filterItem(field: string, value: string): FilterItem {
|
||||
return { id: `f${nextFilterId++}`, field, operator: 'eq', value }
|
||||
}
|
||||
|
||||
// The path segment is the pre-redesign way to pick a registry, so it still seeds the filter.
|
||||
const filterItems = ref<FilterItem[]>(
|
||||
[
|
||||
...[props.registry || queryText('registry')].filter(Boolean).map((r) => filterItem('registry', r)),
|
||||
...[queryText('verdict')].filter(Boolean).map((v) => filterItem('verdict', v)),
|
||||
],
|
||||
)
|
||||
|
||||
const registryOptions = computed(() => {
|
||||
const seen = new Set([...KNOWN_REGISTRIES, ...rows.value.map((p) => p.registry), ...valuesOf('registry')])
|
||||
return [...seen].map((value) => ({ value, label: value }))
|
||||
})
|
||||
|
||||
const filterFields = computed<FilterField[]>(() => [
|
||||
{ id: 'registry', label: 'Registry', type: 'select', options: registryOptions.value, operators: ['eq'] },
|
||||
{ id: 'verdict', label: 'Verdict', type: 'select', options: VERDICT_OPTIONS, operators: ['eq'] },
|
||||
])
|
||||
|
||||
function valuesOf(field: string): string[] {
|
||||
return filterItems.value.filter((f) => f.field === field).map((f) => String(f.value))
|
||||
}
|
||||
|
||||
const SORT_KEYS: Record<string, RowSort> = {
|
||||
name: 'name',
|
||||
version: 'version',
|
||||
registry: 'registry',
|
||||
size: 'size',
|
||||
download_count: 'downloads',
|
||||
last_accessed: 'last_accessed',
|
||||
scanned: 'last_scanned',
|
||||
}
|
||||
|
||||
const rowQuery = computed<RowQuery>(() => ({
|
||||
q: searchTerm.value,
|
||||
registry: valuesOf('registry')[0],
|
||||
verdict: valuesOf('verdict')[0] as ApiVerdict | undefined,
|
||||
sort: sort.value ? SORT_KEYS[sort.value.key] : undefined,
|
||||
order: sort.value?.direction === 'desc' ? 'desc' : 'asc',
|
||||
page: page.value,
|
||||
pageSize: PAGE_SIZE,
|
||||
}))
|
||||
|
||||
const filtered = computed(() => Boolean(searchTerm.value.trim() || valuesOf('registry').length || valuesOf('verdict').length))
|
||||
const rangeStart = computed(() => (total.value === 0 ? 0 : (page.value - 1) * PAGE_SIZE + 1))
|
||||
const rangeEnd = computed(() => Math.min(page.value * PAGE_SIZE, total.value))
|
||||
|
||||
// A new search, filter or sort starts again from the first page.
|
||||
watch([searchTerm, filterItems, sort], () => (page.value = 1))
|
||||
|
||||
// The URL mirrors the filters so a reload or a shared link restores the view.
|
||||
watch([searchTerm, filterItems], () => {
|
||||
const { q: _q, registry: _r, verdict: _v, ...rest } = route.query
|
||||
const next: Record<string, string> = {}
|
||||
if (searchTerm.value.trim()) next.q = searchTerm.value.trim()
|
||||
const [registry] = valuesOf('registry')
|
||||
const [verdict] = valuesOf('verdict')
|
||||
if (registry) next.registry = registry
|
||||
if (verdict) next.verdict = verdict
|
||||
void router.replace({ path: '/packages', query: { ...rest, ...next } })
|
||||
})
|
||||
|
||||
const columns: DataTableColumn<Package>[] = [
|
||||
{ key: 'name', header: 'Package', sortable: true, rowHeader: true },
|
||||
{ key: 'version', header: 'Version', sortable: true, accessor: (p) => withVersionPrefix(displayVersion(p)) },
|
||||
{ key: 'registry', header: 'Registry', sortable: true },
|
||||
{ key: 'size', header: 'Size', sortable: true, numeric: true },
|
||||
{ key: 'download_count', header: 'Downloads', sortable: true, numeric: true },
|
||||
{ key: 'last_accessed', header: 'Last accessed', sortable: true, accessor: (p) => Date.parse(p.last_accessed) || 0 },
|
||||
{ key: 'verdict', header: 'Verdict' },
|
||||
{ key: 'scanned', header: 'Last scanned', sortable: true, accessor: (p) => Date.parse(p.vulnerabilities?.scannedAt ?? '') || 0 },
|
||||
]
|
||||
|
||||
async function load() {
|
||||
await store.fetchPackagePage({
|
||||
page: currentPage.value,
|
||||
pageSize: PAGE_SIZE,
|
||||
registry: selectedRegistry.value,
|
||||
q: activeQuery.value,
|
||||
})
|
||||
await loadRows(rowQuery.value)
|
||||
loaded.value = true
|
||||
}
|
||||
|
||||
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' })
|
||||
}
|
||||
}
|
||||
|
||||
// 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()
|
||||
})
|
||||
|
||||
watch(rowQuery, load)
|
||||
onMounted(load)
|
||||
|
||||
function confirmDelete(pkg: Package) {
|
||||
@@ -273,36 +248,15 @@ async function deletePackage() {
|
||||
await store.deletePackage(target.registry, target.name, target.version)
|
||||
showDeleteModal.value = false
|
||||
packageToDelete.value = null
|
||||
selected.value = null
|
||||
const label = `${target.name}@${target.version}`
|
||||
if (store.error) {
|
||||
toasts.error('Could not delete package', `${label}: ${store.error}`)
|
||||
toasts.error('Could not remove 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)
|
||||
toasts.success('Package removed', 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) {
|
||||
// Navigate to the package details page
|
||||
router.push({
|
||||
name: 'package-details',
|
||||
params: {
|
||||
registry,
|
||||
name,
|
||||
version,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
function changeRegistryFilter(registry: string) {
|
||||
const path = registry === 'all' ? '/packages' : `/packages/${registry}`
|
||||
router.push(path)
|
||||
}
|
||||
</script>
|
||||
|
||||
+76
-20
@@ -2,9 +2,10 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { createPinia, setActivePinia } from 'pinia'
|
||||
import axios from 'axios'
|
||||
import { flushPromises } from '@vue/test-utils'
|
||||
import VulnerablePackages from './VulnerablePackages.vue'
|
||||
import Security from './Security.vue'
|
||||
import type { Package, VulnerabilityCounts } from '@/stores/packages'
|
||||
import { mountStrict } from '@/test/mountStrict'
|
||||
import { serveRows } from '@/test/rowsServer'
|
||||
import { createTestRouter } from '@/test/router'
|
||||
|
||||
vi.mock('axios')
|
||||
@@ -31,7 +32,6 @@ function vulnerable(name: string, counts: Partial<VulnerabilityCounts>): Package
|
||||
}
|
||||
}
|
||||
|
||||
const ALL_SEVERITIES = 'critical,high,moderate,low'
|
||||
const FIXTURE: Package[] = [
|
||||
vulnerable('alpha-critical', { critical: 1 }),
|
||||
vulnerable('bravo-high', { high: 2 }),
|
||||
@@ -42,9 +42,13 @@ const NAMES = FIXTURE.map((p) => p.name)
|
||||
|
||||
let restore: (() => void) | undefined
|
||||
|
||||
function serve(packages: Package[]) {
|
||||
vi.mocked(axios.get).mockImplementation(async (url: string) => ({ data: serveRows(url, packages) }) as never)
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
setActivePinia(createPinia())
|
||||
vi.mocked(axios.get).mockResolvedValue({ data: { packages: FIXTURE } })
|
||||
serve(FIXTURE)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
@@ -53,11 +57,11 @@ afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
async function open(path = '/vulnerable-packages') {
|
||||
async function open(path = '/security?tab=allowed') {
|
||||
const router = await createTestRouter(path)
|
||||
const pinia = createPinia()
|
||||
setActivePinia(pinia)
|
||||
const mounted = await mountStrict(VulnerablePackages, { global: { plugins: [pinia, router] } })
|
||||
const mounted = await mountStrict(Security, { global: { plugins: [pinia, router] } })
|
||||
restore = mounted.restore
|
||||
await flushPromises()
|
||||
return { ...mounted, router }
|
||||
@@ -71,7 +75,7 @@ const pressed = (wrapper: Wrapper) =>
|
||||
wrapper.findAll('button[data-severity]').map((b) => b.attributes('aria-pressed'))
|
||||
const clearButtons = (wrapper: Wrapper) => wrapper.findAll('button').filter((b) => b.text() === 'Clear filters')
|
||||
|
||||
describe('VulnerablePackages severity filter', () => {
|
||||
describe('Security severity filter', () => {
|
||||
it('starts unfiltered: every vulnerable package, no tile pressed, no clear control', async () => {
|
||||
const { wrapper, problems, router } = await open()
|
||||
|
||||
@@ -83,9 +87,27 @@ describe('VulnerablePackages severity filter', () => {
|
||||
expect(router.currentRoute.value.query.severity).toBeUndefined()
|
||||
})
|
||||
|
||||
it('asks the server for vulnerable packages only', async () => {
|
||||
it('asks the server for one page of the open tab, worst first', async () => {
|
||||
await open()
|
||||
expect(axios.get).toHaveBeenCalledWith(`/api/packages?severity=${ALL_SEVERITIES}`)
|
||||
const url = vi.mocked(axios.get).mock.calls.map((c) => String(c[0])).find((u) => u.includes('layout=rows'))!
|
||||
const params = new URL(url, 'http://x').searchParams
|
||||
expect(Object.fromEntries(params)).toEqual({
|
||||
layout: 'rows',
|
||||
page: '1',
|
||||
page_size: '25',
|
||||
verdict: 'cleared',
|
||||
severity: 'critical,high,moderate,low',
|
||||
sort: 'risk',
|
||||
order: 'desc',
|
||||
})
|
||||
})
|
||||
|
||||
it('sends the selected severities with the open tab', async () => {
|
||||
const { wrapper } = await open()
|
||||
await tile(wrapper, 'high').trigger('click')
|
||||
await flushPromises()
|
||||
const last = String(vi.mocked(axios.get).mock.calls[vi.mocked(axios.get).mock.calls.length - 1]![0])
|
||||
expect(new URL(last, 'http://x').searchParams.get('severity')).toBe('high')
|
||||
})
|
||||
|
||||
it('renders the four tiles as keyboard-operable buttons in severity order', async () => {
|
||||
@@ -172,7 +194,7 @@ describe('VulnerablePackages severity filter', () => {
|
||||
})
|
||||
|
||||
it('restores the filter from the URL, as after a reload or a shared link', async () => {
|
||||
const { wrapper } = await open('/vulnerable-packages?severity=high,critical')
|
||||
const { wrapper } = await open('/security?tab=allowed&severity=high,critical')
|
||||
|
||||
expect(shown(wrapper)).toEqual(['alpha-critical', 'bravo-high', 'delta-mixed'])
|
||||
expect(pressed(wrapper)).toEqual(['true', 'true', 'false', 'false'])
|
||||
@@ -180,17 +202,17 @@ describe('VulnerablePackages severity filter', () => {
|
||||
})
|
||||
|
||||
it('ignores unknown severities in the URL and keeps the other query parameters', async () => {
|
||||
const { wrapper, router } = await open('/vulnerable-packages?severity=bogus&ref=mail')
|
||||
const { wrapper, router } = await open('/security?tab=allowed&severity=bogus&ref=mail')
|
||||
expect(shown(wrapper)).toEqual(NAMES)
|
||||
expect(clearButtons(wrapper)).toHaveLength(0)
|
||||
|
||||
await tile(wrapper, 'low').trigger('click')
|
||||
await flushPromises()
|
||||
expect(router.currentRoute.value.query).toEqual({ ref: 'mail', severity: 'low' })
|
||||
expect(router.currentRoute.value.query).toEqual({ tab: 'allowed', ref: 'mail', severity: 'low' })
|
||||
})
|
||||
|
||||
it('shows a library empty state with a clear control when no package matches', async () => {
|
||||
const { wrapper, router } = await open('/vulnerable-packages?severity=low')
|
||||
const { wrapper, router } = await open('/security?tab=allowed&severity=low')
|
||||
|
||||
const empty = wrapper.get('[data-slot="empty-state"]')
|
||||
expect(empty.text()).toContain('No packages match the filter')
|
||||
@@ -206,21 +228,55 @@ describe('VulnerablePackages severity filter', () => {
|
||||
expect(router.currentRoute.value.query.severity).toBeUndefined()
|
||||
})
|
||||
|
||||
it('keeps the success state when nothing is vulnerable, filter or not', async () => {
|
||||
vi.mocked(axios.get).mockResolvedValue({ data: { packages: [] } })
|
||||
const { wrapper } = await open('/vulnerable-packages?severity=critical')
|
||||
it('keeps the success state when nothing has findings, filter or not', async () => {
|
||||
serve([])
|
||||
const { wrapper } = await open('/security?tab=allowed&severity=critical')
|
||||
|
||||
expect(wrapper.text()).toContain('No vulnerable packages')
|
||||
expect(wrapper.text()).toContain('No package carries findings under the policy')
|
||||
expect(wrapper.find('button[data-severity]').exists()).toBe(false)
|
||||
})
|
||||
|
||||
it('still narrows to blocked packages on the blocked route', async () => {
|
||||
const blocked = vulnerable('echo-blocked', { critical: 1 })
|
||||
blocked.vulnerabilities!.isBlocked = true
|
||||
vi.mocked(axios.get).mockResolvedValue({ data: { packages: [...FIXTURE, blocked] } })
|
||||
it('lists a held package under Held, not under Vulnerable but allowed', async () => {
|
||||
const held = vulnerable('echo-blocked', { critical: 1 })
|
||||
held.vulnerabilities!.isBlocked = true
|
||||
held.vulnerabilities!.verdict = 'held'
|
||||
serve([...FIXTURE, held])
|
||||
const { wrapper } = await open('/blocked-packages?severity=critical')
|
||||
|
||||
expect(wrapper.text()).toContain('echo-blocked')
|
||||
expect(wrapper.text()).not.toContain('alpha-critical')
|
||||
})
|
||||
|
||||
it('lists a held package that has no findings, such as a failed scan', async () => {
|
||||
const failed = vulnerable('foxtrot-failed', {})
|
||||
failed.vulnerabilities = { scanned: true, status: 'clean', isBlocked: true, verdict: 'held', reason: 'scan failed - fail closed' }
|
||||
serve([failed])
|
||||
const { wrapper } = await open('/security?tab=held')
|
||||
|
||||
expect(wrapper.text()).toContain('foxtrot-failed')
|
||||
expect(wrapper.text()).toContain('scan failed - fail closed')
|
||||
})
|
||||
|
||||
it('pages through the server and resets to page 1 when the filter changes', async () => {
|
||||
const many = Array.from({ length: 30 }, (_, i) => vulnerable(`pkg-${String(i).padStart(2, '0')}`, { critical: 1 }))
|
||||
serve(many)
|
||||
const { wrapper } = await open()
|
||||
expect(wrapper.findAll('tbody tr')).toHaveLength(25)
|
||||
|
||||
await wrapper.get('nav[aria-label="Security pages"] button[aria-label*="ext"]').trigger('click')
|
||||
await flushPromises()
|
||||
expect(wrapper.findAll('tbody tr')).toHaveLength(5)
|
||||
expect(String(vi.mocked(axios.get).mock.calls[vi.mocked(axios.get).mock.calls.length - 1]![0])).toContain('page=2')
|
||||
|
||||
await tile(wrapper, 'critical').trigger('click')
|
||||
await flushPromises()
|
||||
expect(String(vi.mocked(axios.get).mock.calls[vi.mocked(axios.get).mock.calls.length - 1]![0])).toContain('page=1')
|
||||
})
|
||||
|
||||
it('takes the tab counts from the server, not from the rows on screen', async () => {
|
||||
const many = Array.from({ length: 30 }, (_, i) => vulnerable(`pkg-${i}`, { low: 1 }))
|
||||
serve(many)
|
||||
const { wrapper } = await open()
|
||||
expect(wrapper.findAll('[role="tab"]').map((t) => t.text())).toContain('Vulnerable but allowed (30)')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,236 @@
|
||||
<template>
|
||||
<div class="flex flex-col gap-6">
|
||||
<PageHeader title="Security" description="Packages the scanners found something in, and what the policy did about each.">
|
||||
<template #actions>
|
||||
<Button variant="outline" :icon-start="faRotateRight" @click="load">Refresh</Button>
|
||||
</template>
|
||||
</PageHeader>
|
||||
|
||||
<LoadingState v-if="loading && !loaded" variant="table" label="Loading security findings..." />
|
||||
|
||||
<ErrorState v-else-if="error" variant="card" title="Could not load security findings" :message="error" @retry="load" />
|
||||
|
||||
<template v-else>
|
||||
<SeveritySummary
|
||||
v-if="anyFindings"
|
||||
v-model="selectedSeverities"
|
||||
selectable
|
||||
label="Findings by severity. Select a severity to filter the packages."
|
||||
:counts="severityTotals"
|
||||
:package-counts="severityPackages"
|
||||
/>
|
||||
|
||||
<div v-if="hasFilter" class="flex flex-wrap items-center justify-between gap-3" data-testid="filter-bar">
|
||||
<p class="m-0 text-sm text-muted-foreground" role="status">Showing packages with {{ filterSummary }} vulnerabilities.</p>
|
||||
<Button variant="outline" size="sm" @click="selectedSeverities = []">Clear filters</Button>
|
||||
</div>
|
||||
|
||||
<Tabs v-model="tab">
|
||||
<TabsList aria-label="Security sections">
|
||||
<TabsTrigger v-for="t in TAB_DEFS" :key="t.value" :value="t.value">{{ t.label }} ({{ tabCount(t.value) }})</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<TabsContent v-for="t in TAB_DEFS" :key="t.value" :value="t.value" class="pt-4">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">{{ t.label }}</CardTitle>
|
||||
<CardDescription>{{ t.description }}</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<EmptyState
|
||||
v-if="total === 0"
|
||||
:icon="faCircleCheck"
|
||||
:title="hasFilter ? 'No packages match the filter' : t.empty"
|
||||
:description="hasFilter ? `No package here has a ${filterSummary} vulnerability.` : undefined"
|
||||
>
|
||||
<template v-if="hasFilter" #action>
|
||||
<Button variant="outline" @click="selectedSeverities = []">Clear filters</Button>
|
||||
</template>
|
||||
</EmptyState>
|
||||
<DataTable
|
||||
v-else
|
||||
v-model:sort="sort"
|
||||
:label="t.label"
|
||||
layout="cards"
|
||||
density="compact"
|
||||
row-clickable
|
||||
:loading="loading"
|
||||
:columns="columnsFor(t.value)"
|
||||
:rows="rows"
|
||||
@row-click="open"
|
||||
>
|
||||
<template #cell-name="{ row }">
|
||||
<RouterLink :to="packageRoute(row)" class="break-words font-medium text-foreground underline-offset-4 hover:underline">
|
||||
{{ row.name }}
|
||||
</RouterLink>
|
||||
</template>
|
||||
<template #cell-registry="{ row }"><Badge variant="outline">{{ row.registry }}</Badge></template>
|
||||
<template #cell-findings="{ row }">
|
||||
<VulnerabilityBadge
|
||||
v-if="row.vulnerabilities"
|
||||
:scanned="row.vulnerabilities.scanned"
|
||||
:status="row.vulnerabilities.status"
|
||||
:counts="row.vulnerabilities.counts"
|
||||
:total="row.vulnerabilities.total"
|
||||
@click="open(row)"
|
||||
/>
|
||||
</template>
|
||||
<template #cell-bypass="{ row }">
|
||||
<span v-if="row.vulnerabilities?.bypass" class="block text-sm">
|
||||
{{ row.vulnerabilities.bypass.created_by }}
|
||||
<span class="block text-xs text-muted-foreground">
|
||||
expires <RelativeTime :datetime="row.vulnerabilities.bypass.expires_at" />
|
||||
</span>
|
||||
</span>
|
||||
</template>
|
||||
<template #cell-scanned="{ row }">
|
||||
<RelativeTime v-if="row.vulnerabilities?.scannedAt" :datetime="row.vulnerabilities.scannedAt" />
|
||||
</template>
|
||||
</DataTable>
|
||||
<Pagination
|
||||
v-if="total > PAGE_SIZE"
|
||||
v-model:page="page"
|
||||
class="mt-4"
|
||||
:total="total"
|
||||
:page-size="PAGE_SIZE"
|
||||
aria-label="Security pages"
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import { RouterLink, useRoute, useRouter } from 'vue-router'
|
||||
import {
|
||||
Badge,
|
||||
Button,
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
DataTable,
|
||||
EmptyState,
|
||||
ErrorState,
|
||||
LoadingState,
|
||||
PageHeader,
|
||||
Pagination,
|
||||
RelativeTime,
|
||||
Tabs,
|
||||
TabsContent,
|
||||
TabsList,
|
||||
TabsTrigger,
|
||||
type DataTableColumn,
|
||||
type SortState,
|
||||
} from '@perfect-design/ui'
|
||||
import SeveritySummary from './SeveritySummary.vue'
|
||||
import VulnerabilityBadge from './VulnerabilityBadge.vue'
|
||||
import type { Package, VulnerabilityCounts } from '../stores/packages'
|
||||
import { displayVersion, withVersionPrefix } from '@/lib/format'
|
||||
import { packageRoute } from '@/lib/packages'
|
||||
import { usePackageRows, type RowQuery, type RowSort } from '@/lib/packageRows'
|
||||
import { humanReason } from '@/lib/reason'
|
||||
import { faCircleCheck, faRotateRight } from '@/lib/icons'
|
||||
import { SEVERITY_LEVELS, formatSeverityName, type SeverityLevel } from '@/lib/severity'
|
||||
|
||||
type TabName = 'held' | 'allowed' | 'bypassed'
|
||||
|
||||
const TAB_DEFS: ReadonlyArray<{ value: TabName; label: string; description: string; empty: string }> = [
|
||||
{ value: 'held', label: 'Held', description: 'At or over the block policy. Clients get a 403 until the package is fixed or bypassed.', empty: 'Nothing is held' },
|
||||
{ value: 'allowed', label: 'Vulnerable but allowed', description: 'Findings exist, but none reach the block policy. Clients are served these.', empty: 'No package carries findings under the policy' },
|
||||
{ value: 'bypassed', label: 'Bypassed', description: 'An admin bypass lets these through despite their findings.', empty: 'No bypass is in effect' },
|
||||
]
|
||||
|
||||
const PAGE_SIZE = 25
|
||||
const SEVERITY_QUERY = 'severity'
|
||||
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
const { rows, total, counts, loading, error, load: loadRows } = usePackageRows()
|
||||
|
||||
const loaded = ref(false)
|
||||
const page = ref(1)
|
||||
const sort = ref<SortState | null>(null)
|
||||
|
||||
const tab = ref<TabName>(TAB_DEFS.find((t) => t.value === route.query.tab)?.value ?? 'held')
|
||||
watch(tab, (value) => void router.replace({ query: { ...route.query, tab: value } }))
|
||||
|
||||
/** Reads `?severity=critical,high`: known levels only, in severity order, each once. */
|
||||
function parseSeverityQuery(raw: unknown): SeverityLevel[] {
|
||||
const text = Array.isArray(raw) ? raw.join(',') : typeof raw === 'string' ? raw : ''
|
||||
const wanted = text.split(',').map((part) => part.trim().toLowerCase())
|
||||
return SEVERITY_LEVELS.filter((level) => wanted.includes(level))
|
||||
}
|
||||
|
||||
// The URL is the source of truth, so a reload or a shared link restores the filter.
|
||||
const selectedSeverities = computed<SeverityLevel[]>({
|
||||
get: () => parseSeverityQuery(route.query[SEVERITY_QUERY]),
|
||||
set: (levels) => {
|
||||
const { [SEVERITY_QUERY]: _previous, ...rest } = route.query
|
||||
void router.replace({ query: levels.length > 0 ? { ...rest, [SEVERITY_QUERY]: levels.join(',') } : rest })
|
||||
},
|
||||
})
|
||||
|
||||
const anyFindings = computed(() => counts.value.verdicts.held + counts.value.vulnerable_allowed + counts.value.verdicts.bypassed > 0)
|
||||
// With nothing to filter the tiles are hidden, so a leftover ?severity= must not claim a filter is on.
|
||||
const hasFilter = computed(() => selectedSeverities.value.length > 0 && anyFindings.value)
|
||||
const filterSummary = computed(() => selectedSeverities.value.map((level) => formatSeverityName(level).toLowerCase()).join(' or '))
|
||||
|
||||
function tabCount(name: TabName): number {
|
||||
if (name === 'held') return counts.value.verdicts.held
|
||||
if (name === 'bypassed') return counts.value.verdicts.bypassed
|
||||
return counts.value.vulnerable_allowed
|
||||
}
|
||||
|
||||
const severityTotals = computed<VulnerabilityCounts>(() => ({ ...counts.value.severity_findings }))
|
||||
const severityPackages = computed<VulnerabilityCounts>(() => ({ ...counts.value.severity_packages }))
|
||||
|
||||
const SORT_KEYS: Record<string, RowSort> = { name: 'name', version: 'version', registry: 'registry', scanned: 'last_scanned' }
|
||||
|
||||
// "Vulnerable but allowed" is the cleared packages that have findings, so it always filters by severity.
|
||||
const rowQuery = computed<RowQuery>(() => {
|
||||
const severity = selectedSeverities.value.length > 0 ? selectedSeverities.value : tab.value === 'allowed' ? SEVERITY_LEVELS : []
|
||||
return {
|
||||
verdict: tab.value === 'allowed' ? 'cleared' : tab.value,
|
||||
severity,
|
||||
// Worst first unless the operator picked a column.
|
||||
sort: sort.value ? SORT_KEYS[sort.value.key] : 'risk',
|
||||
order: sort.value ? (sort.value.direction === 'desc' ? 'desc' : 'asc') : 'desc',
|
||||
page: page.value,
|
||||
pageSize: PAGE_SIZE,
|
||||
}
|
||||
})
|
||||
|
||||
watch([tab, selectedSeverities, sort], () => (page.value = 1))
|
||||
|
||||
const BASE_COLUMNS: DataTableColumn<Package>[] = [
|
||||
{ key: 'name', header: 'Package', sortable: true, rowHeader: true },
|
||||
{ key: 'version', header: 'Version', sortable: true, accessor: (p) => withVersionPrefix(displayVersion(p)) },
|
||||
{ key: 'registry', header: 'Registry', sortable: true },
|
||||
{ key: 'findings', header: 'Findings', accessor: (p) => p.vulnerabilities?.total ?? 0 },
|
||||
]
|
||||
const SCANNED: DataTableColumn<Package> = { key: 'scanned', header: 'Last scanned', sortable: true, accessor: (p) => Date.parse(p.vulnerabilities?.scannedAt ?? '') || 0 }
|
||||
|
||||
function columnsFor(name: TabName): DataTableColumn<Package>[] {
|
||||
if (name === 'held') return [...BASE_COLUMNS, { key: 'reason', header: 'Why', accessor: (p) => humanReason(p.vulnerabilities?.reason) }, SCANNED]
|
||||
if (name === 'bypassed') return [...BASE_COLUMNS, { key: 'bypass', header: 'Bypass', accessor: (p) => p.vulnerabilities?.bypass?.created_by ?? '' }, SCANNED]
|
||||
return [...BASE_COLUMNS, SCANNED]
|
||||
}
|
||||
|
||||
function open(pkg: Package) {
|
||||
void router.push(packageRoute(pkg))
|
||||
}
|
||||
|
||||
async function load() {
|
||||
await loadRows(rowQuery.value)
|
||||
loaded.value = true
|
||||
}
|
||||
|
||||
watch(rowQuery, load)
|
||||
onMounted(load)
|
||||
</script>
|
||||
@@ -1,5 +1,5 @@
|
||||
<template>
|
||||
<StatGroup :columns="4" :aria-label="label">
|
||||
<StatGroup :columns="4" class="grid-cols-2! lg:grid-cols-4!" :aria-label="label">
|
||||
<template v-if="selectable">
|
||||
<KpiTile
|
||||
v-for="level in SEVERITY_LEVELS"
|
||||
@@ -10,7 +10,7 @@
|
||||
:label="formatSeverityName(level)"
|
||||
:value="counts[level]"
|
||||
:aria-pressed="isSelected(level)"
|
||||
:class="isSelected(level) && 'ring-2 ring-primary'"
|
||||
:class="['text-left', isSelected(level) && 'ring-2 ring-primary']"
|
||||
:data-severity="level"
|
||||
@click="toggle(level)"
|
||||
>
|
||||
@@ -34,6 +34,7 @@
|
||||
<script setup lang="ts">
|
||||
import { KpiTile, StatGroup, StatusDot } from '@perfect-design/ui'
|
||||
import type { VulnerabilityCounts } from '../stores/packages'
|
||||
import { plural } from '@/lib/reason'
|
||||
import { SEVERITY_LEVELS, SEVERITY_TONES, formatSeverityName, type SeverityLevel } from '@/lib/severity'
|
||||
|
||||
const props = defineProps<{
|
||||
@@ -60,6 +61,6 @@ function toggle(level: SeverityLevel) {
|
||||
}
|
||||
|
||||
function formatPackageCount(n: number): string {
|
||||
return `${n} package${n === 1 ? '' : 's'}`
|
||||
return plural(n, 'package')
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -1,252 +0,0 @@
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest'
|
||||
import { mount as mountWith } from '@vue/test-utils'
|
||||
import { createPinia, setActivePinia } from 'pinia'
|
||||
import Stats from './Stats.vue'
|
||||
import { createTestRouter } from '@/test/router'
|
||||
import { usePackageStore } from '../stores/packages'
|
||||
|
||||
describe('Stats.vue', () => {
|
||||
let router: Awaited<ReturnType<typeof createTestRouter>>
|
||||
const mount = (component: typeof Stats) => mountWith(component, { global: { plugins: [router] } })
|
||||
|
||||
beforeEach(async () => {
|
||||
setActivePinia(createPinia())
|
||||
router = await createTestRouter('/stats')
|
||||
})
|
||||
|
||||
it('renders stats component', () => {
|
||||
const wrapper = mount(Stats)
|
||||
expect(wrapper.find('h1').text()).toBe('Statistics')
|
||||
})
|
||||
|
||||
it('displays loading state when loading', async () => {
|
||||
const wrapper = mount(Stats)
|
||||
const store = usePackageStore()
|
||||
|
||||
store.loading = true
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
expect(wrapper.text()).toContain('Loading statistics...')
|
||||
})
|
||||
|
||||
it('displays error message when error occurs', async () => {
|
||||
const store = usePackageStore()
|
||||
vi.spyOn(store, 'fetchStats').mockResolvedValue()
|
||||
const wrapper = mount(Stats)
|
||||
|
||||
store.loading = false
|
||||
store.error = 'Failed to fetch statistics'
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
expect(wrapper.text()).toContain('Failed to fetch statistics')
|
||||
})
|
||||
|
||||
it('displays overall statistics', async () => {
|
||||
const wrapper = mount(Stats)
|
||||
const store = usePackageStore()
|
||||
|
||||
store.loading = false
|
||||
store.stats = {
|
||||
registry: '',
|
||||
total_packages: 100,
|
||||
total_size: 1073741824, // 1 GB
|
||||
max_cache_size: 10737418240,
|
||||
total_downloads: 500,
|
||||
scanned_packages: 90,
|
||||
vulnerable_packages: 5,
|
||||
blocked_packages: 0,
|
||||
}
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
expect(wrapper.text()).toContain('Overall statistics')
|
||||
expect(wrapper.text()).toContain('100')
|
||||
expect(wrapper.text()).toContain('500')
|
||||
})
|
||||
|
||||
it('displays security scanning statistics', async () => {
|
||||
const wrapper = mount(Stats)
|
||||
const store = usePackageStore()
|
||||
|
||||
store.loading = false
|
||||
store.stats = {
|
||||
registry: '',
|
||||
total_packages: 100,
|
||||
total_size: 1073741824,
|
||||
max_cache_size: 10737418240,
|
||||
total_downloads: 500,
|
||||
scanned_packages: 90,
|
||||
vulnerable_packages: 5,
|
||||
blocked_packages: 0,
|
||||
}
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
expect(wrapper.text()).toContain('Security scanning')
|
||||
expect(wrapper.text()).toContain('Scanned packages')
|
||||
expect(wrapper.text()).toContain('Vulnerable packages')
|
||||
})
|
||||
|
||||
it('displays registry breakdown', async () => {
|
||||
const wrapper = mount(Stats)
|
||||
const store = usePackageStore()
|
||||
|
||||
store.loading = false
|
||||
store.stats = {
|
||||
registry: '',
|
||||
total_packages: 100,
|
||||
total_size: 1073741824,
|
||||
max_cache_size: 10737418240,
|
||||
total_downloads: 500,
|
||||
scanned_packages: 90,
|
||||
vulnerable_packages: 5,
|
||||
blocked_packages: 0,
|
||||
}
|
||||
store.registries = {
|
||||
npm: {
|
||||
count: 50,
|
||||
size: 536870912, // 512 MB
|
||||
downloads: 300,
|
||||
},
|
||||
pypi: {
|
||||
count: 30,
|
||||
size: 322122547, // ~307 MB
|
||||
downloads: 150,
|
||||
},
|
||||
go: {
|
||||
count: 20,
|
||||
size: 214748365, // ~205 MB
|
||||
downloads: 50,
|
||||
},
|
||||
}
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
expect(wrapper.text()).toContain('Registry breakdown')
|
||||
expect(wrapper.text()).toContain('npm')
|
||||
expect(wrapper.text()).toContain('PyPI')
|
||||
expect(wrapper.text()).toContain('Go modules')
|
||||
// The cards layout prefixes each cell with its column label.
|
||||
const packageCounts = wrapper
|
||||
.findAll('tbody tr')
|
||||
.map((row) => row.findAll('td')[0].text().replace(/^Packages/, ''))
|
||||
expect(packageCounts).toEqual(['50', '30', '20'])
|
||||
})
|
||||
|
||||
it('formats bytes correctly in overall stats', async () => {
|
||||
const wrapper = mount(Stats)
|
||||
const store = usePackageStore()
|
||||
|
||||
store.loading = false
|
||||
store.stats = {
|
||||
registry: '',
|
||||
total_packages: 100,
|
||||
total_size: 1073741824, // 1 GB
|
||||
max_cache_size: 10737418240,
|
||||
total_downloads: 500,
|
||||
scanned_packages: 90,
|
||||
vulnerable_packages: 5,
|
||||
blocked_packages: 0,
|
||||
}
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
expect(wrapper.text()).toContain('1 GB')
|
||||
})
|
||||
|
||||
it('calls fetchStats on mount', () => {
|
||||
const store = usePackageStore()
|
||||
const fetchSpy = vi.spyOn(store, 'fetchStats')
|
||||
|
||||
mount(Stats)
|
||||
|
||||
expect(fetchSpy).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('lists the registries in the order the API reports them', async () => {
|
||||
const wrapper = mount(Stats)
|
||||
const store = usePackageStore()
|
||||
|
||||
store.loading = false
|
||||
store.stats = {
|
||||
registry: '',
|
||||
total_packages: 3,
|
||||
total_size: 0,
|
||||
max_cache_size: 10737418240,
|
||||
total_downloads: 0,
|
||||
scanned_packages: 0,
|
||||
vulnerable_packages: 0,
|
||||
blocked_packages: 0,
|
||||
}
|
||||
store.registries = {
|
||||
npm: { count: 1, size: 0, downloads: 0 },
|
||||
pypi: { count: 1, size: 0, downloads: 0 },
|
||||
go: { count: 1, size: 0, downloads: 0 },
|
||||
}
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
const labels = wrapper.findAll('tbody th').map((cell) => cell.text().replace(/^Registry/, ''))
|
||||
expect(labels).toEqual(['npm', 'PyPI', 'Go modules'])
|
||||
})
|
||||
|
||||
it('handles empty registries data', async () => {
|
||||
const wrapper = mount(Stats)
|
||||
const store = usePackageStore()
|
||||
|
||||
store.loading = false
|
||||
store.stats = {
|
||||
registry: '',
|
||||
total_packages: 0,
|
||||
total_size: 0,
|
||||
max_cache_size: 10737418240,
|
||||
total_downloads: 0,
|
||||
scanned_packages: 0,
|
||||
vulnerable_packages: 0,
|
||||
blocked_packages: 0,
|
||||
}
|
||||
store.registries = {}
|
||||
await wrapper.vm.$nextTick()
|
||||
|
||||
expect(wrapper.text()).toContain('Registry breakdown')
|
||||
expect(wrapper.findAll('tbody th')).toHaveLength(0)
|
||||
expect(wrapper.text()).toContain('No registries reported')
|
||||
})
|
||||
|
||||
describe('idle eviction note', () => {
|
||||
const baseStats = {
|
||||
registry: '',
|
||||
total_packages: 100,
|
||||
total_size: 1073741824,
|
||||
max_cache_size: 10737418240,
|
||||
total_downloads: 500,
|
||||
scanned_packages: 90,
|
||||
vulnerable_packages: 5,
|
||||
blocked_packages: 0,
|
||||
}
|
||||
|
||||
async function render(idleTtl?: number) {
|
||||
const wrapper = mount(Stats)
|
||||
const store = usePackageStore()
|
||||
store.loading = false
|
||||
store.stats = idleTtl === undefined ? { ...baseStats } : { ...baseStats, idle_ttl: idleTtl }
|
||||
await wrapper.vm.$nextTick()
|
||||
return wrapper
|
||||
}
|
||||
|
||||
it.each([
|
||||
[604800, 'Cached items not requested for 7 days are removed.'],
|
||||
[86400, 'Cached items not requested for 1 day are removed.'],
|
||||
[129600, 'Cached items not requested for 36 hours are removed.'],
|
||||
[5400, 'Cached items not requested for 90 minutes are removed.'],
|
||||
])('shows the window for idle_ttl=%i', async (seconds, sentence) => {
|
||||
const wrapper = await render(seconds)
|
||||
expect(wrapper.text()).toContain(sentence)
|
||||
})
|
||||
|
||||
it('hides the note when idle eviction is off', async () => {
|
||||
const wrapper = await render(0)
|
||||
expect(wrapper.text()).not.toContain('not requested')
|
||||
})
|
||||
|
||||
it('hides the note when the API sends no idle_ttl', async () => {
|
||||
const wrapper = await render()
|
||||
expect(wrapper.text()).not.toContain('not requested')
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,191 +0,0 @@
|
||||
<template>
|
||||
<div class="flex flex-col gap-6">
|
||||
<PageHeader title="Statistics" description="Storage, traffic and scan results across every registry." />
|
||||
|
||||
<LoadingState v-if="loading" variant="kpi-grid" :columns="3" label="Loading statistics..." />
|
||||
|
||||
<ErrorState
|
||||
v-else-if="error"
|
||||
variant="card"
|
||||
title="Could not load statistics"
|
||||
:message="error"
|
||||
@retry="refresh"
|
||||
/>
|
||||
|
||||
<template v-else>
|
||||
<Alert v-if="idleTtl > 0" variant="info">
|
||||
<AlertDescription>Cached items not requested for {{ formatDuration(idleTtl) }} are removed.</AlertDescription>
|
||||
</Alert>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">Overall statistics</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<StatGroup :columns="3" aria-label="Overall statistics">
|
||||
<KpiTile label="Total packages" :value="stats?.total_packages || 0" :icon="faBoxesStacked" />
|
||||
<KpiTile
|
||||
label="Storage used"
|
||||
:value="`${formatBytes(stats?.total_size || 0)} / ${formatBytes(stats?.max_cache_size || 0)}`"
|
||||
:hint="`${storagePercentage.toFixed(1)}% used`"
|
||||
:progress="storagePercentage"
|
||||
:tone="storageTone"
|
||||
:icon="faHardDrive"
|
||||
/>
|
||||
<KpiTile label="Total downloads" :value="stats?.total_downloads || 0" :icon="faDownload" />
|
||||
</StatGroup>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">Security scanning</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<StatGroup :columns="3" aria-label="Security scanning">
|
||||
<KpiTile label="Scanned packages" :value="stats?.scanned_packages || 0" :icon="faCircleCheck" />
|
||||
<KpiTile
|
||||
as="button"
|
||||
type="button"
|
||||
variant="interactive"
|
||||
label="Vulnerable packages"
|
||||
:value="stats?.vulnerable_packages || 0"
|
||||
:hint="(stats?.vulnerable_packages || 0) > 0 ? 'View the list' : undefined"
|
||||
:icon="faTriangleExclamation"
|
||||
:disabled="(stats?.vulnerable_packages || 0) === 0"
|
||||
@click="showVulnerablePackages"
|
||||
/>
|
||||
<KpiTile
|
||||
as="button"
|
||||
type="button"
|
||||
variant="interactive"
|
||||
label="Blocked packages"
|
||||
:value="stats?.blocked_packages || 0"
|
||||
:hint="(stats?.blocked_packages || 0) > 0 ? 'View the list' : undefined"
|
||||
:icon="faBan"
|
||||
:disabled="(stats?.blocked_packages || 0) === 0"
|
||||
@click="showBlockedPackages"
|
||||
/>
|
||||
</StatGroup>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<TrendChart />
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">Registry breakdown</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<DataTable
|
||||
label="Registry breakdown"
|
||||
layout="cards"
|
||||
row-key="name"
|
||||
empty-text="No registries reported"
|
||||
:columns="registryColumns"
|
||||
:rows="registries"
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted } from 'vue'
|
||||
import { storeToRefs } from 'pinia'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { usePackageStore } from '../stores/packages'
|
||||
import {
|
||||
Alert,
|
||||
AlertDescription,
|
||||
Card,
|
||||
CardContent,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
DataTable,
|
||||
ErrorState,
|
||||
KpiTile,
|
||||
LoadingState,
|
||||
PageHeader,
|
||||
StatGroup,
|
||||
type DataTableColumn,
|
||||
} from '@perfect-design/ui'
|
||||
import TrendChart from './TrendChart.vue'
|
||||
import { formatBytes, formatDuration, formatNumber } from '@/lib/format'
|
||||
import { faBan, faDownload, faHardDrive, faBoxesStacked, faCircleCheck, faTriangleExclamation } from '@/lib/icons'
|
||||
|
||||
const store = usePackageStore()
|
||||
const { stats, loading, error } = storeToRefs(store)
|
||||
const router = useRouter()
|
||||
|
||||
onMounted(async () => {
|
||||
await store.fetchStats()
|
||||
})
|
||||
|
||||
function showVulnerablePackages() {
|
||||
if ((stats.value?.vulnerable_packages || 0) === 0) {
|
||||
return
|
||||
}
|
||||
|
||||
router.push('/vulnerable-packages')
|
||||
}
|
||||
|
||||
function showBlockedPackages() {
|
||||
if ((stats.value?.blocked_packages || 0) === 0) {
|
||||
return
|
||||
}
|
||||
|
||||
router.push('/blocked-packages')
|
||||
}
|
||||
|
||||
const REGISTRY_LABELS: Record<string, string> = {
|
||||
npm: 'npm',
|
||||
pypi: 'PyPI',
|
||||
go: 'Go modules',
|
||||
}
|
||||
|
||||
interface RegistryRow {
|
||||
name: string
|
||||
label: string
|
||||
packages: number
|
||||
size: string
|
||||
downloads: number
|
||||
}
|
||||
|
||||
const registryColumns: DataTableColumn<RegistryRow>[] = [
|
||||
{ key: 'label', header: 'Registry', rowHeader: true },
|
||||
{ key: 'packages', header: 'Packages', numeric: true, accessor: (r) => formatNumber(r.packages) },
|
||||
{ key: 'size', header: 'Size', numeric: true },
|
||||
{ key: 'downloads', header: 'Downloads', numeric: true, accessor: (r) => formatNumber(r.downloads) },
|
||||
]
|
||||
|
||||
const registries = computed(() => {
|
||||
const apiRegistries = store.registries || {}
|
||||
return Object.entries(apiRegistries).map(([name, data]: [string, any]): RegistryRow => ({
|
||||
name,
|
||||
label: REGISTRY_LABELS[name] ?? name.toUpperCase(),
|
||||
packages: data.count || 0,
|
||||
size: formatBytes(data.size || 0),
|
||||
downloads: data.downloads || 0,
|
||||
}))
|
||||
})
|
||||
|
||||
const idleTtl = computed(() => stats.value?.idle_ttl || 0)
|
||||
|
||||
const storagePercentage = computed(() => {
|
||||
const totalSize = stats.value?.total_size || 0
|
||||
const maxSize = stats.value?.max_cache_size || 1
|
||||
return (totalSize / maxSize) * 100
|
||||
})
|
||||
|
||||
const storageTone = computed(() => {
|
||||
if (storagePercentage.value >= 90) return 'danger'
|
||||
if (storagePercentage.value >= 50) return 'warning'
|
||||
return 'success'
|
||||
})
|
||||
|
||||
function refresh() {
|
||||
void store.fetchStats()
|
||||
}
|
||||
</script>
|
||||
@@ -0,0 +1,186 @@
|
||||
<template>
|
||||
<div class="flex flex-col gap-6">
|
||||
<PageHeader title="System" description="The policy the proxy applies, the scanners behind it, and the settings that shape the cache.">
|
||||
<template #actions>
|
||||
<Badge v-if="info" variant="outline" class="font-mono" data-testid="build-version">{{ info.version }}</Badge>
|
||||
<Button variant="outline" :icon-start="faRotateRight" @click="load(true)">Refresh</Button>
|
||||
</template>
|
||||
</PageHeader>
|
||||
|
||||
<LoadingState v-if="!info && !error" variant="card" label="Loading system settings..." />
|
||||
<ErrorState v-else-if="!info" variant="card" title="Could not load system settings" :message="error ?? ''" @retry="load(true)" />
|
||||
|
||||
<template v-else>
|
||||
<div class="grid gap-6 lg:grid-cols-2">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">Policy</CardTitle>
|
||||
<CardDescription>What clears a package and what holds it.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<DescriptionList :columns="1" divided data-testid="policy-list">
|
||||
<DescriptionItem term="Scanning">
|
||||
<StatusBadge :status="info.security.enabled ? 'on' : 'off'" :label="info.security.enabled ? 'On' : 'Off'" :tones="{ on: 'success', off: 'neutral' }" />
|
||||
</DescriptionItem>
|
||||
<DescriptionItem term="Block policy">{{ describePolicy(info.security) }}</DescriptionItem>
|
||||
<DescriptionItem term="When a scan fails">
|
||||
{{ info.security.fail_closed ? 'Fail-closed. The package is held.' : 'Fail-open on scanner outage. The package is served and the scan retried.' }}
|
||||
</DescriptionItem>
|
||||
<DescriptionItem term="Scan on download">{{ info.security.scan_on_download ? 'Yes' : 'No' }}</DescriptionItem>
|
||||
<DescriptionItem term="First download waits">up to {{ formatDuration(info.security.scan_wait_timeout) }} for its scan</DescriptionItem>
|
||||
</DescriptionList>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">Rescans</CardTitle>
|
||||
<CardDescription>Cached packages are inspected again as advisories change.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<DescriptionList :columns="1" divided data-testid="rescan-list">
|
||||
<DescriptionItem term="Interval">{{ duration(info.security.rescan.interval, 'Rescans are off') }}</DescriptionItem>
|
||||
<DescriptionItem term="Active window">{{ duration(info.security.rescan.active_window, 'Every cached package') }}</DescriptionItem>
|
||||
<DescriptionItem term="Parallel scans">{{ info.security.rescan.concurrency }}</DescriptionItem>
|
||||
<DescriptionItem term="Rescan on access">{{ info.security.rescan.on_access ? 'Yes. A stale hit is rescanned before it is served.' : 'No' }}</DescriptionItem>
|
||||
</DescriptionList>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<RescanPanel :enabled="info.security.enabled" :concurrency="info.security.rescan.concurrency" />
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">Inspectors</CardTitle>
|
||||
<CardDescription>Health is probed at most every 30 seconds. A scanner that is off is not probed.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<DataTable label="Scanners" layout="cards" density="compact" row-key="name" :columns="scannerColumns" :rows="info.security.scanners">
|
||||
<template #cell-name="{ row }"><span class="font-medium">{{ row.name }}</span></template>
|
||||
<template #cell-state="{ row }">
|
||||
<StatusBadge :status="scannerState(row)" :label="STATE_LABELS[scannerState(row)]" :tones="STATE_TONES" />
|
||||
</template>
|
||||
<template #cell-version="{ row }">{{ scannerVersion(row) || 'Not applicable' }}</template>
|
||||
</DataTable>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<div class="grid gap-6 lg:grid-cols-2">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">Cache</CardTitle>
|
||||
<CardDescription>Limits and where packages come from.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<DescriptionList :columns="1" divided data-testid="cache-list">
|
||||
<DescriptionItem term="Size limit">{{ info.cache.max_size > 0 ? formatBytes(info.cache.max_size) : 'None' }}</DescriptionItem>
|
||||
<DescriptionItem term="Idle eviction">{{ duration(info.cache.idle_ttl, 'Off', 'Removed after ', ' without a request') }}</DescriptionItem>
|
||||
<DescriptionItem term="Default TTL">{{ duration(info.cache.default_ttl, 'None') }}</DescriptionItem>
|
||||
<DescriptionItem v-for="(host, registry) in info.upstreams" :key="registry" :term="`Upstream ${registry}`">{{ host || 'Not set' }}</DescriptionItem>
|
||||
</DescriptionList>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card data-testid="prewarming">
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">Pre-warming</CardTitle>
|
||||
<CardDescription>Fetches the most requested packages ahead of clients.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent class="flex flex-col gap-4">
|
||||
<DescriptionList :columns="1" divided>
|
||||
<DescriptionItem term="Status">
|
||||
<StatusBadge :status="info.prewarming.enabled ? 'on' : 'off'" :label="info.prewarming.enabled ? 'On' : 'Off'" :tones="{ on: 'success', off: 'neutral' }" />
|
||||
</DescriptionItem>
|
||||
<DescriptionItem term="Interval">{{ duration(info.prewarming.interval, 'None') }}</DescriptionItem>
|
||||
<DescriptionItem term="Top packages">{{ info.prewarming.top_packages }}</DescriptionItem>
|
||||
</DescriptionList>
|
||||
<div class="flex flex-col gap-2 sm:flex-row sm:items-center">
|
||||
<Button :icon-start="faRotateRight" :loading="triggering" :disabled="!info.prewarming.enabled" @click="trigger">Run a cycle now</Button>
|
||||
<p class="m-0 text-sm text-muted-foreground">
|
||||
{{ info.prewarming.enabled ? 'Needs the admin API key.' : 'Pre-warming is off in the configuration.' }}
|
||||
</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<AdminKeyDialog v-model:open="showKeyDialog" description="Enter your admin API key to start a pre-warming cycle." @saved="trigger" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { onMounted, ref } from 'vue'
|
||||
import axios from 'axios'
|
||||
import {
|
||||
Badge,
|
||||
Button,
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
DataTable,
|
||||
DescriptionItem,
|
||||
DescriptionList,
|
||||
ErrorState,
|
||||
LoadingState,
|
||||
PageHeader,
|
||||
StatusBadge,
|
||||
useToastStore,
|
||||
type DataTableColumn,
|
||||
} from '@perfect-design/ui'
|
||||
import AdminKeyDialog from './parts/AdminKeyDialog.vue'
|
||||
import RescanPanel from './parts/RescanPanel.vue'
|
||||
import { useAdminKey } from '@/lib/adminKey'
|
||||
import { formatBytes, formatDuration } from '@/lib/format'
|
||||
import { faRotateRight } from '@/lib/icons'
|
||||
import { describePolicy, scannerState, scannerVersion, useSystem, type ScannerInfo } from '@/lib/system'
|
||||
|
||||
const { info, error, load } = useSystem()
|
||||
const adminKey = useAdminKey()
|
||||
const toasts = useToastStore()
|
||||
|
||||
const triggering = ref(false)
|
||||
const showKeyDialog = ref(false)
|
||||
|
||||
const STATE_LABELS = { healthy: 'Healthy', down: 'Unavailable', off: 'Off' }
|
||||
const STATE_TONES = { healthy: 'success', down: 'danger', off: 'neutral' } as const
|
||||
|
||||
const scannerColumns: DataTableColumn<ScannerInfo>[] = [
|
||||
{ key: 'name', header: 'Scanner', rowHeader: true },
|
||||
{ key: 'state', header: 'State', accessor: (s) => scannerState(s) },
|
||||
{ key: 'version', header: 'Version' },
|
||||
]
|
||||
|
||||
/** Seconds as words; zero means the feature is off, so `zero` explains that. */
|
||||
function duration(seconds: number, zero: string, before = '', after = ''): string {
|
||||
return seconds === 0 ? zero : `${before}${formatDuration(seconds)}${after}`
|
||||
}
|
||||
|
||||
async function trigger() {
|
||||
adminKey.load()
|
||||
if (!adminKey.key.value) {
|
||||
showKeyDialog.value = true
|
||||
return
|
||||
}
|
||||
triggering.value = true
|
||||
try {
|
||||
await axios.post('/api/admin/prewarming/trigger', null, { headers: adminKey.headers.value })
|
||||
toasts.success('Pre-warming started', 'The cycle runs in the background.')
|
||||
} catch (err) {
|
||||
const status = (err as { response?: { status?: number } }).response?.status
|
||||
if (status === 401 || status === 403) {
|
||||
adminKey.clear()
|
||||
toasts.error('Admin key refused', 'Enter a key with the admin role.')
|
||||
} else {
|
||||
toasts.error('Could not start pre-warming', err instanceof Error ? err.message : 'Request failed')
|
||||
}
|
||||
} finally {
|
||||
triggering.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => void load(true))
|
||||
</script>
|
||||
@@ -37,6 +37,20 @@ const charts = (w: Wrapper) => w.findAll('svg[role="img"]')
|
||||
const requested = () => vi.mocked(axios.get).mock.calls.map((c) => c[0])
|
||||
|
||||
describe('TrendChart', () => {
|
||||
it('says so when there is a single day of history, and names the plotted series', async () => {
|
||||
vi.mocked(axios.get).mockResolvedValue({ data: { ...TREND, points: TREND.points.slice(0, 1) } })
|
||||
const { wrapper } = await open()
|
||||
|
||||
expect(wrapper.findAll('[data-testid="trend-single-day"]')).toHaveLength(1)
|
||||
expect(wrapper.text()).toContain('One day of history so far')
|
||||
expect(wrapper.get('[data-testid="trend-series-key"]').text()).toContain('Plotted: packages with any finding.')
|
||||
})
|
||||
|
||||
it('does not show the single-day note with several days', async () => {
|
||||
const { wrapper } = await open()
|
||||
expect(wrapper.text()).not.toContain('One day of history so far')
|
||||
})
|
||||
|
||||
it('requests the 30 day trend and draws both charts with accessible names', async () => {
|
||||
const { wrapper, problems } = await open()
|
||||
|
||||
|
||||
@@ -29,6 +29,7 @@
|
||||
<template v-else>
|
||||
<section class="flex flex-col gap-3" aria-labelledby="trend-packages-heading">
|
||||
<h3 id="trend-packages-heading" class="text-sm font-medium">Cached packages</h3>
|
||||
<p v-if="singleDay" class="m-0 text-sm text-muted-foreground" data-testid="trend-single-day">{{ SINGLE_DAY_NOTE }}</p>
|
||||
<LineChart
|
||||
variant="area"
|
||||
:size="compact ? 'sm' : 'md'"
|
||||
@@ -50,6 +51,7 @@
|
||||
v-model="severities"
|
||||
type="multiple"
|
||||
variant="outline"
|
||||
tone="primary"
|
||||
size="sm"
|
||||
aria-label="Add a line per severity"
|
||||
>
|
||||
@@ -61,6 +63,8 @@
|
||||
<p v-if="vulnerabilityNote" class="text-sm text-muted-foreground" data-testid="trend-vulnerability-note">
|
||||
{{ vulnerabilityNote }}
|
||||
</p>
|
||||
<p v-if="singleDay" class="m-0 text-sm text-muted-foreground">{{ SINGLE_DAY_NOTE }}</p>
|
||||
<p class="m-0 text-sm text-muted-foreground" data-testid="trend-series-key">{{ seriesKey }}</p>
|
||||
<LineChart
|
||||
v-if="data?.vulnerability_history_start"
|
||||
:y-min="0"
|
||||
@@ -100,6 +104,7 @@ import {
|
||||
ToggleGroup,
|
||||
ToggleGroupItem,
|
||||
} from '@perfect-design/ui'
|
||||
import { plural } from '@/lib/reason'
|
||||
import { SEVERITY_LEVELS, formatSeverityName, type SeverityLevel } from '@/lib/severity'
|
||||
import {
|
||||
DEFAULT_TREND_PERIOD,
|
||||
@@ -178,6 +183,15 @@ const vulnerableSeries = computed(() => [
|
||||
})),
|
||||
])
|
||||
|
||||
const SINGLE_DAY_NOTE = 'One day of history so far. A line appears once there is a second day.'
|
||||
const singleDay = computed(() => points.value.length === 1)
|
||||
|
||||
const seriesKey = computed(() => {
|
||||
const all = 'Plotted: packages with any finding.'
|
||||
if (severities.value.length === 0) return `${all} Select a severity to add its own line.`
|
||||
return `${all} Added: ${severities.value.join(', ')}.`
|
||||
})
|
||||
|
||||
// Earlier days were never scanned, so their counts are unknown and drawn as a gap.
|
||||
const vulnerabilityNote = computed(() => {
|
||||
const start = data.value?.vulnerability_history_start
|
||||
@@ -191,6 +205,6 @@ const compactVulnerable = computed(() => {
|
||||
const last = points.value[points.value.length - 1]
|
||||
const n = last?.vulnerable_packages
|
||||
if (n === null || n === undefined) return 'Vulnerability history has not started yet.'
|
||||
return `${n} vulnerable package${n === 1 ? '' : 's'} on ${formatTrendDate(last!.date, true)}.`
|
||||
return `${plural(n, 'vulnerable package')} on ${formatTrendDate(last!.date, true)}.`
|
||||
})
|
||||
</script>
|
||||
|
||||
@@ -1,332 +0,0 @@
|
||||
<template>
|
||||
<div class="flex flex-col gap-6">
|
||||
<PageHeader
|
||||
:title="showOnlyBlocked ? 'Blocked packages' : 'Vulnerable packages'"
|
||||
:description="
|
||||
showOnlyBlocked
|
||||
? 'Packages blocked from download because they exceed the vulnerability thresholds.'
|
||||
: 'Packages with known security vulnerabilities, sorted by risk.'
|
||||
"
|
||||
>
|
||||
<template #back>
|
||||
<Button variant="ghost" size="sm" :icon-start="faArrowLeft" @click="goBack">Back to stats</Button>
|
||||
</template>
|
||||
</PageHeader>
|
||||
|
||||
<LoadingState v-if="loading" variant="card" label="Loading vulnerable packages..." />
|
||||
|
||||
<ErrorState
|
||||
v-else-if="error"
|
||||
variant="card"
|
||||
title="Could not load vulnerable packages"
|
||||
:message="error"
|
||||
@retry="fetchVulnerablePackages"
|
||||
/>
|
||||
|
||||
<Card v-else-if="vulnerablePackages.length === 0">
|
||||
<CardContent>
|
||||
<EmptyState
|
||||
tone="success"
|
||||
:icon="faCircleCheck"
|
||||
:title="showOnlyBlocked ? 'No blocked packages' : 'No vulnerable packages'"
|
||||
description="Every cached package is clean."
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<template v-else>
|
||||
<SeveritySummary
|
||||
v-model="selectedSeverities"
|
||||
selectable
|
||||
:counts="totalCounts"
|
||||
:package-counts="packageCounts"
|
||||
label="Vulnerabilities by severity. Select a severity to filter the packages."
|
||||
/>
|
||||
|
||||
<div v-if="hasFilter" class="flex flex-wrap items-center justify-between gap-3" data-testid="filter-bar">
|
||||
<p class="text-sm text-muted-foreground" role="status">Showing packages with {{ filterSummary }} vulnerabilities.</p>
|
||||
<Button variant="outline" size="sm" @click="clearFilters">Clear filters</Button>
|
||||
</div>
|
||||
|
||||
<Card v-if="sortedVulnerablePackages.length === 0">
|
||||
<CardContent>
|
||||
<EmptyState
|
||||
:icon="faCircleCheck"
|
||||
title="No packages match the filter"
|
||||
:description="`No ${showOnlyBlocked ? 'blocked' : 'vulnerable'} package has a ${filterSummary} vulnerability.`"
|
||||
>
|
||||
<template #action>
|
||||
<Button variant="outline" @click="clearFilters">Clear filters</Button>
|
||||
</template>
|
||||
</EmptyState>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card v-else>
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">
|
||||
{{ showOnlyBlocked ? 'Blocked' : 'Vulnerable' }} packages ({{ sortedVulnerablePackages.length }})
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
{{ groupedPackages.length }} unique package{{ groupedPackages.length !== 1 ? 's' : '' }}, most critical first
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Accordion type="multiple" class="w-full">
|
||||
<AccordionItem
|
||||
v-for="group in groupedPackages"
|
||||
:key="`${group.registry}:${group.name}`"
|
||||
:value="`${group.registry}:${group.name}`"
|
||||
>
|
||||
<AccordionTrigger :heading-level="3">
|
||||
<span class="flex w-full min-w-0 items-center justify-between gap-4">
|
||||
<span class="min-w-0 text-start">
|
||||
<span class="block break-words font-semibold">{{ group.name }}</span>
|
||||
<span class="block text-sm text-muted-foreground">
|
||||
{{ group.versions.length }} vulnerable version{{ group.versions.length > 1 ? 's' : '' }}
|
||||
</span>
|
||||
</span>
|
||||
<span class="flex shrink-0 items-center gap-4">
|
||||
<Badge variant="outline">{{ group.registry }}</Badge>
|
||||
<span class="whitespace-nowrap text-end tabular-nums">
|
||||
<span class="block text-sm font-medium">{{ formatBytes(group.totalSize) }}</span>
|
||||
<span class="block text-xs text-muted-foreground">{{ formatNumber(group.totalDownloads) }} downloads</span>
|
||||
</span>
|
||||
</span>
|
||||
</span>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent>
|
||||
<DataTable
|
||||
:label="`Vulnerable versions of ${group.name}`"
|
||||
layout="cards"
|
||||
row-clickable
|
||||
:columns="versionColumns"
|
||||
:rows="group.versions"
|
||||
@row-click="navigateToPackage"
|
||||
>
|
||||
<template #cell-vulnerabilities="{ row }">
|
||||
<VulnerabilityBadge
|
||||
v-if="row.vulnerabilities"
|
||||
:scanned="row.vulnerabilities.scanned"
|
||||
:status="row.vulnerabilities.status"
|
||||
:counts="row.vulnerabilities.counts"
|
||||
:total="row.vulnerabilities.total"
|
||||
:scannedAt="row.vulnerabilities.scannedAt"
|
||||
:isBlocked="row.vulnerabilities.isBlocked"
|
||||
@click="navigateToPackage(row)"
|
||||
/>
|
||||
</template>
|
||||
</DataTable>
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { useRouter, useRoute } from 'vue-router'
|
||||
import { usePackageStore, type Package, type VulnerabilityCounts } from '../stores/packages'
|
||||
import {
|
||||
Accordion,
|
||||
AccordionContent,
|
||||
AccordionItem,
|
||||
AccordionTrigger,
|
||||
Badge,
|
||||
Button,
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
DataTable,
|
||||
EmptyState,
|
||||
ErrorState,
|
||||
LoadingState,
|
||||
PageHeader,
|
||||
type DataTableColumn,
|
||||
} from '@perfect-design/ui'
|
||||
import VulnerabilityBadge from './VulnerabilityBadge.vue'
|
||||
import SeveritySummary from './SeveritySummary.vue'
|
||||
import { formatBytes, formatDate, formatNumber, displayVersion, withVersionPrefix } from '@/lib/format'
|
||||
import { faArrowLeft, faCircleCheck } from '@/lib/icons'
|
||||
import { NO_VULNERABILITIES, SEVERITY_LEVELS, formatSeverityName, type SeverityLevel } from '@/lib/severity'
|
||||
|
||||
const store = usePackageStore()
|
||||
const router = useRouter()
|
||||
const route = useRoute()
|
||||
|
||||
const SEVERITY_QUERY = 'severity'
|
||||
|
||||
/** Reads `?severity=critical,high`: known levels only, in severity order, each once. */
|
||||
function parseSeverityQuery(raw: unknown): SeverityLevel[] {
|
||||
const text = Array.isArray(raw) ? raw.join(',') : typeof raw === 'string' ? raw : ''
|
||||
const wanted = text.split(',').map((part) => part.trim().toLowerCase())
|
||||
return SEVERITY_LEVELS.filter((level) => wanted.includes(level))
|
||||
}
|
||||
|
||||
// The URL is the source of truth, so a reload or a shared link restores the filter.
|
||||
const selectedSeverities = computed<SeverityLevel[]>({
|
||||
get: () => parseSeverityQuery(route.query[SEVERITY_QUERY]),
|
||||
set: (levels) => {
|
||||
const { [SEVERITY_QUERY]: _previous, ...rest } = route.query
|
||||
void router.replace({ query: levels.length > 0 ? { ...rest, [SEVERITY_QUERY]: levels.join(',') } : rest })
|
||||
},
|
||||
})
|
||||
const hasFilter = computed(() => selectedSeverities.value.length > 0)
|
||||
const filterSummary = computed(() =>
|
||||
selectedSeverities.value.map((level) => formatSeverityName(level).toLowerCase()).join(' or '),
|
||||
)
|
||||
|
||||
function clearFilters() {
|
||||
selectedSeverities.value = []
|
||||
}
|
||||
|
||||
const loading = ref(false)
|
||||
const error = ref<string | null>(null)
|
||||
const vulnerablePackages = ref<Package[]>([])
|
||||
|
||||
// Check if we should filter to show only blocked packages
|
||||
const showOnlyBlocked = computed(() => route.path === '/blocked-packages')
|
||||
|
||||
onMounted(async () => {
|
||||
await fetchVulnerablePackages()
|
||||
})
|
||||
|
||||
async function fetchVulnerablePackages() {
|
||||
loading.value = true
|
||||
error.value = null
|
||||
|
||||
try {
|
||||
// The server drops clean packages; the toggles below narrow the rest without another request.
|
||||
await store.fetchPackages({ severity: SEVERITY_LEVELS })
|
||||
// The store records a failed request in store.error and resolves; surface it instead of an empty list.
|
||||
if (store.error) {
|
||||
error.value = store.error
|
||||
return
|
||||
}
|
||||
vulnerablePackages.value = store.packages.filter(pkg => {
|
||||
const isVulnerable = pkg.vulnerabilities?.status === 'vulnerable'
|
||||
if (showOnlyBlocked.value) {
|
||||
return isVulnerable && pkg.vulnerabilities?.isBlocked === true
|
||||
}
|
||||
return isVulnerable
|
||||
})
|
||||
} catch (err: any) {
|
||||
console.error('Failed to load vulnerable packages:', err)
|
||||
error.value = err.message || 'Failed to load vulnerable packages'
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// A package passes when it has at least one vulnerability of any selected severity.
|
||||
const filteredPackages = computed(() => {
|
||||
if (!hasFilter.value) return vulnerablePackages.value
|
||||
return vulnerablePackages.value.filter((pkg) =>
|
||||
selectedSeverities.value.some((level) => (pkg.vulnerabilities?.counts?.[level] ?? 0) > 0),
|
||||
)
|
||||
})
|
||||
|
||||
// Sort packages by risk: Critical count DESC, High count DESC, Moderate count DESC, Low count DESC
|
||||
const sortedVulnerablePackages = computed(() => {
|
||||
return [...filteredPackages.value].sort((a, b) => {
|
||||
const aVulns = a.vulnerabilities?.counts || { critical: 0, high: 0, moderate: 0, low: 0 }
|
||||
const bVulns = b.vulnerabilities?.counts || { critical: 0, high: 0, moderate: 0, low: 0 }
|
||||
|
||||
// Compare critical count (descending)
|
||||
if (aVulns.critical !== bVulns.critical) {
|
||||
return bVulns.critical - aVulns.critical
|
||||
}
|
||||
|
||||
// Compare high count (descending)
|
||||
if (aVulns.high !== bVulns.high) {
|
||||
return bVulns.high - aVulns.high
|
||||
}
|
||||
|
||||
// Compare moderate count (descending)
|
||||
if (aVulns.moderate !== bVulns.moderate) {
|
||||
return bVulns.moderate - aVulns.moderate
|
||||
}
|
||||
|
||||
// Compare low count (descending)
|
||||
return bVulns.low - aVulns.low
|
||||
})
|
||||
})
|
||||
|
||||
// Group packages by name and registry, with versions sorted by risk
|
||||
const groupedPackages = computed(() => {
|
||||
const groups = new Map<string, {
|
||||
registry: string
|
||||
name: string
|
||||
versions: Package[]
|
||||
totalSize: number
|
||||
totalDownloads: number
|
||||
}>()
|
||||
|
||||
sortedVulnerablePackages.value.forEach((pkg) => {
|
||||
const key = `${pkg.registry}:${pkg.name}`
|
||||
if (!groups.has(key)) {
|
||||
groups.set(key, {
|
||||
registry: pkg.registry,
|
||||
name: pkg.name,
|
||||
versions: [],
|
||||
totalSize: 0,
|
||||
totalDownloads: 0,
|
||||
})
|
||||
}
|
||||
const group = groups.get(key)!
|
||||
group.versions.push(pkg)
|
||||
group.totalSize += pkg.size || 0
|
||||
group.totalDownloads += pkg.download_count || 0
|
||||
})
|
||||
|
||||
return Array.from(groups.values())
|
||||
})
|
||||
|
||||
// Packages holding at least one vulnerability of each severity, before any filter.
|
||||
const packageCounts = computed<VulnerabilityCounts>(() => {
|
||||
const counts = { ...NO_VULNERABILITIES }
|
||||
for (const pkg of vulnerablePackages.value) {
|
||||
for (const level of SEVERITY_LEVELS) {
|
||||
if ((pkg.vulnerabilities?.counts?.[level] ?? 0) > 0) counts[level]++
|
||||
}
|
||||
}
|
||||
return counts
|
||||
})
|
||||
|
||||
// Calculate total counts across all packages, before any filter
|
||||
const totalCounts = computed(() =>
|
||||
vulnerablePackages.value.reduce(
|
||||
(sum, pkg) => {
|
||||
const counts = pkg.vulnerabilities?.counts ?? NO_VULNERABILITIES
|
||||
return {
|
||||
critical: sum.critical + counts.critical,
|
||||
high: sum.high + counts.high,
|
||||
moderate: sum.moderate + counts.moderate,
|
||||
low: sum.low + counts.low,
|
||||
}
|
||||
},
|
||||
{ ...NO_VULNERABILITIES },
|
||||
),
|
||||
)
|
||||
|
||||
const versionColumns: DataTableColumn<Package>[] = [
|
||||
{ key: 'version', header: 'Version', rowHeader: true, accessor: (pkg) => withVersionPrefix(displayVersion(pkg)) },
|
||||
{ key: 'download_count', header: 'Downloads', numeric: true, accessor: (pkg) => formatNumber(pkg.download_count) },
|
||||
{ key: 'size', header: 'Size', numeric: true, accessor: (pkg) => formatBytes(pkg.size) },
|
||||
{ key: 'cached_at', header: 'Cached', accessor: (pkg) => formatDate(pkg.cached_at) },
|
||||
{ key: 'vulnerabilities', header: 'Vulnerabilities', accessor: () => '' },
|
||||
]
|
||||
|
||||
function navigateToPackage(pkg: Package) {
|
||||
router.push(`/package/${pkg.registry}/${pkg.name}/${pkg.version}`)
|
||||
}
|
||||
|
||||
function goBack() {
|
||||
router.push('/stats')
|
||||
}
|
||||
</script>
|
||||
@@ -0,0 +1,46 @@
|
||||
<template>
|
||||
<Dialog :open="open" @update:open="(value: boolean) => emit('update:open', value)">
|
||||
<DialogContent size="sm">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Admin API key</DialogTitle>
|
||||
<DialogDescription>{{ description }}</DialogDescription>
|
||||
</DialogHeader>
|
||||
<form class="flex flex-col gap-4" @submit.prevent="submit">
|
||||
<Field label="API key" required>
|
||||
<Input v-model="draft" type="password" autocomplete="off" />
|
||||
</Field>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" @click="emit('update:open', false)">Cancel</Button>
|
||||
<Button type="submit" :disabled="draft.trim() === ''">Continue</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, watch } from 'vue'
|
||||
import { Button, Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, Field, Input } from '@perfect-design/ui'
|
||||
import { useAdminKey } from '@/lib/adminKey'
|
||||
|
||||
const props = defineProps<{ open: boolean; description: string }>()
|
||||
const emit = defineEmits<{ 'update:open': [open: boolean]; saved: [] }>()
|
||||
|
||||
const adminKey = useAdminKey()
|
||||
const draft = ref('')
|
||||
|
||||
watch(
|
||||
() => props.open,
|
||||
(open) => {
|
||||
if (open) draft.value = ''
|
||||
},
|
||||
)
|
||||
|
||||
function submit() {
|
||||
const value = draft.value.trim()
|
||||
if (!value) return
|
||||
adminKey.save(value)
|
||||
emit('update:open', false)
|
||||
emit('saved')
|
||||
}
|
||||
</script>
|
||||
@@ -0,0 +1,119 @@
|
||||
<template>
|
||||
<div class="flex flex-col gap-6">
|
||||
<section v-if="applied" class="flex flex-col gap-3" aria-labelledby="bypass-applied-heading">
|
||||
<h3 id="bypass-applied-heading" class="m-0 text-sm font-semibold">Bypass in effect</h3>
|
||||
<DescriptionList :columns="2" divided data-testid="applied-bypass">
|
||||
<DescriptionItem term="Scope">{{ applied.type === 'package' ? 'Whole package' : 'One advisory' }}</DescriptionItem>
|
||||
<DescriptionItem term="Target"><InlineCode>{{ applied.target }}</InlineCode></DescriptionItem>
|
||||
<DescriptionItem term="Reason">{{ applied.reason }}</DescriptionItem>
|
||||
<DescriptionItem term="Created by">{{ applied.created_by }}</DescriptionItem>
|
||||
<DescriptionItem term="Created"><RelativeTime :datetime="applied.created_at" /></DescriptionItem>
|
||||
<DescriptionItem term="Expires">{{ formatDate(applied.expires_at) }}</DescriptionItem>
|
||||
</DescriptionList>
|
||||
</section>
|
||||
<p v-else class="m-0 text-sm text-muted-foreground">No bypass applies to this package.</p>
|
||||
|
||||
<section class="flex flex-col gap-3" aria-labelledby="bypass-list-heading">
|
||||
<div class="flex flex-wrap items-center justify-between gap-3">
|
||||
<h3 id="bypass-list-heading" class="m-0 text-sm font-semibold">Bypasses that cover this package</h3>
|
||||
<Button :as="RouterLink" :to="addRoute" variant="outline" size="sm" :icon-start="faPlus">Add a bypass</Button>
|
||||
</div>
|
||||
<Callout v-if="!adminKey.key.value" type="note" size="sm" title="Admin key needed">
|
||||
Listing bypasses needs the admin API key. Enter it on the
|
||||
<Link :as="RouterLink" to="/admin/bypasses">Bypasses page</Link>.
|
||||
</Callout>
|
||||
<LoadingState v-else-if="loading" layout="inline" label="Loading bypasses..." />
|
||||
<ErrorState v-else-if="error" variant="inline" title="Could not load bypasses" :message="error" @retry="load" />
|
||||
<EmptyState v-else-if="covering.length === 0" size="sm" title="No bypass covers this package" description="Add one to serve it despite the findings." />
|
||||
<DataTable v-else label="Bypasses covering this package" layout="cards" density="compact" :columns="columns" :rows="covering">
|
||||
<template #cell-status="{ row }">
|
||||
<StatusBadge :status="statusOf(row)" :label="STATUS_LABELS[statusOf(row)]" :tones="STATUS_TONES" />
|
||||
</template>
|
||||
<template #cell-target="{ row }"><InlineCode>{{ row.target }}</InlineCode></template>
|
||||
</DataTable>
|
||||
</section>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import axios from 'axios'
|
||||
import { RouterLink } from 'vue-router'
|
||||
import {
|
||||
Button,
|
||||
Callout,
|
||||
DataTable,
|
||||
DescriptionItem,
|
||||
DescriptionList,
|
||||
EmptyState,
|
||||
ErrorState,
|
||||
InlineCode,
|
||||
Link,
|
||||
LoadingState,
|
||||
RelativeTime,
|
||||
StatusBadge,
|
||||
type DataTableColumn,
|
||||
} from '@perfect-design/ui'
|
||||
import { useAdminKey } from '@/lib/adminKey'
|
||||
import { bypassesFor, isExpired, type Bypass } from '@/lib/bypass'
|
||||
import { formatDate } from '@/lib/format'
|
||||
import { faPlus } from '@/lib/icons'
|
||||
import type { AppliedBypass } from '@/stores/packages'
|
||||
|
||||
const props = defineProps<{
|
||||
applied: AppliedBypass | null
|
||||
registry: string
|
||||
name: string
|
||||
version: string
|
||||
releaseVersion?: string
|
||||
}>()
|
||||
|
||||
const adminKey = useAdminKey()
|
||||
const all = ref<Bypass[]>([])
|
||||
const loading = ref(false)
|
||||
const error = ref<string | null>(null)
|
||||
|
||||
type BypassStatus = 'active' | 'expired' | 'inactive'
|
||||
const STATUS_LABELS: Record<BypassStatus, string> = { active: 'Active', expired: 'Expired', inactive: 'Inactive' }
|
||||
const STATUS_TONES = { active: 'success', expired: 'neutral', inactive: 'neutral' } as const
|
||||
|
||||
function statusOf(b: Bypass): BypassStatus {
|
||||
if (isExpired(b.expires_at)) return 'expired'
|
||||
return b.active ? 'active' : 'inactive'
|
||||
}
|
||||
|
||||
const covering = computed(() =>
|
||||
bypassesFor(all.value, { registry: props.registry, name: props.name, version: props.version, releaseVersion: props.releaseVersion }),
|
||||
)
|
||||
|
||||
const addRoute = computed(() => ({
|
||||
path: '/admin/bypasses',
|
||||
query: { type: 'package', target: `${props.registry}/${props.name}@${props.releaseVersion || props.version}` },
|
||||
}))
|
||||
|
||||
const columns: DataTableColumn<Bypass>[] = [
|
||||
{ key: 'target', header: 'Target', rowHeader: true },
|
||||
{ key: 'type', header: 'Type' },
|
||||
{ key: 'status', header: 'Status', accessor: (b) => statusOf(b) },
|
||||
{ key: 'reason', header: 'Reason' },
|
||||
{ key: 'created_by', header: 'Created by' },
|
||||
{ key: 'expires_at', header: 'Expires', accessor: (b) => formatDate(b.expires_at) },
|
||||
]
|
||||
|
||||
async function load() {
|
||||
if (!adminKey.key.value) return
|
||||
loading.value = true
|
||||
error.value = null
|
||||
try {
|
||||
const response = await axios.get<{ bypasses: Bypass[] }>('/api/admin/bypasses?include_expired=true', { headers: adminKey.headers.value })
|
||||
all.value = response.data.bypasses ?? []
|
||||
} catch (err) {
|
||||
const status = (err as { response?: { status?: number } }).response?.status
|
||||
error.value = status === 401 || status === 403 ? 'The admin key was refused.' : err instanceof Error ? err.message : 'Failed to load bypasses'
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(load)
|
||||
</script>
|
||||
@@ -0,0 +1,86 @@
|
||||
<template>
|
||||
<Card class="min-w-0" data-testid="cache-capacity">
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">Cache capacity</CardTitle>
|
||||
<CardDescription>Disk the cache holds, by registry.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent class="flex flex-col gap-6">
|
||||
<StatBar
|
||||
v-if="maxSize > 0"
|
||||
label="Used"
|
||||
tone="auto"
|
||||
:value="used"
|
||||
:max="maxSize"
|
||||
:value-text="`${formatBytes(used)} of ${formatBytes(maxSize)}`"
|
||||
/>
|
||||
<p v-else class="m-0 text-sm text-muted-foreground">
|
||||
<span class="font-medium text-foreground">{{ formatBytes(used) }}</span> used. No size limit is set.
|
||||
</p>
|
||||
|
||||
<EmptyState v-if="rows.length === 0" size="sm" title="Nothing cached" description="Each registry appears here after its first download." />
|
||||
<template v-else>
|
||||
<DonutChart
|
||||
:data="donut"
|
||||
:value-formatter="formatBytes"
|
||||
center-text="cached"
|
||||
label="Cache size by registry"
|
||||
layout="stacked"
|
||||
size="md"
|
||||
/>
|
||||
<DataTable label="Cache by registry" layout="cards" density="compact" :columns="columns" :rows="rows" row-key="registry">
|
||||
<template #cell-registry="{ row }"><Badge variant="outline">{{ row.registry }}</Badge></template>
|
||||
</DataTable>
|
||||
</template>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import {
|
||||
Badge,
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
DataTable,
|
||||
DonutChart,
|
||||
EmptyState,
|
||||
StatBar,
|
||||
type DataTableColumn,
|
||||
type DonutDatum,
|
||||
} from '@perfect-design/ui'
|
||||
import { formatBytes, formatNumber } from '@/lib/format'
|
||||
|
||||
export interface RegistryUsage {
|
||||
registry: string
|
||||
count: number
|
||||
size: number
|
||||
downloads: number
|
||||
}
|
||||
|
||||
const props = defineProps<{
|
||||
used: number
|
||||
maxSize: number
|
||||
registries: Record<string, { count?: number; size?: number; downloads?: number }>
|
||||
}>()
|
||||
|
||||
const rows = computed<RegistryUsage[]>(() =>
|
||||
Object.entries(props.registries)
|
||||
.map(([registry, r]) => ({ registry, count: r.count ?? 0, size: r.size ?? 0, downloads: r.downloads ?? 0 }))
|
||||
.sort((a, b) => b.size - a.size),
|
||||
)
|
||||
// chart-1 and chart-2 are neighbouring teals in this theme, so each registry gets a distinct hue.
|
||||
const REGISTRY_TONES: Record<string, DonutDatum['tone']> = { npm: 'info', go: 'primary', pypi: 'warning' }
|
||||
const SPARE_TONES: DonutDatum['tone'][] = ['danger', 'success', 'muted']
|
||||
const donut = computed<DonutDatum[]>(() =>
|
||||
rows.value.map((r, i) => ({ label: r.registry, value: r.size, tone: REGISTRY_TONES[r.registry] ?? SPARE_TONES[i % SPARE_TONES.length] })),
|
||||
)
|
||||
|
||||
const columns: DataTableColumn<RegistryUsage>[] = [
|
||||
{ key: 'registry', header: 'Registry', rowHeader: true },
|
||||
{ key: 'count', header: 'Packages', numeric: true, accessor: (r) => formatNumber(r.count) },
|
||||
{ key: 'size', header: 'Size', numeric: true, accessor: (r) => formatBytes(r.size) },
|
||||
]
|
||||
</script>
|
||||
@@ -0,0 +1,72 @@
|
||||
<template>
|
||||
<Card class="min-w-0" data-testid="download-trend">
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">Downloads</CardTitle>
|
||||
<CardDescription>Packages served to clients, in UTC.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent class="flex flex-col gap-4">
|
||||
<div class="flex sm:justify-end">
|
||||
<SegmentedControl v-model="period" :options="DOWNLOAD_PERIODS" aria-label="Download period" />
|
||||
</div>
|
||||
<LoadingState v-if="loading && points.length === 0" layout="inline" label="Loading downloads..." />
|
||||
<ErrorState v-else-if="error" variant="inline" title="Could not load downloads" :message="error" @retry="load" />
|
||||
<LineChart
|
||||
v-else
|
||||
variant="area"
|
||||
:y-min="0"
|
||||
:labels="labels"
|
||||
:series="[{ name: 'Downloads', data: values, tone: 'primary' }]"
|
||||
:label="`Downloads over the last ${periodLabel}, ${total} in total`"
|
||||
empty-text="No downloads in this period"
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import axios from 'axios'
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
ErrorState,
|
||||
LineChart,
|
||||
LoadingState,
|
||||
SegmentedControl,
|
||||
} from '@perfect-design/ui'
|
||||
import { DOWNLOAD_PERIODS, bucketLabel, type DownloadPeriod, type TimeSeries } from '@/lib/timeseries'
|
||||
|
||||
const period = ref<DownloadPeriod>('1day')
|
||||
const data = ref<TimeSeries | null>(null)
|
||||
const loading = ref(false)
|
||||
const error = ref<string | null>(null)
|
||||
let request = 0
|
||||
|
||||
const points = computed(() => data.value?.data_points ?? [])
|
||||
const values = computed(() => points.value.map((p) => p.value))
|
||||
const labels = computed(() => points.value.map((p) => bucketLabel(period.value, p.timestamp)))
|
||||
const total = computed(() => values.value.reduce((sum, v) => sum + v, 0))
|
||||
const periodLabel = computed(() => DOWNLOAD_PERIODS.find((p) => p.value === period.value)?.label ?? '')
|
||||
|
||||
async function load() {
|
||||
const current = ++request
|
||||
loading.value = true
|
||||
error.value = null
|
||||
try {
|
||||
const response = await axios.get<TimeSeries>(`/api/stats/timeseries?period=${period.value}`)
|
||||
if (current === request) data.value = response.data
|
||||
} catch (err) {
|
||||
if (current !== request) return
|
||||
data.value = null
|
||||
error.value = err instanceof Error ? err.message : 'Failed to load downloads'
|
||||
} finally {
|
||||
if (current === request) loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
watch(period, load)
|
||||
onMounted(load)
|
||||
</script>
|
||||
@@ -0,0 +1,58 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import axios from 'axios'
|
||||
import { flushPromises } from '@vue/test-utils'
|
||||
import DownloadsPanel from './DownloadsPanel.vue'
|
||||
import { PACKAGE_ANALYTICS } from '@/test/fixtures'
|
||||
import { mountStrict } from '@/test/mountStrict'
|
||||
|
||||
vi.mock('axios')
|
||||
|
||||
let restore: (() => void) | undefined
|
||||
|
||||
async function open(props: { registry: string; name: string; downloadCount: number }) {
|
||||
const mounted = await mountStrict(DownloadsPanel, { props })
|
||||
restore = mounted.restore
|
||||
await flushPromises()
|
||||
return mounted.wrapper
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.mocked(axios.get).mockReset()
|
||||
})
|
||||
afterEach(() => {
|
||||
restore?.()
|
||||
restore = undefined
|
||||
})
|
||||
|
||||
describe('DownloadsPanel', () => {
|
||||
it('shows the stored count even when analytics have no record since the restart', async () => {
|
||||
vi.mocked(axios.get).mockResolvedValue({ data: { package: null } })
|
||||
const wrapper = await open({ registry: 'npm', name: 'left-pad', downloadCount: 12 })
|
||||
|
||||
expect(wrapper.text()).toContain('12')
|
||||
expect(wrapper.text()).toContain('No downloads since the last restart')
|
||||
expect(wrapper.text()).not.toContain('Could not load')
|
||||
})
|
||||
|
||||
it('adds the in-memory totals and labels them as since the restart', async () => {
|
||||
vi.mocked(axios.get).mockResolvedValue({ data: PACKAGE_ANALYTICS })
|
||||
const wrapper = await open({ registry: 'npm', name: 'left-pad', downloadCount: 12 })
|
||||
|
||||
expect(wrapper.text()).toContain('kept across restarts')
|
||||
expect(wrapper.text()).toContain('2 versions since the last restart')
|
||||
expect(wrapper.text()).toContain('80 KB')
|
||||
})
|
||||
|
||||
it('asks for a Go module by its path, with no cache-file suffix', async () => {
|
||||
vi.mocked(axios.get).mockResolvedValue({ data: { package: null } })
|
||||
await open({ registry: 'go', name: 'github.com/google/uuid/@v/v1.6.0.zip', downloadCount: 2 })
|
||||
|
||||
expect(vi.mocked(axios.get)).toHaveBeenCalledWith('/api/analytics/package/go/github.com/google/uuid')
|
||||
})
|
||||
|
||||
it('reports a failed request', async () => {
|
||||
vi.mocked(axios.get).mockRejectedValue(new Error('boom'))
|
||||
const wrapper = await open({ registry: 'npm', name: 'left-pad', downloadCount: 1 })
|
||||
expect(wrapper.text()).toContain('Could not load download history')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,81 @@
|
||||
<template>
|
||||
<LoadingState v-if="loading" layout="inline" label="Loading download history..." />
|
||||
<ErrorState v-else-if="error" variant="inline" title="Could not load download history" :message="error" @retry="load" />
|
||||
<div v-else class="flex flex-col gap-4">
|
||||
<StatGroup :columns="3" aria-label="Downloads of this package">
|
||||
<KpiTile label="This version" :value="downloadCount" hint="Times served from the cache, kept across restarts" />
|
||||
<template v-if="stats">
|
||||
<KpiTile
|
||||
label="All versions"
|
||||
:value="stats.TotalDownloads"
|
||||
:hint="`${stats.UniqueVersions} version${stats.UniqueVersions === 1 ? '' : 's'} since the last restart`"
|
||||
/>
|
||||
<KpiTile label="Data served" :value="formatBytes(stats.BytesServed)" hint="Across all versions, since the last restart" />
|
||||
</template>
|
||||
</StatGroup>
|
||||
<DescriptionList v-if="stats" :columns="2" divided>
|
||||
<DescriptionItem term="First seen since restart"><RelativeTime :datetime="stats.FirstSeen" /></DescriptionItem>
|
||||
<DescriptionItem term="Last download"><RelativeTime :datetime="stats.LastDownload" /></DescriptionItem>
|
||||
</DescriptionList>
|
||||
<EmptyState
|
||||
v-else
|
||||
size="sm"
|
||||
:icon="faDownload"
|
||||
title="No downloads since the last restart"
|
||||
description="The totals across versions are counted in memory, so they start again when the server restarts."
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import axios from 'axios'
|
||||
import {
|
||||
DescriptionItem,
|
||||
DescriptionList,
|
||||
EmptyState,
|
||||
ErrorState,
|
||||
KpiTile,
|
||||
LoadingState,
|
||||
RelativeTime,
|
||||
StatGroup,
|
||||
} from '@perfect-design/ui'
|
||||
import { formatBytes, modulePath } from '@/lib/format'
|
||||
import { faDownload } from '@/lib/icons'
|
||||
|
||||
/** The analytics engine serialises Go field names. */
|
||||
interface PackageAnalytics {
|
||||
TotalDownloads: number
|
||||
UniqueVersions: number
|
||||
BytesServed: number
|
||||
FirstSeen: string
|
||||
LastDownload: string
|
||||
}
|
||||
|
||||
const props = defineProps<{ registry: string; name: string; downloadCount: number }>()
|
||||
|
||||
const stats = ref<PackageAnalytics | null>(null)
|
||||
const loading = ref(false)
|
||||
const error = ref<string | null>(null)
|
||||
|
||||
// Analytics are keyed by package name; a Go module is named by its path.
|
||||
const analyticsName = computed(() => modulePath(props.name))
|
||||
|
||||
async function load() {
|
||||
loading.value = true
|
||||
error.value = null
|
||||
try {
|
||||
const response = await axios.get<{ package: PackageAnalytics | null }>(
|
||||
`/api/analytics/package/${props.registry}/${analyticsName.value}`,
|
||||
)
|
||||
stats.value = response.data.package
|
||||
} catch (err) {
|
||||
stats.value = null
|
||||
error.value = err instanceof Error ? err.message : 'Failed to load download history'
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(load)
|
||||
</script>
|
||||
@@ -0,0 +1,48 @@
|
||||
<template>
|
||||
<div class="flex flex-col gap-3">
|
||||
<p class="m-0 text-sm text-muted-foreground">
|
||||
Each scanner reports its own findings before they are merged. A finding several scanners agree on counts once in the verdict.
|
||||
</p>
|
||||
<DataTable label="Findings by scanner and severity" layout="cards" density="compact" row-key="name" :columns="columns" :rows="rows">
|
||||
<template #cell-name="{ row }"><span class="font-medium">{{ row.name }}</span></template>
|
||||
<template #cell-status="{ row }">
|
||||
<span class="flex flex-wrap items-center gap-2">
|
||||
<StatusBadge :status="row.status" :label="INSPECTOR_STATUS_LABELS[row.status]" :tones="STATUS_TONES" />
|
||||
<StatusBadge v-if="row.health === 'down'" status="down" label="Unavailable now" :tones="{ down: 'danger' }" />
|
||||
</span>
|
||||
</template>
|
||||
<template #cell-version="{ row }">{{ row.version ? `v${row.version}` : 'Not reported' }}</template>
|
||||
</DataTable>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import { DataTable, StatusBadge, type DataTableColumn } from '@perfect-design/ui'
|
||||
import { INSPECTOR_STATUS_LABELS, inspectorRows, type InspectorRow, type ScannerResult } from '@/lib/inspectors'
|
||||
import type { ScannerInfo } from '@/lib/system'
|
||||
|
||||
const props = defineProps<{
|
||||
registry: string
|
||||
results: readonly ScannerResult[]
|
||||
configured: readonly ScannerInfo[]
|
||||
}>()
|
||||
|
||||
const STATUS_TONES = { reported: 'success', 'no-result': 'warning', 'not-applicable': 'neutral', off: 'neutral' } as const
|
||||
|
||||
const rows = computed(() => inspectorRows(props.registry, props.results, props.configured))
|
||||
|
||||
function count(row: InspectorRow, level: 'critical' | 'high' | 'moderate' | 'low'): string {
|
||||
return row.counts ? String(row.counts[level]) : '–'
|
||||
}
|
||||
|
||||
const columns: DataTableColumn<InspectorRow>[] = [
|
||||
{ key: 'name', header: 'Scanner', rowHeader: true },
|
||||
{ key: 'critical', header: 'Critical', numeric: true, accessor: (r) => count(r, 'critical') },
|
||||
{ key: 'high', header: 'High', numeric: true, accessor: (r) => count(r, 'high') },
|
||||
{ key: 'moderate', header: 'Moderate', numeric: true, accessor: (r) => count(r, 'moderate') },
|
||||
{ key: 'low', header: 'Low', numeric: true, accessor: (r) => count(r, 'low') },
|
||||
{ key: 'status', header: 'Status' },
|
||||
{ key: 'version', header: 'Version' },
|
||||
]
|
||||
</script>
|
||||
@@ -0,0 +1,68 @@
|
||||
<template>
|
||||
<Sheet :open="pkg !== null" @update:open="(open: boolean) => !open && emit('close')">
|
||||
<SheetContent side="right" size="md">
|
||||
<template v-if="pkg">
|
||||
<SheetHeader>
|
||||
<SheetTitle class="break-words">{{ pkg.name }}</SheetTitle>
|
||||
<SheetDescription>{{ withVersionPrefix(displayVersion(pkg)) }} from {{ pkg.registry }}</SheetDescription>
|
||||
</SheetHeader>
|
||||
|
||||
<div class="flex flex-col gap-5 px-4 pb-4">
|
||||
<div class="flex flex-col gap-2">
|
||||
<VerdictBadge :verdict="verdict" class="self-start" />
|
||||
<p v-if="explanation" class="m-0 text-sm text-muted-foreground" data-testid="quick-view-reason">{{ explanation }}</p>
|
||||
</div>
|
||||
|
||||
<SeveritySummary v-if="pkg.vulnerabilities?.counts" class="grid-cols-2! lg:grid-cols-2!" :counts="pkg.vulnerabilities.counts" label="Findings by severity" />
|
||||
|
||||
<DescriptionList :columns="1" divided>
|
||||
<DescriptionItem term="Size">{{ formatBytes(pkg.size) }}</DescriptionItem>
|
||||
<DescriptionItem term="Downloads">{{ formatNumber(pkg.download_count) }}</DescriptionItem>
|
||||
<DescriptionItem term="Cached"><RelativeTime :datetime="pkg.cached_at" /></DescriptionItem>
|
||||
<DescriptionItem term="Last accessed"><RelativeTime :datetime="pkg.last_accessed" /></DescriptionItem>
|
||||
<DescriptionItem term="Last scanned">
|
||||
<RelativeTime v-if="pkg.vulnerabilities?.scannedAt" :datetime="pkg.vulnerabilities.scannedAt" />
|
||||
<template v-else>Never</template>
|
||||
</DescriptionItem>
|
||||
</DescriptionList>
|
||||
</div>
|
||||
|
||||
<SheetFooter>
|
||||
<Button :as="RouterLink" :to="packageRoute(pkg)" :icon-end="faArrowRight">Open full page</Button>
|
||||
<Button variant="outline" :icon-start="faTrash" @click="emit('delete', pkg)">Remove from cache</Button>
|
||||
</SheetFooter>
|
||||
</template>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import { RouterLink } from 'vue-router'
|
||||
import {
|
||||
Button,
|
||||
DescriptionItem,
|
||||
DescriptionList,
|
||||
RelativeTime,
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetDescription,
|
||||
SheetFooter,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
} from '@perfect-design/ui'
|
||||
import SeveritySummary from '../SeveritySummary.vue'
|
||||
import VerdictBadge from './VerdictBadge.vue'
|
||||
import type { Package } from '@/stores/packages'
|
||||
import { displayVersion, formatBytes, formatNumber, withVersionPrefix } from '@/lib/format'
|
||||
import { packageRoute } from '@/lib/packages'
|
||||
import { humanReason } from '@/lib/reason'
|
||||
import { faArrowRight, faTrash } from '@/lib/icons'
|
||||
import { VERDICT_MEANINGS, verdictOf } from '@/lib/verdict'
|
||||
|
||||
const props = defineProps<{ pkg: Package | null }>()
|
||||
const emit = defineEmits<{ close: []; delete: [pkg: Package] }>()
|
||||
|
||||
const verdict = computed(() => (props.pkg ? verdictOf(props.pkg) : 'unscanned'))
|
||||
const explanation = computed(() => humanReason(props.pkg?.vulnerabilities?.reason) || VERDICT_MEANINGS[verdict.value])
|
||||
</script>
|
||||
@@ -0,0 +1,25 @@
|
||||
<template>
|
||||
<p class="m-0 flex flex-wrap items-center gap-x-3 gap-y-1 text-sm text-muted-foreground" data-testid="policy-line">
|
||||
<template v-if="info">
|
||||
<span class="font-medium text-foreground">Policy</span>
|
||||
<span>{{ describePolicy(info.security) }}</span>
|
||||
<span v-if="info.security.enabled">{{ info.security.fail_closed ? 'Fail-closed' : 'Fail-open on scanner outage' }}.</span>
|
||||
<span v-if="info.security.enabled">{{ enabledScanners }} of {{ info.security.scanners.length }} scanners on.</span>
|
||||
<Link :as="RouterLink" to="/admin/system">System settings</Link>
|
||||
</template>
|
||||
<span v-else-if="error">Policy unavailable: {{ error }}</span>
|
||||
<span v-else>Loading policy...</span>
|
||||
</p>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted } from 'vue'
|
||||
import { RouterLink } from 'vue-router'
|
||||
import { Link } from '@perfect-design/ui'
|
||||
import { describePolicy, useSystem } from '@/lib/system'
|
||||
|
||||
const { info, error, load } = useSystem()
|
||||
const enabledScanners = computed(() => info.value?.security.scanners.filter((s) => s.enabled).length ?? 0)
|
||||
|
||||
onMounted(() => void load())
|
||||
</script>
|
||||
@@ -0,0 +1,162 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { createPinia, setActivePinia } from 'pinia'
|
||||
import axios from 'axios'
|
||||
import { flushPromises } from '@vue/test-utils'
|
||||
import RescanPanel from './RescanPanel.vue'
|
||||
import { mountStrict } from '@/test/mountStrict'
|
||||
|
||||
vi.mock('axios')
|
||||
|
||||
const idle = { enabled: true, running: false, scope: '', queued: 0, done: 0, failed: 0 }
|
||||
const running = { enabled: true, running: true, scope: 'vulnerable', queued: 10, done: 3, failed: 1, elapsed_seconds: 40, eta_seconds: 60 }
|
||||
let estimate: unknown
|
||||
const finished = { ...running, running: false, done: 9 }
|
||||
|
||||
let restore: (() => void) | undefined
|
||||
let statuses: Array<typeof idle | typeof running>
|
||||
|
||||
beforeEach(() => {
|
||||
localStorage.setItem('admin_api_key', 'test-key')
|
||||
statuses = [idle]
|
||||
estimate = { vulnerable: { artifacts: 12, seconds: 30 }, all: { artifacts: 1200, seconds: 6000 }, avg_scan_seconds: 10, concurrency: 2 }
|
||||
vi.mocked(axios.get).mockReset()
|
||||
vi.mocked(axios.post).mockReset()
|
||||
vi.mocked(axios.get).mockImplementation(async (url: string) => {
|
||||
if (url === '/api/admin/rescan/status') return { data: statuses.length > 1 ? statuses.shift() : statuses[0] } as never
|
||||
if (url === '/api/admin/rescan/estimate') return { data: estimate } as never
|
||||
throw new Error(`unexpected request: ${url}`)
|
||||
})
|
||||
})
|
||||
afterEach(() => {
|
||||
restore?.()
|
||||
restore = undefined
|
||||
localStorage.clear()
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
async function open(props = { enabled: true, concurrency: 2 }) {
|
||||
const pinia = createPinia()
|
||||
setActivePinia(pinia)
|
||||
const mounted = await mountStrict(RescanPanel, { props, global: { plugins: [pinia] } })
|
||||
restore = mounted.restore
|
||||
await flushPromises()
|
||||
return mounted.wrapper
|
||||
}
|
||||
|
||||
const body = () => document.body.textContent ?? ''
|
||||
function dialogButton(label: string): HTMLButtonElement {
|
||||
const btn = [...document.body.querySelectorAll('[role="alertdialog"] button, [role="dialog"] button')].find((b) => b.textContent?.trim() === label)
|
||||
if (!btn) throw new Error(`no button "${label}"`)
|
||||
return btn as HTMLButtonElement
|
||||
}
|
||||
|
||||
describe('RescanPanel', () => {
|
||||
it('starts a vulnerable rescan with the admin key and shows progress', async () => {
|
||||
vi.mocked(axios.post).mockResolvedValue({ data: { queued: 10, scope: 'vulnerable' } })
|
||||
statuses = [idle, running]
|
||||
const wrapper = await open()
|
||||
|
||||
await wrapper.get('[data-testid="rescan-vulnerable"]').trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
expect(vi.mocked(axios.post)).toHaveBeenCalledWith('/api/admin/rescan', { scope: 'vulnerable' }, { headers: { Authorization: 'Bearer test-key' } })
|
||||
expect(wrapper.get('[data-testid="rescan-counts"]').text()).toContain('3 scanned, 1 failed, of 10 queued')
|
||||
expect(wrapper.get('[data-testid="rescan-vulnerable"]').attributes('disabled')).toBeDefined()
|
||||
expect(wrapper.get('[data-testid="rescan-note"]').text()).toContain('A rescan is running')
|
||||
})
|
||||
|
||||
it('asks before rescanning everything and says how long it takes', async () => {
|
||||
vi.mocked(axios.post).mockResolvedValue({ data: { queued: 1200, scope: 'all' } })
|
||||
const wrapper = await open()
|
||||
|
||||
await wrapper.get('[data-testid="rescan-all"]').trigger('click')
|
||||
await flushPromises()
|
||||
expect(vi.mocked(axios.post)).not.toHaveBeenCalled()
|
||||
expect(body()).toContain('re-runs all scanners on every cached artifact')
|
||||
expect(body()).toContain('1,200 artifacts, 2 at a time and 10.0 seconds each on recent scans: roughly 100 minutes')
|
||||
expect(vi.mocked(axios.get)).toHaveBeenCalledWith('/api/admin/rescan/estimate', { headers: { Authorization: 'Bearer test-key' } })
|
||||
|
||||
dialogButton('Rescan everything').click()
|
||||
await flushPromises()
|
||||
expect(vi.mocked(axios.post)).toHaveBeenCalledWith('/api/admin/rescan', { scope: 'all' }, expect.anything())
|
||||
})
|
||||
|
||||
it('does not invent an estimate before any scan was timed', async () => {
|
||||
estimate = { vulnerable: { artifacts: 1, seconds: null }, all: { artifacts: 7, seconds: null }, avg_scan_seconds: 0, concurrency: 2 }
|
||||
const wrapper = await open()
|
||||
await wrapper.get('[data-testid="rescan-all"]').trigger('click')
|
||||
await flushPromises()
|
||||
expect(body()).toContain('No scan has been timed yet, so there is no estimate.')
|
||||
expect(body()).not.toContain('roughly')
|
||||
})
|
||||
|
||||
it('shows the live rate and the time left while a rescan runs', async () => {
|
||||
statuses = [running]
|
||||
const wrapper = await open()
|
||||
// 4 processed in 40 s is 6 a minute; the server says 60 s remain.
|
||||
expect(wrapper.get('[data-testid="rescan-live"]').text()).toBe('6.0 artifacts a minute. About 1 minute left.')
|
||||
})
|
||||
|
||||
it('polls until the rescan finishes and then stops', async () => {
|
||||
vi.useFakeTimers({ shouldAdvanceTime: true })
|
||||
vi.mocked(axios.post).mockResolvedValue({ data: { queued: 10, scope: 'vulnerable' } })
|
||||
statuses = [idle, running, running, finished]
|
||||
const wrapper = await open()
|
||||
|
||||
await wrapper.get('[data-testid="rescan-vulnerable"]').trigger('click')
|
||||
await flushPromises()
|
||||
const statusCalls = () => vi.mocked(axios.get).mock.calls.filter(([url]) => url === '/api/admin/rescan/status').length
|
||||
|
||||
await vi.advanceTimersByTimeAsync(2100)
|
||||
await vi.advanceTimersByTimeAsync(2100)
|
||||
await flushPromises()
|
||||
expect(wrapper.get('[data-testid="rescan-counts"]').text()).toContain('Finished.')
|
||||
const settled = statusCalls()
|
||||
await vi.advanceTimersByTimeAsync(10000)
|
||||
expect(statusCalls()).toBe(settled)
|
||||
})
|
||||
|
||||
it('shows the running rescan when the server answers 409', async () => {
|
||||
vi.mocked(axios.post).mockRejectedValue({ response: { status: 409 } })
|
||||
statuses = [idle, running]
|
||||
const wrapper = await open()
|
||||
|
||||
await wrapper.get('[data-testid="rescan-vulnerable"]').trigger('click')
|
||||
await flushPromises()
|
||||
expect(wrapper.get('[data-testid="rescan-counts"]').text()).toContain('3 scanned')
|
||||
})
|
||||
|
||||
it('is disabled and explains why when scanning is off', async () => {
|
||||
const wrapper = await open({ enabled: false, concurrency: 2 })
|
||||
expect(wrapper.get('[data-testid="rescan-vulnerable"]').attributes('disabled')).toBeDefined()
|
||||
expect(wrapper.get('[data-testid="rescan-all"]').attributes('disabled')).toBeDefined()
|
||||
expect(wrapper.get('[data-testid="rescan-note"]').text()).toContain('Security scanning is off')
|
||||
expect(vi.mocked(axios.get)).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('asks for the admin key before it posts anything', async () => {
|
||||
localStorage.clear()
|
||||
const wrapper = await open()
|
||||
await wrapper.get('[data-testid="rescan-vulnerable"]').trigger('click')
|
||||
await flushPromises()
|
||||
expect(vi.mocked(axios.post)).not.toHaveBeenCalled()
|
||||
expect(body()).toContain('Enter your admin API key to start a rescan.')
|
||||
})
|
||||
|
||||
it('asks for the admin key before it sizes a full rescan', async () => {
|
||||
localStorage.clear()
|
||||
const wrapper = await open()
|
||||
await wrapper.get('[data-testid="rescan-all"]').trigger('click')
|
||||
await flushPromises()
|
||||
expect(vi.mocked(axios.get)).not.toHaveBeenCalledWith('/api/admin/rescan/estimate', expect.anything())
|
||||
expect(body()).toContain('Enter your admin API key to start a rescan.')
|
||||
})
|
||||
|
||||
it('forgets a key the server refuses', async () => {
|
||||
vi.mocked(axios.post).mockRejectedValue({ response: { status: 403 } })
|
||||
const wrapper = await open()
|
||||
await wrapper.get('[data-testid="rescan-vulnerable"]').trigger('click')
|
||||
await flushPromises()
|
||||
expect(localStorage.getItem('admin_api_key')).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,201 @@
|
||||
<template>
|
||||
<Card data-testid="rescan-panel">
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">Rescan</CardTitle>
|
||||
<CardDescription>Scan cached packages again now, without waiting for the interval. Stored findings are refreshed with the current scanners.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent class="flex flex-col gap-4">
|
||||
<div class="flex flex-col gap-2 sm:flex-row sm:items-center">
|
||||
<Button :icon-start="faRotateRight" :loading="starting === 'vulnerable'" :disabled="blocked" data-testid="rescan-vulnerable" @click="start('vulnerable')">
|
||||
Rescan vulnerable packages
|
||||
</Button>
|
||||
<Button variant="outline" :icon-start="faRotateRight" :loading="starting === 'all'" :disabled="blocked" data-testid="rescan-all" @click="askAll">
|
||||
Rescan everything
|
||||
</Button>
|
||||
</div>
|
||||
<p class="m-0 text-sm text-muted-foreground" data-testid="rescan-note">{{ note }}</p>
|
||||
|
||||
<div v-if="status && status.queued > 0" class="flex flex-col gap-2" data-testid="rescan-progress">
|
||||
<Progress :model-value="processed" :max="status.queued" label="Rescan progress" show-value />
|
||||
<p class="m-0 text-sm" data-testid="rescan-counts">
|
||||
{{ status.running ? 'Running.' : 'Finished.' }}
|
||||
{{ formatNumber(status.done) }} scanned, {{ formatNumber(status.failed) }} failed, of {{ formatNumber(status.queued) }} queued.
|
||||
</p>
|
||||
<p v-if="status.running && liveRate" class="m-0 text-sm text-muted-foreground" data-testid="rescan-live">{{ liveRate }}</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
|
||||
<ConfirmDialog
|
||||
v-model:open="confirmOpen"
|
||||
title="Rescan every cached package?"
|
||||
:description="everythingWarning"
|
||||
confirm-label="Rescan everything"
|
||||
@confirm="start('all')"
|
||||
/>
|
||||
<AdminKeyDialog v-model:open="showKeyDialog" description="Enter your admin API key to start a rescan." @saved="resume" />
|
||||
</Card>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, onUnmounted, ref } from 'vue'
|
||||
import axios from 'axios'
|
||||
import { Button, Card, CardContent, CardDescription, CardHeader, CardTitle, ConfirmDialog, Progress, useToastStore } from '@perfect-design/ui'
|
||||
import AdminKeyDialog from './AdminKeyDialog.vue'
|
||||
import { useAdminKey } from '@/lib/adminKey'
|
||||
import { formatApproxDuration, formatNumber } from '@/lib/format'
|
||||
import { faRotateRight } from '@/lib/icons'
|
||||
|
||||
type Scope = 'vulnerable' | 'all'
|
||||
|
||||
/** Response of GET /api/admin/rescan/status. */
|
||||
interface RescanStatus {
|
||||
enabled: boolean
|
||||
running: boolean
|
||||
scope: string
|
||||
queued: number
|
||||
done: number
|
||||
failed: number
|
||||
elapsed_seconds?: number
|
||||
/** Absent until the first artifact is processed. */
|
||||
eta_seconds?: number
|
||||
}
|
||||
|
||||
/** Response of GET /api/admin/rescan/estimate; seconds is null until a scan has been timed. */
|
||||
interface RescanEstimate {
|
||||
vulnerable: { artifacts: number; seconds: number | null }
|
||||
all: { artifacts: number; seconds: number | null }
|
||||
avg_scan_seconds: number
|
||||
concurrency: number
|
||||
}
|
||||
|
||||
const props = defineProps<{ enabled: boolean; concurrency: number }>()
|
||||
|
||||
const POLL_MS = 2000
|
||||
|
||||
const adminKey = useAdminKey()
|
||||
const toasts = useToastStore()
|
||||
|
||||
const status = ref<RescanStatus | null>(null)
|
||||
const starting = ref<Scope | null>(null)
|
||||
const confirmOpen = ref(false)
|
||||
const showKeyDialog = ref(false)
|
||||
const estimate = ref<RescanEstimate | null>(null)
|
||||
let pendingScope: Scope | null = null
|
||||
let pendingConfirm = false
|
||||
let timer: ReturnType<typeof setTimeout> | undefined
|
||||
|
||||
const running = computed(() => status.value?.running === true)
|
||||
const blocked = computed(() => !props.enabled || running.value || starting.value !== null)
|
||||
const processed = computed(() => (status.value ? status.value.done + status.value.failed : 0))
|
||||
const note = computed(() => {
|
||||
if (!props.enabled) return 'Security scanning is off in the configuration.'
|
||||
if (running.value) return 'A rescan is running. Another one can start when it finishes.'
|
||||
return 'Needs the admin API key. The rescan runs in the background.'
|
||||
})
|
||||
const liveRate = computed(() => {
|
||||
const st = status.value
|
||||
const elapsed = st?.elapsed_seconds ?? 0
|
||||
if (!st || processed.value === 0 || elapsed <= 0) return ''
|
||||
const perMinute = (processed.value / elapsed) * 60
|
||||
const rate = `${perMinute < 10 ? perMinute.toFixed(1) : formatNumber(Math.round(perMinute))} artifacts a minute`
|
||||
return st.eta_seconds === undefined ? rate : `${rate}. About ${formatApproxDuration(st.eta_seconds)} left.`
|
||||
})
|
||||
const everythingWarning = computed(() => {
|
||||
const base = 'This re-runs all scanners on every cached artifact.'
|
||||
const est = estimate.value
|
||||
const all = est?.all
|
||||
if (!est || !all) return `${base} It can take a long time.`
|
||||
const count = `${formatNumber(all.artifacts)} artifacts`
|
||||
if (all.seconds === null) return `${base} ${count} are cached. No scan has been timed yet, so there is no estimate.`
|
||||
const { avg_scan_seconds: avg, concurrency } = est
|
||||
return `${base} ${count}, ${concurrency} at a time and ${avg.toFixed(1)} seconds each on recent scans: roughly ${formatApproxDuration(all.seconds)}.`
|
||||
})
|
||||
|
||||
function errorStatus(err: unknown): number | undefined {
|
||||
return (err as { response?: { status?: number } }).response?.status
|
||||
}
|
||||
|
||||
async function refresh() {
|
||||
const res = await axios.get<RescanStatus>('/api/admin/rescan/status', { headers: adminKey.headers.value })
|
||||
status.value = res.data
|
||||
return res.data
|
||||
}
|
||||
|
||||
function schedulePoll() {
|
||||
clearTimeout(timer)
|
||||
timer = setTimeout(async () => {
|
||||
try {
|
||||
if ((await refresh()).running) schedulePoll()
|
||||
} catch {
|
||||
// The next click shows the error; a failed poll must not toast every two seconds.
|
||||
}
|
||||
}, POLL_MS)
|
||||
}
|
||||
|
||||
async function askAll() {
|
||||
adminKey.load()
|
||||
if (!adminKey.key.value) {
|
||||
pendingConfirm = true
|
||||
showKeyDialog.value = true
|
||||
return
|
||||
}
|
||||
confirmOpen.value = true
|
||||
try {
|
||||
estimate.value = (await axios.get<RescanEstimate>('/api/admin/rescan/estimate', { headers: adminKey.headers.value })).data
|
||||
} catch {
|
||||
estimate.value = null
|
||||
}
|
||||
}
|
||||
|
||||
async function start(scope: Scope) {
|
||||
adminKey.load()
|
||||
if (!adminKey.key.value) {
|
||||
pendingScope = scope
|
||||
showKeyDialog.value = true
|
||||
return
|
||||
}
|
||||
starting.value = scope
|
||||
try {
|
||||
const res = await axios.post<{ queued: number }>('/api/admin/rescan', { scope }, { headers: adminKey.headers.value })
|
||||
toasts.success('Rescan started', `${formatNumber(res.data.queued)} artifacts queued.`)
|
||||
await refresh()
|
||||
if (status.value?.running) schedulePoll()
|
||||
} catch (err) {
|
||||
const code = errorStatus(err)
|
||||
if (code === 409) {
|
||||
toasts.info('A rescan is already running', 'Wait for it to finish.')
|
||||
await refresh().then(schedulePoll, () => undefined)
|
||||
} else if (code === 401 || code === 403) {
|
||||
adminKey.clear()
|
||||
toasts.error('Admin key refused', 'Enter a key with the admin role.')
|
||||
} else {
|
||||
toasts.error('Could not start the rescan', err instanceof Error ? err.message : 'Request failed')
|
||||
}
|
||||
} finally {
|
||||
starting.value = null
|
||||
}
|
||||
}
|
||||
|
||||
function resume() {
|
||||
const scope = pendingScope
|
||||
pendingScope = null
|
||||
if (pendingConfirm) {
|
||||
pendingConfirm = false
|
||||
void askAll()
|
||||
} else if (scope) {
|
||||
void start(scope)
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
adminKey.load()
|
||||
if (!props.enabled || !adminKey.key.value) return
|
||||
try {
|
||||
if ((await refresh()).running) schedulePoll()
|
||||
} catch {
|
||||
// Progress is optional here; a stale or missing key surfaces when the admin starts a rescan.
|
||||
}
|
||||
})
|
||||
|
||||
onUnmounted(() => clearTimeout(timer))
|
||||
</script>
|
||||
@@ -0,0 +1,55 @@
|
||||
<template>
|
||||
<Card data-testid="scanner-health">
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">Inspectors</CardTitle>
|
||||
<CardDescription>The scanners that examine each package. Health is probed every 30 seconds.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<ErrorState v-if="error && !info" variant="inline" title="Could not load scanners" :message="error" @retry="load(true)" />
|
||||
<LoadingState v-else-if="!info" layout="inline" label="Loading scanners..." />
|
||||
<EmptyState
|
||||
v-else-if="!info.security.enabled"
|
||||
size="sm"
|
||||
title="Scanning is off"
|
||||
description="Packages are served without inspection."
|
||||
/>
|
||||
<ul v-else class="m-0 grid list-none grid-cols-1 gap-2 p-0 sm:grid-cols-2 xl:grid-cols-3">
|
||||
<li
|
||||
v-for="scanner in info.security.scanners"
|
||||
:key="scanner.name"
|
||||
class="flex items-start justify-between gap-3 rounded-md border px-3 py-2"
|
||||
:data-scanner="scanner.name"
|
||||
>
|
||||
<span class="min-w-0">
|
||||
<span class="block break-words text-sm font-medium" :title="scanner.name">{{ scanner.name }}</span>
|
||||
<span v-if="scannerVersion(scanner)" class="block text-xs text-muted-foreground">{{ scannerVersion(scanner) }}</span>
|
||||
</span>
|
||||
<StatusBadge :status="scannerState(scanner)" :label="STATE_LABELS[scannerState(scanner)]" :tones="STATE_TONES" />
|
||||
</li>
|
||||
</ul>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { onMounted } from 'vue'
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
EmptyState,
|
||||
ErrorState,
|
||||
LoadingState,
|
||||
StatusBadge,
|
||||
} from '@perfect-design/ui'
|
||||
import { scannerState, scannerVersion, useSystem } from '@/lib/system'
|
||||
|
||||
const { info, error, load } = useSystem()
|
||||
|
||||
const STATE_LABELS = { healthy: 'Healthy', down: 'Unavailable', off: 'Off' }
|
||||
const STATE_TONES = { healthy: 'success', down: 'danger', off: 'neutral' } as const
|
||||
|
||||
onMounted(() => void load())
|
||||
</script>
|
||||
@@ -0,0 +1,98 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import axios from 'axios'
|
||||
import { flushPromises } from '@vue/test-utils'
|
||||
import TopPackages from './TopPackages.vue'
|
||||
import { mountStrict } from '@/test/mountStrict'
|
||||
|
||||
vi.mock('axios')
|
||||
|
||||
let restore: (() => void) | undefined
|
||||
|
||||
const row = (registry: string, name: string, download_count: number) => ({ registry, name, version: '1.0.0', download_count })
|
||||
|
||||
function serve(rows: unknown[], trending: unknown[] = []) {
|
||||
vi.mocked(axios.get).mockImplementation(async (url: string) => {
|
||||
if (url.startsWith('/api/analytics/trending')) return { data: { packages: trending } } as never
|
||||
if (url.startsWith('/api/packages?layout=rows')) return { data: { packages: rows } } as never
|
||||
throw new Error(`unexpected request: ${url}`)
|
||||
})
|
||||
}
|
||||
|
||||
async function open() {
|
||||
const mounted = await mountStrict(TopPackages)
|
||||
restore = mounted.restore
|
||||
await flushPromises()
|
||||
return mounted.wrapper
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.mocked(axios.get).mockReset()
|
||||
})
|
||||
afterEach(() => {
|
||||
restore?.()
|
||||
restore = undefined
|
||||
})
|
||||
|
||||
describe('TopPackages', () => {
|
||||
it('ranks packages by the stored download counts, so a restart does not empty it', async () => {
|
||||
serve([row('npm', 'left-pad', 12), row('npm', 'left-pad', 5), row('pypi', 'six', 9)])
|
||||
const wrapper = await open()
|
||||
|
||||
const text = wrapper.get('[data-testid="top-packages"]').text()
|
||||
expect(text).toContain('npm · left-pad')
|
||||
expect(text).toContain('pypi · six')
|
||||
expect(text).not.toContain('No downloads yet')
|
||||
expect(vi.mocked(axios.get)).toHaveBeenCalledWith('/api/packages?layout=rows&sort=downloads&order=desc&page=1&page_size=200')
|
||||
expect(vi.mocked(axios.get)).not.toHaveBeenCalledWith(expect.stringContaining('/api/analytics/top'))
|
||||
})
|
||||
|
||||
it('adds the versions of a package and orders by the sum', async () => {
|
||||
serve([row('npm', 'a', 10), row('npm', 'b', 15), row('npm', 'a', 9)])
|
||||
const wrapper = await open()
|
||||
const labels = wrapper.findAll('[data-testid="top-packages"] li').map((li) => li.text())
|
||||
expect(labels[0]).toContain('npm · a')
|
||||
expect(labels[1]).toContain('npm · b')
|
||||
})
|
||||
|
||||
it('counts a Go module once, by its zip, and not its .mod and .info files', async () => {
|
||||
serve([
|
||||
row('go', 'github.com/google/uuid/@v/v1.6.0.zip', 4),
|
||||
row('go', 'github.com/google/uuid/@v/v1.6.0.mod', 4),
|
||||
row('go', 'github.com/google/uuid/@v/v1.6.0.info', 4),
|
||||
])
|
||||
const wrapper = await open()
|
||||
const entries = wrapper.findAll('[data-testid="top-packages"] li')
|
||||
expect(entries).toHaveLength(1)
|
||||
expect(entries[0].text()).toContain('go · github.com/google/uuid')
|
||||
expect(entries[0].text()).toContain('4')
|
||||
expect(entries[0].text()).not.toContain('12')
|
||||
})
|
||||
|
||||
it('says so when no package has a download', async () => {
|
||||
serve([row('npm', 'left-pad', 0)])
|
||||
const wrapper = await open()
|
||||
expect(wrapper.get('[data-testid="top-packages"]').text()).toContain('No downloads yet')
|
||||
})
|
||||
|
||||
it('shows the change against the previous 7 days for trending packages', async () => {
|
||||
serve([], [
|
||||
{ Registry: 'npm', Name: 'left-pad', Downloads: 9, RecentDownloads: 9, PreviousDownloads: 4 },
|
||||
{ Registry: 'npm', Name: 'six', Downloads: 3, RecentDownloads: 3, PreviousDownloads: 8 },
|
||||
])
|
||||
const wrapper = await open()
|
||||
const rows = wrapper.findAll('[data-testid="top-packages"] li').map((li) => li.text())
|
||||
const pad = rows.find((r) => r.includes('left-pad'))
|
||||
const six = rows.find((r) => r.includes('six'))
|
||||
expect(pad).toMatch(/\+5/)
|
||||
expect(six).toMatch(/[-−]5/)
|
||||
})
|
||||
|
||||
it('names where each ranking comes from', async () => {
|
||||
serve([row('npm', 'left-pad', 3)])
|
||||
const wrapper = await open()
|
||||
const text = wrapper.get('[data-testid="top-packages"]').text()
|
||||
expect(text).toContain('The counts survive restarts.')
|
||||
expect(text).toContain('the change from the 7 days before')
|
||||
expect(text).not.toContain('restarts with the server')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,122 @@
|
||||
<template>
|
||||
<div class="grid gap-6 lg:grid-cols-2" data-testid="top-packages">
|
||||
<Card class="min-w-0">
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">Most requested</CardTitle>
|
||||
<CardDescription>Downloads served from the cache. The counts survive restarts.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<LoadingState v-if="loading" layout="inline" label="Loading top packages..." />
|
||||
<ErrorState v-else-if="error" variant="inline" title="Could not load top packages" :message="error" @retry="load" />
|
||||
<EmptyState v-else-if="top.length === 0" size="sm" title="No downloads yet" description="Rankings appear after the first download." />
|
||||
<Leaderboard v-else label="Most requested packages" bars :entries="top" :column-labels="{ rank: 'Rank', name: 'Package', value: 'Downloads', delta: 'Change' }" />
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Card class="min-w-0">
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">Trending</CardTitle>
|
||||
<CardDescription>Downloads in the last 7 days, and the change from the 7 days before. The counts survive restarts.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<LoadingState v-if="loading" layout="inline" label="Loading trending packages..." />
|
||||
<ErrorState v-else-if="error" variant="inline" title="Could not load trending packages" :message="error" @retry="load" />
|
||||
<EmptyState v-else-if="trending.length === 0" size="sm" title="Nothing trending" description="No package was downloaded in the last 7 days." />
|
||||
<Leaderboard v-else label="Trending packages" bars :entries="trending" :column-labels="{ rank: 'Rank', name: 'Package', value: 'Last 7 days', delta: 'Change' }" />
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import axios from 'axios'
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
EmptyState,
|
||||
ErrorState,
|
||||
Leaderboard,
|
||||
LoadingState,
|
||||
type LeaderboardEntry,
|
||||
} from '@perfect-design/ui'
|
||||
import { modulePath } from '@/lib/format'
|
||||
|
||||
/** The trending endpoint serialises Go field names. */
|
||||
interface PopularPackage {
|
||||
Registry: string
|
||||
Name: string
|
||||
Downloads: number
|
||||
RecentDownloads: number
|
||||
PreviousDownloads?: number
|
||||
}
|
||||
|
||||
/** One stored version row; its count is kept in the database. */
|
||||
interface DownloadRow {
|
||||
registry: string
|
||||
name: string
|
||||
download_count: number
|
||||
}
|
||||
|
||||
const LIMIT = 8
|
||||
// Go keeps one row per file (.zip, .mod, .info) of a version; only the zip is a module download.
|
||||
const GO_METADATA = /\.(mod|info)$/
|
||||
const ROWS_URL = '/api/packages?layout=rows&sort=downloads&order=desc&page=1&page_size=200'
|
||||
const stored = ref<DownloadRow[]>([])
|
||||
const recent = ref<PopularPackage[]>([])
|
||||
const loading = ref(false)
|
||||
const error = ref<string | null>(null)
|
||||
|
||||
// Rows with equal registry and module path (a Go module's .zip, .mod and .info) are one package.
|
||||
function entries(rows: PopularPackage[], pick: (p: PopularPackage) => number, change?: (p: PopularPackage) => number): LeaderboardEntry[] {
|
||||
const totals = new Map<string, LeaderboardEntry>()
|
||||
for (const row of rows) {
|
||||
const id = `${row.Registry}/${modulePath(row.Name)}`
|
||||
const existing = totals.get(id)
|
||||
if (existing) {
|
||||
existing.value += pick(row)
|
||||
if (change) existing.delta = (existing.delta ?? 0) + change(row)
|
||||
} else {
|
||||
totals.set(id, { id, label: `${row.Registry} · ${modulePath(row.Name)}`, value: pick(row), ...(change ? { delta: change(row) } : {}) })
|
||||
}
|
||||
}
|
||||
return [...totals.values()].filter((e) => e.value > 0).sort((a, b) => b.value - a.value).slice(0, LIMIT)
|
||||
}
|
||||
|
||||
const top = computed(() =>
|
||||
entries(
|
||||
stored.value
|
||||
.filter((r) => !(r.registry === 'go' && GO_METADATA.test(r.name)))
|
||||
.map((r) => ({ Registry: r.registry, Name: r.name, Downloads: r.download_count, RecentDownloads: 0 })),
|
||||
(p) => p.Downloads,
|
||||
),
|
||||
)
|
||||
const trending = computed(() =>
|
||||
entries(
|
||||
recent.value,
|
||||
(p) => p.RecentDownloads,
|
||||
(p) => p.RecentDownloads - (p.PreviousDownloads ?? 0),
|
||||
),
|
||||
)
|
||||
|
||||
async function load() {
|
||||
loading.value = true
|
||||
error.value = null
|
||||
try {
|
||||
const [topRes, trendRes] = await Promise.all([
|
||||
axios.get<{ packages: DownloadRow[] }>(ROWS_URL),
|
||||
axios.get<{ packages: PopularPackage[] }>('/api/analytics/trending?limit=50'),
|
||||
])
|
||||
stored.value = topRes.data.packages ?? []
|
||||
recent.value = trendRes.data.packages ?? []
|
||||
} catch (err) {
|
||||
error.value = err instanceof Error ? err.message : 'Failed to load package rankings'
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(load)
|
||||
</script>
|
||||
@@ -0,0 +1,12 @@
|
||||
<template>
|
||||
<StatusBadge :status="verdict" :label="VERDICT_LABELS[verdict]" :tones="TONES" :title="VERDICT_MEANINGS[verdict]" />
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { StatusBadge } from '@perfect-design/ui'
|
||||
import { VERDICT_LABELS, VERDICT_MEANINGS, VERDICT_TONES, type Verdict } from '@/lib/verdict'
|
||||
|
||||
defineProps<{ verdict: Verdict }>()
|
||||
|
||||
const TONES = VERDICT_TONES
|
||||
</script>
|
||||
@@ -0,0 +1,50 @@
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import VulnerabilityTable from './VulnerabilityTable.vue'
|
||||
import { mountStrict } from '@/test/mountStrict'
|
||||
import { createTestRouter } from '@/test/router'
|
||||
import type { VulnerabilityEntry } from '@/lib/report'
|
||||
|
||||
let restore: (() => void) | undefined
|
||||
afterEach(() => {
|
||||
restore?.()
|
||||
restore = undefined
|
||||
})
|
||||
|
||||
const entry = (over: Partial<VulnerabilityEntry>): VulnerabilityEntry => ({
|
||||
id: 'GHSA-xvch-5gv4-984h',
|
||||
severity: 'critical',
|
||||
title: 'Prototype pollution',
|
||||
description: '',
|
||||
references: [],
|
||||
fixed_in: '1.2.6',
|
||||
bypassed: false,
|
||||
...over,
|
||||
})
|
||||
|
||||
async function open(vulnerabilities: VulnerabilityEntry[]) {
|
||||
const router = await createTestRouter('/')
|
||||
const mounted = await mountStrict(VulnerabilityTable, { props: { vulnerabilities }, global: { plugins: [router] } })
|
||||
restore = mounted.restore
|
||||
return mounted.wrapper
|
||||
}
|
||||
|
||||
describe('VulnerabilityTable aliases', () => {
|
||||
it('names the other ids of a finding next to its advisory id', async () => {
|
||||
const w = await open([entry({ aliases: ['CVE-2021-44906'] })])
|
||||
expect(w.text()).toContain('GHSA-xvch-5gv4-984h')
|
||||
expect(w.text()).toContain('Also CVE-2021-44906')
|
||||
})
|
||||
|
||||
it('shows no alias line for an older finding without aliases', async () => {
|
||||
const w = await open([entry({})])
|
||||
expect(w.text()).not.toContain('Also ')
|
||||
})
|
||||
|
||||
it('offers a bypass link for the id and for each alias', async () => {
|
||||
const w = await open([entry({ aliases: ['CVE-2021-44906'] })])
|
||||
await w.find('tbody tr').trigger('click')
|
||||
const hrefs = w.findAll('a').map((a) => a.attributes('href') ?? '')
|
||||
expect(hrefs).toContain('/admin/bypasses?type=cve&target=GHSA-xvch-5gv4-984h')
|
||||
expect(hrefs).toContain('/admin/bypasses?type=cve&target=CVE-2021-44906')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,129 @@
|
||||
<template>
|
||||
<Table label="Detected vulnerabilities" layout="cards">
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Severity</TableHead>
|
||||
<TableHead>Advisory</TableHead>
|
||||
<TableHead>Summary</TableHead>
|
||||
<TableHead>Fixed in</TableHead>
|
||||
<TableHead>Found by</TableHead>
|
||||
<TableHead align="center">Details</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
<template v-for="vuln in sorted" :key="vuln.id">
|
||||
<TableRow class="cursor-pointer" :selected="isOpen(vuln.id)" @click="toggle(vuln.id)">
|
||||
<TableCell label="Severity">
|
||||
<span class="flex flex-wrap items-center gap-2">
|
||||
<StatusBadge :status="vuln.severity" :tones="SEVERITY_TONES" :label="formatSeverityName(vuln.severity)" />
|
||||
<StatusBadge v-if="vuln.bypassed" status="bypassed" label="Bypassed" :tones="{ bypassed: 'info' }" />
|
||||
</span>
|
||||
</TableCell>
|
||||
<TableCell label="Advisory" class="font-mono font-medium">
|
||||
<span class="block">{{ vuln.id }}</span>
|
||||
<span v-if="vuln.aliases?.length" class="block text-xs font-normal text-muted-foreground">
|
||||
Also {{ vuln.aliases.join(', ') }}
|
||||
</span>
|
||||
</TableCell>
|
||||
<TableCell label="Summary">
|
||||
<p class="m-0 line-clamp-2 break-words">{{ vuln.title || vuln.description }}</p>
|
||||
</TableCell>
|
||||
<TableCell label="Fixed in">
|
||||
<span v-if="vuln.fixed_in">{{ withVersionPrefix(vuln.fixed_in) }}</span>
|
||||
<span v-else class="text-muted-foreground">No fix yet</span>
|
||||
</TableCell>
|
||||
<TableCell label="Found by">
|
||||
<span class="flex flex-wrap gap-1">
|
||||
<Badge v-for="scanner in vuln.detected_by ?? []" :key="scanner" variant="secondary">{{ scanner }}</Badge>
|
||||
</span>
|
||||
</TableCell>
|
||||
<TableCell label="Details" align="center">
|
||||
<IconButton
|
||||
size="icon-sm"
|
||||
:icon="isOpen(vuln.id) ? faChevronUp : faChevronDown"
|
||||
:label="`${isOpen(vuln.id) ? 'Hide' : 'Show'} details for ${vuln.id}`"
|
||||
:aria-expanded="isOpen(vuln.id)"
|
||||
@click.stop="toggle(vuln.id)"
|
||||
/>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
|
||||
<TableRow v-if="isOpen(vuln.id)" :hoverable="false">
|
||||
<TableCell :colspan="6">
|
||||
<div class="flex flex-col gap-4 py-2">
|
||||
<section v-if="vuln.description">
|
||||
<h3 class="mb-2 text-sm font-semibold">Description</h3>
|
||||
<Markdown :source="vuln.description" :heading-offset="3" />
|
||||
</section>
|
||||
|
||||
<Callout v-if="vuln.bypassed && vuln.bypass" type="note" title="Bypass active" size="sm">
|
||||
{{ vuln.bypass.reason }}. Created by {{ vuln.bypass.created_by }}, expires {{ formatDate(vuln.bypass.expires_at) }}.
|
||||
</Callout>
|
||||
|
||||
<Callout v-if="vuln.fixed_in" type="tip" title="Fix available" size="sm">
|
||||
Upgrade to <strong>{{ withVersionPrefix(vuln.fixed_in) }}</strong> or later.
|
||||
</Callout>
|
||||
|
||||
<section>
|
||||
<h3 class="mb-2 text-sm font-semibold">Bypass this advisory</h3>
|
||||
<p class="m-0 mb-1 text-sm text-muted-foreground">A bypass for any of these ids covers this finding.</p>
|
||||
<ul class="m-0 flex list-none flex-wrap gap-3 p-0 text-sm">
|
||||
<li v-for="id in [vuln.id, ...(vuln.aliases ?? [])]" :key="id">
|
||||
<Link :as="RouterLink" :to="{ path: '/admin/bypasses', query: { type: 'cve', target: id } }">{{ id }}</Link>
|
||||
</li>
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<section v-if="vuln.references && vuln.references.length > 0">
|
||||
<h3 class="mb-2 text-sm font-semibold">References ({{ vuln.references.length }})</h3>
|
||||
<ul class="m-0 flex list-none flex-col gap-1 p-0 text-sm">
|
||||
<li v-for="ref in vuln.references" :key="ref" class="break-all">
|
||||
<Link :href="ref" external>{{ ref }}</Link>
|
||||
</li>
|
||||
</ul>
|
||||
</section>
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
</template>
|
||||
</TableBody>
|
||||
</Table>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, ref } from 'vue'
|
||||
import { RouterLink } from 'vue-router'
|
||||
import {
|
||||
Badge,
|
||||
Callout,
|
||||
IconButton,
|
||||
Link,
|
||||
Markdown,
|
||||
StatusBadge,
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from '@perfect-design/ui'
|
||||
import { formatDate, withVersionPrefix } from '@/lib/format'
|
||||
import type { VulnerabilityEntry } from '@/lib/report'
|
||||
import { faChevronDown, faChevronUp } from '@/lib/icons'
|
||||
import { SEVERITY_TONES, formatSeverityName, severityRank } from '@/lib/severity'
|
||||
|
||||
const props = defineProps<{ vulnerabilities: readonly VulnerabilityEntry[] }>()
|
||||
|
||||
const open = ref(new Set<string>())
|
||||
const sorted = computed(() => [...props.vulnerabilities].sort((a, b) => severityRank(b.severity) - severityRank(a.severity)))
|
||||
|
||||
function isOpen(id: string): boolean {
|
||||
return open.value.has(id)
|
||||
}
|
||||
|
||||
function toggle(id: string) {
|
||||
const next = new Set(open.value)
|
||||
if (!next.delete(id)) next.add(id)
|
||||
open.value = next
|
||||
}
|
||||
</script>
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
faBoxesStacked,
|
||||
faChartColumn,
|
||||
faChartPie,
|
||||
faGear,
|
||||
faShieldHalved,
|
||||
faTriangleExclamation,
|
||||
} from '@/lib/icons'
|
||||
@@ -17,11 +18,17 @@ defineProps<{ readonly sheet?: boolean }>()
|
||||
const GROUPS: SidebarNavGroup[] = [
|
||||
{
|
||||
items: [
|
||||
{ label: 'Dashboard', to: '/', icon: faChartPie },
|
||||
{ label: 'Overview', to: '/', icon: faChartPie },
|
||||
{ label: 'Packages', to: '/packages', icon: faBoxesStacked },
|
||||
{ label: 'Vulnerable', to: '/vulnerable-packages', icon: faTriangleExclamation },
|
||||
{ label: 'Security', to: '/security', icon: faTriangleExclamation },
|
||||
{ label: 'Insights', to: '/stats', icon: faChartColumn },
|
||||
],
|
||||
},
|
||||
{
|
||||
label: 'Admin',
|
||||
items: [
|
||||
{ label: 'Bypasses', to: '/admin/bypasses', icon: faShieldHalved },
|
||||
{ label: 'Stats', to: '/stats', icon: faChartColumn },
|
||||
{ label: 'System', to: '/admin/system', icon: faGear },
|
||||
],
|
||||
},
|
||||
]
|
||||
@@ -29,9 +36,11 @@ const GROUPS: SidebarNavGroup[] = [
|
||||
const SECTION_PREFIXES: ReadonlyArray<readonly [string, string]> = [
|
||||
['/packages', '/packages'],
|
||||
['/package/', '/packages'],
|
||||
['/vulnerable-packages', '/vulnerable-packages'],
|
||||
['/blocked-packages', '/vulnerable-packages'],
|
||||
['/security', '/security'],
|
||||
['/vulnerable-packages', '/security'],
|
||||
['/blocked-packages', '/security'],
|
||||
['/admin/bypasses', '/admin/bypasses'],
|
||||
['/admin/system', '/admin/system'],
|
||||
['/stats', '/stats'],
|
||||
]
|
||||
|
||||
|
||||
@@ -3,12 +3,14 @@ import { createPinia, setActivePinia } from 'pinia'
|
||||
import axios from 'axios'
|
||||
import { flushPromises } from '@vue/test-utils'
|
||||
import App from '@/App.vue'
|
||||
import Dashboard from './Dashboard.vue'
|
||||
import Overview from './Overview.vue'
|
||||
import PackageList from './PackageList.vue'
|
||||
import PackageDetails from './PackageDetails.vue'
|
||||
import VulnerablePackages from './VulnerablePackages.vue'
|
||||
import Security from './Security.vue'
|
||||
import BypassManagementPanel from './BypassManagementPanel.vue'
|
||||
import Stats from './Stats.vue'
|
||||
import Insights from './Insights.vue'
|
||||
import System from './System.vue'
|
||||
import { __resetSystem } from '@/lib/system'
|
||||
import { __resetRealtimeSingleton, useRealtimeStore } from '@/stores/realtime'
|
||||
import { mountStrict } from '@/test/mountStrict'
|
||||
import { createTestRouter } from '@/test/router'
|
||||
@@ -21,20 +23,21 @@ const FAILURE = Object.assign(new Error('Request failed with status code 502'),
|
||||
|
||||
// What each view must not say when the request failed: an empty state would tell the operator there is nothing to see.
|
||||
const EMPTY_TEXT: Record<string, string> = {
|
||||
Dashboard: 'No packages cached yet',
|
||||
Overview: 'Quiet at the desk',
|
||||
PackageList: 'No packages cached yet',
|
||||
VulnerablePackages: 'No vulnerable packages',
|
||||
Stats: 'No registries reported',
|
||||
Security: 'Nothing is held',
|
||||
Insights: 'No registry data yet',
|
||||
BypassManagementPanel: 'No bypasses found',
|
||||
}
|
||||
|
||||
const CASES: Array<[string, Parameters<typeof mountStrict>[0], string]> = [
|
||||
['Dashboard', Dashboard, '/'],
|
||||
['Overview', Overview, '/'],
|
||||
['PackageList', PackageList, '/packages'],
|
||||
['PackageDetails', PackageDetails, '/package/npm/left-pad/1.3.0'],
|
||||
['VulnerablePackages', VulnerablePackages, '/vulnerable-packages'],
|
||||
['Security', Security, '/security'],
|
||||
['BypassManagementPanel', BypassManagementPanel, '/admin/bypasses'],
|
||||
['Stats', Stats, '/stats'],
|
||||
['Insights', Insights, '/stats'],
|
||||
['System', System, '/admin/system'],
|
||||
]
|
||||
|
||||
let restore: (() => void) | undefined
|
||||
@@ -42,6 +45,7 @@ let restore: (() => void) | undefined
|
||||
beforeEach(() => {
|
||||
setActivePinia(createPinia())
|
||||
__resetRealtimeSingleton()
|
||||
__resetSystem()
|
||||
vi.mocked(axios.get).mockRejectedValue(FAILURE)
|
||||
localStorage.setItem('admin_api_key', 'test-key')
|
||||
})
|
||||
@@ -73,16 +77,16 @@ describe('an API failure renders ErrorState, never an empty state', () => {
|
||||
})
|
||||
|
||||
it('retry fetches again and clears the error when the backend is back', async () => {
|
||||
const router = await createTestRouter('/vulnerable-packages')
|
||||
const router = await createTestRouter('/security')
|
||||
const pinia = createPinia()
|
||||
setActivePinia(pinia)
|
||||
const mounted = await mountStrict(VulnerablePackages, { global: { plugins: [pinia, router] } })
|
||||
const mounted = await mountStrict(Security, { global: { plugins: [pinia, router] } })
|
||||
restore = mounted.restore
|
||||
vi.mocked(axios.get).mockResolvedValue({ data: { packages: [] } })
|
||||
await mounted.wrapper.find('[data-slot="error-state"] button').trigger('click')
|
||||
await flushPromises()
|
||||
expect(mounted.wrapper.find('[data-slot="error-state"]').exists()).toBe(false)
|
||||
expect(mounted.wrapper.text()).toContain('No vulnerable packages')
|
||||
expect(mounted.wrapper.text()).toContain('Nothing is held')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -102,6 +106,6 @@ describe('unknown routes', () => {
|
||||
expect(main.find('h1').text()).toBe('Page not found')
|
||||
expect(main.find('[data-slot="empty-state"]').text()).toContain('/vulnerable')
|
||||
const link = main.find('a[href="/"]')
|
||||
expect(link.text()).toMatch(/dashboard/i)
|
||||
expect(link.text()).toMatch(/overview|dashboard/i)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -3,16 +3,29 @@ import { createPinia, setActivePinia } from 'pinia'
|
||||
import axios from 'axios'
|
||||
import { flushPromises } from '@vue/test-utils'
|
||||
import App from '@/App.vue'
|
||||
import Dashboard from './Dashboard.vue'
|
||||
import Overview from './Overview.vue'
|
||||
import PackageList from './PackageList.vue'
|
||||
import PackageDetails from './PackageDetails.vue'
|
||||
import VulnerablePackages from './VulnerablePackages.vue'
|
||||
import Security from './Security.vue'
|
||||
import BypassManagementPanel from './BypassManagementPanel.vue'
|
||||
import Stats from './Stats.vue'
|
||||
import Insights from './Insights.vue'
|
||||
import System from './System.vue'
|
||||
import VulnerabilityBadge from './VulnerabilityBadge.vue'
|
||||
import { __resetSystem } from '@/lib/system'
|
||||
import { serveRows } from '@/test/rowsServer'
|
||||
import { __resetRealtimeSingleton, useRealtimeStore } from '@/stores/realtime'
|
||||
import { usePackageStore } from '@/stores/packages'
|
||||
import { BYPASSES, PACKAGES, REGISTRIES, STATS, TIMESERIES, TREND, VULNERABILITY_REPORT } from '@/test/fixtures'
|
||||
import {
|
||||
BYPASSES,
|
||||
PACKAGES,
|
||||
PACKAGE_ANALYTICS,
|
||||
REGISTRIES,
|
||||
STATS,
|
||||
SYSTEM,
|
||||
TIMESERIES,
|
||||
TOP_PACKAGES,
|
||||
TREND,
|
||||
VULNERABILITY_REPORT,
|
||||
} from '@/test/fixtures'
|
||||
import { mountStrict } from '@/test/mountStrict'
|
||||
import { createTestRouter } from '@/test/router'
|
||||
|
||||
@@ -21,11 +34,22 @@ vi.mock('axios')
|
||||
const API_KEY_STORAGE = 'admin_api_key'
|
||||
|
||||
function respond(url: string) {
|
||||
if (url.startsWith('/api/system')) return { data: SYSTEM }
|
||||
if (url.startsWith('/api/admin/rescan/status')) return { data: { enabled: true, running: false, scope: '', queued: 0, done: 0, failed: 0 } }
|
||||
if (url.startsWith('/api/analytics/package/')) return { data: PACKAGE_ANALYTICS }
|
||||
if (url.startsWith('/api/analytics/')) return { data: TOP_PACKAGES }
|
||||
if (url.startsWith('/api/stats/timeseries')) return { data: TIMESERIES }
|
||||
if (url.startsWith('/api/stats/trend')) return { data: TREND }
|
||||
if (url.startsWith('/api/stats')) return { data: { stats: STATS, registries: REGISTRIES } }
|
||||
if (url.endsWith('/vulnerabilities')) return { data: VULNERABILITY_REPORT }
|
||||
if (url.startsWith('/api/admin/bypasses')) return { data: { bypasses: BYPASSES } }
|
||||
if (url.includes('layout=rows')) return { data: serveRows(url, PACKAGES) }
|
||||
const single = /^\/api\/packages\/([^/]+)\/(.+)\/([^/?]+)$/.exec(url)
|
||||
if (single) {
|
||||
const row = PACKAGES.find((p) => p.registry === single[1] && p.name === single[2] && p.version === single[3])
|
||||
if (!row) throw Object.assign(new Error('not found'), { response: { status: 404 } })
|
||||
return { data: row }
|
||||
}
|
||||
if (url.startsWith('/api/packages')) return { data: { packages: PACKAGES } }
|
||||
throw new Error(`unexpected request: ${url}`)
|
||||
}
|
||||
@@ -35,6 +59,7 @@ let restore: (() => void) | undefined
|
||||
beforeEach(() => {
|
||||
setActivePinia(createPinia())
|
||||
__resetRealtimeSingleton()
|
||||
__resetSystem()
|
||||
vi.mocked(axios.get).mockImplementation(async (url: string) => respond(url) as never)
|
||||
localStorage.setItem(API_KEY_STORAGE, 'test-key')
|
||||
})
|
||||
@@ -57,52 +82,83 @@ async function smoke(component: Parameters<typeof mountStrict>[0], path: string,
|
||||
}
|
||||
|
||||
describe('view smoke tests (strict mode throw, fixture data)', () => {
|
||||
it('Dashboard renders the tiles, chart, feed and recent packages', async () => {
|
||||
it('Overview renders the verdict strip, policy, capacity, trend, rankings, inspectors and feed', async () => {
|
||||
const router = await createTestRouter('/')
|
||||
const pinia = createPinia()
|
||||
setActivePinia(pinia)
|
||||
const rt = useRealtimeStore()
|
||||
vi.spyOn(rt, 'connect').mockImplementation(() => {})
|
||||
rt.events = [{ type: 'package_cached', payload: { name: 'left-pad', version: '1.3.0', registry: 'npm' }, timestamp: Date.now() }]
|
||||
const { wrapper, problems, restore: r } = await mountStrict(Dashboard, { global: { plugins: [pinia, router] } })
|
||||
const { wrapper, problems, restore: r } = await mountStrict(Overview, { global: { plugins: [pinia, router] } })
|
||||
restore = r
|
||||
await flushPromises()
|
||||
|
||||
expect(problems).toEqual([])
|
||||
expect(wrapper.find('h1').text()).toBe('Dashboard')
|
||||
expect(wrapper.text()).toContain('Total packages')
|
||||
expect(wrapper.find('h1').text()).toBe('Overview')
|
||||
|
||||
const strip = wrapper.find('[data-testid="verdict-strip"]').text()
|
||||
for (const word of ['Cleared', 'Held', 'Bypassed', 'Awaiting scan']) expect(strip).toContain(word)
|
||||
// 3 scanned, 1 held, 1 bypassed: 1 cleared; 4 cached, 3 scanned: 1 awaiting.
|
||||
expect(wrapper.find('[data-verdict="cleared"]').text()).toContain('1')
|
||||
expect(wrapper.find('[data-verdict="held"]').attributes('href')).toBe('/security?tab=held')
|
||||
|
||||
expect(wrapper.find('[data-testid="policy-line"]').text()).toContain('Blocks any CRITICAL.')
|
||||
expect(wrapper.find('[data-testid="policy-line"]').text()).toContain('Fail-closed')
|
||||
expect(wrapper.find('[data-testid="cache-capacity"]').text()).toContain('5 GB of 10 GB')
|
||||
expect(wrapper.find('[data-testid="download-trend"] [role="img"]').exists()).toBe(true)
|
||||
expect(wrapper.find('[data-testid="top-packages"]').text()).toContain('npm · left-pad')
|
||||
expect(wrapper.find('[data-testid="scanner-health"]').text()).toContain('grype')
|
||||
expect(wrapper.find('[data-testid="scanner-health"]').text()).toContain('Unavailable')
|
||||
expect(wrapper.find('[data-testid="ws-event-feed"]').text()).toContain('left-pad')
|
||||
expect(wrapper.find('[role="img"]').exists()).toBe(true)
|
||||
expect(wrapper.text()).toContain('Recent packages')
|
||||
expect(wrapper.text()).toContain('github.com/example/module')
|
||||
})
|
||||
|
||||
it('PackageList groups fixture packages and shows severity words', async () => {
|
||||
it('PackageList shows a verdict for each row and filters by it', async () => {
|
||||
const { wrapper, problems } = await smoke(PackageList, '/packages')
|
||||
expect(problems).toEqual([])
|
||||
expect(wrapper.find('h1').text()).toBe('Packages')
|
||||
expect(wrapper.text()).toContain('left-pad')
|
||||
expect(wrapper.text()).toContain('2 versions')
|
||||
expect(wrapper.text()).toContain('requests')
|
||||
|
||||
const trigger = wrapper.findAll('button').find((b) => b.text().includes('left-pad'))
|
||||
await trigger!.trigger('click')
|
||||
await flushPromises()
|
||||
expect(wrapper.text()).toContain('Critical: 1')
|
||||
expect(wrapper.text()).toContain('Blocked')
|
||||
expect(wrapper.find('[data-testid="package-count"]').text()).toContain('1–4 of 4')
|
||||
const text = wrapper.text()
|
||||
for (const word of ['left-pad', 'requests', 'github.com/example/module', 'Held', 'Cleared', 'Bypassed', 'Awaiting scan']) {
|
||||
expect(text).toContain(word)
|
||||
}
|
||||
})
|
||||
|
||||
it('PackageDetails renders the report, severity table and expanded row', async () => {
|
||||
it('PackageList seeds the verdict filter from the URL', async () => {
|
||||
const { wrapper, problems } = await smoke(PackageList, '/packages?verdict=held')
|
||||
expect(problems).toEqual([])
|
||||
expect(wrapper.find('[data-testid="package-count"]').text()).toContain('1–1 of 1')
|
||||
expect(wrapper.text()).toContain('left-pad')
|
||||
expect(wrapper.text()).not.toContain('requests')
|
||||
})
|
||||
|
||||
it('PackageList opens a quick view with a link to the full page', async () => {
|
||||
const { wrapper, problems } = await smoke(PackageList, '/packages?verdict=held')
|
||||
await wrapper.find('tbody tr').trigger('click')
|
||||
await flushPromises()
|
||||
expect(problems).toEqual([])
|
||||
const sheet = document.body.querySelector('[data-slot="sheet-content"]')
|
||||
expect(sheet?.textContent).toContain('1 critical finding. Policy holds any critical finding.')
|
||||
expect(sheet?.querySelector('a[href^="/package/npm/left-pad/1.3.0"]')).not.toBeNull()
|
||||
})
|
||||
|
||||
it('PackageDetails explains the verdict and lists findings most severe first', async () => {
|
||||
const { wrapper, problems } = await smoke(PackageDetails, '/package/npm/left-pad/1.3.0')
|
||||
const router = (wrapper.vm as unknown as { $router: Awaited<ReturnType<typeof createTestRouter>> }).$router
|
||||
await router.push('/package/npm/left-pad/1.3.0')
|
||||
await flushPromises()
|
||||
expect(problems).toEqual([])
|
||||
expect(wrapper.find('h1').text()).toBe('left-pad')
|
||||
expect(wrapper.text()).toContain('Security scan summary')
|
||||
expect(wrapper.text()).toContain('trivy')
|
||||
|
||||
// Most severe first: CRITICAL, HIGH, then LOW.
|
||||
const ids = wrapper.findAll('tbody td.font-mono').map((td) => td.text().replace('CVE ID', ''))
|
||||
const banner = wrapper.find('[data-testid="verdict-banner"]').text()
|
||||
expect(banner).toContain('Held: CVE-2026-0003 is HIGH')
|
||||
expect(banner).toContain('1 critical finding. Policy holds any critical finding.')
|
||||
|
||||
const meta = wrapper.find('[data-testid="package-meta"]').text()
|
||||
expect(meta).toContain('2 KB')
|
||||
expect(meta).toContain('https://registry.npmjs.org')
|
||||
expect(meta).toContain('Removed after 30 days without a request')
|
||||
|
||||
const ids = wrapper.findAll('tbody td.font-mono').map((td) => td.text().replace('Advisory', ''))
|
||||
expect(ids.slice(0, 3)).toEqual(['CVE-2026-0002', 'CVE-2026-0003', 'CVE-2026-0001'])
|
||||
|
||||
await wrapper.find('button[aria-label^="Show details for CVE-2026-0002"]').trigger('click')
|
||||
@@ -111,26 +167,58 @@ describe('view smoke tests (strict mode throw, fixture data)', () => {
|
||||
expect(wrapper.text()).toContain('No fix available')
|
||||
})
|
||||
|
||||
it('VulnerablePackages lists the vulnerable fixture packages', async () => {
|
||||
const { wrapper, problems } = await smoke(VulnerablePackages, '/vulnerable-packages')
|
||||
it('PackageDetails reads its own row, not the grouped package list', async () => {
|
||||
const { wrapper, problems } = await smoke(PackageDetails, '/package/npm/left-pad/1.3.0')
|
||||
expect(problems).toEqual([])
|
||||
expect(wrapper.find('h1').text()).toBe('Vulnerable packages')
|
||||
expect(wrapper.text()).toContain('left-pad')
|
||||
expect(wrapper.text()).not.toContain('requests')
|
||||
expect(wrapper.text()).toContain('Critical')
|
||||
const urls = vi.mocked(axios.get).mock.calls.map((c) => String(c[0]))
|
||||
expect(urls).toContain('/api/packages/npm/left-pad/1.3.0')
|
||||
expect(urls.filter((u) => u.startsWith('/api/packages?'))).toEqual([])
|
||||
expect(wrapper.text()).toContain('2 KB')
|
||||
})
|
||||
|
||||
it('VulnerablePackages on the blocked route keeps only blocked packages', async () => {
|
||||
const { wrapper, problems } = await smoke(VulnerablePackages, '/blocked-packages')
|
||||
it('PackageDetails Inspectors tab shows one row per scanner', async () => {
|
||||
const { wrapper, problems } = await smoke(PackageDetails, '/package/npm/left-pad/1.3.0?tab=inspectors')
|
||||
const router = (wrapper.vm as unknown as { $router: Awaited<ReturnType<typeof createTestRouter>> }).$router
|
||||
await router.push('/package/npm/left-pad/1.3.0?tab=inspectors')
|
||||
await flushPromises()
|
||||
expect(problems).toEqual([])
|
||||
expect(wrapper.find('h1').text()).toBe('Blocked packages')
|
||||
expect(wrapper.text()).toContain('1 vulnerable version')
|
||||
const panel = wrapper.find('[role="tabpanel"]:not([hidden])')
|
||||
const text = panel.text()
|
||||
for (const word of ['trivy', 'osv', 'grype', 'govulncheck', 'v0.58.1', 'No result', 'Off']) expect(text).toContain(word)
|
||||
})
|
||||
|
||||
it('PackageDetails Downloads tab reads the per-package analytics', async () => {
|
||||
const { wrapper, problems } = await smoke(PackageDetails, '/package/npm/left-pad/1.3.0?tab=downloads')
|
||||
const router = (wrapper.vm as unknown as { $router: Awaited<ReturnType<typeof createTestRouter>> }).$router
|
||||
await router.push('/package/npm/left-pad/1.3.0?tab=downloads')
|
||||
await flushPromises()
|
||||
expect(problems).toEqual([])
|
||||
expect(vi.mocked(axios.get)).toHaveBeenCalledWith('/api/analytics/package/npm/left-pad')
|
||||
expect(wrapper.text()).toContain('80 KB')
|
||||
})
|
||||
|
||||
it('Security splits packages by what the policy did', async () => {
|
||||
const { wrapper, problems } = await smoke(Security, '/security')
|
||||
expect(problems).toEqual([])
|
||||
expect(wrapper.find('h1').text()).toBe('Security')
|
||||
const triggers = wrapper.findAll('[role="tab"]').map((t) => t.text())
|
||||
expect(triggers).toEqual(['Held (1)', 'Vulnerable but allowed (1)', 'Bypassed (1)'])
|
||||
expect(wrapper.text()).toContain('left-pad')
|
||||
expect(wrapper.text()).toContain('1 critical finding. Policy holds any critical finding.')
|
||||
})
|
||||
|
||||
it('Security opens on the tab named in the URL', async () => {
|
||||
const { wrapper, problems } = await smoke(Security, '/security?tab=bypassed')
|
||||
expect(problems).toEqual([])
|
||||
const selected = wrapper.findAll('[role="tab"]').find((t) => t.attributes('aria-selected') === 'true')
|
||||
expect(selected?.text()).toBe('Bypassed (1)')
|
||||
expect(wrapper.text()).toContain('a.khan')
|
||||
})
|
||||
|
||||
it('BypassManagementPanel lists bypasses and opens the create dialog', async () => {
|
||||
const { wrapper, problems } = await smoke(BypassManagementPanel, '/admin/bypasses')
|
||||
expect(problems).toEqual([])
|
||||
expect(wrapper.find('h1').text()).toBe('CVE bypass management')
|
||||
expect(wrapper.find('h1').text()).toBe('Bypasses')
|
||||
expect(wrapper.text()).toContain('CVE-2026-0002')
|
||||
expect(wrapper.text()).toContain('Expired')
|
||||
|
||||
@@ -141,6 +229,14 @@ describe('view smoke tests (strict mode throw, fixture data)', () => {
|
||||
expect(document.body.querySelector('textarea')).not.toBeNull()
|
||||
})
|
||||
|
||||
it('BypassManagementPanel opens the form prefilled from a package page link', async () => {
|
||||
const { problems } = await smoke(BypassManagementPanel, '/admin/bypasses?type=package&target=npm/[email protected]')
|
||||
await flushPromises()
|
||||
expect(problems).toEqual([])
|
||||
const input = Array.from(document.body.querySelectorAll<HTMLInputElement>('input')).find((i) => i.value === 'npm/[email protected]')
|
||||
expect(input).toBeDefined()
|
||||
})
|
||||
|
||||
it('BypassManagementPanel asks for the admin key in a dialog, not a native prompt', async () => {
|
||||
localStorage.clear()
|
||||
const prompt = vi.spyOn(window, 'prompt')
|
||||
@@ -166,14 +262,51 @@ describe('view smoke tests (strict mode throw, fixture data)', () => {
|
||||
expect(wrapper.text()).toContain('CVE-2026-0002')
|
||||
})
|
||||
|
||||
it('Stats renders totals, the storage tile and the registry table', async () => {
|
||||
const { wrapper, problems } = await smoke(Stats, '/stats')
|
||||
it('Insights renders the registry breakdown, scan coverage and daily downloads', async () => {
|
||||
const { wrapper, problems } = await smoke(Insights, '/stats')
|
||||
expect(problems).toEqual([])
|
||||
expect(wrapper.find('h1').text()).toBe('Statistics')
|
||||
expect(wrapper.text()).toContain('5 GB / 10 GB')
|
||||
expect(wrapper.text()).toContain('50.0% used')
|
||||
expect(wrapper.text()).toContain('Go modules')
|
||||
expect(wrapper.find('[role="progressbar"]').exists()).toBe(true)
|
||||
expect(wrapper.find('h1').text()).toBe('Insights')
|
||||
const breakdown = wrapper.find('[data-testid="registry-breakdown"]').text()
|
||||
for (const word of ['npm', 'pypi', 'go', '2 GB']) expect(breakdown).toContain(word)
|
||||
expect(wrapper.find('[data-testid="scan-coverage"]').text()).toContain('3 of 4')
|
||||
expect(wrapper.find('[data-testid="daily-downloads"] [role="img"]').exists()).toBe(true)
|
||||
})
|
||||
|
||||
it('System shows the policy, scanners, rescans, cache, pre-warming and build version', async () => {
|
||||
const { wrapper, problems } = await smoke(System, '/admin/system')
|
||||
await flushPromises()
|
||||
expect(problems).toEqual([])
|
||||
expect(wrapper.find('h1').text()).toBe('System')
|
||||
expect(wrapper.find('[data-testid="build-version"]').text()).toBe('v1.8.0')
|
||||
expect(wrapper.find('[data-testid="policy-list"]').text()).toContain('Blocks any CRITICAL.')
|
||||
expect(wrapper.find('[data-testid="policy-list"]').text()).toContain('Fail-closed')
|
||||
expect(wrapper.find('[data-testid="rescan-list"]').text()).toContain('1 day')
|
||||
expect(wrapper.find('[data-testid="cache-list"]').text()).toContain('10 GB')
|
||||
expect(wrapper.text()).toContain('v0.58.1')
|
||||
expect(wrapper.find('[data-testid="prewarming"] button').text()).toContain('Run a cycle now')
|
||||
})
|
||||
|
||||
it('System starts a pre-warming cycle with the admin key', async () => {
|
||||
vi.mocked(axios.post).mockResolvedValue({ data: {} })
|
||||
const { wrapper } = await smoke(System, '/admin/system')
|
||||
await flushPromises()
|
||||
await wrapper.find('[data-testid="prewarming"] button').trigger('click')
|
||||
await flushPromises()
|
||||
expect(vi.mocked(axios.post)).toHaveBeenCalledWith(
|
||||
'/api/admin/prewarming/trigger',
|
||||
null,
|
||||
expect.objectContaining({ headers: { Authorization: 'Bearer test-key' } }),
|
||||
)
|
||||
})
|
||||
|
||||
it('System asks for the key before it triggers anything', async () => {
|
||||
localStorage.clear()
|
||||
const { wrapper } = await smoke(System, '/admin/system')
|
||||
await flushPromises()
|
||||
await wrapper.find('[data-testid="prewarming"] button').trigger('click')
|
||||
await flushPromises()
|
||||
expect(vi.mocked(axios.post)).not.toHaveBeenCalled()
|
||||
expect(document.body.textContent).toContain('Enter your admin API key to start a pre-warming cycle.')
|
||||
})
|
||||
|
||||
it('VulnerabilityBadge prints the severity word for every tone', async () => {
|
||||
@@ -191,7 +324,7 @@ describe('view smoke tests (strict mode throw, fixture data)', () => {
|
||||
expect(tones).toEqual(['danger', 'danger', 'warning', 'info', 'neutral'])
|
||||
})
|
||||
|
||||
it('App renders one banner, one main, a skip link first and the five sections', async () => {
|
||||
it('App renders one banner, one main, a skip link first and the sections', async () => {
|
||||
const { wrapper, problems } = await smoke(App, '/')
|
||||
expect(problems).toEqual([])
|
||||
// A page's own <header> inside <main> is not a banner landmark.
|
||||
@@ -200,16 +333,38 @@ describe('view smoke tests (strict mode throw, fixture data)', () => {
|
||||
const first = document.body.querySelector<HTMLElement>('a[href], button')
|
||||
expect(first?.getAttribute('href')).toBe('#main-content')
|
||||
const nav = wrapper.find('nav[aria-label="Sections"]')
|
||||
expect(nav.findAll('a').map((a) => a.text())).toEqual(['Dashboard', 'Packages', 'Vulnerable', 'Bypasses', 'Stats'])
|
||||
expect(nav.findAll('a').map((a) => a.text())).toEqual(['Overview', 'Packages', 'Security', 'Insights', 'Bypasses', 'System'])
|
||||
expect(document.documentElement.getAttribute('data-style')).toBe('workbench')
|
||||
// Brand column and sidebar items share one left edge: 6 spacing units each.
|
||||
expect(document.body.querySelector('header')?.className).toContain('[&>div]:px-6')
|
||||
expect(nav.classes()).toContain('p-3')
|
||||
})
|
||||
|
||||
it('PackageList still fetches through the store on mount', async () => {
|
||||
it('PackageList asks for one page of rows on mount', async () => {
|
||||
await smoke(PackageList, '/packages')
|
||||
expect(usePackageStore().packagePage.packages.length).toBe(PACKAGES.length)
|
||||
await flushPromises()
|
||||
expect(vi.mocked(axios.get)).toHaveBeenCalledWith(expect.stringContaining('/api/packages?layout=rows'))
|
||||
})
|
||||
})
|
||||
|
||||
describe('old URLs land on the new pages', () => {
|
||||
it.each([
|
||||
['/vulnerable-packages', '/security', 'allowed'],
|
||||
['/blocked-packages', '/security', 'held'],
|
||||
])('%s redirects to %s with tab %s', async (from, path, tab) => {
|
||||
const router = await createTestRouter(from)
|
||||
expect(router.currentRoute.value.path).toBe(path)
|
||||
expect(router.currentRoute.value.query.tab).toBe(tab)
|
||||
})
|
||||
|
||||
it('keeps the severity filter of the old link', async () => {
|
||||
const router = await createTestRouter('/vulnerable-packages?severity=critical')
|
||||
expect(router.currentRoute.value.query).toEqual({ severity: 'critical', tab: 'allowed' })
|
||||
})
|
||||
|
||||
it('/packages/npm still seeds the registry filter', async () => {
|
||||
const { wrapper } = await smoke(PackageList, '/packages/npm', { registry: 'npm' })
|
||||
expect(wrapper.find('[data-testid="package-count"]').text()).toContain('1–2 of 2')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -240,26 +395,28 @@ describe('PyPI rows show the release version, not the file name', () => {
|
||||
if (url.endsWith('/vulnerabilities')) {
|
||||
return { data: { ...VULNERABILITY_REPORT, package: { release_version: '1.17.0' } } } as never
|
||||
}
|
||||
if (url.includes('layout=rows')) return { data: serveRows(url, [SIX as never]) } as never
|
||||
if (url === `/api/packages/pypi/six/${FILE}`) return { data: SIX } as never
|
||||
if (url.startsWith('/api/packages')) return { data: { packages: [SIX] } } as never
|
||||
return respond(url) as never
|
||||
})
|
||||
})
|
||||
|
||||
it('Dashboard recent packages', async () => {
|
||||
const { wrapper } = await smoke(Dashboard, '/')
|
||||
it('PackageList version column', async () => {
|
||||
const { wrapper } = await smoke(PackageList, '/packages')
|
||||
await flushPromises()
|
||||
expect(wrapper.text()).toContain('v1.17.0')
|
||||
expect(wrapper.text()).not.toContain('py2.py3-none-any.whl')
|
||||
})
|
||||
|
||||
it('Dashboard activity feed', async () => {
|
||||
it('Overview activity feed', async () => {
|
||||
const router = await createTestRouter('/')
|
||||
const pinia = createPinia()
|
||||
setActivePinia(pinia)
|
||||
const rt = useRealtimeStore()
|
||||
vi.spyOn(rt, 'connect').mockImplementation(() => {})
|
||||
rt.events = [{ type: 'package_cached', payload: { name: 'six', version: FILE, release_version: '1.17.0', registry: 'pypi' }, timestamp: Date.now() }]
|
||||
const { wrapper, restore: r } = await mountStrict(Dashboard, { global: { plugins: [pinia, router] } })
|
||||
const { wrapper, restore: r } = await mountStrict(Overview, { global: { plugins: [pinia, router] } })
|
||||
restore = r
|
||||
await flushPromises()
|
||||
const feed = wrapper.find('[data-testid="ws-event-feed"]').text()
|
||||
@@ -267,10 +424,8 @@ describe('PyPI rows show the release version, not the file name', () => {
|
||||
expect(feed).not.toContain('whl')
|
||||
})
|
||||
|
||||
it('VulnerablePackages version column', async () => {
|
||||
const { wrapper } = await smoke(VulnerablePackages, '/vulnerable-packages')
|
||||
await flushPromises()
|
||||
await wrapper.find('button[aria-expanded]').trigger('click')
|
||||
it('Security version column', async () => {
|
||||
const { wrapper } = await smoke(Security, '/security?tab=allowed')
|
||||
await flushPromises()
|
||||
expect(wrapper.text()).toContain('v1.17.0')
|
||||
expect(wrapper.text()).not.toContain('py2.py3-none-any.whl')
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
import { computed, ref } from 'vue'
|
||||
|
||||
const STORAGE_KEY = 'admin_api_key'
|
||||
|
||||
const key = ref(typeof localStorage === 'undefined' ? '' : (localStorage.getItem(STORAGE_KEY) ?? ''))
|
||||
|
||||
/** The admin API key the dashboard sends with admin calls; kept in localStorage. */
|
||||
export function useAdminKey() {
|
||||
function load() {
|
||||
key.value = localStorage.getItem(STORAGE_KEY) ?? ''
|
||||
}
|
||||
function save(value: string) {
|
||||
key.value = value
|
||||
localStorage.setItem(STORAGE_KEY, value)
|
||||
}
|
||||
function clear() {
|
||||
key.value = ''
|
||||
localStorage.removeItem(STORAGE_KEY)
|
||||
}
|
||||
const headers = computed(() => ({ Authorization: `Bearer ${key.value}` }))
|
||||
return { key, headers, load, save, clear }
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { bypassesFor, isLive, type Bypass } from './bypass'
|
||||
|
||||
function bypass(over: Partial<Bypass>): Bypass {
|
||||
return {
|
||||
id: 'b',
|
||||
type: 'package',
|
||||
target: 'npm/left-pad',
|
||||
reason: 'r',
|
||||
created_by: 'a',
|
||||
created_at: '2026-01-01T00:00:00Z',
|
||||
expires_at: '2099-01-01T00:00:00Z',
|
||||
notify_on_expiry: false,
|
||||
active: true,
|
||||
...over,
|
||||
}
|
||||
}
|
||||
|
||||
describe('bypassesFor', () => {
|
||||
const pkg = { registry: 'npm', name: 'left-pad', version: '1.3.0' }
|
||||
|
||||
it('matches a package bypass by name and by name@version', () => {
|
||||
const all = [
|
||||
bypass({ id: 'any', target: 'npm/left-pad' }),
|
||||
bypass({ id: 'pinned', target: 'npm/[email protected]' }),
|
||||
bypass({ id: 'other-version', target: 'npm/[email protected]' }),
|
||||
bypass({ id: 'other-package', target: 'npm/lodash' }),
|
||||
]
|
||||
expect(bypassesFor(all, pkg).map((b) => b.id)).toEqual(['any', 'pinned'])
|
||||
})
|
||||
|
||||
it('matches a CVE bypass with no scope or a scope on this package', () => {
|
||||
const all = [
|
||||
bypass({ id: 'global', type: 'cve', target: 'CVE-1' }),
|
||||
bypass({ id: 'scoped', type: 'cve', target: 'CVE-2', applies_to: 'npm/[email protected]' }),
|
||||
bypass({ id: 'elsewhere', type: 'cve', target: 'CVE-3', applies_to: 'npm/lodash' }),
|
||||
]
|
||||
expect(bypassesFor(all, pkg).map((b) => b.id)).toEqual(['global', 'scoped'])
|
||||
})
|
||||
|
||||
it('keys Go packages by module path, not by cache key', () => {
|
||||
const go = { registry: 'go', name: 'github.com/a/b/@v/v1.0.0.zip', version: 'v1.0.0' }
|
||||
expect(bypassesFor([bypass({ target: 'go/github.com/a/[email protected]' })], go)).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('matches a PyPI release version', () => {
|
||||
const py = { registry: 'pypi', name: 'six', version: 'six-1.0.tar.gz', releaseVersion: '1.0' }
|
||||
expect(bypassesFor([bypass({ target: 'pypi/[email protected]' })], py)).toHaveLength(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('isLive', () => {
|
||||
it('requires active and unexpired', () => {
|
||||
const now = Date.parse('2026-06-01T00:00:00Z')
|
||||
expect(isLive(bypass({}), now)).toBe(true)
|
||||
expect(isLive(bypass({ active: false }), now)).toBe(false)
|
||||
expect(isLive(bypass({ expires_at: '2026-01-01T00:00:00Z' }), now)).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,38 @@
|
||||
export interface Bypass {
|
||||
id: string
|
||||
type: 'cve' | 'package'
|
||||
target: string
|
||||
reason: string
|
||||
created_by: string
|
||||
created_at: string
|
||||
expires_at: string
|
||||
applies_to?: string
|
||||
notify_on_expiry: boolean
|
||||
active: boolean
|
||||
}
|
||||
|
||||
export function isExpired(expiresAt: string, now = Date.now()): boolean {
|
||||
return Date.parse(expiresAt) < now
|
||||
}
|
||||
|
||||
/** Active and not yet expired. */
|
||||
export function isLive(bypass: Bypass, now = Date.now()): boolean {
|
||||
return bypass.active && !isExpired(bypass.expires_at, now)
|
||||
}
|
||||
|
||||
/** Bypass keys use the module path for Go, where stored rows end in `/@v/<version>.<ext>`. */
|
||||
function bypassName(registry: string, name: string): string {
|
||||
const at = name.indexOf('/@v/')
|
||||
return registry === 'go' && at !== -1 ? name.slice(0, at) : name
|
||||
}
|
||||
|
||||
/** The bypasses that cover one package version, by the same keys the server matches. */
|
||||
export function bypassesFor(
|
||||
all: readonly Bypass[],
|
||||
pkg: { registry: string; name: string; version: string; releaseVersion?: string },
|
||||
): Bypass[] {
|
||||
const base = `${pkg.registry}/${bypassName(pkg.registry, pkg.name)}`
|
||||
const keys = new Set([`${base}@${pkg.version}`, base])
|
||||
if (pkg.releaseVersion) keys.add(`${base}@${pkg.releaseVersion}`)
|
||||
return all.filter((b) => (b.type === 'package' ? keys.has(b.target) : !b.applies_to || keys.has(b.applies_to)))
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { formatDuration } from './format'
|
||||
import { formatApproxDuration, formatDuration } from './format'
|
||||
|
||||
describe('formatDuration', () => {
|
||||
it.each([
|
||||
@@ -13,3 +13,18 @@ describe('formatDuration', () => {
|
||||
expect(formatDuration(seconds)).toBe(expected)
|
||||
})
|
||||
})
|
||||
|
||||
describe('formatApproxDuration', () => {
|
||||
it.each([
|
||||
[0, '1 second'],
|
||||
[40, '40 seconds'],
|
||||
[59.4, '59 seconds'],
|
||||
[60, '1 minute'],
|
||||
[750, '13 minutes'],
|
||||
[7199, '120 minutes'],
|
||||
[7200, '2 hours'],
|
||||
[36000, '10 hours'],
|
||||
])('%d seconds reads %s', (seconds, expected) => {
|
||||
expect(formatApproxDuration(seconds)).toBe(expected)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -26,6 +26,13 @@ export function formatDuration(seconds: number): string {
|
||||
return plural(Math.round(seconds / SECONDS_PER_MINUTE), 'minute')
|
||||
}
|
||||
|
||||
/** A span in the largest fitting unit, rounded: "40 seconds", "12 minutes", "3 hours". */
|
||||
export function formatApproxDuration(seconds: number): string {
|
||||
if (seconds < SECONDS_PER_MINUTE) return plural(Math.max(1, Math.round(seconds)), 'second')
|
||||
if (seconds < 2 * SECONDS_PER_HOUR) return plural(Math.round(seconds / SECONDS_PER_MINUTE), 'minute')
|
||||
return plural(Math.round(seconds / SECONDS_PER_HOUR), 'hour')
|
||||
}
|
||||
|
||||
export function formatDate(date: string): string {
|
||||
if (!date) return 'N/A'
|
||||
const parsed = new Date(date)
|
||||
@@ -40,3 +47,9 @@ export function displayVersion(pkg: { version: string; release_version?: string
|
||||
export function withVersionPrefix(version: string): string {
|
||||
return version.startsWith('v') ? version : 'v' + version
|
||||
}
|
||||
|
||||
/** Go cache keys end in `/@v/<version>.<ext>`; the module path is what a person recognises. */
|
||||
export function modulePath(name: string): string {
|
||||
const at = name.indexOf('/@v/')
|
||||
return at === -1 ? name : name.slice(0, at)
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
export {
|
||||
faArrowLeft,
|
||||
faArrowRight,
|
||||
faBan,
|
||||
faBox,
|
||||
faBoxOpen,
|
||||
@@ -8,10 +9,14 @@ export {
|
||||
faChartLine,
|
||||
faChartPie,
|
||||
faDownload,
|
||||
faGear,
|
||||
faHardDrive,
|
||||
faHourglassHalf,
|
||||
faKey,
|
||||
faPen,
|
||||
faShieldHalved,
|
||||
faTrash,
|
||||
faUnlockKeyhole,
|
||||
faTriangleExclamation,
|
||||
} from '@fortawesome/free-solid-svg-icons'
|
||||
export {
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { inspectorRows, type ScannerResult } from './inspectors'
|
||||
import type { ScannerInfo } from './system'
|
||||
|
||||
const counts = (critical: number) => ({ critical, high: 0, moderate: 0, low: 0 })
|
||||
|
||||
const configured: ScannerInfo[] = [
|
||||
{ name: 'trivy', enabled: true, healthy: true, version: '0.58.1' },
|
||||
{ name: 'grype', enabled: true, healthy: false, version: '' },
|
||||
{ name: 'govulncheck', enabled: true, healthy: true, version: '1.1.4' },
|
||||
{ name: 'pip-audit', enabled: false, healthy: null, version: '' },
|
||||
]
|
||||
|
||||
describe('inspectorRows', () => {
|
||||
it('lists reporting scanners first, with their counts and the configured version', () => {
|
||||
const results: ScannerResult[] = [{ name: 'trivy', findings: 1, severity_counts: counts(1) }]
|
||||
const [first] = inspectorRows('npm', results, configured)
|
||||
expect(first).toMatchObject({ name: 'trivy', status: 'reported', version: '0.58.1', findings: 1, health: 'healthy' })
|
||||
expect(first.counts?.critical).toBe(1)
|
||||
})
|
||||
|
||||
it('explains each scanner that did not report', () => {
|
||||
const rows = inspectorRows('npm', [{ name: 'trivy', findings: 0, severity_counts: counts(0) }], configured)
|
||||
const status = Object.fromEntries(rows.map((r) => [r.name, r.status]))
|
||||
expect(status).toEqual({
|
||||
trivy: 'reported',
|
||||
grype: 'no-result',
|
||||
govulncheck: 'not-applicable',
|
||||
'pip-audit': 'off',
|
||||
})
|
||||
})
|
||||
|
||||
it('flags a reporting scanner that is now unhealthy', () => {
|
||||
const rows = inspectorRows('npm', [{ name: 'grype', findings: 0, severity_counts: counts(0) }], configured)
|
||||
expect(rows[0].health).toBe('down')
|
||||
})
|
||||
|
||||
it('keeps a reported scanner that is no longer configured', () => {
|
||||
const rows = inspectorRows('npm', [{ name: 'retired', findings: 2, severity_counts: counts(2) }], configured)
|
||||
expect(rows[0]).toMatchObject({ name: 'retired', health: null, version: '' })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,61 @@
|
||||
import { scannerState, type ScannerInfo, type ScannerState } from '@/lib/system'
|
||||
import type { VulnerabilityCounts } from '@/stores/packages'
|
||||
|
||||
/** One entry of the `scanners` array on a package's vulnerability response. */
|
||||
export interface ScannerResult {
|
||||
name: string
|
||||
findings: number
|
||||
severity_counts: VulnerabilityCounts
|
||||
}
|
||||
|
||||
/** Ecosystem-specific scanners only inspect their own registry (mirrors the server's shouldRunScanner). */
|
||||
const REGISTRY_SCANNERS: Record<string, string> = { govulncheck: 'go', 'npm-audit': 'npm', 'pip-audit': 'pypi' }
|
||||
|
||||
export type InspectorStatus = 'reported' | 'no-result' | 'not-applicable' | 'off'
|
||||
|
||||
export interface InspectorRow {
|
||||
name: string
|
||||
version: string
|
||||
status: InspectorStatus
|
||||
health: ScannerState | null
|
||||
counts: VulnerabilityCounts | null
|
||||
findings: number | null
|
||||
}
|
||||
|
||||
export const INSPECTOR_STATUS_LABELS: Record<InspectorStatus, string> = {
|
||||
reported: 'Reported',
|
||||
'no-result': 'No result',
|
||||
'not-applicable': 'Not applicable',
|
||||
off: 'Off',
|
||||
}
|
||||
|
||||
/**
|
||||
* Scanner by severity for one package: every scanner that reported, then each configured scanner that did not,
|
||||
* with the reason it is absent where the registry explains it.
|
||||
*/
|
||||
export function inspectorRows(
|
||||
registry: string,
|
||||
results: readonly ScannerResult[],
|
||||
configured: readonly ScannerInfo[],
|
||||
): InspectorRow[] {
|
||||
const byName = new Map(configured.map((s) => [s.name, s]))
|
||||
const rows: InspectorRow[] = results.map((r) => {
|
||||
const info = byName.get(r.name)
|
||||
return {
|
||||
name: r.name,
|
||||
version: info?.version ?? '',
|
||||
status: 'reported',
|
||||
health: info ? scannerState(info) : null,
|
||||
counts: r.severity_counts,
|
||||
findings: r.findings,
|
||||
}
|
||||
})
|
||||
const reported = new Set(results.map((r) => r.name))
|
||||
for (const info of configured) {
|
||||
if (reported.has(info.name)) continue
|
||||
const own = REGISTRY_SCANNERS[info.name]
|
||||
const status: InspectorStatus = !info.enabled ? 'off' : own && own !== registry ? 'not-applicable' : 'no-result'
|
||||
rows.push({ name: info.name, version: info.version, status, health: scannerState(info), counts: null, findings: null })
|
||||
}
|
||||
return rows
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import axios from 'axios'
|
||||
import { rowsUrl, usePackageRows } from './packageRows'
|
||||
|
||||
vi.mock('axios')
|
||||
|
||||
describe('rowsUrl', () => {
|
||||
it('asks for the rows layout with the page', () => {
|
||||
expect(rowsUrl({ page: 2, pageSize: 25 })).toBe('/api/packages?layout=rows&page=2&page_size=25')
|
||||
})
|
||||
|
||||
it('adds only the filters that are set', () => {
|
||||
const url = rowsUrl({ q: ' left ', registry: 'npm', verdict: 'held', severity: ['critical', 'high'], sort: 'size', order: 'desc', page: 1, pageSize: 50 })
|
||||
const params = new URL(url, 'http://x').searchParams
|
||||
expect(Object.fromEntries(params)).toEqual({
|
||||
layout: 'rows',
|
||||
page: '1',
|
||||
page_size: '50',
|
||||
q: 'left',
|
||||
registry: 'npm',
|
||||
verdict: 'held',
|
||||
severity: 'critical,high',
|
||||
sort: 'size',
|
||||
order: 'desc',
|
||||
})
|
||||
})
|
||||
|
||||
it('sends an order only with a sort key', () => {
|
||||
expect(rowsUrl({ order: 'desc', page: 1, pageSize: 25 })).not.toContain('order')
|
||||
})
|
||||
})
|
||||
|
||||
describe('usePackageRows', () => {
|
||||
beforeEach(() => vi.mocked(axios.get).mockReset())
|
||||
|
||||
it('keeps the answer of the last query when an earlier one returns late', async () => {
|
||||
let releaseFirst: (v: unknown) => void = () => {}
|
||||
vi.mocked(axios.get)
|
||||
.mockImplementationOnce(() => new Promise((resolve) => (releaseFirst = resolve)))
|
||||
.mockResolvedValueOnce({ data: { packages: [{ id: 'new' }], total: 1, page: 1, page_size: 25 } })
|
||||
const { rows, total, load } = usePackageRows()
|
||||
|
||||
const first = load({ q: 'a', page: 1, pageSize: 25 })
|
||||
await load({ q: 'ab', page: 1, pageSize: 25 })
|
||||
releaseFirst({ data: { packages: [{ id: 'old' }], total: 9, page: 1, page_size: 25 } })
|
||||
await first
|
||||
|
||||
expect(rows.value.map((r) => r.id)).toEqual(['new'])
|
||||
expect(total.value).toBe(1)
|
||||
})
|
||||
|
||||
it('reports a failure without clearing the rows it already has', async () => {
|
||||
vi.mocked(axios.get)
|
||||
.mockResolvedValueOnce({ data: { packages: [{ id: 'a' }], total: 1, page: 1, page_size: 25 } })
|
||||
.mockRejectedValueOnce(new Error('Request failed with status code 502'))
|
||||
const { rows, error, load } = usePackageRows()
|
||||
|
||||
await load({ page: 1, pageSize: 25 })
|
||||
await load({ page: 2, pageSize: 25 })
|
||||
|
||||
expect(error.value).toContain('502')
|
||||
expect(rows.value).toHaveLength(1)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,96 @@
|
||||
import { ref, type Ref } from 'vue'
|
||||
import axios from 'axios'
|
||||
import type { ApiVerdict, Package } from '@/stores/packages'
|
||||
|
||||
export type RowSort = 'name' | 'version' | 'registry' | 'size' | 'downloads' | 'last_accessed' | 'last_scanned' | 'risk'
|
||||
|
||||
export interface RowQuery {
|
||||
q?: string
|
||||
registry?: string
|
||||
verdict?: ApiVerdict
|
||||
severity?: readonly string[]
|
||||
sort?: RowSort
|
||||
order?: 'asc' | 'desc'
|
||||
page: number
|
||||
pageSize: number
|
||||
}
|
||||
|
||||
type Tally = Record<'critical' | 'high' | 'moderate' | 'low', number>
|
||||
|
||||
/** Counts over the registry and search matches, before the verdict and severity filters. */
|
||||
export interface RowCounts {
|
||||
verdicts: Record<ApiVerdict, number>
|
||||
severity_packages: Tally
|
||||
severity_findings: Tally
|
||||
vulnerable_allowed: number
|
||||
}
|
||||
|
||||
export interface RowsResponse {
|
||||
packages: Package[]
|
||||
total: number
|
||||
page: number
|
||||
page_size: number
|
||||
counts: RowCounts
|
||||
}
|
||||
|
||||
export const EMPTY_COUNTS: RowCounts = {
|
||||
verdicts: { cleared: 0, held: 0, bypassed: 0, pending: 0 },
|
||||
severity_packages: { critical: 0, high: 0, moderate: 0, low: 0 },
|
||||
severity_findings: { critical: 0, high: 0, moderate: 0, low: 0 },
|
||||
vulnerable_allowed: 0,
|
||||
}
|
||||
|
||||
/** URL of one page of package rows; empty filters are left out. */
|
||||
export function rowsUrl(query: RowQuery): string {
|
||||
const params = new URLSearchParams({ layout: 'rows', page: String(query.page), page_size: String(query.pageSize) })
|
||||
if (query.q?.trim()) params.set('q', query.q.trim())
|
||||
if (query.registry) params.set('registry', query.registry)
|
||||
if (query.verdict) params.set('verdict', query.verdict)
|
||||
if (query.severity?.length) params.set('severity', query.severity.join(','))
|
||||
if (query.sort) params.set('sort', query.sort)
|
||||
if (query.sort && query.order) params.set('order', query.order)
|
||||
return `/api/packages?${params.toString()}`
|
||||
}
|
||||
|
||||
export interface PackageRows {
|
||||
rows: Ref<Package[]>
|
||||
total: Ref<number>
|
||||
counts: Ref<RowCounts>
|
||||
loading: Ref<boolean>
|
||||
error: Ref<string | null>
|
||||
load: (query: RowQuery) => Promise<void>
|
||||
}
|
||||
|
||||
/** One page of rows from the server. An answer to an older request is dropped, so the last query wins. */
|
||||
export function usePackageRows(): PackageRows {
|
||||
const rows = ref<Package[]>([])
|
||||
const total = ref(0)
|
||||
const counts = ref<RowCounts>(EMPTY_COUNTS)
|
||||
const loading = ref(false)
|
||||
const error = ref<string | null>(null)
|
||||
let latest = 0
|
||||
|
||||
async function load(query: RowQuery) {
|
||||
const request = ++latest
|
||||
loading.value = true
|
||||
error.value = null
|
||||
try {
|
||||
const { data } = await axios.get(rowsUrl(query))
|
||||
if (request !== latest) return
|
||||
if (!data || !Array.isArray(data.packages)) {
|
||||
error.value = 'Unexpected response format from server'
|
||||
return
|
||||
}
|
||||
rows.value = data.packages
|
||||
total.value = Number.isFinite(data.total) ? data.total : data.packages.length
|
||||
counts.value = data.counts ?? EMPTY_COUNTS
|
||||
} catch (err) {
|
||||
if (request !== latest) return
|
||||
error.value = err instanceof Error ? err.message : 'Failed to load packages'
|
||||
} finally {
|
||||
if (request === latest) loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
return { rows, total, counts, loading, error, load }
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { packageRoute } from './packages'
|
||||
|
||||
describe('packageRoute', () => {
|
||||
it('splits a name with slashes into route segments', () => {
|
||||
expect(packageRoute({ registry: 'go', name: 'github.com/a/b', version: 'v1.0.0' })).toEqual({
|
||||
name: 'package-details',
|
||||
params: { registry: 'go', name: ['github.com', 'a', 'b'], version: 'v1.0.0' },
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,12 @@
|
||||
import type { RouteLocationRaw } from 'vue-router'
|
||||
import type { Package } from '@/stores/packages'
|
||||
import { displayVersion } from '@/lib/format'
|
||||
|
||||
/** Route of a package's full page. A name with slashes becomes the repeatable `name` segments. */
|
||||
export function packageRoute(pkg: Pick<Package, 'registry' | 'name' | 'version'>): RouteLocationRaw {
|
||||
return { name: 'package-details', params: { registry: pkg.registry, name: pkg.name.split('/'), version: pkg.version } }
|
||||
}
|
||||
|
||||
export function packageLabel(pkg: Package): string {
|
||||
return `${pkg.name} ${displayVersion(pkg)}`
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { humanReason, plural } from './reason'
|
||||
|
||||
describe('plural', () => {
|
||||
it.each([
|
||||
[0, '0 findings'],
|
||||
[1, '1 finding'],
|
||||
[2, '2 findings'],
|
||||
])('%i', (n, want) => expect(plural(n, 'finding')).toBe(want))
|
||||
})
|
||||
|
||||
describe('humanReason', () => {
|
||||
it('rewrites a zero threshold as "any"', () => {
|
||||
expect(humanReason('Package has 1 CRITICAL vulnerabilities (threshold: 0)')).toBe('1 critical finding. Policy holds any critical finding.')
|
||||
})
|
||||
|
||||
it('states a count threshold and pluralises both numbers', () => {
|
||||
expect(humanReason('Package has 5 HIGH vulnerabilities (threshold: 3)')).toBe('5 high findings. Policy holds more than 3 high findings.')
|
||||
expect(humanReason('Package has 2 LOW vulnerabilities (threshold: 1)')).toBe('2 low findings. Policy holds more than 1 low finding.')
|
||||
})
|
||||
|
||||
it('rewrites a severity-floor reason', () => {
|
||||
expect(humanReason('Package has HIGH or CRITICAL vulnerabilities')).toBe('Has a high or critical finding. Policy holds a finding at that level.')
|
||||
expect(humanReason('Package has MODERATE, HIGH, or CRITICAL vulnerabilities')).toBe(
|
||||
'Has a moderate, high or critical finding. Policy holds a finding at that level.',
|
||||
)
|
||||
})
|
||||
|
||||
it('passes an unknown or empty reason through', () => {
|
||||
expect(humanReason('scan failed - fail closed')).toBe('scan failed - fail closed')
|
||||
expect(humanReason(undefined)).toBe('')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,33 @@
|
||||
import { formatSeverityName } from '@/lib/severity'
|
||||
|
||||
/** "1 finding", "2 findings". */
|
||||
export function plural(count: number, noun: string): string {
|
||||
return `${count} ${noun}${count === 1 ? '' : 's'}`
|
||||
}
|
||||
|
||||
const THRESHOLD_REASON = /^Package has (\d+) (CRITICAL|HIGH|MODERATE|MEDIUM|LOW) vulnerabilities \(threshold: (-?\d+)\)$/i
|
||||
const FLOOR_REASON = /^Package has ([A-Za-z, ]+?) vulnerabilities$/
|
||||
|
||||
/** Turns the server's hold reason into a sentence a reader can act on. Unknown reasons pass through. */
|
||||
export function humanReason(reason: string | undefined): string {
|
||||
if (!reason) return ''
|
||||
const t = THRESHOLD_REASON.exec(reason)
|
||||
if (t) {
|
||||
const count = Number(t[1])
|
||||
const level = t[2].toLowerCase()
|
||||
const limit = Number(t[3])
|
||||
const rule = limit <= 0 ? `Policy holds any ${level} finding.` : `Policy holds more than ${plural(limit, `${level} finding`)}.`
|
||||
return `${plural(count, `${level} finding`)}. ${rule}`
|
||||
}
|
||||
const f = FLOOR_REASON.exec(reason)
|
||||
if (f) {
|
||||
const levels = f[1]
|
||||
.split(/,\s*(?:or\s+)?|\s+or\s+/)
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean)
|
||||
.map((s) => formatSeverityName(s).toLowerCase())
|
||||
const named = levels.length > 1 ? `${levels.slice(0, -1).join(', ')} or ${levels[levels.length - 1]}` : levels[0]
|
||||
return `Has a ${named} finding. Policy holds a finding at that level.`
|
||||
}
|
||||
return reason
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import type { ScannerResult } from '@/lib/inspectors'
|
||||
import type { AppliedBypass, ApiVerdict, VulnerabilityCounts } from '@/stores/packages'
|
||||
|
||||
export interface VulnerabilityEntry {
|
||||
id: string
|
||||
severity: string
|
||||
title: string
|
||||
description: string
|
||||
references: string[]
|
||||
fixed_in: string
|
||||
detected_by?: string[]
|
||||
aliases?: string[]
|
||||
bypassed: boolean
|
||||
bypass?: { id: string; reason: string; created_by: string; expires_at: string }
|
||||
}
|
||||
|
||||
/** Response of GET /api/packages/{registry}/{name}/{version}/vulnerabilities. */
|
||||
export interface PackageReport {
|
||||
package?: { release_version?: string }
|
||||
scanned: boolean
|
||||
scanner?: string
|
||||
scanned_at?: string
|
||||
status: string
|
||||
message?: string
|
||||
vulnerabilities: VulnerabilityEntry[]
|
||||
vulnerability_count: number
|
||||
severity_counts?: VulnerabilityCounts
|
||||
bypassed_count?: number
|
||||
scanners: ScannerResult[]
|
||||
decision: { verdict: ApiVerdict; blocked: boolean; reason: string; bypass: AppliedBypass | null }
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { describePolicy, scannerState, scannerVersion, type SystemInfo } from './system'
|
||||
|
||||
function security(over: Partial<SystemInfo['security']>): SystemInfo['security'] {
|
||||
return {
|
||||
enabled: true,
|
||||
fail_closed: true,
|
||||
scan_on_download: true,
|
||||
block_on_severity: 'none',
|
||||
block_thresholds: { critical: -1, high: -1, moderate: -1, low: -1 },
|
||||
scan_wait_timeout: 30,
|
||||
scanners: [],
|
||||
rescan: { interval: 0, active_window: 0, concurrency: 1, on_access: false },
|
||||
...over,
|
||||
}
|
||||
}
|
||||
|
||||
describe('describePolicy', () => {
|
||||
it('names a critical-only threshold policy', () => {
|
||||
const policy = describePolicy(security({ block_thresholds: { critical: 0, high: -1, moderate: -1, low: -1 } }))
|
||||
expect(policy).toBe('Blocks any CRITICAL.')
|
||||
})
|
||||
|
||||
it('states a count threshold', () => {
|
||||
const policy = describePolicy(security({ block_thresholds: { critical: 0, high: 3, moderate: -1, low: -1 } }))
|
||||
expect(policy).toBe('Blocks any CRITICAL, more than 3 HIGH.')
|
||||
})
|
||||
|
||||
it('expands the block-on-severity floor to every level at or above it', () => {
|
||||
expect(describePolicy(security({ block_on_severity: 'high' }))).toBe('Blocks any CRITICAL or HIGH.')
|
||||
})
|
||||
|
||||
it('does not repeat a level the thresholds already cover', () => {
|
||||
const policy = describePolicy(security({ block_on_severity: 'critical', block_thresholds: { critical: 0, high: -1, moderate: -1, low: -1 } }))
|
||||
expect(policy).toBe('Blocks any CRITICAL.')
|
||||
})
|
||||
|
||||
it('says so when nothing blocks and when scanning is off', () => {
|
||||
expect(describePolicy(security({}))).toBe('No severity blocks a package.')
|
||||
expect(describePolicy(security({ enabled: false }))).toBe('Scanning is off. Every package is served.')
|
||||
})
|
||||
})
|
||||
|
||||
describe('scannerState', () => {
|
||||
it('maps config and probe to a state', () => {
|
||||
expect(scannerState({ name: 'a', enabled: false, healthy: null, version: '' })).toBe('off')
|
||||
expect(scannerState({ name: 'a', enabled: true, healthy: false, version: '' })).toBe('down')
|
||||
expect(scannerState({ name: 'a', enabled: true, healthy: true, version: '' })).toBe('healthy')
|
||||
})
|
||||
})
|
||||
|
||||
describe('scannerVersion', () => {
|
||||
it('shows the version, API for hosted databases, and nothing for a scanner that is off', () => {
|
||||
expect(scannerVersion({ name: 'trivy', enabled: true, healthy: true, version: '0.58.1' })).toBe('v0.58.1')
|
||||
expect(scannerVersion({ name: 'osv', enabled: true, healthy: true, version: '' })).toBe('API')
|
||||
expect(scannerVersion({ name: 'grype', enabled: true, healthy: false, version: '' })).toBe('Version not reported')
|
||||
expect(scannerVersion({ name: 'npm-audit', enabled: false, healthy: null, version: '' })).toBe('')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,97 @@
|
||||
import { ref } from 'vue'
|
||||
import axios from 'axios'
|
||||
|
||||
export interface ScannerInfo {
|
||||
name: string
|
||||
enabled: boolean
|
||||
/** Null while the scanner is off or has not been probed. */
|
||||
healthy: boolean | null
|
||||
version: string
|
||||
}
|
||||
|
||||
/** Response of GET /api/system. Durations are seconds; a negative threshold means unlimited. */
|
||||
export interface SystemInfo {
|
||||
version: string
|
||||
security: {
|
||||
enabled: boolean
|
||||
fail_closed: boolean
|
||||
scan_on_download: boolean
|
||||
block_on_severity: string
|
||||
block_thresholds: { critical: number; high: number; moderate: number; low: number }
|
||||
scan_wait_timeout: number
|
||||
scanners: ScannerInfo[]
|
||||
rescan: { interval: number; active_window: number; concurrency: number; on_access: boolean }
|
||||
}
|
||||
upstreams: Record<string, string>
|
||||
cache: { max_size: number; idle_ttl: number; default_ttl: number }
|
||||
prewarming: { enabled: boolean; interval: number; top_packages: number }
|
||||
}
|
||||
|
||||
export type ScannerState = 'healthy' | 'down' | 'off'
|
||||
|
||||
export function scannerState(scanner: ScannerInfo): ScannerState {
|
||||
if (!scanner.enabled) return 'off'
|
||||
return scanner.healthy === false ? 'down' : 'healthy'
|
||||
}
|
||||
|
||||
// These scanners query a hosted database, so they have no local binary version.
|
||||
const API_SCANNERS = new Set(['osv', 'github-advisory-database'])
|
||||
|
||||
/** Version line for a scanner: empty when it is off, "API" for hosted databases. */
|
||||
export function scannerVersion(scanner: ScannerInfo): string {
|
||||
if (!scanner.enabled) return ''
|
||||
if (scanner.version) return `v${scanner.version}`
|
||||
return API_SCANNERS.has(scanner.name) ? 'API' : 'Version not reported'
|
||||
}
|
||||
|
||||
const SEVERITY_NAMES = { critical: 'CRITICAL', high: 'HIGH', moderate: 'MODERATE', low: 'LOW' } as const
|
||||
const SEVERITY_ORDER = ['critical', 'high', 'moderate', 'low'] as const
|
||||
|
||||
/** The block policy in words, from the threshold counts and the block-on-severity floor. */
|
||||
export function describePolicy(security: SystemInfo['security']): string {
|
||||
if (!security.enabled) return 'Scanning is off. Every package is served.'
|
||||
const parts: string[] = []
|
||||
for (const level of SEVERITY_ORDER) {
|
||||
const limit = security.block_thresholds[level]
|
||||
if (limit < 0) continue
|
||||
parts.push(limit === 0 ? `any ${SEVERITY_NAMES[level]}` : `more than ${limit} ${SEVERITY_NAMES[level]}`)
|
||||
}
|
||||
const floor = security.block_on_severity.toLowerCase() as keyof typeof SEVERITY_NAMES
|
||||
if (floor in SEVERITY_NAMES) {
|
||||
const covered = SEVERITY_ORDER.slice(0, SEVERITY_ORDER.indexOf(floor) + 1).map((l) => SEVERITY_NAMES[l])
|
||||
parts.push(`any ${covered.join(' or ')}`)
|
||||
}
|
||||
return parts.length === 0 ? 'No severity blocks a package.' : `Blocks ${[...new Set(parts)].join(', ')}.`
|
||||
}
|
||||
|
||||
const info = ref<SystemInfo | null>(null)
|
||||
const error = ref<string | null>(null)
|
||||
let inflight: Promise<void> | null = null
|
||||
|
||||
/** Shared GET /api/system state; concurrent callers share one request. */
|
||||
export function useSystem() {
|
||||
function load(force = false): Promise<void> {
|
||||
if (info.value && !force) return Promise.resolve()
|
||||
inflight ??= axios
|
||||
.get<SystemInfo>('/api/system')
|
||||
.then((res) => {
|
||||
info.value = res.data
|
||||
error.value = null
|
||||
})
|
||||
.catch((err: unknown) => {
|
||||
error.value = err instanceof Error ? err.message : 'Could not load system settings'
|
||||
})
|
||||
.finally(() => {
|
||||
inflight = null
|
||||
})
|
||||
return inflight
|
||||
}
|
||||
return { info, error, load }
|
||||
}
|
||||
|
||||
/** Test hook: forgets the cached response. */
|
||||
export function __resetSystem(): void {
|
||||
info.value = null
|
||||
error.value = null
|
||||
inflight = null
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
export type DownloadPeriod = '1h' | '1day' | '7day' | '30day'
|
||||
|
||||
export const DOWNLOAD_PERIODS: { value: DownloadPeriod; label: string }[] = [
|
||||
{ value: '1h', label: '1 hour' },
|
||||
{ value: '1day', label: '24 hours' },
|
||||
{ value: '7day', label: '7 days' },
|
||||
{ value: '30day', label: '30 days' },
|
||||
]
|
||||
|
||||
export interface TimeSeriesPoint {
|
||||
timestamp: string
|
||||
value: number
|
||||
}
|
||||
|
||||
export interface TimeSeries {
|
||||
period: DownloadPeriod
|
||||
registry: string
|
||||
data_points: TimeSeriesPoint[]
|
||||
}
|
||||
|
||||
/** Axis label of one bucket: a time of day for hourly spans, a day otherwise. */
|
||||
export function bucketLabel(period: DownloadPeriod, timestamp: string): string {
|
||||
const date = new Date(timestamp)
|
||||
if (Number.isNaN(date.getTime())) return timestamp
|
||||
if (period === '1h' || period === '1day') {
|
||||
return date.toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit', timeZone: 'UTC' })
|
||||
}
|
||||
return date.toLocaleDateString('en-GB', { day: 'numeric', month: 'short', timeZone: 'UTC' })
|
||||
}
|
||||
|
||||
/** "2026-11-04T00:00:00Z" as "2026-11-04", the date form the heatmap reads. */
|
||||
export function isoDay(timestamp: string): string {
|
||||
return timestamp.slice(0, 10)
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { verdictOf, VERDICT_LABELS } from './verdict'
|
||||
|
||||
describe('verdictOf', () => {
|
||||
it.each([
|
||||
['the server verdict when present', { scanned: true, status: 'vulnerable', verdict: 'bypassed', isBlocked: false }, 'bypassed'],
|
||||
['held for a blocked package from an older server', { scanned: true, status: 'vulnerable', isBlocked: true }, 'held'],
|
||||
['cleared for a scanned package from an older server', { scanned: true, status: 'clean' }, 'cleared'],
|
||||
['pending for an unscanned package', { scanned: false, status: 'pending' }, 'pending'],
|
||||
] as const)('%s', (_name, vulnerabilities, want) => {
|
||||
expect(verdictOf({ vulnerabilities: { ...vulnerabilities } })).toBe(want)
|
||||
})
|
||||
|
||||
it('is unscanned when the server sends no scan block, as with scanning off', () => {
|
||||
expect(verdictOf({})).toBe('unscanned')
|
||||
})
|
||||
})
|
||||
|
||||
describe('VERDICT_LABELS', () => {
|
||||
it('uses the checkpoint vocabulary', () => {
|
||||
expect(VERDICT_LABELS).toMatchObject({ cleared: 'Cleared', held: 'Held', bypassed: 'Bypassed', pending: 'Awaiting scan' })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,54 @@
|
||||
import type { Package } from '@/stores/packages'
|
||||
|
||||
/** The customs-desk outcome of a package; `unscanned` is a server with scanning off. */
|
||||
export type Verdict = 'cleared' | 'held' | 'bypassed' | 'pending' | 'unscanned'
|
||||
|
||||
export const VERDICT_LABELS: Record<Verdict, string> = {
|
||||
cleared: 'Cleared',
|
||||
held: 'Held',
|
||||
bypassed: 'Bypassed',
|
||||
pending: 'Awaiting scan',
|
||||
unscanned: 'Not scanned',
|
||||
}
|
||||
|
||||
export const VERDICT_TONES: Record<Verdict, 'success' | 'danger' | 'info' | 'warning' | 'neutral'> = {
|
||||
cleared: 'success',
|
||||
held: 'danger',
|
||||
bypassed: 'info',
|
||||
pending: 'warning',
|
||||
unscanned: 'neutral',
|
||||
}
|
||||
|
||||
/** Text colour of a verdict's icon; the label is always shown beside it. */
|
||||
export const VERDICT_TEXT: Record<Verdict, string> = {
|
||||
cleared: 'text-success',
|
||||
held: 'text-destructive',
|
||||
bypassed: 'text-info',
|
||||
pending: 'text-warning',
|
||||
unscanned: 'text-muted-foreground',
|
||||
}
|
||||
|
||||
/** One sentence per verdict, for tooltips and headings. */
|
||||
export const VERDICT_MEANINGS: Record<Verdict, string> = {
|
||||
cleared: 'Scanned and under the block policy. Served to clients.',
|
||||
held: 'At or over the block policy. Clients get a 403.',
|
||||
bypassed: 'An admin bypass applies. Served to clients.',
|
||||
pending: 'No scan result yet.',
|
||||
unscanned: 'Security scanning is off.',
|
||||
}
|
||||
|
||||
export const VERDICT_OPTIONS = (['cleared', 'held', 'bypassed', 'pending'] as const).map((value) => ({
|
||||
value,
|
||||
label: VERDICT_LABELS[value],
|
||||
}))
|
||||
|
||||
/** Sort order for a verdict column: worst first. */
|
||||
export const VERDICT_RANK: Record<Verdict, number> = { held: 4, pending: 3, bypassed: 2, cleared: 1, unscanned: 0 }
|
||||
|
||||
export function verdictOf(pkg: Pick<Package, 'vulnerabilities'>): Verdict {
|
||||
const info = pkg.vulnerabilities
|
||||
if (!info) return 'unscanned'
|
||||
if (info.verdict) return info.verdict
|
||||
if (info.isBlocked) return 'held'
|
||||
return info.scanned ? 'cleared' : 'pending'
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { verdictBanner } from './verdictBanner'
|
||||
import type { PackageReport } from './report'
|
||||
|
||||
function report(over: Partial<PackageReport>): PackageReport {
|
||||
return {
|
||||
scanned: true,
|
||||
status: 'vulnerable',
|
||||
vulnerabilities: [],
|
||||
vulnerability_count: 0,
|
||||
scanners: [],
|
||||
decision: { verdict: 'cleared', blocked: false, reason: '', bypass: null },
|
||||
...over,
|
||||
}
|
||||
}
|
||||
|
||||
const vuln = (id: string, severity: string, extra: object = {}) => ({
|
||||
id,
|
||||
severity,
|
||||
title: '',
|
||||
description: '',
|
||||
references: [],
|
||||
fixed_in: '',
|
||||
bypassed: false,
|
||||
...extra,
|
||||
})
|
||||
|
||||
describe('verdictBanner', () => {
|
||||
it('names the blocking advisory, its severity, the policy and the fix', () => {
|
||||
const banner = verdictBanner(
|
||||
report({
|
||||
vulnerabilities: [vuln('CVE-2021-44906', 'CRITICAL', { fixed_in: '1.2.6' }), vuln('CVE-2022-0001', 'LOW')],
|
||||
decision: { verdict: 'held', blocked: true, reason: 'Package has 1 CRITICAL vulnerabilities (threshold: 0)', bypass: null },
|
||||
}),
|
||||
'Blocks any CRITICAL.',
|
||||
true,
|
||||
)
|
||||
expect(banner.type).toBe('danger')
|
||||
expect(banner.title).toBe('Held: CVE-2021-44906 is CRITICAL')
|
||||
expect(banner.body).toContain('1 critical finding. Policy holds any critical finding.')
|
||||
expect(banner.body).not.toContain('threshold')
|
||||
expect(banner.body).toContain('403')
|
||||
expect(banner.body).toContain('Fixed in v1.2.6')
|
||||
})
|
||||
|
||||
it('summarises many blockers and ignores bypassed ones', () => {
|
||||
const vulns = ['A', 'B', 'C', 'D', 'E'].map((id) => vuln(id, 'critical'))
|
||||
vulns.push(vuln('Z', 'critical', { bypassed: true }))
|
||||
const banner = verdictBanner(report({ vulnerabilities: vulns, decision: { verdict: 'held', blocked: true, reason: '', bypass: null } }), '', true)
|
||||
expect(banner.title).toBe('Held: A, B, C and 2 more are CRITICAL')
|
||||
})
|
||||
|
||||
it('falls back to the reason when no finding explains the hold', () => {
|
||||
const banner = verdictBanner(
|
||||
report({ decision: { verdict: 'held', blocked: true, reason: 'scan failed - fail closed', bypass: null } }),
|
||||
'Blocks any CRITICAL.',
|
||||
true,
|
||||
)
|
||||
expect(banner.title).toBe('Held: scan failed - fail closed')
|
||||
})
|
||||
|
||||
it('says who bypassed a package and when it expires', () => {
|
||||
const banner = verdictBanner(
|
||||
report({
|
||||
decision: {
|
||||
verdict: 'bypassed',
|
||||
blocked: false,
|
||||
reason: '',
|
||||
bypass: {
|
||||
id: 'b1',
|
||||
type: 'package',
|
||||
target: 'npm/x@1',
|
||||
reason: 'Vendored fix',
|
||||
created_by: 'a.khan',
|
||||
created_at: '2026-11-01T00:00:00Z',
|
||||
expires_at: '2026-12-01T00:00:00Z',
|
||||
},
|
||||
},
|
||||
}),
|
||||
'',
|
||||
true,
|
||||
)
|
||||
expect(banner.type).toBe('note')
|
||||
expect(banner.title).toBe('Bypassed: Vendored fix')
|
||||
expect(banner.body).toContain('a.khan')
|
||||
expect(banner.body).toContain('package bypass')
|
||||
})
|
||||
|
||||
it('reports an unscanned package by the fail-closed rule', () => {
|
||||
const base = report({ scanned: false, decision: { verdict: 'pending', blocked: false, reason: '', bypass: null } })
|
||||
expect(verdictBanner(base, '', true).body).toContain('held until one does')
|
||||
expect(verdictBanner(base, '', false).body).not.toContain('held')
|
||||
})
|
||||
|
||||
it('counts findings that stay under the policy', () => {
|
||||
expect(verdictBanner(report({ vulnerability_count: 2 }), '', true).body).toContain('2 findings below the block policy')
|
||||
expect(verdictBanner(report({}), '', true).body).toContain('reported nothing')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,71 @@
|
||||
import type { PackageReport } from '@/lib/report'
|
||||
import { formatDate, withVersionPrefix } from '@/lib/format'
|
||||
import { humanReason, plural } from '@/lib/reason'
|
||||
import { formatSeverityName, severityRank } from '@/lib/severity'
|
||||
|
||||
export interface BannerContent {
|
||||
type: 'danger' | 'success' | 'note' | 'warning'
|
||||
title: string
|
||||
body: string
|
||||
}
|
||||
|
||||
const MAX_NAMED = 3
|
||||
|
||||
function listIds(ids: readonly string[]): string {
|
||||
const shown = ids.slice(0, MAX_NAMED).join(', ')
|
||||
return ids.length > MAX_NAMED ? `${shown} and ${ids.length - MAX_NAMED} more` : shown
|
||||
}
|
||||
|
||||
function heldBanner(report: PackageReport, policy: string): BannerContent {
|
||||
const live = report.vulnerabilities.filter((v) => !v.bypassed)
|
||||
const top = live.reduce((max, v) => Math.max(max, severityRank(v.severity)), 0)
|
||||
const blockers = live.filter((v) => severityRank(v.severity) === top)
|
||||
const reason = humanReason(report.decision.reason)
|
||||
const clients = 'Clients that request this version get a 403.'
|
||||
if (blockers.length === 0) {
|
||||
return { type: 'danger', title: `Held: ${reason || 'the scan did not complete'}`, body: `${policy} ${clients}`.trim() }
|
||||
}
|
||||
const verb = blockers.length === 1 ? 'is' : 'are'
|
||||
const fixes = [...new Set(blockers.map((b) => b.fixed_in).filter(Boolean))]
|
||||
const fix = fixes.length > 0 ? ` Fixed in ${fixes.map(withVersionPrefix).join(', ')}.` : ' No fixed version is listed.'
|
||||
return {
|
||||
type: 'danger',
|
||||
title: `Held: ${listIds(blockers.map((b) => b.id))} ${verb} ${formatSeverityName(blockers[0].severity).toUpperCase()}`,
|
||||
body: `${reason || policy} ${clients}${fix}`.replace(/\s+/g, ' ').trim(),
|
||||
}
|
||||
}
|
||||
|
||||
/** The sentence at the top of a package page: what the verdict is and why. */
|
||||
export function verdictBanner(report: PackageReport, policy: string, failClosed: boolean): BannerContent {
|
||||
const { verdict, bypass } = report.decision
|
||||
switch (verdict) {
|
||||
case 'held':
|
||||
return heldBanner(report, policy)
|
||||
case 'bypassed': {
|
||||
const scope = bypass?.type === 'package' ? 'package' : 'advisory'
|
||||
return {
|
||||
type: 'note',
|
||||
title: `Bypassed: ${bypass?.reason ?? 'an admin bypass applies'}`,
|
||||
body: bypass
|
||||
? `${bypass.created_by} created this ${scope} bypass on ${formatDate(bypass.created_at)}. It expires on ${formatDate(bypass.expires_at)}. Clients are served this version.`
|
||||
: 'Clients are served this version.',
|
||||
}
|
||||
}
|
||||
case 'pending':
|
||||
return {
|
||||
type: 'warning',
|
||||
title: 'Awaiting scan',
|
||||
body: failClosed
|
||||
? 'No scanner has reported on this version yet. The policy is fail-closed, so it is held until one does.'
|
||||
: 'No scanner has reported on this version yet.',
|
||||
}
|
||||
default: {
|
||||
const n = report.vulnerability_count
|
||||
return {
|
||||
type: 'success',
|
||||
title: 'Cleared: no finding reaches the block policy',
|
||||
body: n === 0 ? 'The scanners reported nothing. Clients are served this version.' : `${plural(n, 'finding')} below the block policy. Clients are served this version.`,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,15 @@
|
||||
import { createRouter, createWebHistory, type RouteRecordRaw, type RouterHistory } from 'vue-router'
|
||||
import { createRouter, createWebHistory, type LocationQuery, type RouteRecordRaw, type RouterHistory } from 'vue-router'
|
||||
|
||||
/** Keeps the query string of an old URL when it moves to a tab of the Security page. */
|
||||
function toSecurityTab(tab: string) {
|
||||
return (to: { query: LocationQuery }) => ({ path: '/security', query: { ...to.query, tab } })
|
||||
}
|
||||
|
||||
export const routes: RouteRecordRaw[] = [
|
||||
{
|
||||
path: '/',
|
||||
name: 'dashboard',
|
||||
component: () => import('../components/Dashboard.vue'),
|
||||
name: 'overview',
|
||||
component: () => import('../components/Overview.vue'),
|
||||
},
|
||||
{
|
||||
path: '/packages/:registry?',
|
||||
@@ -20,25 +25,35 @@ export const routes: RouteRecordRaw[] = [
|
||||
props: true,
|
||||
},
|
||||
{
|
||||
path: '/stats',
|
||||
name: 'stats',
|
||||
component: () => import('../components/Stats.vue'),
|
||||
path: '/security',
|
||||
name: 'security',
|
||||
component: () => import('../components/Security.vue'),
|
||||
},
|
||||
{
|
||||
path: '/vulnerable-packages',
|
||||
name: 'vulnerable-packages',
|
||||
component: () => import('../components/VulnerablePackages.vue'),
|
||||
redirect: toSecurityTab('allowed'),
|
||||
},
|
||||
{
|
||||
path: '/blocked-packages',
|
||||
name: 'blocked-packages',
|
||||
component: () => import('../components/VulnerablePackages.vue'),
|
||||
redirect: toSecurityTab('held'),
|
||||
},
|
||||
{
|
||||
path: '/stats',
|
||||
name: 'insights',
|
||||
component: () => import('../components/Insights.vue'),
|
||||
},
|
||||
{
|
||||
path: '/admin/bypasses',
|
||||
name: 'bypasses',
|
||||
component: () => import('../components/BypassManagementPanel.vue'),
|
||||
},
|
||||
{
|
||||
path: '/admin/system',
|
||||
name: 'system',
|
||||
component: () => import('../components/System.vue'),
|
||||
},
|
||||
{
|
||||
path: '/:pathMatch(.*)*',
|
||||
name: 'not-found',
|
||||
|
||||
@@ -1,127 +1,55 @@
|
||||
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'
|
||||
import { usePackageStore } 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', () => {
|
||||
describe('package store', () => {
|
||||
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 } })
|
||||
it('loads the stats of one registry', async () => {
|
||||
vi.mocked(axios.get).mockResolvedValue({ data: { stats: { total_packages: 3 }, registries: { npm: {} } } })
|
||||
const store = usePackageStore()
|
||||
|
||||
await store.fetchPackagePage({ page: 2, pageSize: 25, registry: 'pypi', q: ' six ' })
|
||||
await store.fetchPackagePage({ page: 1, pageSize: 25, registry: 'all', q: '' })
|
||||
await store.fetchStats('npm')
|
||||
|
||||
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',
|
||||
])
|
||||
expect(vi.mocked(axios.get)).toHaveBeenCalledWith('/api/stats?registry=npm')
|
||||
expect(store.stats?.total_packages).toBe(3)
|
||||
expect(store.registries).toEqual({ npm: {} })
|
||||
})
|
||||
|
||||
it('fetchPackages asks for the listed severities only, and for everything without them', async () => {
|
||||
vi.mocked(axios.get).mockResolvedValue({ data: { packages: [] } })
|
||||
it('keeps the last stats and reports the error when a request fails', async () => {
|
||||
vi.mocked(axios.get).mockResolvedValueOnce({ data: { stats: { total_packages: 3 }, registries: {} } })
|
||||
const store = usePackageStore()
|
||||
await store.fetchStats()
|
||||
|
||||
await store.fetchPackages()
|
||||
await store.fetchPackages({ severity: [] })
|
||||
await store.fetchPackages({ severity: ['critical', 'high'] })
|
||||
|
||||
expect(vi.mocked(axios.get).mock.calls.map((c) => c[0])).toEqual([
|
||||
'/api/packages',
|
||||
'/api/packages',
|
||||
'/api/packages?severity=critical,high',
|
||||
])
|
||||
})
|
||||
|
||||
it('keeps the server group count, and counts groups itself when the server sends none', async () => {
|
||||
const store = usePackageStore()
|
||||
vi.mocked(axios.get).mockResolvedValueOnce({ data: { packages: [pkg(1, '2026-01-01T00:00:00Z')], total_groups: 80 } })
|
||||
await store.fetchPackagePage({ page: 3, pageSize: 25 })
|
||||
expect(store.packagePage).toMatchObject({ totalGroups: 80, page: 3, pageSize: 25 })
|
||||
|
||||
vi.mocked(axios.get).mockResolvedValueOnce({
|
||||
data: { packages: [pkg(1, '2026-01-01T00:00:00Z'), pkg(1, '2026-01-02T00:00:00Z', { version: '2.0.0' })] },
|
||||
})
|
||||
await store.fetchPackagePage({ page: 1, pageSize: 25 })
|
||||
expect(store.packagePage.totalGroups).toBe(1)
|
||||
})
|
||||
|
||||
it('drops the answer of a request a newer one has replaced', async () => {
|
||||
const store = usePackageStore()
|
||||
let release: (v: unknown) => void = () => {}
|
||||
vi.mocked(axios.get)
|
||||
.mockImplementationOnce(() => new Promise((resolve) => { release = resolve }))
|
||||
.mockResolvedValueOnce({ data: { packages: [pkg(2, '2026-01-01T00:00:00Z')], total_groups: 1 } })
|
||||
|
||||
const slow = store.fetchPackagePage({ page: 1, pageSize: 25, q: 'old' })
|
||||
await store.fetchPackagePage({ page: 1, pageSize: 25, q: 'new' })
|
||||
release({ data: { packages: [pkg(1, '2026-01-01T00:00:00Z')], total_groups: 1 } })
|
||||
await slow
|
||||
|
||||
expect(store.packagePage.packages.map((p) => p.id)).toEqual(['2'])
|
||||
expect(store.loading).toBe(false)
|
||||
})
|
||||
|
||||
it('reports a failed page request and leaves the last page in place', async () => {
|
||||
const store = usePackageStore()
|
||||
vi.mocked(axios.get).mockRejectedValueOnce(new Error('boom'))
|
||||
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 })
|
||||
await store.fetchStats()
|
||||
|
||||
expect(store.error).toBe('502')
|
||||
expect(store.packagePage.packages).toHaveLength(1)
|
||||
expect(store.stats?.total_packages).toBe(3)
|
||||
expect(store.error).toBe('boom')
|
||||
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()
|
||||
const first = store.fetchStats()
|
||||
const second = store.fetchStats('pypi')
|
||||
expect(store.loading).toBe(true)
|
||||
releases[0]({ data: { stats: { total_packages: 1 }, registries: {} } })
|
||||
await stats
|
||||
await first
|
||||
expect(store.loading).toBe(true)
|
||||
releases[1]({ data: { packages: [] } })
|
||||
await recent
|
||||
releases[1]({ data: { stats: { total_packages: 2 }, registries: {} } })
|
||||
await second
|
||||
expect(store.loading).toBe(false)
|
||||
})
|
||||
|
||||
|
||||
+21
-121
@@ -9,6 +9,20 @@ export interface VulnerabilityCounts {
|
||||
low: number
|
||||
}
|
||||
|
||||
/** What the proxy did with a package; absent on servers that predate verdicts. */
|
||||
export type ApiVerdict = 'cleared' | 'held' | 'bypassed' | 'pending'
|
||||
|
||||
/** The admin bypass that applied to a package. */
|
||||
export interface AppliedBypass {
|
||||
id: string
|
||||
type: 'cve' | 'package'
|
||||
target: string
|
||||
reason: string
|
||||
created_by: string
|
||||
created_at: string
|
||||
expires_at: string
|
||||
}
|
||||
|
||||
export interface VulnerabilityInfo {
|
||||
scanned: boolean
|
||||
status: 'clean' | 'vulnerable' | 'pending' | 'not_scanned'
|
||||
@@ -16,6 +30,10 @@ export interface VulnerabilityInfo {
|
||||
total?: number
|
||||
scannedAt?: string // ISO 8601 timestamp
|
||||
isBlocked?: boolean // Whether download is blocked due to vulnerability thresholds
|
||||
verdict?: ApiVerdict
|
||||
/** Why the package is held. */
|
||||
reason?: string
|
||||
bypass?: AppliedBypass
|
||||
}
|
||||
|
||||
export interface Package {
|
||||
@@ -25,6 +43,7 @@ export interface Package {
|
||||
version: string
|
||||
release_version?: string
|
||||
size: number
|
||||
checksum_sha256?: string
|
||||
cached_at: string
|
||||
last_accessed: string
|
||||
download_count: number
|
||||
@@ -40,49 +59,18 @@ export interface Stats {
|
||||
scanned_packages: number
|
||||
vulnerable_packages: number
|
||||
blocked_packages: number
|
||||
bypassed_packages?: number
|
||||
/** Seconds a cached item can go unrequested before cleanup removes it; 0 means never. */
|
||||
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)
|
||||
|
||||
// Requests overlap (stats next to the recent list, a new search before the last answer),
|
||||
// so loading stays on until the last one settles.
|
||||
// Requests overlap, so loading stays on until the last one settles.
|
||||
let inFlight = 0
|
||||
function begin() {
|
||||
inFlight++
|
||||
@@ -93,88 +81,6 @@ export const usePackageStore = defineStore('packages', () => {
|
||||
inFlight = Math.max(inFlight - 1, 0)
|
||||
if (inFlight === 0) loading.value = false
|
||||
}
|
||||
let pageRequest = 0
|
||||
|
||||
/**
|
||||
* Every package, unpaginated. Only views that filter on scan results need it.
|
||||
* `severity` keeps the packages whose latest scan has a vulnerability of any listed severity.
|
||||
*/
|
||||
async function fetchPackages(options: { severity?: readonly string[] } = {}) {
|
||||
begin()
|
||||
try {
|
||||
const query = options.severity?.length ? `?severity=${options.severity.join(',')}` : ''
|
||||
const response = await axios.get(`/api/packages${query}`)
|
||||
// Only update packages if we got valid data
|
||||
if (response.data && Array.isArray(response.data.packages)) {
|
||||
packages.value = response.data.packages
|
||||
} else {
|
||||
console.warn('Unexpected API response format:', response.data)
|
||||
error.value = 'Unexpected response format from server'
|
||||
}
|
||||
} catch (err: any) {
|
||||
console.error('Failed to fetch packages:', err)
|
||||
error.value = err.message
|
||||
// Don't clear packages on error - keep showing the cached data
|
||||
} finally {
|
||||
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 = '') {
|
||||
begin()
|
||||
@@ -211,16 +117,10 @@ export const usePackageStore = defineStore('packages', () => {
|
||||
}
|
||||
|
||||
return {
|
||||
packages,
|
||||
packagePage,
|
||||
recentPackages,
|
||||
stats,
|
||||
registries,
|
||||
loading,
|
||||
error,
|
||||
fetchPackages,
|
||||
fetchPackagePage,
|
||||
fetchRecentPackages,
|
||||
fetchStats,
|
||||
deletePackage,
|
||||
}
|
||||
|
||||
@@ -4,20 +4,24 @@
|
||||
/* Only the library components the app imports, plus their transitive imports: scanning all of dist adds every component's classes. `pnpm sources` regenerates this list. */
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/ActivityFeed/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/BarChart/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/CalendarHeatmap/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/Card/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/CodeViewer/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/CodeViewer/tokenize/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/DataTable/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/DescriptionList/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/DonutChart/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/KpiTile/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/Leaderboard/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/LineChart/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/Sparkline/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/StatBar/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/StatGroup/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/Table/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/_chart/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/data-display/_shared/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/feedback/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/feedback/Alert/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/feedback/Callout/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/feedback/ConfirmDialog/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/feedback/EmptyState/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/feedback/ErrorState/*.js";
|
||||
@@ -27,41 +31,50 @@
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/forms/Checkbox/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/forms/CheckboxCard/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/forms/Combobox/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/forms/DateInput/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/forms/Field/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/forms/FilterBar/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/forms/Input/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/forms/InputGroup/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/forms/Label/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/forms/NativeSelect/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/forms/NumberInput/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/forms/SearchInput/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/forms/SegmentedControl/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/forms/Textarea/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/forms/TimeInput/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/layout/AppShell/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/layout/ConfigProvider/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/layout/Container/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/layout/PageHeader/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/navigation/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/navigation/Accordion/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/navigation/AppHeader/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/navigation/MobileNav/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/navigation/NavLink/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/navigation/Pagination/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/navigation/SidebarNav/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/navigation/Tabs/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/navigation/ThemeToggle/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/overlays/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/overlays/AlertDialog/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/overlays/Dialog/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/overlays/Popover/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/overlays/Sheet/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/primitives/Avatar/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/primitives/Badge/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/primitives/Button/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/primitives/Icon/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/primitives/IconButton/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/primitives/Link/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/primitives/Progress/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/primitives/ScrollArea/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/primitives/Spinner/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/primitives/StatusBadge/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/primitives/StatusDot/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/primitives/Toggle/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/primitives/ToggleGroup/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/typography/FormattedNumber/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/typography/InlineCode/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/typography/Markdown/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/typography/Markdown/parse/*.js";
|
||||
@source "../../node_modules/@perfect-design/ui/dist/components/typography/RelativeTime/*.js";
|
||||
@@ -122,3 +135,8 @@ html {
|
||||
scroll-behavior: auto !important;
|
||||
}
|
||||
}
|
||||
|
||||
/* The library sort button is 1rem wider than its cell but shifts left only by the cell padding, so the last column overflows the table. */
|
||||
[data-slot='table-head']:last-child {
|
||||
padding-right: calc(1rem - var(--spacing) * 2);
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ export const STATS: Stats = {
|
||||
scanned_packages: 3,
|
||||
vulnerable_packages: 2,
|
||||
blocked_packages: 1,
|
||||
bypassed_packages: 1,
|
||||
}
|
||||
|
||||
export const REGISTRIES = {
|
||||
@@ -34,6 +35,8 @@ export const PACKAGES: Package[] = [
|
||||
total: 4,
|
||||
scannedAt: '2026-01-03T10:05:00Z',
|
||||
isBlocked: true,
|
||||
verdict: 'held',
|
||||
reason: 'Package has 1 CRITICAL vulnerabilities (threshold: 0)',
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -52,6 +55,7 @@ export const PACKAGES: Package[] = [
|
||||
total: 3,
|
||||
scannedAt: '2026-01-02T10:05:00Z',
|
||||
isBlocked: false,
|
||||
verdict: 'cleared',
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -63,7 +67,24 @@ export const PACKAGES: Package[] = [
|
||||
cached_at: '2026-01-01T10:00:00Z',
|
||||
last_accessed: '2026-01-01T10:00:00Z',
|
||||
download_count: 30,
|
||||
vulnerabilities: { scanned: true, status: 'clean', total: 0, scannedAt: '2026-01-01T10:05:00Z' },
|
||||
vulnerabilities: {
|
||||
scanned: true,
|
||||
status: 'vulnerable',
|
||||
counts: { critical: 1, high: 0, moderate: 0, low: 0 },
|
||||
total: 1,
|
||||
scannedAt: '2026-01-01T10:05:00Z',
|
||||
isBlocked: false,
|
||||
verdict: 'bypassed',
|
||||
bypass: {
|
||||
id: 'bypass-1',
|
||||
type: 'package',
|
||||
target: 'pypi/[email protected]',
|
||||
reason: 'Vendored fix',
|
||||
created_by: 'a.khan',
|
||||
created_at: '2026-01-01T00:00:00Z',
|
||||
expires_at: '2099-01-01T00:00:00Z',
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'go-1',
|
||||
@@ -74,7 +95,7 @@ export const PACKAGES: Package[] = [
|
||||
cached_at: '2026-01-04T10:00:00Z',
|
||||
last_accessed: '2026-01-04T10:00:00Z',
|
||||
download_count: 10,
|
||||
vulnerabilities: { scanned: false, status: 'not_scanned' },
|
||||
vulnerabilities: { scanned: false, status: 'not_scanned', isBlocked: false, verdict: 'pending' },
|
||||
},
|
||||
]
|
||||
|
||||
@@ -89,6 +110,16 @@ export const TIMESERIES = {
|
||||
}
|
||||
|
||||
export const VULNERABILITY_REPORT = {
|
||||
decision: {
|
||||
verdict: 'held',
|
||||
blocked: true,
|
||||
reason: 'Package has 1 CRITICAL vulnerabilities (threshold: 0)',
|
||||
bypass: null,
|
||||
},
|
||||
scanners: [
|
||||
{ name: 'trivy', findings: 2, severity_counts: { critical: 1, high: 0, moderate: 0, low: 1 } },
|
||||
{ name: 'osv', findings: 3, severity_counts: { critical: 1, high: 1, moderate: 0, low: 1 } },
|
||||
],
|
||||
scanned: true,
|
||||
scanner: 'trivy+osv',
|
||||
scanned_at: '2026-01-03T10:05:00Z',
|
||||
@@ -104,6 +135,7 @@ export const VULNERABILITY_REPORT = {
|
||||
description: 'A **low** severity sample description.',
|
||||
references: ['https://example.com/advisory/1'],
|
||||
fixed_in: '1.3.1',
|
||||
detected_by: ['trivy', 'osv'],
|
||||
bypassed: false,
|
||||
},
|
||||
{
|
||||
@@ -174,3 +206,45 @@ export const TREND = {
|
||||
{ date: trendDay(0), total_packages: 4, total_size: 7168, vulnerable_packages: 2, critical: 1, high: 1, moderate: 0, low: 0, blocked: 1 },
|
||||
],
|
||||
}
|
||||
|
||||
export const SYSTEM = {
|
||||
version: 'v1.8.0',
|
||||
security: {
|
||||
enabled: true,
|
||||
fail_closed: true,
|
||||
scan_on_download: true,
|
||||
block_on_severity: 'none',
|
||||
block_thresholds: { critical: 0, high: -1, moderate: -1, low: -1 },
|
||||
scan_wait_timeout: 30,
|
||||
scanners: [
|
||||
{ name: 'trivy', enabled: true, healthy: true, version: '0.58.1' },
|
||||
{ name: 'grype', enabled: true, healthy: false, version: '' },
|
||||
{ name: 'osv', enabled: true, healthy: true, version: '' },
|
||||
{ name: 'govulncheck', enabled: false, healthy: null, version: '' },
|
||||
],
|
||||
rescan: { interval: 86400, active_window: 2592000, concurrency: 2, on_access: false },
|
||||
},
|
||||
upstreams: { go: 'https://proxy.golang.org', npm: 'https://registry.npmjs.org', pypi: 'https://pypi.org' },
|
||||
cache: { max_size: 10737418240, idle_ttl: 2592000, default_ttl: 86400 },
|
||||
prewarming: { enabled: true, interval: 3600, top_packages: 100 },
|
||||
}
|
||||
|
||||
export const TOP_PACKAGES = {
|
||||
packages: [
|
||||
{ Registry: 'npm', Name: 'left-pad', Downloads: 40, RecentDownloads: 12, Trend: 0.4 },
|
||||
{ Registry: 'go', Name: 'github.com/example/module/@v/v0.4.1.zip', Downloads: 10, RecentDownloads: 4, Trend: 0 },
|
||||
],
|
||||
total: 2,
|
||||
}
|
||||
|
||||
export const PACKAGE_ANALYTICS = {
|
||||
package: {
|
||||
Registry: 'npm',
|
||||
Name: 'left-pad',
|
||||
TotalDownloads: 40,
|
||||
UniqueVersions: 2,
|
||||
BytesServed: 81920,
|
||||
FirstSeen: '2026-01-01T10:00:00Z',
|
||||
LastDownload: '2026-01-03T10:00:00Z',
|
||||
},
|
||||
}
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
import type { Package } from '@/stores/packages'
|
||||
|
||||
const LEVELS = ['critical', 'high', 'moderate', 'low'] as const
|
||||
|
||||
function verdictOf(p: Package): string {
|
||||
return p.vulnerabilities?.verdict ?? (p.vulnerabilities?.isBlocked ? 'held' : p.vulnerabilities?.scanned ? 'cleared' : 'pending')
|
||||
}
|
||||
|
||||
function count(p: Package, level: (typeof LEVELS)[number]): number {
|
||||
return p.vulnerabilities?.counts?.[level] ?? 0
|
||||
}
|
||||
|
||||
/** A stand-in for GET /api/packages?layout=rows, so views can be tested against the real query contract. */
|
||||
export function serveRows(url: string, all: readonly Package[]) {
|
||||
const params = new URL(url, 'http://test').searchParams
|
||||
const q = (params.get('q') ?? '').toLowerCase()
|
||||
const registry = params.get('registry')
|
||||
const verdict = params.get('verdict')
|
||||
const severities = (params.get('severity') ?? '').split(',').filter(Boolean)
|
||||
const page = Number(params.get('page') ?? 1)
|
||||
const pageSize = Number(params.get('page_size') ?? 25)
|
||||
|
||||
const base = all.filter(
|
||||
(p) =>
|
||||
(!registry || p.registry === registry) &&
|
||||
(!q || [p.name, p.version, p.release_version ?? ''].some((f) => f.toLowerCase().includes(q))),
|
||||
)
|
||||
const counts = {
|
||||
verdicts: { cleared: 0, held: 0, bypassed: 0, pending: 0 } as Record<string, number>,
|
||||
severity_packages: { critical: 0, high: 0, moderate: 0, low: 0 } as Record<string, number>,
|
||||
severity_findings: { critical: 0, high: 0, moderate: 0, low: 0 } as Record<string, number>,
|
||||
vulnerable_allowed: 0,
|
||||
}
|
||||
for (const p of base) {
|
||||
counts.verdicts[verdictOf(p)]++
|
||||
if (verdictOf(p) === 'cleared' && (p.vulnerabilities?.total ?? 0) > 0) counts.vulnerable_allowed++
|
||||
for (const level of LEVELS) {
|
||||
if (count(p, level) > 0) counts.severity_packages[level]++
|
||||
counts.severity_findings[level] += count(p, level)
|
||||
}
|
||||
}
|
||||
|
||||
const matched = base
|
||||
.filter((p) => !verdict || verdictOf(p) === verdict)
|
||||
.filter((p) => severities.length === 0 || severities.some((s) => count(p, s as (typeof LEVELS)[number]) > 0))
|
||||
const sort = params.get('sort')
|
||||
if (sort === 'risk') {
|
||||
matched.sort((a, b) => {
|
||||
for (const level of LEVELS) if (count(a, level) !== count(b, level)) return count(b, level) - count(a, level)
|
||||
return 0
|
||||
})
|
||||
}
|
||||
if (sort === 'downloads') matched.sort((a, b) => (params.get('order') === 'asc' ? 1 : -1) * (a.download_count - b.download_count))
|
||||
return {
|
||||
packages: matched.slice((page - 1) * pageSize, page * pageSize),
|
||||
total: matched.length,
|
||||
page,
|
||||
page_size: pageSize,
|
||||
counts,
|
||||
}
|
||||
}
|
||||
@@ -50,7 +50,7 @@ require (
|
||||
github.com/aws/aws-sdk-go-v2/service/sso v1.39.5 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.44.5 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/sts v1.53.0 // indirect
|
||||
github.com/aws/smithy-go v1.28.9 // indirect
|
||||
github.com/aws/smithy-go v1.28.10 // indirect
|
||||
github.com/beorn7/perks v1.0.1 // indirect
|
||||
github.com/cenkalti/backoff/v4 v4.3.0 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||
@@ -71,7 +71,7 @@ require (
|
||||
github.com/go-logr/stdr v1.2.2 // indirect
|
||||
github.com/go-ole/go-ole v1.3.0 // indirect
|
||||
github.com/go-viper/mapstructure/v2 v2.5.0 // indirect
|
||||
github.com/gofiber/schema v1.10.0 // indirect
|
||||
github.com/gofiber/schema v1.10.2 // indirect
|
||||
github.com/gofiber/utils/v2 v2.6.5 // indirect
|
||||
github.com/google/uuid v1.6.0 // indirect
|
||||
github.com/hashicorp/go-uuid v1.0.4 // indirect
|
||||
@@ -100,7 +100,7 @@ require (
|
||||
github.com/moby/moby/client v0.6.3 // indirect
|
||||
github.com/moby/patternmatcher v0.6.1 // indirect
|
||||
github.com/moby/sys/sequential v0.7.0 // indirect
|
||||
github.com/moby/sys/user v0.5.0 // indirect
|
||||
github.com/moby/sys/user v0.5.1 // indirect
|
||||
github.com/moby/sys/userns v0.2.1 // indirect
|
||||
github.com/moby/term v0.5.2 // indirect
|
||||
github.com/molecule-man/go-brrr v1.3.1 // indirect
|
||||
@@ -125,7 +125,7 @@ require (
|
||||
github.com/tklauser/go-sysconf v0.4.0 // indirect
|
||||
github.com/tklauser/numcpus v0.12.0 // indirect
|
||||
github.com/valyala/bytebufferpool v1.0.0 // indirect
|
||||
github.com/valyala/fasthttp v1.79.0 // indirect
|
||||
github.com/valyala/fasthttp v1.80.0 // indirect
|
||||
github.com/yusufpapurcu/wmi v1.2.4 // indirect
|
||||
go.opentelemetry.io/auto/sdk v1.2.2 // indirect
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.72.0 // indirect
|
||||
|
||||
@@ -42,8 +42,8 @@ github.com/aws/aws-sdk-go-v2/service/ssooidc v1.44.5 h1:uIOBLMhef4N16WguadoHKuBy
|
||||
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.44.5/go.mod h1:NwWmkFLtsTVyXQpbzPOlYLwEoANkdCFjJRtrNcbg/vY=
|
||||
github.com/aws/aws-sdk-go-v2/service/sts v1.53.0 h1:my9Y6lxcqvPV5k4OTqnxr8XbiTDDRos1leEh050Z93U=
|
||||
github.com/aws/aws-sdk-go-v2/service/sts v1.53.0/go.mod h1:MG6N8U9+lY4LqchrlHPqCOSr7hyxw70XU0Et2YR3eNA=
|
||||
github.com/aws/smithy-go v1.28.9 h1:zkZ058OpNX0iGTK24b+ZUEQSMc11CBA6oO7xtKZfzkY=
|
||||
github.com/aws/smithy-go v1.28.9/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc=
|
||||
github.com/aws/smithy-go v1.28.10 h1:SfPnj8fGCVAI/P5YC4/1JjuMsucbPp2dROnSTYNo2PE=
|
||||
github.com/aws/smithy-go v1.28.10/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc=
|
||||
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
|
||||
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
|
||||
github.com/cenkalti/backoff/v4 v4.3.0 h1:MyRJ/UdXutAwSAT+s3wNd7MfTIcy71VQueUuFK343L8=
|
||||
@@ -105,8 +105,8 @@ github.com/goccy/go-json v0.12.0 h1:pD+oWouAiz4yruwXIt/iT+lOMeyhr1aTtxzaMP/RgVI=
|
||||
github.com/goccy/go-json v0.12.0/go.mod h1:3NdmfEkZlB7YI5UFw/qdFKq8XN1aiWR0YyRPWZNQltY=
|
||||
github.com/gofiber/fiber/v3 v3.7.0 h1:aF+GfB7nP9Dd0wVsv6wmr8675v66OGfjSyoDhPmvKEo=
|
||||
github.com/gofiber/fiber/v3 v3.7.0/go.mod h1:7dlbpUZ789TJg4q/VfdS1UWDtB6Fl/Smk6ZYZusMpAQ=
|
||||
github.com/gofiber/schema v1.10.0 h1:d/2/NpHOVD0f29aNvM3KSPmaEDLJZvxW5edtN4Ymd8U=
|
||||
github.com/gofiber/schema v1.10.0/go.mod h1:scfpXbReJ8y9xKlNnrwlewJ8nIGVZZmzoHZ4i5yGxG0=
|
||||
github.com/gofiber/schema v1.10.2 h1:mjqtglIvi/+NK3gJTra6wKOaBLZYx+tdNu7xtaCVPOg=
|
||||
github.com/gofiber/schema v1.10.2/go.mod h1:scfpXbReJ8y9xKlNnrwlewJ8nIGVZZmzoHZ4i5yGxG0=
|
||||
github.com/gofiber/utils/v2 v2.6.5 h1:rU+8ao6LKi3fKOA3sEjfLv1T+2C2IwomeVmEKaqkr4A=
|
||||
github.com/gofiber/utils/v2 v2.6.5/go.mod h1:OqPxdhDW7fPz0dupDanqf4e5O15IyFKy724y/EY9RI4=
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
@@ -187,8 +187,8 @@ github.com/moby/sys/mountinfo v0.7.2 h1:1shs6aH5s4o5H2zQLn796ADW1wMrIwHsyJ2v9Kou
|
||||
github.com/moby/sys/mountinfo v0.7.2/go.mod h1:1YOa8w8Ih7uW0wALDUgT1dTTSBrZ+HiBLGws92L2RU4=
|
||||
github.com/moby/sys/sequential v0.7.0 h1:ASQNGNROJSuOO6LL6bPHbKvuZu6NU8P4ldPWk31zj/8=
|
||||
github.com/moby/sys/sequential v0.7.0/go.mod h1:NfSTAp6V3fw4tmkD62PEcOKeZKquXT8VKCkf7aVR79o=
|
||||
github.com/moby/sys/user v0.5.0 h1:5+S4lyoavGyX1DGs68NW8xpx48T9+a7ogSUc0KjZg8Y=
|
||||
github.com/moby/sys/user v0.5.0/go.mod h1:4mQzP5aTmaLjDLp/dc870oNkik6E9vjRtWYwI05gvow=
|
||||
github.com/moby/sys/user v0.5.1 h1:IMM/21OvpU2icUZczWBwLMf8iBEx1bOoiCQqcy1eKu0=
|
||||
github.com/moby/sys/user v0.5.1/go.mod h1:4mQzP5aTmaLjDLp/dc870oNkik6E9vjRtWYwI05gvow=
|
||||
github.com/moby/sys/userns v0.2.1 h1:4OvdM7BcPkASbuouHsbW3aeMJSFlYDldBRnXVZhaRk8=
|
||||
github.com/moby/sys/userns v0.2.1/go.mod h1:IHUYgu/kao6N8YZlp9Cf444ySSvCmDlmzUcYfDHOl28=
|
||||
github.com/moby/term v0.5.2 h1:6qk3FJAFDs6i/q3W/pQ97SX192qKfZgGjCQqfCJkgzQ=
|
||||
@@ -271,8 +271,8 @@ github.com/tklauser/numcpus v0.12.0 h1:NR85qdvHA9pFse3x3weVZ0r0ST8R6l5RHbZrlRaqo
|
||||
github.com/tklauser/numcpus v0.12.0/go.mod h1:ABHeXzJnr/qqwguhClkZKT1/8VABcYrsyUiUGobwWJg=
|
||||
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
|
||||
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
|
||||
github.com/valyala/fasthttp v1.79.0 h1:32ur91W4kWG+1s6x3oDlP8/KNmjlZZlUzSSC4p9LSWE=
|
||||
github.com/valyala/fasthttp v1.79.0/go.mod h1:NQN+PlgP93+JRPnCiApN5XwnI24oMQf8kuzrxtsTy9A=
|
||||
github.com/valyala/fasthttp v1.80.0 h1:10pVr/QLFGbSX8ikDS0i+wOi2AGY2Sy0TACVpoiG+7U=
|
||||
github.com/valyala/fasthttp v1.80.0/go.mod h1:oulvtxx5dQeORu6sKWaJItcnWXRqiGmrTFQ4gmZjLFM=
|
||||
github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM=
|
||||
github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg=
|
||||
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
|
||||
|
||||
@@ -89,6 +89,10 @@ data:
|
||||
block_on_severity: {{ .Values.security.blockOnSeverity | quote }}
|
||||
scan_on_download: {{ .Values.security.scanOnDownload }}
|
||||
rescan_interval: {{ .Values.security.rescanInterval | quote }}
|
||||
rescan_active_window: {{ .Values.security.rescanActiveWindow | quote }}
|
||||
rescan_concurrency: {{ .Values.security.rescanConcurrency }}
|
||||
rescan_on_access: {{ .Values.security.rescanOnAccess }}
|
||||
scan_wait_timeout: {{ .Values.security.scanWaitTimeout | quote }}
|
||||
update_db_on_startup: {{ .Values.security.updateDbOnStartup }}
|
||||
block_thresholds:
|
||||
critical: {{ .Values.security.blockThresholds.critical }}
|
||||
|
||||
@@ -395,6 +395,10 @@ security:
|
||||
blockOnSeverity: "high" # none, low, medium, high, critical
|
||||
scanOnDownload: true
|
||||
rescanInterval: "24h"
|
||||
rescanActiveWindow: "0s" # rescan only packages requested within this window; 0 = all
|
||||
rescanConcurrency: 1 # scans run in parallel per rescan cycle
|
||||
rescanOnAccess: false # rescan a stale cache hit before serving it
|
||||
scanWaitTimeout: "30s" # how long a first download waits for its scan
|
||||
updateDbOnStartup: false
|
||||
|
||||
blockThresholds:
|
||||
|
||||
@@ -4,6 +4,7 @@ package analytics
|
||||
|
||||
import (
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
@@ -23,6 +24,7 @@ type PackageDownload struct {
|
||||
|
||||
// PackageStats holds statistics for a package
|
||||
type PackageStats struct {
|
||||
versions map[string]struct{}
|
||||
LastDownload time.Time
|
||||
FirstSeen time.Time
|
||||
Registry string
|
||||
@@ -111,6 +113,11 @@ func NewEngine(cfg Config) *Engine {
|
||||
// engine: append to the buffer under downloadsMu, release it, then update
|
||||
// stats under statsMu.
|
||||
func (e *Engine) TrackDownload(download PackageDownload) {
|
||||
// Callers pass names sliced from a request buffer that the server reuses; keep our own copy.
|
||||
download.Registry = strings.Clone(download.Registry)
|
||||
download.Name = strings.Clone(download.Name)
|
||||
download.Version = strings.Clone(download.Version)
|
||||
|
||||
// Append to buffer and decide whether buffer is full.
|
||||
e.downloadsMu.Lock()
|
||||
e.downloads = append(e.downloads, download)
|
||||
@@ -154,8 +161,11 @@ func (e *Engine) updateStats(download PackageDownload) {
|
||||
stats.BytesServed += download.BytesSize
|
||||
stats.LastDownload = download.Timestamp
|
||||
|
||||
// Track unique versions (simplified)
|
||||
stats.UniqueVersions++
|
||||
if stats.versions == nil {
|
||||
stats.versions = make(map[string]struct{})
|
||||
}
|
||||
stats.versions[download.Version] = struct{}{}
|
||||
stats.UniqueVersions = len(stats.versions)
|
||||
}
|
||||
|
||||
// GetPackageStats returns statistics for a specific package
|
||||
@@ -171,6 +181,7 @@ func (e *Engine) GetPackageStats(registry, name string) (*PackageStats, bool) {
|
||||
|
||||
// Return a copy to avoid race conditions
|
||||
statsCopy := *stats
|
||||
statsCopy.versions = nil
|
||||
return &statsCopy, true
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
package analytics
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
func newTestEngine(t *testing.T) *Engine {
|
||||
t.Helper()
|
||||
e := NewEngine(Config{MaxEvents: 100, FlushInterval: time.Hour})
|
||||
t.Cleanup(e.Close)
|
||||
return e
|
||||
}
|
||||
|
||||
// The proxy passes names sliced from a request buffer the server reuses.
|
||||
func TestTrackDownloadKeepsItsOwnCopyOfTheNames(t *testing.T) {
|
||||
e := newTestEngine(t)
|
||||
shared := []byte("lodash")
|
||||
aliased := unsafe.String(&shared[0], len(shared)) // #nosec G103 -- reproduces a string backed by a reused buffer
|
||||
e.TrackDownload(PackageDownload{Registry: "npm", Name: aliased, Version: "1.0.0", Timestamp: time.Now()})
|
||||
copy(shared, "xxxxxx")
|
||||
|
||||
if _, ok := e.GetPackageStats("npm", "lodash"); !ok {
|
||||
t.Errorf("stats lost the package name after the caller reused its buffer: %v", e.GetTopPackages(0))
|
||||
}
|
||||
for _, p := range e.GetTopPackages(0) {
|
||||
if p.Name != "lodash" {
|
||||
t.Errorf("name = %q, want lodash", p.Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestUniqueVersionsCountsDistinctVersions(t *testing.T) {
|
||||
e := newTestEngine(t)
|
||||
for _, v := range []string{"1.0.0", "1.0.0", "1.1.0", "1.0.0"} {
|
||||
e.TrackDownload(PackageDownload{Registry: "npm", Name: "left-pad", Version: v, Timestamp: time.Now(), BytesSize: 10})
|
||||
}
|
||||
stats, ok := e.GetPackageStats("npm", "left-pad")
|
||||
if !ok {
|
||||
t.Fatal("no stats")
|
||||
}
|
||||
if stats.TotalDownloads != 4 || stats.UniqueVersions != 2 || stats.BytesServed != 40 {
|
||||
t.Errorf("stats = %+v, want 4 downloads, 2 versions, 40 bytes", stats)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnknownPackageHasNoStats(t *testing.T) {
|
||||
if _, ok := newTestEngine(t).GetPackageStats("npm", "nope"); ok {
|
||||
t.Error("unknown package reported stats")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/config"
|
||||
)
|
||||
|
||||
// analyticsDownloads maps "registry:name" to downloads as the analytics engine reports them.
|
||||
func analyticsDownloads(a *App) map[string]int64 {
|
||||
out := map[string]int64{}
|
||||
for _, p := range a.analyticsEngine.GetTopPackages(0) {
|
||||
out[p.Registry+":"+p.Name] = p.Downloads
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// scrub sends requests whose paths differ from the proxied ones. The server reuses its request
|
||||
// buffers, so a name kept from an earlier request changes under the analytics engine.
|
||||
func scrub(t *testing.T, a *App) {
|
||||
t.Helper()
|
||||
for i := 0; i < 5; i++ {
|
||||
doRequest(t, a, "/api/analytics/top?limit="+strings.Repeat("9", 40+i), nil)
|
||||
}
|
||||
}
|
||||
|
||||
func assertDownloads(t *testing.T, a *App, want map[string]int64) {
|
||||
t.Helper()
|
||||
scrub(t, a)
|
||||
got := analyticsDownloads(a)
|
||||
if len(got) != len(want) {
|
||||
t.Errorf("analytics keys = %v, want %v", got, want)
|
||||
return
|
||||
}
|
||||
for key, n := range want {
|
||||
if got[key] != n {
|
||||
t.Errorf("analytics keys = %v, want %v", got, want)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnalyticsNameNpmPackagesAfterRegistryPaths(t *testing.T) {
|
||||
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if strings.HasSuffix(r.URL.Path, ".tgz") {
|
||||
_, _ = w.Write([]byte("TARBALL"))
|
||||
return
|
||||
}
|
||||
_, _ = w.Write([]byte(`{"name":"x","versions":{}}`))
|
||||
}))
|
||||
t.Cleanup(upstream.Close)
|
||||
a := newTestApp(t, func(c *config.Config) { c.Handlers.NPM.UpstreamRegistry = upstream.URL })
|
||||
|
||||
for _, target := range []string{
|
||||
"/npm/lodash/-/lodash-4.17.21.tgz",
|
||||
"/npm/@types/node/-/node-18.0.0.tgz",
|
||||
"/npm/@types%2fnode/-/node-18.0.0.tgz",
|
||||
"/npm/lodash",
|
||||
"/npm/@types%2fnode",
|
||||
} {
|
||||
if code, _, body := doRequest(t, a, target, nil); code != http.StatusOK {
|
||||
t.Fatalf("GET %s: %d %s", target, code, body)
|
||||
}
|
||||
}
|
||||
// Tarballs are downloads; the packument is metadata and does not count.
|
||||
assertDownloads(t, a, map[string]int64{"npm:lodash": 1, "npm:@types/node": 2})
|
||||
}
|
||||
|
||||
func TestAnalyticsNameGoModuleCountsOnlyTheZip(t *testing.T) {
|
||||
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
_, _ = w.Write([]byte("BODY " + r.URL.Path)) // #nosec G705 -- test upstream, plain text body
|
||||
}))
|
||||
t.Cleanup(upstream.Close)
|
||||
a := newTestApp(t, func(c *config.Config) {
|
||||
c.Handlers.Go.UpstreamProxy = upstream.URL
|
||||
c.Handlers.Go.VerifyChecksums = false
|
||||
})
|
||||
|
||||
const base = "/go/github.com/google/uuid/@v/"
|
||||
for _, target := range []string{base + "list", base + "v1.6.0.info", base + "v1.6.0.mod", base + "v1.6.0.zip", base + "v1.5.0.zip"} {
|
||||
if code, _, body := doRequest(t, a, target, nil); code != http.StatusOK {
|
||||
t.Fatalf("GET %s: %d %s", target, code, body)
|
||||
}
|
||||
}
|
||||
// One key per module: both zips are downloads of the module, .info, .mod and list are not.
|
||||
assertDownloads(t, a, map[string]int64{"go:github.com/google/uuid": 2})
|
||||
}
|
||||
|
||||
func TestAnalyticsNamePyPIFilesNotPages(t *testing.T) {
|
||||
upstream, _ := newPyPIUpstream(t)
|
||||
a := newTestApp(t, func(c *config.Config) { c.Handlers.PyPI.SimpleAPIURL = upstream.URL + "/simple" })
|
||||
|
||||
file := "/pypi/foo/" + pypiWheel + "?original_url=" + url.QueryEscape(upstream.URL+"/packages/"+pypiWheel)
|
||||
for _, target := range []string{"/pypi/simple/foo/", file} {
|
||||
if code, _, body := doRequest(t, a, target, nil); code != http.StatusOK {
|
||||
t.Fatalf("GET %s: %d %.80s", target, code, body)
|
||||
}
|
||||
}
|
||||
doRequest(t, a, "/pypi/simple/foo/", map[string]string{"Accept": pypiJSONType})
|
||||
assertDownloads(t, a, map[string]int64{"pypi:foo": 1})
|
||||
}
|
||||
|
||||
// The proxy hands the cache names that alias the server's request buffer. Analytics keeps them
|
||||
// after the request ends, so they must be copied or later requests rewrite them.
|
||||
func TestAnalyticsKeepsNamesAfterTheRequestBufferIsReused(t *testing.T) {
|
||||
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
_, _ = w.Write([]byte("TARBALL"))
|
||||
}))
|
||||
t.Cleanup(upstream.Close)
|
||||
a := newTestApp(t, func(c *config.Config) { c.Handlers.NPM.UpstreamRegistry = upstream.URL })
|
||||
|
||||
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
go func() { _ = a.app.Listener(ln, fiber.ListenConfig{DisableStartupMessage: true}) }()
|
||||
base := "http://" + ln.Addr().String()
|
||||
|
||||
get := func(path string) {
|
||||
resp, err := http.Get(base + path) // #nosec G107 -- loopback test server
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, _ = io.Copy(io.Discard, resp.Body)
|
||||
_ = resp.Body.Close()
|
||||
}
|
||||
names := []string{"lodash", "express", "@types/node", "left-pad"}
|
||||
for _, name := range names {
|
||||
bare := name[strings.Index(name, "/")+1:]
|
||||
get("/npm/" + name + "/-/" + bare + "-1.0.0.tgz")
|
||||
}
|
||||
for i := 0; i < 20; i++ {
|
||||
get("/api/analytics/top?limit=" + strings.Repeat("7", 30+i))
|
||||
}
|
||||
|
||||
got := analyticsDownloads(a)
|
||||
for _, name := range names {
|
||||
if got["npm:"+name] != 1 {
|
||||
t.Fatalf("analytics keys = %v, want each of %v once", got, names)
|
||||
}
|
||||
}
|
||||
}
|
||||
+43
-22
@@ -17,7 +17,6 @@ import (
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/gofiber/fiber/v3/middleware/adaptor"
|
||||
"github.com/gofiber/fiber/v3/middleware/static"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/analytics"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/auth"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/cache"
|
||||
@@ -57,9 +56,11 @@ type App struct {
|
||||
networkClient *network.Client
|
||||
scanManager *scanner.Manager
|
||||
rescanWorker *scanner.RescanWorker
|
||||
workerCtx context.Context
|
||||
analyticsEngine *analytics.Engine
|
||||
wsServer *websocket.Server
|
||||
prewarmWorker *prewarming.Worker
|
||||
prewarmFetcher *prewarming.ProxyFetcher
|
||||
cdnMiddleware *cdn.Middleware
|
||||
}
|
||||
|
||||
@@ -308,22 +309,24 @@ func (a *App) initializeComponents() error {
|
||||
log.Info().Msg("Initializing authentication manager")
|
||||
authCfg := auth.Config{BcryptCost: a.config.Auth.BcryptCost}
|
||||
a.authManager = auth.NewWithStore(authCfg, a.metadata)
|
||||
// Bootstrap before Load: a key saved after the cache is hydrated stays invalid until the next restart.
|
||||
bootCtx, bootCancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
if err := auth.BootstrapAdminFromEnv(bootCtx, a.metadata, authCfg); err != nil {
|
||||
log.Warn().Err(err).Msg("Failed to bootstrap admin API key from environment")
|
||||
}
|
||||
bootCancel()
|
||||
loadCtx, loadCancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
if err := a.authManager.Load(loadCtx); err != nil {
|
||||
// Empty key set is recoverable: log and continue rather than fail boot.
|
||||
log.Warn().Err(err).Msg("Failed to load API keys from metadata store; starting with empty key set")
|
||||
}
|
||||
loadCancel()
|
||||
bootCtx, bootCancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
if err := auth.BootstrapAdminFromEnv(bootCtx, a.metadata, authCfg); err != nil {
|
||||
log.Warn().Err(err).Msg("Failed to bootstrap admin API key from environment")
|
||||
}
|
||||
bootCancel()
|
||||
|
||||
a.scanManager.SetFileSource(a.cache.ScanFile)
|
||||
|
||||
// Initialize rescan worker if enabled
|
||||
if a.config.Security.Enabled && a.config.Security.RescanInterval > 0 {
|
||||
// Built whenever scanning is on: an interval of 0 only turns off the periodic cycle, not admin rescans.
|
||||
if a.config.Security.Enabled {
|
||||
log.Info().Dur("interval", a.config.Security.RescanInterval).Msg("Initializing package rescan worker")
|
||||
a.rescanWorker = scanner.NewRescanWorker(a.scanManager, a.metadata, a.config.Security.RescanInterval,
|
||||
scanner.WithActiveWindow(a.config.Security.RescanActiveWindow),
|
||||
@@ -348,14 +351,14 @@ func (a *App) initializeComponents() error {
|
||||
// Initialize pre-warming worker. Operator-controlled via cfg.Prewarming;
|
||||
// defaults are baked into config.Default() so unset fields stay sane.
|
||||
log.Info().Msg("Initializing pre-warming worker")
|
||||
a.prewarmFetcher = prewarming.NewProxyFetcher()
|
||||
a.prewarmWorker = prewarming.NewWorker(prewarming.Config{
|
||||
Enabled: a.config.Prewarming.Enabled,
|
||||
Interval: a.config.Prewarming.Interval,
|
||||
MaxConcurrent: a.config.Prewarming.MaxConcurrent,
|
||||
TopPackages: a.config.Prewarming.TopPackages,
|
||||
CacheManager: a.cache,
|
||||
Analytics: a.analyticsEngine,
|
||||
NetworkClient: a.networkClient,
|
||||
Popularity: a.analyticsEngine,
|
||||
Fetcher: a.prewarmFetcher,
|
||||
})
|
||||
|
||||
// Initialize CDN middleware
|
||||
@@ -462,13 +465,14 @@ func (a *App) setupServer() error {
|
||||
a.app.Get("/api/stats/timeseries", mwAuth, a.handleTimeSeriesStats)
|
||||
a.app.Get("/api/stats/trend", mwAuth, a.handleStatsTrend)
|
||||
a.app.Get("/api/info", mwAuth, a.handleInfo)
|
||||
a.app.Get("/api/system", mwAuth, a.handleSystem)
|
||||
|
||||
a.app.Get("/api/analytics/top", mwAuth, a.handleAnalyticsTopPackages)
|
||||
a.app.Get("/api/analytics/trending", mwAuth, a.handleAnalyticsTrendingPackages)
|
||||
a.app.Get("/api/analytics/trends", mwAuth, a.handleAnalyticsTrends)
|
||||
a.app.Get("/api/analytics/total", mwAuth, a.handleAnalyticsTotalStats)
|
||||
a.app.Get("/api/analytics/registry/:registry", mwAuth, a.handleAnalyticsRegistryStats)
|
||||
a.app.Get("/api/analytics/package/:registry/:name", mwAuth, a.handleAnalyticsPackageStats)
|
||||
a.app.Get("/api/analytics/package/:registry/*", mwAuth, a.handleAnalyticsPackageStats)
|
||||
a.app.Get("/api/analytics/search", mwAuth, a.handleAnalyticsSearch)
|
||||
} else {
|
||||
a.app.Get("/api/config", a.handleConfig)
|
||||
@@ -477,13 +481,14 @@ func (a *App) setupServer() error {
|
||||
a.app.Get("/api/stats/timeseries", a.handleTimeSeriesStats)
|
||||
a.app.Get("/api/stats/trend", a.handleStatsTrend)
|
||||
a.app.Get("/api/info", a.handleInfo)
|
||||
a.app.Get("/api/system", a.handleSystem)
|
||||
|
||||
a.app.Get("/api/analytics/top", a.handleAnalyticsTopPackages)
|
||||
a.app.Get("/api/analytics/trending", a.handleAnalyticsTrendingPackages)
|
||||
a.app.Get("/api/analytics/trends", a.handleAnalyticsTrends)
|
||||
a.app.Get("/api/analytics/total", a.handleAnalyticsTotalStats)
|
||||
a.app.Get("/api/analytics/registry/:registry", a.handleAnalyticsRegistryStats)
|
||||
a.app.Get("/api/analytics/package/:registry/:name", a.handleAnalyticsPackageStats)
|
||||
a.app.Get("/api/analytics/package/:registry/*", a.handleAnalyticsPackageStats)
|
||||
a.app.Get("/api/analytics/search", a.handleAnalyticsSearch)
|
||||
}
|
||||
|
||||
@@ -495,6 +500,11 @@ func (a *App) setupServer() error {
|
||||
a.app.Post("/api/admin/prewarming/trigger", a.requireAdmin, a.handlePrewarmingTrigger)
|
||||
a.app.Post("/api/admin/prewarming/package", a.requireAdmin, a.handlePrewarmingPackage)
|
||||
|
||||
// Admin endpoints (forced rescan)
|
||||
a.app.Post("/api/admin/rescan", a.requireAdmin, a.handleRescanTrigger)
|
||||
a.app.Get("/api/admin/rescan/status", a.requireAdmin, a.handleRescanStatus)
|
||||
a.app.Get("/api/admin/rescan/estimate", a.requireAdmin, a.handleRescanEstimate)
|
||||
|
||||
// Admin endpoints (API key management)
|
||||
a.app.Post("/api/admin/keys", a.requireAdmin, a.handleGenerateAPIKey)
|
||||
a.app.Get("/api/admin/keys", a.requireAdmin, a.handleListAPIKeys)
|
||||
@@ -536,11 +546,13 @@ func (a *App) setupServer() error {
|
||||
SumDBURL: sumDB,
|
||||
CredStore: credStore,
|
||||
})
|
||||
goProxyWithCDN := a.cdnMiddleware.Handler(http.StripPrefix("/go", goProxyHandler))
|
||||
goProxyMounted := http.StripPrefix("/go", goProxyHandler)
|
||||
a.prewarmFetcher.Mount("go", goProxyMounted)
|
||||
goProxyWithCDN := a.cdnMiddleware.Handler(goProxyMounted)
|
||||
if authEnabled {
|
||||
a.app.All("/go/*", mwAuth, adaptor.HTTPHandler(goProxyWithCDN))
|
||||
a.app.All("/go/*", mwAuth, proxyHandler(goProxyWithCDN))
|
||||
} else {
|
||||
a.app.All("/go/*", adaptor.HTTPHandler(goProxyWithCDN))
|
||||
a.app.All("/go/*", proxyHandler(goProxyWithCDN))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -552,7 +564,9 @@ func (a *App) setupServer() error {
|
||||
npmProxyHandler := npm.New(a.cache, a.networkClient, npm.Config{
|
||||
Upstream: npmUpstream,
|
||||
})
|
||||
npmProxyWithCDN := a.cdnMiddleware.Handler(http.StripPrefix("/npm", npmProxyHandler))
|
||||
npmProxyMounted := http.StripPrefix("/npm", npmProxyHandler)
|
||||
a.prewarmFetcher.Mount("npm", npmProxyMounted)
|
||||
npmProxyWithCDN := a.cdnMiddleware.Handler(npmProxyMounted)
|
||||
a.app.Use("/npm", func(c fiber.Ctx) error {
|
||||
if canonical := npm.CanonicalPath(c.Path()); canonical != c.Path() {
|
||||
c.Path(canonical)
|
||||
@@ -560,9 +574,9 @@ func (a *App) setupServer() error {
|
||||
return c.Next()
|
||||
})
|
||||
if authEnabled {
|
||||
a.app.All("/npm/*", mwAuth, adaptor.HTTPHandler(npmProxyWithCDN))
|
||||
a.app.All("/npm/*", mwAuth, proxyHandler(npmProxyWithCDN))
|
||||
} else {
|
||||
a.app.All("/npm/*", adaptor.HTTPHandler(npmProxyWithCDN))
|
||||
a.app.All("/npm/*", proxyHandler(npmProxyWithCDN))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -574,11 +588,13 @@ func (a *App) setupServer() error {
|
||||
pypiProxyHandler := pypi.New(a.cache, a.networkClient, pypi.Config{
|
||||
Upstream: pypiUpstream,
|
||||
})
|
||||
pypiProxyWithCDN := a.cdnMiddleware.Handler(http.StripPrefix("/pypi", pypiProxyHandler))
|
||||
pypiProxyMounted := http.StripPrefix("/pypi", pypiProxyHandler)
|
||||
a.prewarmFetcher.Mount("pypi", pypiProxyMounted)
|
||||
pypiProxyWithCDN := a.cdnMiddleware.Handler(pypiProxyMounted)
|
||||
if authEnabled {
|
||||
a.app.All("/pypi/*", mwAuth, adaptor.HTTPHandler(pypiProxyWithCDN))
|
||||
a.app.All("/pypi/*", mwAuth, proxyHandler(pypiProxyWithCDN))
|
||||
} else {
|
||||
a.app.All("/pypi/*", adaptor.HTTPHandler(pypiProxyWithCDN))
|
||||
a.app.All("/pypi/*", proxyHandler(pypiProxyWithCDN))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -586,7 +602,7 @@ func (a *App) setupServer() error {
|
||||
frontendDir := "frontend/dist"
|
||||
if _, err := os.Stat(frontendDir); err == nil {
|
||||
log.Info().Str("dir", frontendDir).Msg("Serving frontend static files")
|
||||
a.app.Use("/", static.New(frontendDir))
|
||||
a.app.Use("/", spaStatic(frontendDir))
|
||||
} else {
|
||||
log.Warn().Msg("Frontend dist directory not found, frontend won't be served")
|
||||
a.app.Get("/", func(c fiber.Ctx) error {
|
||||
@@ -617,6 +633,8 @@ func (a *App) setupServer() error {
|
||||
|
||||
// startWorkers starts the background loops that live as long as ctx.
|
||||
func (a *App) startWorkers(ctx context.Context) {
|
||||
a.workerCtx = ctx
|
||||
|
||||
// Without the event loop the broadcast channel fills after 256 events and websocket clients never register.
|
||||
a.wsServer.Start(ctx)
|
||||
|
||||
@@ -631,6 +649,9 @@ func (a *App) startWorkers(ctx context.Context) {
|
||||
if a.rescanWorker != nil {
|
||||
go a.rescanWorker.Start(ctx)
|
||||
}
|
||||
|
||||
// Start is a no-op unless prewarming.enabled is set.
|
||||
a.prewarmWorker.Start(ctx)
|
||||
}
|
||||
|
||||
func (a *App) Run() error {
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/auth"
|
||||
)
|
||||
|
||||
// The env-bootstrapped admin key must work on the boot that creates it, not only after a restart.
|
||||
func TestBootstrapAdminKeyWorksOnFirstBoot(t *testing.T) {
|
||||
const key = "bootstrap-admin-key-for-test"
|
||||
t.Setenv(auth.BootstrapAdminEnvVar, key)
|
||||
a := newTestApp(t, nil)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/admin/prewarming/status", nil)
|
||||
req.Header.Set("X-API-Key", key)
|
||||
resp, err := a.app.Test(req, fiber.TestConfig{Timeout: 10 * time.Second})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_ = resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("admin route with the bootstrap key = %d, want 200", resp.StatusCode)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/gofiber/fiber/v3/middleware/adaptor"
|
||||
)
|
||||
|
||||
// proxyHandler mounts a net/http proxy handler on fiber with a request that owns its strings.
|
||||
// The adaptor builds URL, Host, Method and header strings over fasthttp's request buffer, which the
|
||||
// next request on the connection overwrites; the proxies hand these strings to background scans,
|
||||
// singleflight keys and analytics that outlive the request.
|
||||
func proxyHandler(h http.Handler) fiber.Handler {
|
||||
return adaptor.HTTPHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
h.ServeHTTP(w, detachRequest(r))
|
||||
}))
|
||||
}
|
||||
|
||||
func detachRequest(r *http.Request) *http.Request {
|
||||
d := r.Clone(r.Context())
|
||||
d.Method = strings.Clone(r.Method)
|
||||
d.Proto = strings.Clone(r.Proto)
|
||||
d.Host = strings.Clone(r.Host)
|
||||
d.RequestURI = strings.Clone(r.RequestURI)
|
||||
u := *r.URL
|
||||
u.Scheme = strings.Clone(u.Scheme)
|
||||
u.Host = strings.Clone(u.Host)
|
||||
u.Path = strings.Clone(u.Path)
|
||||
u.RawPath = strings.Clone(u.RawPath)
|
||||
u.RawQuery = strings.Clone(u.RawQuery)
|
||||
u.Fragment = strings.Clone(u.Fragment)
|
||||
u.User = nil
|
||||
if r.URL.User != nil {
|
||||
if p, ok := r.URL.User.Password(); ok {
|
||||
u.User = url.UserPassword(strings.Clone(r.URL.User.Username()), strings.Clone(p))
|
||||
} else {
|
||||
u.User = url.User(strings.Clone(r.URL.User.Username()))
|
||||
}
|
||||
}
|
||||
d.URL = &u
|
||||
h := make(http.Header, len(r.Header))
|
||||
for k, vs := range r.Header {
|
||||
cp := make([]string, len(vs))
|
||||
for i, v := range vs {
|
||||
cp[i] = strings.Clone(v)
|
||||
}
|
||||
h[strings.Clone(k)] = cp
|
||||
}
|
||||
d.Header = h
|
||||
return d
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
"testing"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
// The adaptor's strings point into a buffer fasthttp reuses; a detached request must not see later writes.
|
||||
func TestDetachRequestSurvivesBufferReuse(t *testing.T) {
|
||||
buf := []byte("GET/npm/lodash/-/lodash-1.0.0.tgzq=1proxy.lanBearer secret")
|
||||
alias := func(from, to int) string { return unsafe.String(&buf[from], to-from) } // #nosec G103 -- reproduces the adaptor's aliasing
|
||||
r := &http.Request{
|
||||
Method: alias(0, 3),
|
||||
Host: alias(36, 45),
|
||||
URL: &url.URL{Path: alias(3, 33), RawQuery: alias(33, 36), User: url.UserPassword(alias(36, 41), alias(52, 58))},
|
||||
Header: http.Header{"Authorization": {alias(45, 58)}},
|
||||
}
|
||||
|
||||
d := detachRequest(r)
|
||||
for i := range buf {
|
||||
buf[i] = 'x'
|
||||
}
|
||||
|
||||
pw, _ := d.URL.User.Password()
|
||||
got := []string{d.Method, d.Host, d.URL.Path, d.URL.RawQuery, d.Header.Get("Authorization"), d.URL.User.Username(), pw}
|
||||
want := []string{"GET", "proxy.lan", "/npm/lodash/-/lodash-1.0.0.tgz", "q=1", "Bearer secret", "proxy", "secret"}
|
||||
for i := range want {
|
||||
if got[i] != want[i] {
|
||||
t.Fatalf("field %d = %q after the buffer changed, want %q", i, got[i], want[i])
|
||||
}
|
||||
}
|
||||
if r.URL == d.URL {
|
||||
t.Fatal("detached request shares the URL with the original")
|
||||
}
|
||||
}
|
||||
+80
-7
@@ -32,6 +32,9 @@ func (a *App) handlePackages(c fiber.Ctx) error {
|
||||
|
||||
switch c.Method() {
|
||||
case "GET":
|
||||
if registry, name, version, ok := packagePath(c.Path()); ok {
|
||||
return a.handleGetPackage(c, registry, name, version)
|
||||
}
|
||||
return a.handleListPackages(c)
|
||||
case "DELETE":
|
||||
return a.handleDeletePackage(c)
|
||||
@@ -40,6 +43,30 @@ func (a *App) handlePackages(c fiber.Ctx) error {
|
||||
}
|
||||
}
|
||||
|
||||
// packagePath splits /api/packages/{registry}/{name}/{version}. The name can hold slashes
|
||||
// (@scope/pkg, Go module paths); the version is the last segment.
|
||||
func packagePath(path string) (registry, name, version string, ok bool) {
|
||||
parts := strings.Split(strings.Trim(strings.TrimPrefix(path, "/api/packages/"), "/"), "/")
|
||||
if len(parts) < 3 {
|
||||
return "", "", "", false
|
||||
}
|
||||
return parts[0], strings.Join(parts[1:len(parts)-1], "/"), parts[len(parts)-1], true
|
||||
}
|
||||
|
||||
// handleGetPackage serves one stored package version.
|
||||
func (a *App) handleGetPackage(c fiber.Ctx, registry, name, version string) error {
|
||||
_, pkg, err := a.resolvePackageKey(c.Context(), registry, name, version)
|
||||
if err != nil {
|
||||
var appErr *apperrors.Error
|
||||
if stderrors.As(err, &appErr) && appErr.Code == apperrors.ErrCodeNotFound {
|
||||
return c.Status(fiber.StatusNotFound).JSON(fiber.Map{"error": "package not found"})
|
||||
}
|
||||
log.Error().Err(err).Str("registry", registry).Str("package", name).Msg("Failed to get package")
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": "failed to get package"})
|
||||
}
|
||||
return c.Status(fiber.StatusOK).JSON(packageSummary(pkg))
|
||||
}
|
||||
|
||||
// packageSummary is the list payload for one package when scan results are attached.
|
||||
func packageSummary(pkg *metadata.Package) map[string]interface{} {
|
||||
summary := map[string]interface{}{
|
||||
@@ -139,17 +166,53 @@ func (a *App) scanDecisions(ctx context.Context, ids []string) ([]scanner.ScanDe
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// vulnerabilityInfo is the per-row scan block of the list payload.
|
||||
// Verdicts the dashboard shows for a cached package.
|
||||
const (
|
||||
VerdictCleared = "cleared"
|
||||
VerdictHeld = "held"
|
||||
VerdictBypassed = "bypassed"
|
||||
VerdictPending = "pending"
|
||||
)
|
||||
|
||||
// verdictOf names the outcome of a scan decision: held beats bypassed, which beats cleared.
|
||||
func verdictOf(d scanner.ScanDecision) string {
|
||||
switch {
|
||||
case d.Blocked:
|
||||
return VerdictHeld
|
||||
case d.Bypass != nil:
|
||||
return VerdictBypassed
|
||||
default:
|
||||
return VerdictCleared
|
||||
}
|
||||
}
|
||||
|
||||
// bypassSummary is the public view of the bypass that waved a package through.
|
||||
func bypassSummary(b *metadata.CVEBypass) map[string]interface{} {
|
||||
if b == nil {
|
||||
return nil
|
||||
}
|
||||
return map[string]interface{}{
|
||||
"id": b.ID,
|
||||
"type": b.Type,
|
||||
"target": b.Target,
|
||||
"reason": b.Reason,
|
||||
"created_by": b.CreatedBy,
|
||||
"created_at": b.CreatedAt,
|
||||
"expires_at": b.ExpiresAt,
|
||||
}
|
||||
}
|
||||
|
||||
// vulnerabilityInfo is the per-package scan block of the list response; verdict, reason and bypass extend the original fields.
|
||||
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}
|
||||
return map[string]interface{}{"scanned": false, "status": "not_scanned", "isBlocked": false, "verdict": VerdictPending}
|
||||
}
|
||||
d, ok := decisions[pkg.ID]
|
||||
if !ok || !d.Summary.HasScan {
|
||||
return map[string]interface{}{"scanned": false, "status": "pending", "isBlocked": false}
|
||||
return map[string]interface{}{"scanned": false, "status": "pending", "isBlocked": false, "verdict": VerdictPending}
|
||||
}
|
||||
sum := d.Summary
|
||||
return map[string]interface{}{
|
||||
info := map[string]interface{}{
|
||||
"scanned": true,
|
||||
"status": sum.Status,
|
||||
"scannedAt": sum.ScannedAt.Format(time.RFC3339),
|
||||
@@ -161,12 +224,21 @@ func vulnerabilityInfo(pkg *metadata.Package, decisions map[string]scanner.ScanD
|
||||
},
|
||||
"total": sum.Total,
|
||||
"isBlocked": d.Blocked,
|
||||
"verdict": verdictOf(d),
|
||||
}
|
||||
if d.Reason != "" {
|
||||
info["reason"] = d.Reason
|
||||
}
|
||||
if d.Bypass != nil {
|
||||
info["bypass"] = bypassSummary(d.Bypass)
|
||||
}
|
||||
return info
|
||||
}
|
||||
|
||||
// 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 {
|
||||
if c.Query("layout") == layoutRows {
|
||||
return a.handleListPackageRows(c)
|
||||
}
|
||||
ctx := c.Context()
|
||||
params, err := parseListParams(c)
|
||||
if err != nil {
|
||||
@@ -391,7 +463,7 @@ func (a *App) handleStats(c fiber.Ctx) error {
|
||||
}
|
||||
|
||||
// Blocked packages need the blocking policy, so judge every scanned package in one batch.
|
||||
blockedCount, err := a.countBlocked(ctx)
|
||||
blockedCount, bypassedCount, err := a.countVerdicts(ctx)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Failed to judge scanned packages")
|
||||
}
|
||||
@@ -410,6 +482,7 @@ func (a *App) handleStats(c fiber.Ctx) error {
|
||||
"scanned_packages": cacheStats.ScannedPackages,
|
||||
"vulnerable_packages": cacheStats.VulnerablePackages,
|
||||
"blocked_packages": blockedCount,
|
||||
"bypassed_packages": bypassedCount,
|
||||
}
|
||||
|
||||
// Convert registry stats to interface map
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
)
|
||||
|
||||
func seedAliased(t *testing.T, a *App) {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
now := time.Now()
|
||||
if err := a.metadata.SavePackage(ctx, &metadata.Package{
|
||||
Registry: "npm", Name: "aliased", Version: "1.0.0", StorageKey: "npm/aliased", Size: 10, CachedAt: now, LastAccessed: now,
|
||||
}); err != nil {
|
||||
t.Fatalf("SavePackage: %v", err)
|
||||
}
|
||||
if err := a.metadata.SaveScanResult(ctx, &metadata.ScanResult{
|
||||
Registry: "npm", PackageName: "aliased", PackageVersion: "1.0.0", Scanner: "osv", Status: metadata.ScanStatusVulnerable, ScannedAt: now,
|
||||
VulnerabilityCount: 1,
|
||||
Vulnerabilities: []metadata.Vulnerability{{
|
||||
ID: "GHSA-xvch-5gv4-984h", Aliases: []string{"CVE-2021-44906"}, Severity: "critical", DetectedBy: []string{"osv"},
|
||||
}},
|
||||
}); err != nil {
|
||||
t.Fatalf("SaveScanResult: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDetailsShowAliasesAndHonourABypassOnAnAlias(t *testing.T) {
|
||||
a, _ := newScanningApp(t)
|
||||
a.config.Security.BlockOnSeverity = "critical"
|
||||
seedAliased(t, a)
|
||||
|
||||
held, _ := getJSON(t, a, "/api/packages/npm/aliased/1.0.0/vulnerabilities")
|
||||
if jsonAt(held, "decision", "verdict") != VerdictHeld {
|
||||
t.Fatalf("verdict before the bypass = %v, want held", jsonAt(held, "decision", "verdict"))
|
||||
}
|
||||
if got, _ := jsonAt(held, "vulnerabilities", 0, "aliases").([]any); len(got) != 1 || got[0] != "CVE-2021-44906" {
|
||||
t.Errorf("aliases = %v, want [CVE-2021-44906]", got)
|
||||
}
|
||||
|
||||
if err := a.metadata.SaveCVEBypass(context.Background(), &metadata.CVEBypass{
|
||||
Type: metadata.BypassTypeCVE, Target: "cve-2021-44906", Reason: "not reachable", CreatedBy: "alice",
|
||||
Active: true, ExpiresAt: time.Now().Add(time.Hour),
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
waved, _ := getJSON(t, a, "/api/packages/npm/aliased/1.0.0/vulnerabilities")
|
||||
if jsonAt(waved, "decision", "verdict") != VerdictBypassed {
|
||||
t.Errorf("verdict with a CVE bypass = %v, want bypassed", jsonAt(waved, "decision", "verdict"))
|
||||
}
|
||||
if jsonAt(waved, "vulnerabilities", 0, "bypassed") != true {
|
||||
t.Errorf("finding bypassed = %v, want true", jsonAt(waved, "vulnerabilities", 0, "bypassed"))
|
||||
}
|
||||
if jsonAt(waved, "vulnerabilities", 0, "bypass", "created_by") != "alice" {
|
||||
t.Errorf("bypass = %v", jsonAt(waved, "vulnerabilities", 0, "bypass"))
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"strconv"
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
@@ -27,7 +28,18 @@ func (a *App) handleAnalyticsTopPackages(c fiber.Ctx) error {
|
||||
})
|
||||
}
|
||||
|
||||
// handleAnalyticsTrendingPackages returns trending packages
|
||||
// trendingPackage keeps the Go field names the dashboard reads from the analytics engine.
|
||||
type trendingPackage struct {
|
||||
Registry string
|
||||
Name string
|
||||
Downloads int64
|
||||
RecentDownloads int64
|
||||
PreviousDownloads int64
|
||||
Trend float64
|
||||
}
|
||||
|
||||
// handleAnalyticsTrendingPackages ranks packages by downloads in the last 7 days. Persisted
|
||||
// history serves it so a restart keeps the ranking; the in-memory engine covers stores without it.
|
||||
func (a *App) handleAnalyticsTrendingPackages(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "application/json")
|
||||
|
||||
@@ -39,6 +51,35 @@ func (a *App) handleAnalyticsTrendingPackages(c fiber.Ctx) error {
|
||||
}
|
||||
}
|
||||
|
||||
if source, ok := a.metadata.(metadata.TrendingSource); ok {
|
||||
stored, err := source.GetTrendingPackages(c.Context(), limit)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Failed to read trending packages")
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"error": "failed to read trending packages",
|
||||
})
|
||||
}
|
||||
packages := make([]trendingPackage, 0, len(stored))
|
||||
for _, p := range stored {
|
||||
trend := 0.0
|
||||
if p.Previous > 0 {
|
||||
trend = float64(p.Recent-p.Previous) / float64(p.Previous) * 100
|
||||
}
|
||||
packages = append(packages, trendingPackage{
|
||||
Registry: p.Registry,
|
||||
Name: p.Name,
|
||||
Downloads: p.Recent,
|
||||
RecentDownloads: p.Recent,
|
||||
PreviousDownloads: p.Previous,
|
||||
Trend: trend,
|
||||
})
|
||||
}
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"packages": packages,
|
||||
"total": len(packages),
|
||||
})
|
||||
}
|
||||
|
||||
packages := a.analyticsEngine.GetTrendingPackages(limit)
|
||||
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
@@ -88,7 +129,8 @@ func (a *App) handleAnalyticsPackageStats(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "application/json")
|
||||
|
||||
registry := c.Params("registry")
|
||||
name := c.Params("name")
|
||||
// The wildcard route carries names with slashes (@scope/pkg, Go module paths).
|
||||
name := c.Params("*")
|
||||
|
||||
if registry == "" || name == "" {
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
@@ -96,13 +138,9 @@ func (a *App) handleAnalyticsPackageStats(c fiber.Ctx) error {
|
||||
})
|
||||
}
|
||||
|
||||
stats, exists := a.analyticsEngine.GetPackageStats(registry, name)
|
||||
if !exists {
|
||||
return c.Status(fiber.StatusNotFound).JSON(fiber.Map{
|
||||
"error": "package not found in analytics",
|
||||
})
|
||||
}
|
||||
|
||||
// Analytics live in memory and restart empty, so a package with no record yet is a normal
|
||||
// answer, not a missing resource: a 404 here shows up as a failed request in every client.
|
||||
stats, _ := a.analyticsEngine.GetPackageStats(registry, name)
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"package": stats,
|
||||
})
|
||||
|
||||
@@ -62,7 +62,7 @@ func (s *AnalyticsHandlersTestSuite) SetupTest() {
|
||||
s.app.Get("/api/analytics/trends", s.appInst.handleAnalyticsTrends)
|
||||
s.app.Get("/api/analytics/total", s.appInst.handleAnalyticsTotalStats)
|
||||
s.app.Get("/api/analytics/registry/:registry", s.appInst.handleAnalyticsRegistryStats)
|
||||
s.app.Get("/api/analytics/package/:registry/:name", s.appInst.handleAnalyticsPackageStats)
|
||||
s.app.Get("/api/analytics/package/:registry/*", s.appInst.handleAnalyticsPackageStats)
|
||||
s.app.Get("/api/analytics/search", s.appInst.handleAnalyticsSearch)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
)
|
||||
|
||||
func seedOnePackage(t *testing.T, a *App, registry, name, version string, downloads int) {
|
||||
t.Helper()
|
||||
now := time.Now()
|
||||
if err := a.metadata.SavePackage(context.Background(), &metadata.Package{
|
||||
Registry: registry, Name: name, Version: version, StorageKey: registry + "/" + name + "/" + version,
|
||||
Size: 2048, ChecksumSHA256: "abc123", CachedAt: now, LastAccessed: now,
|
||||
}); err != nil {
|
||||
t.Fatalf("SavePackage: %v", err)
|
||||
}
|
||||
for i := 0; i < downloads; i++ {
|
||||
if err := a.metadata.UpdateDownloadCount(context.Background(), registry, name, version); err != nil {
|
||||
t.Fatalf("UpdateDownloadCount: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetOnePackageByRegistryNameVersion(t *testing.T) {
|
||||
a := newTestApp(t, nil)
|
||||
seedOnePackage(t, a, "npm", "left-pad", "1.3.0", 3)
|
||||
seedOnePackage(t, a, "npm", "@types/node", "18.0.0", 1)
|
||||
seedOnePackage(t, a, "go", "github.com/google/uuid/@v/v1.6.0.zip", "v1.6.0", 2)
|
||||
|
||||
for _, tc := range []struct {
|
||||
path, name, version string
|
||||
}{
|
||||
{"/api/packages/npm/left-pad/1.3.0", "left-pad", "1.3.0"},
|
||||
{"/api/packages/npm/@types/node/18.0.0", "@types/node", "18.0.0"},
|
||||
{"/api/packages/go/github.com/google/uuid/v1.6.0", "github.com/google/uuid/@v/v1.6.0.zip", "v1.6.0"},
|
||||
} {
|
||||
out, body := getJSON(t, a, tc.path)
|
||||
if out["name"] != tc.name || out["version"] != tc.version || out["checksum_sha256"] != "abc123" {
|
||||
t.Errorf("GET %s = %s", tc.path, body)
|
||||
}
|
||||
}
|
||||
|
||||
out, _ := getJSON(t, a, "/api/packages/npm/left-pad/1.3.0")
|
||||
if out["download_count"] != float64(3) {
|
||||
t.Errorf("download_count = %v, want the persisted count", out["download_count"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetOnePackageIsNotFoundWhenMissing(t *testing.T) {
|
||||
a := newTestApp(t, nil)
|
||||
seedOnePackage(t, a, "npm", "left-pad", "1.3.0", 0)
|
||||
for _, path := range []string{
|
||||
"/api/packages/npm/left-pad/9.9.9",
|
||||
"/api/packages/npm/nope/1.0.0",
|
||||
"/api/packages/rubygems/left-pad/1.3.0",
|
||||
} {
|
||||
if code, _, body := doRequest(t, a, path, nil); code != http.StatusNotFound {
|
||||
t.Errorf("GET %s = %d %s, want 404", path, code, body)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestListStillServesTwoSegmentPaths(t *testing.T) {
|
||||
a := newTestApp(t, nil)
|
||||
seedOnePackage(t, a, "npm", "left-pad", "1.3.0", 0)
|
||||
out, body := getJSON(t, a, "/api/packages")
|
||||
if pkgs, _ := out["packages"].([]any); len(pkgs) != 1 {
|
||||
t.Errorf("list = %s", body)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,298 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"cmp"
|
||||
"context"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
// layoutRows is the value of ?layout= that selects one flat page of package rows.
|
||||
const layoutRows = "rows"
|
||||
|
||||
// Sort keys of the rows layout.
|
||||
const (
|
||||
rowSortName = "name"
|
||||
rowSortVersion = "version"
|
||||
rowSortRegistry = "registry"
|
||||
rowSortSize = "size"
|
||||
rowSortDownloads = "downloads"
|
||||
rowSortLastAccessed = "last_accessed"
|
||||
rowSortLastScanned = "last_scanned"
|
||||
rowSortRisk = "risk"
|
||||
)
|
||||
|
||||
// decisionChunk bounds the id list of one scan summary query.
|
||||
const decisionChunk = 500
|
||||
|
||||
type rowParams struct {
|
||||
registry string
|
||||
query string
|
||||
verdict string
|
||||
sortBy string
|
||||
severities []string
|
||||
page int
|
||||
pageSize int
|
||||
desc bool
|
||||
}
|
||||
|
||||
// parseRowParams reads registry, q, verdict, severity, sort, order, page and page_size.
|
||||
func parseRowParams(c fiber.Ctx) (rowParams, error) {
|
||||
p := rowParams{
|
||||
registry: c.Query("registry"),
|
||||
query: c.Query("q"),
|
||||
sortBy: rowSortName,
|
||||
page: max(fiber.Query[int](c, "page", 1), 1),
|
||||
pageSize: fiber.Query[int](c, "page_size", defaultPageSize),
|
||||
}
|
||||
if p.pageSize < 1 {
|
||||
p.pageSize = defaultPageSize
|
||||
}
|
||||
p.pageSize = min(p.pageSize, maxPageSize)
|
||||
|
||||
switch v := c.Query("verdict"); v {
|
||||
case "":
|
||||
case VerdictCleared, VerdictHeld, VerdictBypassed, VerdictPending:
|
||||
p.verdict = v
|
||||
default:
|
||||
return p, fiber.NewError(fiber.StatusBadRequest, "invalid verdict, must be one of: cleared, held, bypassed, pending")
|
||||
}
|
||||
switch s := c.Query("sort"); s {
|
||||
case "":
|
||||
case rowSortName, rowSortVersion, rowSortRegistry, rowSortSize, rowSortDownloads, rowSortLastAccessed, rowSortLastScanned, rowSortRisk:
|
||||
p.sortBy = s
|
||||
default:
|
||||
return p, fiber.NewError(fiber.StatusBadRequest, "invalid sort key")
|
||||
}
|
||||
switch c.Query("order") {
|
||||
case "desc":
|
||||
p.desc = true
|
||||
case "asc", "":
|
||||
default:
|
||||
return p, fiber.NewError(fiber.StatusBadRequest, "invalid order, must be asc or desc")
|
||||
}
|
||||
sev, err := parseSeverities(c.Query("severity"))
|
||||
if err != nil {
|
||||
return p, fiber.NewError(fiber.StatusBadRequest, err.Error())
|
||||
}
|
||||
p.severities = sev
|
||||
return p, nil
|
||||
}
|
||||
|
||||
// packageRow is a cached package with the verdict the policy gives it now.
|
||||
type packageRow struct {
|
||||
pkg *metadata.Package
|
||||
verdict string
|
||||
scannedAt time.Time
|
||||
dec scanner.ScanDecision
|
||||
scanned bool
|
||||
}
|
||||
|
||||
func (r packageRow) severityCount(level string) int {
|
||||
s := r.dec.Summary
|
||||
switch level {
|
||||
case metadata.SeverityCritical:
|
||||
return s.Critical
|
||||
case metadata.SeverityHigh:
|
||||
return s.High
|
||||
case metadata.SeverityModerate:
|
||||
return s.Moderate
|
||||
default:
|
||||
return s.Low
|
||||
}
|
||||
}
|
||||
|
||||
// loadDecisions judges every scanned row in bounded chunks.
|
||||
func (a *App) loadDecisions(ctx context.Context, pkgs []*metadata.Package) (map[string]scanner.ScanDecision, error) {
|
||||
var ids []string
|
||||
for _, p := range pkgs {
|
||||
if p.SecurityScanned {
|
||||
ids = append(ids, p.ID)
|
||||
}
|
||||
}
|
||||
out := make(map[string]scanner.ScanDecision, len(ids))
|
||||
for chunk := range slices.Chunk(ids, decisionChunk) {
|
||||
list, err := a.scanDecisions(ctx, chunk)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, d := range list {
|
||||
out[d.Summary.PackageID] = d
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func rowOf(pkg *metadata.Package, decisions map[string]scanner.ScanDecision) packageRow {
|
||||
row := packageRow{pkg: pkg, verdict: VerdictPending}
|
||||
if d, ok := decisions[pkg.ID]; ok && pkg.SecurityScanned && d.Summary.HasScan {
|
||||
row.dec, row.scanned, row.verdict, row.scannedAt = d, true, verdictOf(d), d.Summary.ScannedAt
|
||||
}
|
||||
return row
|
||||
}
|
||||
|
||||
func compareRows(sortBy string, a, b packageRow) int {
|
||||
switch sortBy {
|
||||
case rowSortVersion:
|
||||
return cmp.Compare(strings.ToLower(displayVersionOf(a.pkg)), strings.ToLower(displayVersionOf(b.pkg)))
|
||||
case rowSortRegistry:
|
||||
return cmp.Compare(a.pkg.Registry, b.pkg.Registry)
|
||||
case rowSortSize:
|
||||
return cmp.Compare(a.pkg.Size, b.pkg.Size)
|
||||
case rowSortDownloads:
|
||||
return cmp.Compare(a.pkg.DownloadCount, b.pkg.DownloadCount)
|
||||
case rowSortLastAccessed:
|
||||
return a.pkg.LastAccessed.Compare(b.pkg.LastAccessed)
|
||||
case rowSortLastScanned:
|
||||
return a.scannedAt.Compare(b.scannedAt)
|
||||
case rowSortRisk:
|
||||
return compareRisk(a, b)
|
||||
default:
|
||||
return cmp.Compare(strings.ToLower(a.pkg.Name), strings.ToLower(b.pkg.Name))
|
||||
}
|
||||
}
|
||||
|
||||
// compareRisk orders by critical, then high, then moderate, then low findings.
|
||||
func compareRisk(a, b packageRow) int {
|
||||
for _, level := range metadata.Severities {
|
||||
if c := cmp.Compare(a.severityCount(level), b.severityCount(level)); c != 0 {
|
||||
return c
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func displayVersionOf(p *metadata.Package) string {
|
||||
if p.ReleaseVersion != "" {
|
||||
return p.ReleaseVersion
|
||||
}
|
||||
return p.Version
|
||||
}
|
||||
|
||||
func sortRows(rows []packageRow, p rowParams) {
|
||||
slices.SortStableFunc(rows, func(a, b packageRow) int {
|
||||
c := compareRows(p.sortBy, a, b)
|
||||
if p.desc {
|
||||
c = -c
|
||||
}
|
||||
if c != 0 {
|
||||
return c
|
||||
}
|
||||
return cmp.Or(
|
||||
cmp.Compare(strings.ToLower(a.pkg.Name), strings.ToLower(b.pkg.Name)),
|
||||
cmp.Compare(a.pkg.Registry, b.pkg.Registry),
|
||||
cmp.Compare(a.pkg.Version, b.pkg.Version),
|
||||
cmp.Compare(a.pkg.ID, b.pkg.ID),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
// rowCounts summarise the rows that match the registry and query, before the verdict and severity filters.
|
||||
type rowCounts struct {
|
||||
Verdicts map[string]int `json:"verdicts"`
|
||||
SeverityPackages map[string]int `json:"severity_packages"`
|
||||
SeverityFindings map[string]int `json:"severity_findings"`
|
||||
VulnerableAllow int `json:"vulnerable_allowed"`
|
||||
}
|
||||
|
||||
func countRows(rows []packageRow) rowCounts {
|
||||
c := rowCounts{
|
||||
Verdicts: map[string]int{VerdictCleared: 0, VerdictHeld: 0, VerdictBypassed: 0, VerdictPending: 0},
|
||||
SeverityPackages: map[string]int{},
|
||||
SeverityFindings: map[string]int{},
|
||||
}
|
||||
for _, level := range metadata.Severities {
|
||||
c.SeverityPackages[level], c.SeverityFindings[level] = 0, 0
|
||||
}
|
||||
for _, r := range rows {
|
||||
c.Verdicts[r.verdict]++
|
||||
if !r.scanned {
|
||||
continue
|
||||
}
|
||||
if r.verdict == VerdictCleared && r.dec.Summary.Total > 0 {
|
||||
c.VulnerableAllow++
|
||||
}
|
||||
for _, level := range metadata.Severities {
|
||||
if n := r.severityCount(level); n > 0 {
|
||||
c.SeverityPackages[level]++
|
||||
c.SeverityFindings[level] += n
|
||||
}
|
||||
}
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
func (p rowParams) keeps(r packageRow) bool {
|
||||
if p.verdict != "" && r.verdict != p.verdict {
|
||||
return false
|
||||
}
|
||||
if len(p.severities) == 0 {
|
||||
return true
|
||||
}
|
||||
return slices.ContainsFunc(p.severities, func(level string) bool { return r.severityCount(level) > 0 })
|
||||
}
|
||||
|
||||
// handleListPackageRows serves one sorted, filtered page of package rows.
|
||||
//
|
||||
// The store filters by registry and query in SQL and returns the matching rows.
|
||||
// The verdict depends on the scan policy and the live bypasses, so it is computed in
|
||||
// memory for those rows, in chunks of decisionChunk ids. Sorting and paging then run on
|
||||
// the filtered rows. The cost is one pass over the registry/query matches, never the page.
|
||||
func (a *App) handleListPackageRows(c fiber.Ctx) error {
|
||||
ctx := c.Context()
|
||||
p, err := parseRowParams(c)
|
||||
if err != nil {
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": err.Error()})
|
||||
}
|
||||
page, err := a.metadata.ListPackageGroups(ctx, metadata.GroupListOptions{Registry: p.registry, Query: p.query, SortBy: metadata.GroupSortName})
|
||||
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"})
|
||||
}
|
||||
|
||||
securityOn := a.config.Security.Enabled
|
||||
decisions := map[string]scanner.ScanDecision{}
|
||||
if securityOn {
|
||||
if decisions, err = a.loadDecisions(ctx, page.Packages); 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"})
|
||||
}
|
||||
}
|
||||
all := make([]packageRow, len(page.Packages))
|
||||
for i, pkg := range page.Packages {
|
||||
all[i] = rowOf(pkg, decisions)
|
||||
}
|
||||
counts := countRows(all)
|
||||
|
||||
matched := all
|
||||
if securityOn {
|
||||
matched = slices.DeleteFunc(slices.Clone(all), func(r packageRow) bool { return !p.keeps(r) })
|
||||
} else if p.verdict != "" || len(p.severities) > 0 {
|
||||
matched = nil
|
||||
}
|
||||
sortRows(matched, p)
|
||||
|
||||
start := min((p.page-1)*p.pageSize, len(matched))
|
||||
end := min(start+p.pageSize, len(matched))
|
||||
items := make([]map[string]interface{}, 0, end-start)
|
||||
for _, r := range matched[start:end] {
|
||||
item := packageSummary(r.pkg)
|
||||
if securityOn {
|
||||
item["vulnerabilities"] = vulnerabilityInfo(r.pkg, decisions)
|
||||
}
|
||||
items = append(items, item)
|
||||
}
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"packages": items,
|
||||
"total": len(matched),
|
||||
"page": p.page,
|
||||
"page_size": p.pageSize,
|
||||
"counts": counts,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"slices"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
)
|
||||
|
||||
func rowNames(out map[string]any) []string {
|
||||
items, _ := out["packages"].([]any)
|
||||
names := make([]string, 0, len(items))
|
||||
for i := range items {
|
||||
name, _ := jsonAt(items, i, "name").(string)
|
||||
names = append(names, name)
|
||||
}
|
||||
return names
|
||||
}
|
||||
|
||||
func TestRowsLayoutFiltersByVerdict(t *testing.T) {
|
||||
a := newVerdictApp(t)
|
||||
for verdict, want := range map[string][]string{
|
||||
"held": {"held"},
|
||||
"bypassed": {"waved"},
|
||||
"cleared": {"plain"},
|
||||
"pending": {},
|
||||
} {
|
||||
out, _ := getJSON(t, a, "/api/packages?layout=rows&verdict="+verdict)
|
||||
if got := rowNames(out); !slices.Equal(got, want) {
|
||||
t.Errorf("verdict=%s names = %v, want %v", verdict, got, want)
|
||||
}
|
||||
if int(out["total"].(float64)) != len(want) {
|
||||
t.Errorf("verdict=%s total = %v, want %d", verdict, out["total"], len(want))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRowsLayoutCountsIgnoreTheVerdictFilter(t *testing.T) {
|
||||
a := newVerdictApp(t)
|
||||
out, _ := getJSON(t, a, "/api/packages?layout=rows&verdict=held")
|
||||
for verdict, want := range map[string]float64{"held": 1, "bypassed": 1, "cleared": 1, "pending": 0} {
|
||||
if got := jsonAt(out, "counts", "verdicts", verdict); got != want {
|
||||
t.Errorf("counts.verdicts.%s = %v, want %v", verdict, got, want)
|
||||
}
|
||||
}
|
||||
if got := jsonAt(out, "counts", "severity_packages", "critical"); got != float64(2) {
|
||||
t.Errorf("counts.severity_packages.critical = %v, want 2", got)
|
||||
}
|
||||
if got := jsonAt(out, "counts", "vulnerable_allowed"); got != float64(0) {
|
||||
t.Errorf("counts.vulnerable_allowed = %v, want 0", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRowsLayoutSeverityFilterNarrowsRows(t *testing.T) {
|
||||
a := newVerdictApp(t)
|
||||
out, _ := getJSON(t, a, "/api/packages?layout=rows&severity=critical")
|
||||
if got := rowNames(out); !slices.Equal(got, []string{"held", "waved"}) {
|
||||
t.Errorf("names = %v, want held and waved", got)
|
||||
}
|
||||
out, _ = getJSON(t, a, "/api/packages?layout=rows&severity=high")
|
||||
if got := rowNames(out); len(got) != 0 {
|
||||
t.Errorf("high names = %v, want none", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRowsLayoutSearchesAndSorts(t *testing.T) {
|
||||
a := newVerdictApp(t)
|
||||
out, _ := getJSON(t, a, "/api/packages?layout=rows&q=WAV")
|
||||
if got := rowNames(out); !slices.Equal(got, []string{"waved"}) {
|
||||
t.Errorf("q names = %v", got)
|
||||
}
|
||||
out, _ = getJSON(t, a, "/api/packages?layout=rows&sort=name&order=desc")
|
||||
if got := rowNames(out); !slices.Equal(got, []string{"waved", "plain", "held"}) {
|
||||
t.Errorf("desc names = %v", got)
|
||||
}
|
||||
out, _ = getJSON(t, a, "/api/packages?layout=rows&sort=last_scanned&order=asc")
|
||||
if len(rowNames(out)) != 3 {
|
||||
t.Errorf("last_scanned sort lost rows: %v", rowNames(out))
|
||||
}
|
||||
}
|
||||
|
||||
func TestRowsLayoutPagesAndReportsTotals(t *testing.T) {
|
||||
a := newVerdictApp(t)
|
||||
out, _ := getJSON(t, a, "/api/packages?layout=rows&page=2&page_size=2")
|
||||
if got := rowNames(out); !slices.Equal(got, []string{"waved"}) {
|
||||
t.Errorf("page 2 names = %v, want waved", got)
|
||||
}
|
||||
if out["total"] != float64(3) || out["page"] != float64(2) || out["page_size"] != float64(2) {
|
||||
t.Errorf("total/page/page_size = %v/%v/%v", out["total"], out["page"], out["page_size"])
|
||||
}
|
||||
out, _ = getJSON(t, a, "/api/packages?layout=rows&page=9&page_size=2")
|
||||
if len(rowNames(out)) != 0 || out["total"] != float64(3) {
|
||||
t.Errorf("past the end: names %v total %v", rowNames(out), out["total"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestRowsLayoutCapsPageSize(t *testing.T) {
|
||||
a := newVerdictApp(t)
|
||||
out, _ := getJSON(t, a, "/api/packages?layout=rows&page_size=100000")
|
||||
if out["page_size"] != float64(maxPageSize) {
|
||||
t.Errorf("page_size = %v, want %d", out["page_size"], maxPageSize)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRowsLayoutRejectsBadParams(t *testing.T) {
|
||||
a := newVerdictApp(t)
|
||||
for _, q := range []string{"verdict=maybe", "sort=colour", "order=sideways", "severity=huge"} {
|
||||
code, _, body := doRequest(t, a, "/api/packages?layout=rows&"+q, nil)
|
||||
if code != http.StatusBadRequest {
|
||||
t.Errorf("%s = %d %s, want 400", q, code, body)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRowsLayoutKeepsPendingRows(t *testing.T) {
|
||||
a := newVerdictApp(t)
|
||||
now := time.Now()
|
||||
if err := a.metadata.SavePackage(context.Background(), &metadata.Package{
|
||||
Registry: "npm", Name: "unscanned", Version: "1.0.0", StorageKey: "npm/unscanned", Size: 1, CachedAt: now, LastAccessed: now,
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
out, _ := getJSON(t, a, "/api/packages?layout=rows&verdict=pending")
|
||||
if got := rowNames(out); !slices.Equal(got, []string{"unscanned"}) {
|
||||
t.Errorf("pending names = %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListWithoutLayoutIsUnchanged(t *testing.T) {
|
||||
a := newVerdictApp(t)
|
||||
out, _ := getJSON(t, a, "/api/packages?verdict=held&sort=last_scanned")
|
||||
if got := rowNames(out); len(got) != 3 {
|
||||
t.Errorf("legacy list ignored nothing: %v", got)
|
||||
}
|
||||
if _, ok := out["counts"]; ok {
|
||||
t.Error("legacy response gained counts")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRowsLayoutSortsByRisk(t *testing.T) {
|
||||
a := newVerdictApp(t)
|
||||
out, _ := getJSON(t, a, "/api/packages?layout=rows&sort=risk&order=desc")
|
||||
got := rowNames(out)
|
||||
if len(got) != 3 || got[2] != "plain" {
|
||||
t.Errorf("risk desc names = %v, want the clean package last", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRowsLayoutExcludesGoMetadataFiles(t *testing.T) {
|
||||
a := newVerdictApp(t)
|
||||
before, _ := getJSON(t, a, "/api/packages?layout=rows")
|
||||
now := time.Now()
|
||||
for _, name := range []string{"example.com/m/@v/v1.0.0.mod", "example.com/m/@v/v1.0.0.info", "example.com/m/@v/v1.0.0.zip", "example.com/only/@v/v0.1.0.mod"} {
|
||||
if err := a.metadata.SavePackage(context.Background(), &metadata.Package{
|
||||
Registry: "go", Name: name, Version: "v1.0.0", StorageKey: "go/" + name, Size: 1, CachedAt: now, LastAccessed: now,
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
out, _ := getJSON(t, a, "/api/packages?layout=rows®istry=go")
|
||||
if got := rowNames(out); !slices.Equal(got, []string{"example.com/m"}) {
|
||||
t.Errorf("go rows = %v, want only the .zip", got)
|
||||
}
|
||||
if out["total"].(float64) != 1 {
|
||||
t.Errorf("total = %v, want 1", out["total"])
|
||||
}
|
||||
if pending := out["counts"].(map[string]any)["verdicts"].(map[string]any)["pending"].(float64); pending != 1 {
|
||||
t.Errorf("pending count = %v, want 1", pending)
|
||||
}
|
||||
|
||||
after, _ := getJSON(t, a, "/api/packages?layout=rows")
|
||||
if after["total"].(float64) != before["total"].(float64)+1 {
|
||||
t.Errorf("total = %v, want %v", after["total"], before["total"].(float64)+1)
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
@@ -18,8 +20,7 @@ func (a *App) handlePrewarmingStatus(c fiber.Ctx) error {
|
||||
func (a *App) handlePrewarmingTrigger(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "application/json")
|
||||
|
||||
ctx := c.Context()
|
||||
a.prewarmWorker.TriggerPrewarm(ctx)
|
||||
a.prewarmWorker.TriggerPrewarm(context.Background())
|
||||
|
||||
log.Info().Msg("Pre-warming manually triggered via API")
|
||||
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"math"
|
||||
"time"
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
type rescanRequest struct {
|
||||
Scope scanner.RescanScope `json:"scope"`
|
||||
}
|
||||
|
||||
// jobContext is the context of work that outlives a request: it ends with the server.
|
||||
func (a *App) jobContext() context.Context {
|
||||
if a.workerCtx != nil {
|
||||
return a.workerCtx
|
||||
}
|
||||
return context.Background()
|
||||
}
|
||||
|
||||
func rescanStatusBody(a *App) fiber.Map {
|
||||
body := fiber.Map{"enabled": a.rescanWorker != nil, "running": false, "scope": "", "queued": 0, "done": 0, "failed": 0}
|
||||
if a.rescanWorker == nil {
|
||||
return body
|
||||
}
|
||||
st := a.rescanWorker.Status()
|
||||
body["running"], body["scope"] = st.Running, string(st.Scope)
|
||||
body["queued"], body["done"], body["failed"] = st.Queued, st.Done, st.Failed
|
||||
body["elapsed_seconds"] = int64(st.Elapsed.Seconds())
|
||||
// The rate so far predicts the rest; nothing is known before the first artifact finishes.
|
||||
if processed := st.Done + st.Failed; st.Running && processed > 0 {
|
||||
body["eta_seconds"] = int64(st.Elapsed.Seconds() * float64(st.Queued-processed) / float64(processed))
|
||||
}
|
||||
if !st.StartedAt.IsZero() {
|
||||
body["started_at"] = st.StartedAt.UTC().Format(time.RFC3339)
|
||||
}
|
||||
if !st.FinishedAt.IsZero() {
|
||||
body["finished_at"] = st.FinishedAt.UTC().Format(time.RFC3339)
|
||||
}
|
||||
return body
|
||||
}
|
||||
|
||||
// handleRescanTrigger queues a rescan of cached artifacts and answers 202 with the queued count.
|
||||
func (a *App) handleRescanTrigger(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "application/json")
|
||||
|
||||
var req rescanRequest
|
||||
if err := c.Bind().Body(&req); err != nil || !req.Scope.Valid() {
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": `scope must be "vulnerable" or "all"`})
|
||||
}
|
||||
if a.rescanWorker == nil {
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": scanner.ErrRescanDisabled.Error()})
|
||||
}
|
||||
|
||||
queued, err := a.rescanWorker.RescanNow(a.jobContext(), req.Scope)
|
||||
switch {
|
||||
case errors.Is(err, scanner.ErrRescanRunning):
|
||||
return c.Status(fiber.StatusConflict).JSON(fiber.Map{"error": err.Error(), "status": rescanStatusBody(a)})
|
||||
case errors.Is(err, scanner.ErrRescanDisabled):
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": err.Error()})
|
||||
case err != nil:
|
||||
log.Error().Err(err).Msg("Failed to queue rescan")
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": "failed to queue rescan"})
|
||||
}
|
||||
|
||||
log.Info().Str("scope", string(req.Scope)).Int("queued", queued).Msg("Rescan queued via API")
|
||||
return c.Status(fiber.StatusAccepted).JSON(fiber.Map{"queued": queued, "scope": req.Scope})
|
||||
}
|
||||
|
||||
type rescanScopeEstimate struct {
|
||||
// Seconds is null until the store has recorded a scan duration.
|
||||
Seconds *int64 `json:"seconds"`
|
||||
Artifacts int `json:"artifacts"`
|
||||
}
|
||||
|
||||
// handleRescanEstimate sizes each scope from the artifact counts, the average of recent scan
|
||||
// durations and the configured concurrency.
|
||||
func (a *App) handleRescanEstimate(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "application/json")
|
||||
if a.rescanWorker == nil {
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": scanner.ErrRescanDisabled.Error()})
|
||||
}
|
||||
est, err := a.rescanWorker.Estimate(a.jobContext())
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Failed to estimate rescan")
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": "failed to estimate rescan"})
|
||||
}
|
||||
sized := func(artifacts int) rescanScopeEstimate {
|
||||
out := rescanScopeEstimate{Artifacts: artifacts}
|
||||
if est.AvgScan > 0 {
|
||||
secs := int64(math.Ceil(est.AvgScan.Seconds() * float64(artifacts) / float64(max(est.Concurrency, 1))))
|
||||
out.Seconds = &secs
|
||||
}
|
||||
return out
|
||||
}
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"vulnerable": sized(est.Vulnerable),
|
||||
"all": sized(est.All),
|
||||
"avg_scan_seconds": est.AvgScan.Seconds(),
|
||||
"concurrency": est.Concurrency,
|
||||
})
|
||||
}
|
||||
|
||||
// handleRescanStatus reports the progress of the latest admin-triggered rescan.
|
||||
func (a *App) handleRescanStatus(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "application/json")
|
||||
return c.Status(fiber.StatusOK).JSON(rescanStatusBody(a))
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/config"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func rescanApp(t *testing.T) (*App, *fiber.App) {
|
||||
t.Helper()
|
||||
a := newTestApp(t, func(c *config.Config) {
|
||||
c.Security.Enabled = true
|
||||
c.Security.UpdateDBOnStartup = false
|
||||
c.Security.RescanInterval = 0
|
||||
disableAllScanners(c)
|
||||
})
|
||||
f := fiber.New()
|
||||
f.Post("/api/admin/rescan", a.handleRescanTrigger)
|
||||
f.Get("/api/admin/rescan/status", a.handleRescanStatus)
|
||||
return a, f
|
||||
}
|
||||
|
||||
func decodeBody(t *testing.T, resp *http.Response) map[string]any {
|
||||
t.Helper()
|
||||
var out map[string]any
|
||||
require.NoError(t, json.NewDecoder(resp.Body).Decode(&out))
|
||||
return out
|
||||
}
|
||||
|
||||
func postRescan(t *testing.T, f *fiber.App, body string) (int, map[string]any) {
|
||||
t.Helper()
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/admin/rescan", strings.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
resp, err := f.Test(req)
|
||||
require.NoError(t, err)
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
return resp.StatusCode, decodeBody(t, resp)
|
||||
}
|
||||
|
||||
func rescanStatus(t *testing.T, f *fiber.App) map[string]any {
|
||||
t.Helper()
|
||||
resp, err := f.Test(httptest.NewRequest(http.MethodGet, "/api/admin/rescan/status", nil))
|
||||
require.NoError(t, err)
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
require.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
return decodeBody(t, resp)
|
||||
}
|
||||
|
||||
func saveRescanPackage(t *testing.T, a *App, name, version string) {
|
||||
t.Helper()
|
||||
now := time.Now()
|
||||
require.NoError(t, a.metadata.SavePackage(context.Background(), &metadata.Package{
|
||||
Registry: "npm", Name: name, Version: version, StorageKey: "npm/" + name + "/" + version, Size: 1, CachedAt: now, LastAccessed: now,
|
||||
}))
|
||||
}
|
||||
|
||||
func TestRescanTriggerQueuesAndReportsProgress(t *testing.T) {
|
||||
a, f := rescanApp(t)
|
||||
saveRescanPackage(t, a, "left-pad", "1.3.0")
|
||||
saveRescanPackage(t, a, "left-pad", "metadata")
|
||||
|
||||
code, body := postRescan(t, f, `{"scope":"all"}`)
|
||||
require.Equal(t, http.StatusAccepted, code)
|
||||
require.EqualValues(t, 1, body["queued"], "the metadata row is not queued")
|
||||
require.Equal(t, "all", body["scope"])
|
||||
|
||||
require.Eventually(t, func() bool { return rescanStatus(t, f)["running"] == false }, 5*time.Second, 10*time.Millisecond)
|
||||
st := rescanStatus(t, f)
|
||||
require.EqualValues(t, 1, st["queued"])
|
||||
require.EqualValues(t, 1, st["done"].(float64)+st["failed"].(float64), "the one artifact is processed")
|
||||
require.NotEmpty(t, st["finished_at"])
|
||||
}
|
||||
|
||||
func TestRescanTriggerRefusesASecondRunWhileActive(t *testing.T) {
|
||||
a, f := rescanApp(t)
|
||||
saveRescanPackage(t, a, "left-pad", "1.3.0")
|
||||
release, entered := make(chan struct{}), make(chan struct{}, 1)
|
||||
a.scanManager.SetFileSource(func(context.Context, string, string, string) (string, func(), error) {
|
||||
select {
|
||||
case entered <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
<-release
|
||||
return "", func() {}, context.Canceled
|
||||
})
|
||||
|
||||
code, _ := postRescan(t, f, `{"scope":"all"}`)
|
||||
require.Equal(t, http.StatusAccepted, code)
|
||||
<-entered
|
||||
require.Equal(t, true, rescanStatus(t, f)["running"])
|
||||
|
||||
code, body := postRescan(t, f, `{"scope":"vulnerable"}`)
|
||||
require.Equal(t, http.StatusConflict, code)
|
||||
require.NotEmpty(t, body["error"])
|
||||
|
||||
close(release)
|
||||
require.Eventually(t, func() bool { return rescanStatus(t, f)["running"] == false }, 5*time.Second, 10*time.Millisecond)
|
||||
}
|
||||
|
||||
func TestRescanTriggerRejectsBadInput(t *testing.T) {
|
||||
_, f := rescanApp(t)
|
||||
for _, body := range []string{``, `{}`, `{"scope":"everything"}`, `not json`} {
|
||||
code, _ := postRescan(t, f, body)
|
||||
require.Equal(t, http.StatusBadRequest, code, body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRescanTriggerNeedsScanningOn(t *testing.T) {
|
||||
a := newTestApp(t, func(c *config.Config) { c.Security.Enabled = false })
|
||||
f := fiber.New()
|
||||
f.Post("/api/admin/rescan", a.handleRescanTrigger)
|
||||
f.Get("/api/admin/rescan/status", a.handleRescanStatus)
|
||||
|
||||
code, _ := postRescan(t, f, `{"scope":"all"}`)
|
||||
require.Equal(t, http.StatusBadRequest, code)
|
||||
require.Equal(t, false, rescanStatus(t, f)["enabled"])
|
||||
}
|
||||
|
||||
func TestRescanRoutesNeedAdmin(t *testing.T) {
|
||||
a, _ := rescanApp(t)
|
||||
for _, tc := range []struct{ method, path string }{
|
||||
{http.MethodPost, "/api/admin/rescan"},
|
||||
{http.MethodGet, "/api/admin/rescan/status"},
|
||||
} {
|
||||
req := httptest.NewRequest(tc.method, tc.path, strings.NewReader(`{"scope":"all"}`))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
resp, err := a.app.Test(req)
|
||||
require.NoError(t, err)
|
||||
_ = resp.Body.Close()
|
||||
require.Equal(t, http.StatusUnauthorized, resp.StatusCode, tc.path)
|
||||
}
|
||||
}
|
||||
|
||||
type fixedScanner struct{}
|
||||
|
||||
func (fixedScanner) Name() string { return "fixed" }
|
||||
func (fixedScanner) Scan(_ context.Context, registry, name, version, _ string) (*metadata.ScanResult, error) {
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
return &metadata.ScanResult{Registry: registry, PackageName: name, PackageVersion: version, Scanner: "fixed", ScannedAt: time.Now(), Status: metadata.ScanStatusClean}, nil
|
||||
}
|
||||
func (fixedScanner) Health(context.Context) error { return nil }
|
||||
|
||||
func getRescan(t *testing.T, f *fiber.App, path string) map[string]any {
|
||||
t.Helper()
|
||||
resp, err := f.Test(httptest.NewRequest(http.MethodGet, path, nil))
|
||||
require.NoError(t, err)
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
require.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
return decodeBody(t, resp)
|
||||
}
|
||||
|
||||
func TestRescanEstimateUsesMeasuredScanTimeAndConcurrency(t *testing.T) {
|
||||
a, f := rescanApp(t)
|
||||
f.Get("/api/admin/rescan/estimate", a.handleRescanEstimate)
|
||||
a.scanManager.RegisterScanner(fixedScanner{})
|
||||
a.scanManager.SetFileSource(func(context.Context, string, string, string) (string, func(), error) {
|
||||
return "/tmp/dummy", func() {}, nil
|
||||
})
|
||||
for _, v := range []string{"1.0.0", "1.1.0", "1.2.0", "1.3.0"} {
|
||||
saveRescanPackage(t, a, "left-pad", v)
|
||||
}
|
||||
|
||||
before := getRescan(t, f, "/api/admin/rescan/estimate")
|
||||
require.EqualValues(t, 4, jsonAt(before, "all", "artifacts"))
|
||||
require.Nil(t, jsonAt(before, "all", "seconds"), "no scan was timed yet")
|
||||
|
||||
code, _ := postRescan(t, f, `{"scope":"all"}`)
|
||||
require.Equal(t, http.StatusAccepted, code)
|
||||
require.Eventually(t, func() bool { return rescanStatus(t, f)["running"] == false }, 10*time.Second, 10*time.Millisecond)
|
||||
|
||||
after := getRescan(t, f, "/api/admin/rescan/estimate")
|
||||
avg := after["avg_scan_seconds"].(float64)
|
||||
require.Greater(t, avg, 0.019, "the 20 ms scanner was measured")
|
||||
concurrency := after["concurrency"].(float64)
|
||||
require.EqualValues(t, 4, jsonAt(after, "all", "artifacts"))
|
||||
require.InDelta(t, avg*4/concurrency, jsonAt(after, "all", "seconds"), 1, "ceil of artifacts x average / concurrency")
|
||||
require.EqualValues(t, 0, jsonAt(after, "vulnerable", "artifacts"))
|
||||
}
|
||||
|
||||
func TestRescanStatusReportsEtaWhileRunning(t *testing.T) {
|
||||
a, f := rescanApp(t)
|
||||
a.scanManager.RegisterScanner(fixedScanner{})
|
||||
saveRescanPackage(t, a, "a", "1.0.0")
|
||||
saveRescanPackage(t, a, "b", "1.0.0")
|
||||
release, calls := make(chan struct{}), make(chan struct{}, 2)
|
||||
a.scanManager.SetFileSource(func(context.Context, string, string, string) (string, func(), error) {
|
||||
calls <- struct{}{}
|
||||
if len(calls) > 1 {
|
||||
<-release
|
||||
}
|
||||
return "/tmp/dummy", func() {}, nil
|
||||
})
|
||||
|
||||
code, _ := postRescan(t, f, `{"scope":"all"}`)
|
||||
require.Equal(t, http.StatusAccepted, code)
|
||||
require.Eventually(t, func() bool { return len(calls) == 2 && rescanStatus(t, f)["done"].(float64) == 1 }, 5*time.Second, 5*time.Millisecond)
|
||||
|
||||
st := rescanStatus(t, f)
|
||||
require.Equal(t, true, st["running"])
|
||||
require.Contains(t, st, "eta_seconds", "one of two is done, so the rate predicts the rest")
|
||||
require.Contains(t, st, "elapsed_seconds")
|
||||
close(release)
|
||||
require.Eventually(t, func() bool { return rescanStatus(t, f)["running"] == false }, 5*time.Second, 10*time.Millisecond)
|
||||
require.NotContains(t, rescanStatus(t, f), "eta_seconds")
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/url"
|
||||
"time"
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/lukaszraczylo/gohoarder/internal/version"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/cache"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/config"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner/ghsa"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner/govulncheck"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner/grype"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner/npmaudit"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner/osv"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner/pipaudit"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner/trivy"
|
||||
)
|
||||
|
||||
type scannerSwitch struct {
|
||||
name string
|
||||
enabled bool
|
||||
}
|
||||
|
||||
// scannerSwitches lists every scanner the manager can register, in display order.
|
||||
func scannerSwitches(s config.ScannersConfig) []scannerSwitch {
|
||||
return []scannerSwitch{
|
||||
{trivy.ScannerName, s.Trivy.Enabled},
|
||||
{grype.ScannerName, s.Grype.Enabled},
|
||||
{osv.ScannerName, s.OSV.Enabled},
|
||||
{govulncheck.ScannerName, s.Govulncheck.Enabled},
|
||||
{npmaudit.ScannerName, s.NpmAudit.Enabled},
|
||||
{pipaudit.ScannerName, s.PipAudit.Enabled},
|
||||
{ghsa.ScannerName, s.GHSA.Enabled},
|
||||
}
|
||||
}
|
||||
|
||||
// originOnly keeps scheme and host, so credentials, paths and queries in an upstream URL never leave the server.
|
||||
func originOnly(raw string) string {
|
||||
u, err := url.Parse(raw)
|
||||
if err != nil || u.Host == "" {
|
||||
return ""
|
||||
}
|
||||
return u.Scheme + "://" + u.Host
|
||||
}
|
||||
|
||||
func seconds(d time.Duration) int64 { return int64(d / time.Second) }
|
||||
|
||||
// systemScanners joins the configured scanners with their cached health; disabled scanners report no health.
|
||||
func (a *App) systemScanners(ctx context.Context) []fiber.Map {
|
||||
sec := a.config.Security
|
||||
health := map[string]fiber.Map{}
|
||||
if sec.Enabled && a.scanManager != nil {
|
||||
for _, st := range a.scanManager.Statuses(ctx) {
|
||||
health[st.Name] = fiber.Map{"healthy": st.Healthy, "version": st.Version}
|
||||
}
|
||||
}
|
||||
out := make([]fiber.Map, 0, 7)
|
||||
for _, sw := range scannerSwitches(sec.Scanners) {
|
||||
entry := fiber.Map{"name": sw.name, "enabled": sw.enabled && sec.Enabled, "healthy": nil, "version": ""}
|
||||
if h, ok := health[sw.name]; ok {
|
||||
entry["healthy"], entry["version"] = h["healthy"], h["version"]
|
||||
}
|
||||
out = append(out, entry)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// handleSystem reports the effective policy and settings; it exposes no credentials, DSNs or paths.
|
||||
// Durations are whole seconds; a negative threshold means unlimited.
|
||||
func (a *App) handleSystem(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "application/json")
|
||||
|
||||
if c.Method() == "OPTIONS" {
|
||||
return c.SendStatus(fiber.StatusOK)
|
||||
}
|
||||
|
||||
if c.Method() != "GET" {
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "method not allowed"})
|
||||
}
|
||||
|
||||
sec := a.config.Security
|
||||
scanWait := sec.ScanWaitTimeout
|
||||
if scanWait == 0 {
|
||||
scanWait = cache.DefaultScanWaitTimeout
|
||||
}
|
||||
concurrency := max(sec.RescanConcurrency, 1)
|
||||
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"version": version.Version,
|
||||
"security": fiber.Map{
|
||||
"enabled": sec.Enabled,
|
||||
"fail_closed": sec.FailClosed,
|
||||
"scan_on_download": sec.ScanOnDownload,
|
||||
"block_on_severity": sec.BlockOnSeverity,
|
||||
"block_thresholds": fiber.Map{
|
||||
"critical": sec.BlockThresholds.Critical,
|
||||
"high": sec.BlockThresholds.High,
|
||||
"moderate": sec.BlockThresholds.Medium,
|
||||
"low": sec.BlockThresholds.Low,
|
||||
},
|
||||
"scan_wait_timeout": seconds(scanWait),
|
||||
"scanners": a.systemScanners(c.Context()),
|
||||
"rescan": fiber.Map{
|
||||
"interval": seconds(sec.RescanInterval),
|
||||
"active_window": seconds(sec.RescanActiveWindow),
|
||||
"concurrency": concurrency,
|
||||
"on_access": sec.RescanOnAccess,
|
||||
},
|
||||
},
|
||||
"upstreams": fiber.Map{
|
||||
"go": originOnly(a.config.Handlers.Go.UpstreamProxy),
|
||||
"npm": originOnly(a.config.Handlers.NPM.UpstreamRegistry),
|
||||
"pypi": originOnly(a.config.Handlers.PyPI.UpstreamURL),
|
||||
},
|
||||
"cache": fiber.Map{
|
||||
"max_size": a.config.Cache.MaxSizeBytes,
|
||||
"idle_ttl": seconds(a.config.Cache.IdleTTL),
|
||||
"default_ttl": seconds(a.config.Cache.DefaultTTL),
|
||||
},
|
||||
"prewarming": fiber.Map{
|
||||
"enabled": a.prewarmWorker != nil && a.config.Prewarming.Enabled,
|
||||
"interval": seconds(a.config.Prewarming.Interval),
|
||||
"top_packages": a.config.Prewarming.TopPackages,
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,273 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/analytics"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/config"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
)
|
||||
|
||||
// jsonAt walks decoded JSON along keys (strings) and indexes (ints); a missing step yields nil.
|
||||
func jsonAt(v any, path ...any) any {
|
||||
for _, step := range path {
|
||||
switch k := step.(type) {
|
||||
case string:
|
||||
m, ok := v.(map[string]any)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
v = m[k]
|
||||
case int:
|
||||
l, ok := v.([]any)
|
||||
if !ok || k >= len(l) {
|
||||
return nil
|
||||
}
|
||||
v = l[k]
|
||||
}
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
func getJSON(t *testing.T, a *App, target string) (map[string]any, string) {
|
||||
t.Helper()
|
||||
code, _, body := doRequest(t, a, target, nil)
|
||||
if code != http.StatusOK {
|
||||
t.Fatalf("GET %s = %d %s", target, code, body)
|
||||
}
|
||||
var out map[string]any
|
||||
if err := json.Unmarshal([]byte(body), &out); err != nil {
|
||||
t.Fatalf("decode %s: %v", body, err)
|
||||
}
|
||||
return out, body
|
||||
}
|
||||
|
||||
func disableAllScanners(c *config.Config) {
|
||||
sc := &c.Security.Scanners
|
||||
sc.Trivy.Enabled, sc.Grype.Enabled, sc.OSV.Enabled, sc.Govulncheck.Enabled = false, false, false, false
|
||||
sc.NpmAudit.Enabled, sc.PipAudit.Enabled, sc.GHSA.Enabled = false, false, false
|
||||
}
|
||||
|
||||
func TestSystemReportsEffectivePolicy(t *testing.T) {
|
||||
a := newTestApp(t, func(c *config.Config) {
|
||||
c.Security.Enabled = true
|
||||
c.Security.UpdateDBOnStartup = false
|
||||
c.Security.FailClosed = true
|
||||
c.Security.BlockOnSeverity = "critical"
|
||||
c.Security.RescanInterval = 6 * time.Hour
|
||||
c.Security.RescanConcurrency = 0
|
||||
c.Security.ScanWaitTimeout = 0
|
||||
disableAllScanners(c)
|
||||
c.Cache.MaxSizeBytes = 1 << 30
|
||||
c.Cache.IdleTTL = 24 * time.Hour
|
||||
c.Cache.DefaultTTL = 7 * 24 * time.Hour
|
||||
})
|
||||
|
||||
out, _ := getJSON(t, a, "/api/system")
|
||||
checks := map[string][2]any{
|
||||
"fail_closed": {jsonAt(out, "security", "fail_closed"), true},
|
||||
"block_on_severity": {jsonAt(out, "security", "block_on_severity"), "critical"},
|
||||
"rescan interval": {jsonAt(out, "security", "rescan", "interval"), float64(6 * 3600)},
|
||||
"rescan workers": {jsonAt(out, "security", "rescan", "concurrency"), float64(1)},
|
||||
"scan wait": {jsonAt(out, "security", "scan_wait_timeout"), float64(30)},
|
||||
"cache max": {jsonAt(out, "cache", "max_size"), float64(1 << 30)},
|
||||
"cache idle": {jsonAt(out, "cache", "idle_ttl"), float64(86400)},
|
||||
"cache default": {jsonAt(out, "cache", "default_ttl"), float64(7 * 86400)},
|
||||
}
|
||||
for name, c := range checks {
|
||||
if c[0] != c[1] {
|
||||
t.Errorf("%s = %v, want %v", name, c[0], c[1])
|
||||
}
|
||||
}
|
||||
scanners, _ := jsonAt(out, "security", "scanners").([]any)
|
||||
if len(scanners) != 7 {
|
||||
t.Fatalf("scanners = %d entries, want all 7", len(scanners))
|
||||
}
|
||||
for i := range scanners {
|
||||
if jsonAt(scanners, i, "enabled") != false || jsonAt(scanners, i, "healthy") != nil {
|
||||
t.Errorf("disabled scanner %v reported %v", jsonAt(scanners, i, "name"), scanners[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The system view is for display only; no configured secret or path may appear in it.
|
||||
func TestSystemLeaksNoSecrets(t *testing.T) {
|
||||
const secret = "ghp_super-secret-token"
|
||||
a := newTestApp(t, func(c *config.Config) {
|
||||
c.Security.Enabled = true
|
||||
c.Security.UpdateDBOnStartup = false
|
||||
disableAllScanners(c)
|
||||
c.Security.Scanners.GHSA.Token = secret
|
||||
c.Security.Scanners.Trivy.CacheDB = "/srv/private/trivy-db"
|
||||
})
|
||||
_, body := getJSON(t, a, "/api/system")
|
||||
for _, banned := range []string{secret, "/srv/private", "token", "dsn", "password"} {
|
||||
if strings.Contains(strings.ToLower(body), strings.ToLower(banned)) {
|
||||
t.Errorf("/api/system exposes %q: %s", banned, body)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSystemUpstreamsKeepOnlySchemeAndHost(t *testing.T) {
|
||||
a := newTestApp(t, func(c *config.Config) {
|
||||
c.Handlers.NPM.UpstreamRegistry = fmt.Sprintf("https://%s:%[email protected]:8443/private/path?token=abc", "deploy", "s3cret")
|
||||
c.Handlers.PyPI.UpstreamURL = "not a url"
|
||||
})
|
||||
out, body := getJSON(t, a, "/api/system")
|
||||
if got := jsonAt(out, "upstreams", "npm"); got != "https://npm.example.com:8443" {
|
||||
t.Errorf("npm upstream = %v", got)
|
||||
}
|
||||
if got := jsonAt(out, "upstreams", "pypi"); got != "" {
|
||||
t.Errorf("unparseable upstream = %v, want empty", got)
|
||||
}
|
||||
for _, banned := range []string{"s3cret", "deploy", "private/path", "abc"} {
|
||||
if strings.Contains(body, banned) {
|
||||
t.Errorf("/api/system exposes %q: %s", banned, body)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSystemRequiresAuthWhenEnabled(t *testing.T) {
|
||||
a := newTestApp(t, func(c *config.Config) { c.Auth.Enabled = true })
|
||||
code, _, _ := doRequest(t, a, "/api/system", nil)
|
||||
if code != http.StatusUnauthorized {
|
||||
t.Errorf("GET /api/system without a key = %d, want 401", code)
|
||||
}
|
||||
}
|
||||
|
||||
func seedBypassed(t *testing.T, a *App) {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
now := time.Now()
|
||||
for _, name := range []string{"held", "waved", "plain"} {
|
||||
if err := a.metadata.SavePackage(ctx, &metadata.Package{
|
||||
Registry: "npm", Name: name, Version: "1.0.0", StorageKey: "npm/" + name, Size: 10, CachedAt: now, LastAccessed: now,
|
||||
}); err != nil {
|
||||
t.Fatalf("SavePackage: %v", err)
|
||||
}
|
||||
res := &metadata.ScanResult{Registry: "npm", PackageName: name, PackageVersion: "1.0.0", Scanner: "trivy+osv", Status: metadata.ScanStatusClean, ScannedAt: now}
|
||||
if name != "plain" {
|
||||
res.Status = metadata.ScanStatusVulnerable
|
||||
res.VulnerabilityCount = 2
|
||||
res.Vulnerabilities = []metadata.Vulnerability{
|
||||
{ID: "CVE-2021-44906", Severity: "critical", DetectedBy: []string{"trivy", "osv"}, FixedIn: "1.2.6"},
|
||||
{ID: "CVE-2022-0001", Severity: "low", DetectedBy: []string{"osv"}},
|
||||
}
|
||||
}
|
||||
if err := a.metadata.SaveScanResult(ctx, res); err != nil {
|
||||
t.Fatalf("SaveScanResult: %v", err)
|
||||
}
|
||||
}
|
||||
if err := a.metadata.SaveCVEBypass(ctx, &metadata.CVEBypass{
|
||||
Type: metadata.BypassTypePackage, Target: "npm/[email protected]", Reason: "vendor patch", CreatedBy: "alice",
|
||||
Active: true, ExpiresAt: now.Add(48 * time.Hour),
|
||||
}); err != nil {
|
||||
t.Fatalf("SaveCVEBypass: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func newVerdictApp(t *testing.T) *App {
|
||||
t.Helper()
|
||||
a, _ := newScanningApp(t)
|
||||
a.config.Security.BlockOnSeverity = "critical"
|
||||
seedBypassed(t, a)
|
||||
return a
|
||||
}
|
||||
|
||||
func TestListPackagesCarriesVerdicts(t *testing.T) {
|
||||
a := newVerdictApp(t)
|
||||
out, _ := getJSON(t, a, "/api/packages")
|
||||
pkgs, _ := out["packages"].([]any)
|
||||
got := map[string]string{}
|
||||
for i := range pkgs {
|
||||
name, _ := jsonAt(pkgs, i, "name").(string)
|
||||
verdict, _ := jsonAt(pkgs, i, "vulnerabilities", "verdict").(string)
|
||||
got[name] = verdict
|
||||
if name == "held" && jsonAt(pkgs, i, "vulnerabilities", "reason") == nil {
|
||||
t.Errorf("held package has no reason")
|
||||
}
|
||||
if name == "waved" && jsonAt(pkgs, i, "vulnerabilities", "bypass", "created_by") != "alice" {
|
||||
t.Errorf("bypassed package bypass = %v", jsonAt(pkgs, i, "vulnerabilities", "bypass"))
|
||||
}
|
||||
}
|
||||
want := map[string]string{"held": VerdictHeld, "waved": VerdictBypassed, "plain": VerdictCleared}
|
||||
for name, verdict := range want {
|
||||
if got[name] != verdict {
|
||||
t.Errorf("%s verdict = %q, want %q", name, got[name], verdict)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestStatsCountsBypassedPackages(t *testing.T) {
|
||||
a := newVerdictApp(t)
|
||||
out, _ := getJSON(t, a, "/api/stats")
|
||||
if jsonAt(out, "stats", "blocked_packages") != float64(1) || jsonAt(out, "stats", "bypassed_packages") != float64(1) {
|
||||
t.Errorf("stats = %v, want 1 held and 1 bypassed", out["stats"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestVulnerabilityDetailsExplainVerdictAndScanners(t *testing.T) {
|
||||
a := newVerdictApp(t)
|
||||
details := func(name string) map[string]any {
|
||||
out, _ := getJSON(t, a, "/api/packages/npm/"+name+"/1.0.0/vulnerabilities")
|
||||
return out
|
||||
}
|
||||
|
||||
held := details("held")
|
||||
if jsonAt(held, "decision", "verdict") != VerdictHeld || jsonAt(held, "decision", "blocked") != true || jsonAt(held, "decision", "reason") == "" {
|
||||
t.Errorf("held decision = %v", held["decision"])
|
||||
}
|
||||
scanners, _ := held["scanners"].([]any)
|
||||
if len(scanners) != 2 {
|
||||
t.Fatalf("scanners = %v, want trivy and osv", scanners)
|
||||
}
|
||||
findings := map[string]any{}
|
||||
for i := range scanners {
|
||||
findings[jsonAt(scanners, i, "name").(string)] = jsonAt(scanners, i, "findings")
|
||||
}
|
||||
if findings["trivy"] != float64(1) || findings["osv"] != float64(2) {
|
||||
t.Errorf("findings per scanner = %v, want trivy 1, osv 2", findings)
|
||||
}
|
||||
if jsonAt(scanners, 0, "severity_counts", "critical") != float64(1) {
|
||||
t.Errorf("trivy severity counts = %v", jsonAt(scanners, 0, "severity_counts"))
|
||||
}
|
||||
if by, _ := jsonAt(held, "vulnerabilities", 0, "detected_by").([]any); len(by) != 2 {
|
||||
t.Errorf("detected_by = %v", by)
|
||||
}
|
||||
|
||||
waved := details("waved")
|
||||
if jsonAt(waved, "decision", "verdict") != VerdictBypassed || jsonAt(waved, "decision", "blocked") != false ||
|
||||
jsonAt(waved, "decision", "bypass", "reason") != "vendor patch" {
|
||||
t.Errorf("bypassed decision = %v", waved["decision"])
|
||||
}
|
||||
|
||||
plain := details("plain")
|
||||
if jsonAt(plain, "decision", "verdict") != VerdictCleared || jsonAt(plain, "decision", "bypass") != nil {
|
||||
t.Errorf("clean decision = %v", plain["decision"])
|
||||
}
|
||||
}
|
||||
|
||||
// Scoped npm names and Go module paths contain slashes; the per-package analytics route must accept them.
|
||||
func TestPackageAnalyticsAcceptsNamesWithSlashes(t *testing.T) {
|
||||
a := newTestApp(t, nil)
|
||||
for _, name := range []string{"@types/node", "github.com/google/uuid/@v/v1.6.0.zip", "lodash"} {
|
||||
a.analyticsEngine.TrackDownload(analytics.PackageDownload{Registry: "npm", Name: name, Version: "1.0.0", Timestamp: time.Now(), BytesSize: 5})
|
||||
}
|
||||
for _, name := range []string{"@types/node", "github.com/google/uuid/@v/v1.6.0.zip", "lodash"} {
|
||||
out, body := getJSON(t, a, "/api/analytics/package/npm/"+name)
|
||||
if jsonAt(out, "package", "TotalDownloads") != float64(1) {
|
||||
t.Errorf("analytics for %q = %s, want one download", name, body)
|
||||
}
|
||||
}
|
||||
// A package with no record yet is a normal answer; a 404 would show as a failed request in the browser.
|
||||
out, body := getJSON(t, a, "/api/analytics/package/npm/@types/missing")
|
||||
if pkg, present := out["package"]; !present || pkg != nil {
|
||||
t.Errorf("unknown package = %s, want 200 with a null package", body)
|
||||
}
|
||||
}
|
||||
@@ -55,20 +55,31 @@ func (a *App) handleStatsTrend(c fiber.Ctx) error {
|
||||
|
||||
// countBlocked counts scanned artifacts the blocking policy refuses.
|
||||
func (a *App) countBlocked(ctx context.Context) (int64, error) {
|
||||
blocked, _, err := a.countVerdicts(ctx)
|
||||
return blocked, err
|
||||
}
|
||||
|
||||
// countVerdicts counts scanned artifacts that are held and that pass only because an admin bypass applies.
|
||||
func (a *App) countVerdicts(ctx context.Context) (blocked, bypassed int64, err error) {
|
||||
if !a.config.Security.Enabled || a.scanManager == nil {
|
||||
return 0, nil
|
||||
return 0, 0, nil
|
||||
}
|
||||
decisions, err := a.scanManager.ScanDecisions(ctx, nil)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
return 0, 0, err
|
||||
}
|
||||
var blocked int64
|
||||
for _, d := range decisions {
|
||||
if d.Blocked && !metadata.IsMetadataVersion(d.Summary.Version) {
|
||||
if metadata.IsMetadataVersion(d.Summary.Version) {
|
||||
continue
|
||||
}
|
||||
switch verdictOf(d) {
|
||||
case VerdictHeld:
|
||||
blocked++
|
||||
case VerdictBypassed:
|
||||
bypassed++
|
||||
}
|
||||
}
|
||||
return blocked, nil
|
||||
return blocked, bypassed, nil
|
||||
}
|
||||
|
||||
// blockedCounterSetter is implemented by stores that snapshot blocked packages.
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/analytics"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata/gormstore"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
type trendingResponse struct {
|
||||
Packages []trendingPackage `json:"packages"`
|
||||
Total int `json:"total"`
|
||||
}
|
||||
|
||||
func getTrending(t *testing.T, a *App, query string) trendingResponse {
|
||||
t.Helper()
|
||||
f := fiber.New()
|
||||
f.Get("/api/analytics/trending", a.handleAnalyticsTrendingPackages)
|
||||
resp, err := f.Test(httptest.NewRequest("GET", "/api/analytics/trending"+query, nil))
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 200, resp.StatusCode)
|
||||
var out trendingResponse
|
||||
require.NoError(t, json.NewDecoder(resp.Body).Decode(&out))
|
||||
return out
|
||||
}
|
||||
|
||||
func seedDownloads(t *testing.T, store metadata.Store, registry, name, version string, n int) {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
now := time.Now()
|
||||
require.NoError(t, store.SavePackage(ctx, &metadata.Package{
|
||||
Registry: registry, Name: name, Version: version, StorageKey: registry + "/" + name + "/" + version,
|
||||
Size: 1, CachedAt: now, LastAccessed: now,
|
||||
}))
|
||||
for i := 0; i < n; i++ {
|
||||
require.NoError(t, store.UpdateDownloadCount(ctx, registry, name, version))
|
||||
}
|
||||
}
|
||||
|
||||
func TestTrendingServedFromPersistedDownloads(t *testing.T) {
|
||||
store, err := gormstore.NewV2(gormstore.Config{
|
||||
Driver: "sqlite", DSN: fmt.Sprintf("file:trend_%d?mode=memory&cache=shared", time.Now().UnixNano()),
|
||||
MaxOpenConns: 1, MaxIdleConns: 1, LogLevel: "silent",
|
||||
})
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { _ = store.Close() })
|
||||
seedDownloads(t, store, "npm", "left-pad", "1.3.0", 3)
|
||||
seedDownloads(t, store, "go", "github.com/google/uuid/@v/v1.6.0.zip", "v1.6.0", 2)
|
||||
seedDownloads(t, store, "go", "github.com/google/uuid/@v/v1.6.0.mod", "v1.6.0", 2)
|
||||
|
||||
// A fresh engine is what a restarted server has: it must not decide the ranking.
|
||||
engine := analytics.NewEngine(analytics.Config{MaxEvents: 10, FlushInterval: time.Minute})
|
||||
t.Cleanup(engine.Close)
|
||||
|
||||
got := getTrending(t, &App{metadata: store, analyticsEngine: engine}, "")
|
||||
require.Equal(t, 2, got.Total)
|
||||
require.Equal(t, "npm", got.Packages[0].Registry)
|
||||
require.Equal(t, "left-pad", got.Packages[0].Name)
|
||||
require.Equal(t, int64(3), got.Packages[0].RecentDownloads)
|
||||
require.Equal(t, int64(0), got.Packages[0].PreviousDownloads)
|
||||
require.Equal(t, "github.com/google/uuid", got.Packages[1].Name)
|
||||
require.Equal(t, int64(2), got.Packages[1].RecentDownloads)
|
||||
|
||||
limited := getTrending(t, &App{metadata: store, analyticsEngine: engine}, "?limit=1")
|
||||
require.Len(t, limited.Packages, 1)
|
||||
}
|
||||
|
||||
func TestTrendingFallsBackToEngineWithoutPersistedHistory(t *testing.T) {
|
||||
engine := analytics.NewEngine(analytics.Config{MaxEvents: 10, FlushInterval: time.Minute})
|
||||
t.Cleanup(engine.Close)
|
||||
engine.TrackDownload(analytics.PackageDownload{Registry: "npm", Name: "lodash", Version: "4", Timestamp: time.Now()})
|
||||
|
||||
got := getTrending(t, &App{analyticsEngine: engine}, "")
|
||||
require.Equal(t, 1, got.Total)
|
||||
require.Equal(t, "lodash", got.Packages[0].Name)
|
||||
}
|
||||
@@ -70,6 +70,8 @@ func (a *App) handleVulnerabilities(c fiber.Ctx) error {
|
||||
"vulnerability_count": 0,
|
||||
"message": "Package not yet scanned for vulnerabilities",
|
||||
"security_scanned": pkg.SecurityScanned,
|
||||
"decision": fiber.Map{"verdict": VerdictPending, "blocked": false, "reason": "", "bypass": nil},
|
||||
"scanners": []interface{}{},
|
||||
})
|
||||
}
|
||||
|
||||
@@ -115,7 +117,7 @@ func (a *App) handleVulnerabilities(c fiber.Ctx) error {
|
||||
var bypassInfo map[string]interface{}
|
||||
|
||||
// Check if this CVE is bypassed
|
||||
if bypass, ok := bypassedCVEs[strings.ToUpper(vuln.ID)]; ok {
|
||||
if bypass, ok := metadata.BypassFor(bypassedCVEs, vuln); ok {
|
||||
bypassed = true
|
||||
bypassInfo = map[string]interface{}{
|
||||
"id": bypass.ID,
|
||||
@@ -135,6 +137,8 @@ func (a *App) handleVulnerabilities(c fiber.Ctx) error {
|
||||
"description": vuln.Description,
|
||||
"references": vuln.References,
|
||||
"fixed_in": vuln.FixedIn,
|
||||
"detected_by": vuln.DetectedBy,
|
||||
"aliases": vuln.Aliases,
|
||||
"bypassed": bypassed,
|
||||
}
|
||||
|
||||
@@ -166,6 +170,8 @@ func (a *App) handleVulnerabilities(c fiber.Ctx) error {
|
||||
"low": severityCounts["LOW"],
|
||||
},
|
||||
"bypassed_count": len(scanResult.Vulnerabilities) - (severityCounts["CRITICAL"] + severityCounts["HIGH"] + severityCounts["MODERATE"] + severityCounts["LOW"]),
|
||||
"scanners": scannerBreakdown(scanResult),
|
||||
"decision": a.packageDecision(ctx, pkg),
|
||||
}
|
||||
|
||||
return c.Status(fiber.StatusOK).JSON(response)
|
||||
@@ -190,3 +196,58 @@ func (a *App) resolvePackageKey(ctx context.Context, registry, name, version str
|
||||
}
|
||||
return name, nil, err
|
||||
}
|
||||
|
||||
// scannerBreakdown counts each scanner's findings by severity, from the merged scan's detected_by lists.
|
||||
func scannerBreakdown(res *metadata.ScanResult) []map[string]interface{} {
|
||||
names := strings.Split(res.Scanner, "+")
|
||||
counts := make(map[string]map[string]int, len(names))
|
||||
for _, n := range names {
|
||||
counts[n] = map[string]int{"critical": 0, "high": 0, "moderate": 0, "low": 0}
|
||||
}
|
||||
for _, v := range res.Vulnerabilities {
|
||||
by := v.DetectedBy
|
||||
if len(by) == 0 && len(names) == 1 {
|
||||
by = names
|
||||
}
|
||||
sev := strings.ToLower(metadata.NormalizeSeverity(v.Severity))
|
||||
for _, n := range by {
|
||||
if c, ok := counts[n]; ok {
|
||||
c[sev]++
|
||||
}
|
||||
}
|
||||
}
|
||||
out := make([]map[string]interface{}, 0, len(names))
|
||||
for _, n := range names {
|
||||
if n == "" {
|
||||
continue
|
||||
}
|
||||
c := counts[n]
|
||||
out = append(out, map[string]interface{}{
|
||||
"name": n,
|
||||
"findings": c["critical"] + c["high"] + c["moderate"] + c["low"],
|
||||
"severity_counts": c,
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// packageDecision is the verdict the proxy applies to one package, with the bypass that applied.
|
||||
func (a *App) packageDecision(ctx context.Context, pkg *metadata.Package) fiber.Map {
|
||||
decision := fiber.Map{"verdict": VerdictCleared, "blocked": false, "reason": "", "bypass": nil}
|
||||
if pkg == nil {
|
||||
return decision
|
||||
}
|
||||
list, err := a.scanDecisions(ctx, []string{pkg.ID})
|
||||
if err != nil || len(list) == 0 {
|
||||
if err != nil {
|
||||
log.Warn().Err(err).Str("package", pkg.Name).Msg("Failed to judge package")
|
||||
}
|
||||
return decision
|
||||
}
|
||||
d := list[0]
|
||||
decision["verdict"] = verdictOf(d)
|
||||
decision["blocked"] = d.Blocked
|
||||
decision["reason"] = d.Reason
|
||||
decision["bypass"] = bypassSummary(d.Bypass)
|
||||
return decision
|
||||
}
|
||||
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
"net/url"
|
||||
"os"
|
||||
"os/exec"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
@@ -316,3 +317,35 @@ func TestNPMMetadataTTLOverrideReachesCache(t *testing.T) {
|
||||
}
|
||||
t.Fatalf("no npm metadata entry with an expiry among %d packages", len(pkgs))
|
||||
}
|
||||
|
||||
// The mount already strips the registry prefix, so a package named after the registry must keep its name.
|
||||
func TestPackagesNamedAfterTheRegistryKeepTheirName(t *testing.T) {
|
||||
var npmSeen, pypiSeen []string
|
||||
npmUp := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
npmSeen = append(npmSeen, r.URL.Path)
|
||||
_, _ = w.Write([]byte(`{"name":"x","versions":{}}`))
|
||||
}))
|
||||
t.Cleanup(npmUp.Close)
|
||||
pypiUp := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
pypiSeen = append(pypiSeen, r.URL.Path)
|
||||
w.Header().Set("Content-Type", "text/html")
|
||||
_, _ = w.Write([]byte(`<html><body></body></html>`))
|
||||
}))
|
||||
t.Cleanup(pypiUp.Close)
|
||||
|
||||
a := newTestApp(t, func(c *config.Config) {
|
||||
c.Handlers.NPM.UpstreamRegistry = npmUp.URL
|
||||
c.Handlers.PyPI.SimpleAPIURL = pypiUp.URL + "/simple"
|
||||
})
|
||||
for _, target := range []string{"/npm/npm-run-all", "/npm/npm", "/pypi/simple/pypi-a/", "/pypi/pypi-b/"} {
|
||||
if code, _, body := doRequest(t, a, target, nil); code != http.StatusOK {
|
||||
t.Fatalf("GET %s: status = %d, body %q", target, code, body)
|
||||
}
|
||||
}
|
||||
if want := []string{"/npm-run-all", "/npm"}; !slices.Equal(npmSeen, want) {
|
||||
t.Errorf("npm upstream paths = %v, want %v", npmSeen, want)
|
||||
}
|
||||
if want := []string{"/simple/pypi-a/", "/simple/pypi-b/"}; !slices.Equal(pypiSeen, want) {
|
||||
t.Errorf("pypi upstream paths = %v, want %v", pypiSeen, want)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/gofiber/fiber/v3/middleware/static"
|
||||
)
|
||||
|
||||
// A page load sends Accept: text/html; a missing asset does not, and version segments such as v1.0.0 have dots.
|
||||
// Paths that belong to the server; an unknown one stays a 404 instead of the SPA shell.
|
||||
var nonSPAPrefixes = []string{"/api/", "/go/", "/npm/", "/pypi/", "/ws"}
|
||||
|
||||
// spaStatic serves dir and falls back to index.html for client-side routes, so reload and shared links work.
|
||||
func spaStatic(dir string) fiber.Handler {
|
||||
return static.New(dir, static.Config{
|
||||
NotFoundHandler: func(c fiber.Ctx) error {
|
||||
p := c.Path()
|
||||
if (c.Method() != fiber.MethodGet && c.Method() != fiber.MethodHead) || !strings.Contains(c.Get(fiber.HeaderAccept), "text/html") {
|
||||
return fiber.ErrNotFound
|
||||
}
|
||||
for _, prefix := range nonSPAPrefixes {
|
||||
if strings.HasPrefix(p, prefix) {
|
||||
return fiber.ErrNotFound
|
||||
}
|
||||
}
|
||||
index, err := os.ReadFile(filepath.Join(dir, "index.html")) // #nosec G304 -- fixed file under the configured frontend dir
|
||||
if err != nil {
|
||||
return fiber.ErrNotFound
|
||||
}
|
||||
c.Status(fiber.StatusOK).Type("html")
|
||||
return c.Send(index)
|
||||
},
|
||||
})
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user