mirror of
https://github.com/lukaszraczylo/gohoarder.git
synced 2026-11-25 06:35:21 +00:00
feat(vulnerable): filter vulnerable packages by severity
The four severity tiles on the vulnerable packages page are now toggle buttons with aria-pressed. Each tile shows "Filter on" while active. A tile selects packages with at least one vulnerability of that severity. Several tiles combine with OR. A second click clears the tile, and a Clear filters control clears all of them. The selection lives in the URL (?severity=critical,high), so it survives a reload and works as a link. An empty result shows the library empty state with a clear action. GET /api/packages accepts a severity list. The page uses it to load only vulnerable packages instead of the whole cache. The filter is a subquery on the latest scan result, so the statement count does not grow with the number of rows. An unknown severity returns 400.
This commit is contained in:
@@ -1,18 +1,65 @@
|
||||
<template>
|
||||
<StatGroup :columns="4" :aria-label="label">
|
||||
<KpiTile v-for="level in SEVERITY_LEVELS" :key="level" :label="formatSeverityName(level)" :value="counts[level]">
|
||||
<template #icon><StatusDot :tone="SEVERITY_TONES[level]" /></template>
|
||||
</KpiTile>
|
||||
<template v-if="selectable">
|
||||
<KpiTile
|
||||
v-for="level in SEVERITY_LEVELS"
|
||||
:key="level"
|
||||
as="button"
|
||||
type="button"
|
||||
variant="interactive"
|
||||
:label="formatSeverityName(level)"
|
||||
:value="counts[level]"
|
||||
:aria-pressed="isSelected(level)"
|
||||
:class="isSelected(level) && 'ring-2 ring-primary'"
|
||||
:data-severity="level"
|
||||
@click="toggle(level)"
|
||||
>
|
||||
<template #icon><StatusDot :tone="SEVERITY_TONES[level]" /></template>
|
||||
<template #hint>
|
||||
<span v-if="packageCounts">{{ formatPackageCount(packageCounts[level]) }}</span>
|
||||
<span v-if="isSelected(level)" class="font-medium text-foreground" data-testid="severity-filter-on">
|
||||
{{ packageCounts ? ' · ' : '' }}Filter on
|
||||
</span>
|
||||
</template>
|
||||
</KpiTile>
|
||||
</template>
|
||||
<template v-else>
|
||||
<KpiTile v-for="level in SEVERITY_LEVELS" :key="level" :label="formatSeverityName(level)" :value="counts[level]">
|
||||
<template #icon><StatusDot :tone="SEVERITY_TONES[level]" /></template>
|
||||
</KpiTile>
|
||||
</template>
|
||||
</StatGroup>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { KpiTile, StatGroup, StatusDot } from '@perfect-design/ui'
|
||||
import type { VulnerabilityCounts } from '../stores/packages'
|
||||
import { SEVERITY_LEVELS, SEVERITY_TONES, formatSeverityName } from '@/lib/severity'
|
||||
import { SEVERITY_LEVELS, SEVERITY_TONES, formatSeverityName, type SeverityLevel } from '@/lib/severity'
|
||||
|
||||
defineProps<{
|
||||
const props = defineProps<{
|
||||
counts: VulnerabilityCounts
|
||||
label: string
|
||||
/** Tiles become toggle buttons that edit `modelValue`. */
|
||||
selectable?: boolean
|
||||
/** Selected severities; several are allowed. */
|
||||
modelValue?: readonly SeverityLevel[]
|
||||
/** Packages per severity, shown on each tile in selectable mode. */
|
||||
packageCounts?: VulnerabilityCounts
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{ 'update:modelValue': [value: SeverityLevel[]] }>()
|
||||
|
||||
function isSelected(level: SeverityLevel): boolean {
|
||||
return props.modelValue?.includes(level) ?? false
|
||||
}
|
||||
|
||||
function toggle(level: SeverityLevel) {
|
||||
const current = props.modelValue ?? []
|
||||
const next = current.includes(level) ? current.filter((l) => l !== level) : [...current, level]
|
||||
emit('update:modelValue', SEVERITY_LEVELS.filter((l) => next.includes(l)))
|
||||
}
|
||||
|
||||
function formatPackageCount(n: number): string {
|
||||
return `${n} package${n === 1 ? '' : 's'}`
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -0,0 +1,226 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { createPinia, setActivePinia } from 'pinia'
|
||||
import axios from 'axios'
|
||||
import { flushPromises } from '@vue/test-utils'
|
||||
import VulnerablePackages from './VulnerablePackages.vue'
|
||||
import type { Package, VulnerabilityCounts } from '@/stores/packages'
|
||||
import { mountStrict } from '@/test/mountStrict'
|
||||
import { createTestRouter } from '@/test/router'
|
||||
|
||||
vi.mock('axios')
|
||||
|
||||
function vulnerable(name: string, counts: Partial<VulnerabilityCounts>): Package {
|
||||
const full = { critical: 0, high: 0, moderate: 0, low: 0, ...counts }
|
||||
return {
|
||||
id: name,
|
||||
registry: 'npm',
|
||||
name,
|
||||
version: '1.0.0',
|
||||
size: 1024,
|
||||
cached_at: '2026-01-03T10:00:00Z',
|
||||
last_accessed: '2026-01-03T10:00:00Z',
|
||||
download_count: 1,
|
||||
vulnerabilities: {
|
||||
scanned: true,
|
||||
status: 'vulnerable',
|
||||
counts: full,
|
||||
total: full.critical + full.high + full.moderate + full.low,
|
||||
scannedAt: '2026-01-03T10:05:00Z',
|
||||
isBlocked: false,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
const ALL_SEVERITIES = 'critical,high,moderate,low'
|
||||
const FIXTURE: Package[] = [
|
||||
vulnerable('alpha-critical', { critical: 1 }),
|
||||
vulnerable('bravo-high', { high: 2 }),
|
||||
vulnerable('charlie-moderate', { moderate: 1 }),
|
||||
vulnerable('delta-mixed', { critical: 1, moderate: 3 }),
|
||||
]
|
||||
const NAMES = FIXTURE.map((p) => p.name)
|
||||
|
||||
let restore: (() => void) | undefined
|
||||
|
||||
beforeEach(() => {
|
||||
setActivePinia(createPinia())
|
||||
vi.mocked(axios.get).mockResolvedValue({ data: { packages: FIXTURE } })
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
restore?.()
|
||||
restore = undefined
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
async function open(path = '/vulnerable-packages') {
|
||||
const router = await createTestRouter(path)
|
||||
const pinia = createPinia()
|
||||
setActivePinia(pinia)
|
||||
const mounted = await mountStrict(VulnerablePackages, { global: { plugins: [pinia, router] } })
|
||||
restore = mounted.restore
|
||||
await flushPromises()
|
||||
return { ...mounted, router }
|
||||
}
|
||||
|
||||
type Wrapper = Awaited<ReturnType<typeof open>>['wrapper']
|
||||
|
||||
const tile = (wrapper: Wrapper, severity: string) => wrapper.get(`button[data-severity="${severity}"]`)
|
||||
const shown = (wrapper: Wrapper) => NAMES.filter((name) => wrapper.text().includes(name))
|
||||
const pressed = (wrapper: Wrapper) =>
|
||||
wrapper.findAll('button[data-severity]').map((b) => b.attributes('aria-pressed'))
|
||||
const clearButtons = (wrapper: Wrapper) => wrapper.findAll('button').filter((b) => b.text() === 'Clear filters')
|
||||
|
||||
describe('VulnerablePackages severity filter', () => {
|
||||
it('starts unfiltered: every vulnerable package, no tile pressed, no clear control', async () => {
|
||||
const { wrapper, problems, router } = await open()
|
||||
|
||||
expect(problems).toEqual([])
|
||||
expect(shown(wrapper)).toEqual(NAMES)
|
||||
expect(pressed(wrapper)).toEqual(['false', 'false', 'false', 'false'])
|
||||
expect(wrapper.text()).not.toContain('Filter on')
|
||||
expect(clearButtons(wrapper)).toHaveLength(0)
|
||||
expect(router.currentRoute.value.query.severity).toBeUndefined()
|
||||
})
|
||||
|
||||
it('asks the server for vulnerable packages only', async () => {
|
||||
await open()
|
||||
expect(axios.get).toHaveBeenCalledWith(`/api/packages?severity=${ALL_SEVERITIES}`)
|
||||
})
|
||||
|
||||
it('renders the four tiles as keyboard-operable buttons in severity order', async () => {
|
||||
const { wrapper } = await open()
|
||||
const tiles = wrapper.findAll('button[data-severity]')
|
||||
|
||||
expect(tiles.map((t) => t.attributes('data-severity'))).toEqual(['critical', 'high', 'moderate', 'low'])
|
||||
for (const t of tiles) {
|
||||
expect(t.element.tagName).toBe('BUTTON')
|
||||
expect(t.attributes('type')).toBe('button')
|
||||
expect(t.attributes('tabindex')).not.toBe('-1')
|
||||
expect(t.attributes('aria-pressed')).toBeDefined()
|
||||
}
|
||||
})
|
||||
|
||||
it('one click filters to that severity and shows the state in text, not colour alone', async () => {
|
||||
const { wrapper, router } = await open()
|
||||
|
||||
await tile(wrapper, 'high').trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
expect(shown(wrapper)).toEqual(['bravo-high'])
|
||||
expect(pressed(wrapper)).toEqual(['false', 'true', 'false', 'false'])
|
||||
expect(tile(wrapper, 'high').text()).toContain('Filter on')
|
||||
expect(tile(wrapper, 'critical').text()).not.toContain('Filter on')
|
||||
expect(wrapper.get('[data-testid="filter-bar"]').text()).toContain('Showing packages with high vulnerabilities.')
|
||||
expect(clearButtons(wrapper)).toHaveLength(1)
|
||||
expect(router.currentRoute.value.query.severity).toBe('high')
|
||||
})
|
||||
|
||||
it('keeps the tile counts of the whole list while a filter is on', async () => {
|
||||
const { wrapper } = await open()
|
||||
const before = tile(wrapper, 'critical').text()
|
||||
|
||||
await tile(wrapper, 'high').trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
expect(tile(wrapper, 'critical').text()).toBe(before)
|
||||
expect(tile(wrapper, 'critical').text()).toContain('2 packages')
|
||||
})
|
||||
|
||||
it('selects several severities with OR semantics', async () => {
|
||||
const { wrapper, router } = await open()
|
||||
|
||||
await tile(wrapper, 'critical').trigger('click')
|
||||
await flushPromises()
|
||||
expect(shown(wrapper)).toEqual(['alpha-critical', 'delta-mixed'])
|
||||
|
||||
await tile(wrapper, 'high').trigger('click')
|
||||
await flushPromises()
|
||||
expect(shown(wrapper)).toEqual(['alpha-critical', 'bravo-high', 'delta-mixed'])
|
||||
expect(pressed(wrapper)).toEqual(['true', 'true', 'false', 'false'])
|
||||
expect(router.currentRoute.value.query.severity).toBe('critical,high')
|
||||
expect(wrapper.get('[data-testid="filter-bar"]').text()).toContain('critical or high')
|
||||
})
|
||||
|
||||
it('a second click toggles the filter off and removes the query', async () => {
|
||||
const { wrapper, router } = await open()
|
||||
|
||||
await tile(wrapper, 'moderate').trigger('click')
|
||||
await flushPromises()
|
||||
expect(shown(wrapper)).toEqual(['charlie-moderate', 'delta-mixed'])
|
||||
|
||||
await tile(wrapper, 'moderate').trigger('click')
|
||||
await flushPromises()
|
||||
expect(shown(wrapper)).toEqual(NAMES)
|
||||
expect(pressed(wrapper)).toEqual(['false', 'false', 'false', 'false'])
|
||||
expect(clearButtons(wrapper)).toHaveLength(0)
|
||||
expect(router.currentRoute.value.query.severity).toBeUndefined()
|
||||
})
|
||||
|
||||
it('Clear filters resets every selected severity at once', async () => {
|
||||
const { wrapper, router } = await open()
|
||||
await tile(wrapper, 'critical').trigger('click')
|
||||
await tile(wrapper, 'high').trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
await clearButtons(wrapper)[0]!.trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
expect(shown(wrapper)).toEqual(NAMES)
|
||||
expect(pressed(wrapper)).toEqual(['false', 'false', 'false', 'false'])
|
||||
expect(router.currentRoute.value.query.severity).toBeUndefined()
|
||||
})
|
||||
|
||||
it('restores the filter from the URL, as after a reload or a shared link', async () => {
|
||||
const { wrapper } = await open('/vulnerable-packages?severity=high,critical')
|
||||
|
||||
expect(shown(wrapper)).toEqual(['alpha-critical', 'bravo-high', 'delta-mixed'])
|
||||
expect(pressed(wrapper)).toEqual(['true', 'true', 'false', 'false'])
|
||||
expect(clearButtons(wrapper)).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('ignores unknown severities in the URL and keeps the other query parameters', async () => {
|
||||
const { wrapper, router } = await open('/vulnerable-packages?severity=bogus&ref=mail')
|
||||
expect(shown(wrapper)).toEqual(NAMES)
|
||||
expect(clearButtons(wrapper)).toHaveLength(0)
|
||||
|
||||
await tile(wrapper, 'low').trigger('click')
|
||||
await flushPromises()
|
||||
expect(router.currentRoute.value.query).toEqual({ ref: 'mail', severity: 'low' })
|
||||
})
|
||||
|
||||
it('shows a library empty state with a clear control when no package matches', async () => {
|
||||
const { wrapper, router } = await open('/vulnerable-packages?severity=low')
|
||||
|
||||
const empty = wrapper.get('[data-slot="empty-state"]')
|
||||
expect(empty.text()).toContain('No packages match the filter')
|
||||
expect(shown(wrapper)).toEqual([])
|
||||
// The tiles stay so the filter can be changed without leaving the page.
|
||||
expect(pressed(wrapper)).toEqual(['false', 'false', 'false', 'true'])
|
||||
|
||||
await empty.findAll('button').find((b) => b.text() === 'Clear filters')!.trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
expect(shown(wrapper)).toEqual(NAMES)
|
||||
expect(wrapper.find('[data-slot="empty-state"]').exists()).toBe(false)
|
||||
expect(router.currentRoute.value.query.severity).toBeUndefined()
|
||||
})
|
||||
|
||||
it('keeps the success state when nothing is vulnerable, filter or not', async () => {
|
||||
vi.mocked(axios.get).mockResolvedValue({ data: { packages: [] } })
|
||||
const { wrapper } = await open('/vulnerable-packages?severity=critical')
|
||||
|
||||
expect(wrapper.text()).toContain('No vulnerable packages')
|
||||
expect(wrapper.find('button[data-severity]').exists()).toBe(false)
|
||||
})
|
||||
|
||||
it('still narrows to blocked packages on the blocked route', async () => {
|
||||
const blocked = vulnerable('echo-blocked', { critical: 1 })
|
||||
blocked.vulnerabilities!.isBlocked = true
|
||||
vi.mocked(axios.get).mockResolvedValue({ data: { packages: [...FIXTURE, blocked] } })
|
||||
const { wrapper } = await open('/blocked-packages?severity=critical')
|
||||
|
||||
expect(wrapper.text()).toContain('echo-blocked')
|
||||
expect(wrapper.text()).not.toContain('alpha-critical')
|
||||
})
|
||||
})
|
||||
@@ -23,7 +23,7 @@
|
||||
@retry="fetchVulnerablePackages"
|
||||
/>
|
||||
|
||||
<Card v-else-if="sortedVulnerablePackages.length === 0">
|
||||
<Card v-else-if="vulnerablePackages.length === 0">
|
||||
<CardContent>
|
||||
<EmptyState
|
||||
tone="success"
|
||||
@@ -35,9 +35,34 @@
|
||||
</Card>
|
||||
|
||||
<template v-else>
|
||||
<SeveritySummary :counts="totalCounts" label="Vulnerabilities by severity" />
|
||||
<SeveritySummary
|
||||
v-model="selectedSeverities"
|
||||
selectable
|
||||
:counts="totalCounts"
|
||||
:package-counts="packageCounts"
|
||||
label="Vulnerabilities by severity. Select a severity to filter the packages."
|
||||
/>
|
||||
|
||||
<Card>
|
||||
<div v-if="hasFilter" class="flex flex-wrap items-center justify-between gap-3" data-testid="filter-bar">
|
||||
<p class="text-sm text-muted-foreground" role="status">Showing packages with {{ filterSummary }} vulnerabilities.</p>
|
||||
<Button variant="outline" size="sm" @click="clearFilters">Clear filters</Button>
|
||||
</div>
|
||||
|
||||
<Card v-if="sortedVulnerablePackages.length === 0">
|
||||
<CardContent>
|
||||
<EmptyState
|
||||
:icon="faCircleCheck"
|
||||
title="No packages match the filter"
|
||||
:description="`No ${showOnlyBlocked ? 'blocked' : 'vulnerable'} package has a ${filterSummary} vulnerability.`"
|
||||
>
|
||||
<template #action>
|
||||
<Button variant="outline" @click="clearFilters">Clear filters</Button>
|
||||
</template>
|
||||
</EmptyState>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card v-else>
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">
|
||||
{{ showOnlyBlocked ? 'Blocked' : 'Vulnerable' }} packages ({{ sortedVulnerablePackages.length }})
|
||||
@@ -104,7 +129,7 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { useRouter, useRoute } from 'vue-router'
|
||||
import { usePackageStore, type Package } from '../stores/packages'
|
||||
import { usePackageStore, type Package, type VulnerabilityCounts } from '../stores/packages'
|
||||
import {
|
||||
Accordion,
|
||||
AccordionContent,
|
||||
@@ -128,12 +153,38 @@ import VulnerabilityBadge from './VulnerabilityBadge.vue'
|
||||
import SeveritySummary from './SeveritySummary.vue'
|
||||
import { formatBytes, formatDate, formatNumber, displayVersion, withVersionPrefix } from '@/lib/format'
|
||||
import { faArrowLeft, faCircleCheck } from '@/lib/icons'
|
||||
import { NO_VULNERABILITIES } from '@/lib/severity'
|
||||
import { NO_VULNERABILITIES, SEVERITY_LEVELS, formatSeverityName, type SeverityLevel } from '@/lib/severity'
|
||||
|
||||
const store = usePackageStore()
|
||||
const router = useRouter()
|
||||
const route = useRoute()
|
||||
|
||||
const SEVERITY_QUERY = 'severity'
|
||||
|
||||
/** Reads `?severity=critical,high`: known levels only, in severity order, each once. */
|
||||
function parseSeverityQuery(raw: unknown): SeverityLevel[] {
|
||||
const text = Array.isArray(raw) ? raw.join(',') : typeof raw === 'string' ? raw : ''
|
||||
const wanted = text.split(',').map((part) => part.trim().toLowerCase())
|
||||
return SEVERITY_LEVELS.filter((level) => wanted.includes(level))
|
||||
}
|
||||
|
||||
// The URL is the source of truth, so a reload or a shared link restores the filter.
|
||||
const selectedSeverities = computed<SeverityLevel[]>({
|
||||
get: () => parseSeverityQuery(route.query[SEVERITY_QUERY]),
|
||||
set: (levels) => {
|
||||
const { [SEVERITY_QUERY]: _previous, ...rest } = route.query
|
||||
void router.replace({ query: levels.length > 0 ? { ...rest, [SEVERITY_QUERY]: levels.join(',') } : rest })
|
||||
},
|
||||
})
|
||||
const hasFilter = computed(() => selectedSeverities.value.length > 0)
|
||||
const filterSummary = computed(() =>
|
||||
selectedSeverities.value.map((level) => formatSeverityName(level).toLowerCase()).join(' or '),
|
||||
)
|
||||
|
||||
function clearFilters() {
|
||||
selectedSeverities.value = []
|
||||
}
|
||||
|
||||
const loading = ref(false)
|
||||
const error = ref<string | null>(null)
|
||||
const vulnerablePackages = ref<Package[]>([])
|
||||
@@ -150,7 +201,8 @@ async function fetchVulnerablePackages() {
|
||||
error.value = null
|
||||
|
||||
try {
|
||||
await store.fetchPackages()
|
||||
// The server drops clean packages; the toggles below narrow the rest without another request.
|
||||
await store.fetchPackages({ severity: SEVERITY_LEVELS })
|
||||
// The store records a failed request in store.error and resolves; surface it instead of an empty list.
|
||||
if (store.error) {
|
||||
error.value = store.error
|
||||
@@ -171,9 +223,17 @@ async function fetchVulnerablePackages() {
|
||||
}
|
||||
}
|
||||
|
||||
// A package passes when it has at least one vulnerability of any selected severity.
|
||||
const filteredPackages = computed(() => {
|
||||
if (!hasFilter.value) return vulnerablePackages.value
|
||||
return vulnerablePackages.value.filter((pkg) =>
|
||||
selectedSeverities.value.some((level) => (pkg.vulnerabilities?.counts?.[level] ?? 0) > 0),
|
||||
)
|
||||
})
|
||||
|
||||
// Sort packages by risk: Critical count DESC, High count DESC, Moderate count DESC, Low count DESC
|
||||
const sortedVulnerablePackages = computed(() => {
|
||||
return [...vulnerablePackages.value].sort((a, b) => {
|
||||
return [...filteredPackages.value].sort((a, b) => {
|
||||
const aVulns = a.vulnerabilities?.counts || { critical: 0, high: 0, moderate: 0, low: 0 }
|
||||
const bVulns = b.vulnerabilities?.counts || { critical: 0, high: 0, moderate: 0, low: 0 }
|
||||
|
||||
@@ -227,7 +287,18 @@ const groupedPackages = computed(() => {
|
||||
return Array.from(groups.values())
|
||||
})
|
||||
|
||||
// Calculate total counts across all packages
|
||||
// Packages holding at least one vulnerability of each severity, before any filter.
|
||||
const packageCounts = computed<VulnerabilityCounts>(() => {
|
||||
const counts = { ...NO_VULNERABILITIES }
|
||||
for (const pkg of vulnerablePackages.value) {
|
||||
for (const level of SEVERITY_LEVELS) {
|
||||
if ((pkg.vulnerabilities?.counts?.[level] ?? 0) > 0) counts[level]++
|
||||
}
|
||||
}
|
||||
return counts
|
||||
})
|
||||
|
||||
// Calculate total counts across all packages, before any filter
|
||||
const totalCounts = computed(() =>
|
||||
vulnerablePackages.value.reduce(
|
||||
(sum, pkg) => {
|
||||
|
||||
@@ -39,6 +39,21 @@ describe('package store paging', () => {
|
||||
])
|
||||
})
|
||||
|
||||
it('fetchPackages asks for the listed severities only, and for everything without them', async () => {
|
||||
vi.mocked(axios.get).mockResolvedValue({ data: { packages: [] } })
|
||||
const store = usePackageStore()
|
||||
|
||||
await store.fetchPackages()
|
||||
await store.fetchPackages({ severity: [] })
|
||||
await store.fetchPackages({ severity: ['critical', 'high'] })
|
||||
|
||||
expect(vi.mocked(axios.get).mock.calls.map((c) => c[0])).toEqual([
|
||||
'/api/packages',
|
||||
'/api/packages',
|
||||
'/api/packages?severity=critical,high',
|
||||
])
|
||||
})
|
||||
|
||||
it('keeps the server group count, and counts groups itself when the server sends none', async () => {
|
||||
const store = usePackageStore()
|
||||
vi.mocked(axios.get).mockResolvedValueOnce({ data: { packages: [pkg(1, '2026-01-01T00:00:00Z')], total_groups: 80 } })
|
||||
|
||||
@@ -95,11 +95,15 @@ export const usePackageStore = defineStore('packages', () => {
|
||||
}
|
||||
let pageRequest = 0
|
||||
|
||||
/** Every package, unpaginated. Only views that filter on scan results need it. */
|
||||
async function fetchPackages() {
|
||||
/**
|
||||
* Every package, unpaginated. Only views that filter on scan results need it.
|
||||
* `severity` keeps the packages whose latest scan has a vulnerability of any listed severity.
|
||||
*/
|
||||
async function fetchPackages(options: { severity?: readonly string[] } = {}) {
|
||||
begin()
|
||||
try {
|
||||
const response = await axios.get('/api/packages')
|
||||
const query = options.severity?.length ? `?severity=${options.severity.join(',')}` : ''
|
||||
const response = await axios.get(`/api/packages${query}`)
|
||||
// Only update packages if we got valid data
|
||||
if (response.data && Array.isArray(response.data.packages)) {
|
||||
packages.value = response.data.packages
|
||||
|
||||
+32
-5
@@ -3,6 +3,8 @@ package app
|
||||
import (
|
||||
"context"
|
||||
stderrors "errors"
|
||||
"fmt"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -69,9 +71,25 @@ type listParams struct {
|
||||
paged bool
|
||||
}
|
||||
|
||||
// parseListParams reads page, page_size, registry, q, sort and order. Without
|
||||
// page or page_size the list is unpaginated, as it was before paging existed.
|
||||
func parseListParams(c fiber.Ctx) listParams {
|
||||
// parseSeverities reads a comma-separated severity filter such as "critical,high".
|
||||
func parseSeverities(raw string) ([]string, error) {
|
||||
var out []string
|
||||
for _, part := range strings.Split(raw, ",") {
|
||||
sev := strings.ToLower(strings.TrimSpace(part))
|
||||
if sev == "" || slices.Contains(out, sev) {
|
||||
continue
|
||||
}
|
||||
if !slices.Contains(metadata.Severities, sev) {
|
||||
return nil, fmt.Errorf("invalid severity %q, must be one of: %s", sev, strings.Join(metadata.Severities, ", "))
|
||||
}
|
||||
out = append(out, sev)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// parseListParams reads page, page_size, registry, q, sort, order and severity.
|
||||
// Without page or page_size the list is unpaginated, as it was before paging existed.
|
||||
func parseListParams(c fiber.Ctx) (listParams, error) {
|
||||
p := listParams{opts: metadata.GroupListOptions{
|
||||
Registry: c.Query("registry"),
|
||||
Query: c.Query("q"),
|
||||
@@ -88,6 +106,11 @@ func parseListParams(c fiber.Ctx) listParams {
|
||||
case "desc":
|
||||
p.opts.SortDesc = true
|
||||
}
|
||||
severities, err := parseSeverities(c.Query("severity"))
|
||||
if err != nil {
|
||||
return p, err
|
||||
}
|
||||
p.opts.Severities = severities
|
||||
if c.Query("page") != "" || c.Query("page_size") != "" {
|
||||
p.paged = true
|
||||
p.opts.Page = max(fiber.Query[int](c, "page", 1), 1)
|
||||
@@ -97,7 +120,7 @@ func parseListParams(c fiber.Ctx) listParams {
|
||||
}
|
||||
p.opts.PageSize = min(p.opts.PageSize, maxPageSize)
|
||||
}
|
||||
return p
|
||||
return p, nil
|
||||
}
|
||||
|
||||
// scanDecisions judges scanned packages, falling back to plain summaries without a scan manager.
|
||||
@@ -145,7 +168,10 @@ func vulnerabilityInfo(pkg *metadata.Package, decisions map[string]scanner.ScanD
|
||||
// page_size is given and every group otherwise.
|
||||
func (a *App) handleListPackages(c fiber.Ctx) error {
|
||||
ctx := c.Context()
|
||||
params := parseListParams(c)
|
||||
params, err := parseListParams(c)
|
||||
if err != nil {
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": err.Error()})
|
||||
}
|
||||
|
||||
page, err := a.metadata.ListPackageGroups(ctx, params.opts)
|
||||
if err != nil {
|
||||
@@ -378,6 +404,7 @@ func (a *App) handleStats(c fiber.Ctx) error {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Combine statistics using database stats for accuracy
|
||||
stats := map[string]interface{}{
|
||||
"total_packages": cacheStats.TotalPackages,
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestSeverityFilterOnPackagesList(t *testing.T) {
|
||||
a, _ := newScanningApp(t)
|
||||
seedScanned(t, a, 0, 60) // every fifth package carries one critical finding
|
||||
|
||||
cases := []struct {
|
||||
query string
|
||||
want int
|
||||
}{
|
||||
{"", 60},
|
||||
{"?severity=", 60},
|
||||
{"?severity=critical", 12},
|
||||
{"?severity=Critical,high", 12},
|
||||
{"?severity=high", 0},
|
||||
{"?severity=high,moderate,low", 0},
|
||||
{"?severity=critical&q=pkg-005", 1},
|
||||
{"?severity=critical&q=pkg-006", 0},
|
||||
}
|
||||
for _, c := range cases {
|
||||
if got := getList(t, a, "/api/packages"+c.query); len(got.Packages) != c.want {
|
||||
t.Errorf("%q returned %d packages, want %d", c.query, len(got.Packages), c.want)
|
||||
}
|
||||
}
|
||||
|
||||
paged := getList(t, a, "/api/packages?severity=critical&page=1&page_size=5")
|
||||
if paged.TotalGroups != 12 || len(paged.Packages) != 5 {
|
||||
t.Errorf("paged severity list = %d groups, %d rows; want 12 groups, 5 rows", paged.TotalGroups, len(paged.Packages))
|
||||
}
|
||||
for _, p := range getList(t, a, "/api/packages?severity=critical").Packages {
|
||||
if p.Vulnerabilities.Counts.Critical == 0 {
|
||||
t.Errorf("%s has no critical finding but passed the critical filter", p.Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSeverityFilterRejectsUnknownValue(t *testing.T) {
|
||||
a, _ := newScanningApp(t)
|
||||
for _, q := range []string{"?severity=urgent", "?severity=critical,nope"} {
|
||||
if code, _, body := doRequest(t, a, "/api/packages"+q, nil); code != http.StatusBadRequest {
|
||||
t.Errorf("%q = %d %s, want 400", q, code, body)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -37,9 +37,39 @@ func (s *Store) ListPackageGroups(ctx context.Context, opts metadata.GroupListOp
|
||||
p.ID = packageKey(p)
|
||||
}
|
||||
}
|
||||
if len(opts.Severities) > 0 {
|
||||
if all, err = s.withSeverity(ctx, all, opts.Severities); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return metadata.PageGroups(all, opts), nil
|
||||
}
|
||||
|
||||
// withSeverity keeps the packages whose scan holds a vulnerability of one of the severities.
|
||||
func (s *Store) withSeverity(ctx context.Context, all []*metadata.Package, severities []string) ([]*metadata.Package, error) {
|
||||
sums, err := s.GetScanSummaries(ctx, nil, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
hit := make(map[string]struct{}, len(sums))
|
||||
for _, sum := range sums {
|
||||
for _, sev := range severities {
|
||||
if (sev == metadata.SeverityCritical && sum.Critical > 0) || (sev == metadata.SeverityHigh && sum.High > 0) ||
|
||||
(sev == metadata.SeverityModerate && sum.Moderate > 0) || (sev == metadata.SeverityLow && sum.Low > 0) {
|
||||
hit[sum.PackageID] = struct{}{}
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
out := all[:0]
|
||||
for _, p := range all {
|
||||
if _, ok := hit[p.ID]; ok {
|
||||
out = append(out, p)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// GetScanSummaries reads each scanned package's latest scan file.
|
||||
func (s *Store) GetScanSummaries(ctx context.Context, packageIDs []string, withDetails bool) ([]*metadata.ScanSummary, error) {
|
||||
all, err := s.listRecords(ctx)
|
||||
|
||||
@@ -63,6 +63,10 @@ func (s *GORMStoreV2) groupFilter(opts metadata.GroupListOptions) (clause string
|
||||
clause += " AND registry_id = ?"
|
||||
args = append(args, id)
|
||||
}
|
||||
if sev := severityFilter(opts.Severities); sev != "" {
|
||||
clause += " AND security_scanned = ? AND id IN (" + latestScanWith(sev) + ")"
|
||||
args = append(args, true)
|
||||
}
|
||||
if q := strings.TrimSpace(opts.Query); q != "" {
|
||||
like := escapeLike(q)
|
||||
clause += " AND (LOWER(name) LIKE ? ESCAPE '" + likeEscape + "'" +
|
||||
@@ -73,6 +77,38 @@ func (s *GORMStoreV2) groupFilter(opts metadata.GroupListOptions) (clause string
|
||||
return clause, args, false, nil
|
||||
}
|
||||
|
||||
// severityColumns maps a severity filter value to its scan_results count column.
|
||||
var severityColumns = map[string]string{
|
||||
metadata.SeverityCritical: "critical_count",
|
||||
metadata.SeverityHigh: "high_count",
|
||||
metadata.SeverityModerate: "medium_count",
|
||||
metadata.SeverityLow: "low_count",
|
||||
}
|
||||
|
||||
// severityFilter ORs the count columns of the known severities; unknown values are ignored.
|
||||
func severityFilter(severities []string) string {
|
||||
var conds []string
|
||||
seen := map[string]bool{}
|
||||
for _, sev := range severities {
|
||||
col, ok := severityColumns[sev]
|
||||
if !ok || seen[sev] {
|
||||
continue
|
||||
}
|
||||
seen[sev] = true
|
||||
conds = append(conds, col+" > 0")
|
||||
}
|
||||
return strings.Join(conds, " OR ")
|
||||
}
|
||||
|
||||
// latestScanWith selects the packages whose newest scan satisfies cond. A tie on
|
||||
// scanned_at goes to the higher id, as GetScanSummaries decides it.
|
||||
func latestScanWith(cond string) string {
|
||||
return `SELECT package_id FROM scan_results WHERE deleted_at IS NULL AND (` + cond + `)
|
||||
AND scanned_at = (SELECT MAX(x.scanned_at) FROM scan_results x WHERE x.package_id = scan_results.package_id AND x.deleted_at IS NULL)
|
||||
AND NOT EXISTS (SELECT 1 FROM scan_results y WHERE y.package_id = scan_results.package_id AND y.deleted_at IS NULL
|
||||
AND y.scanned_at = scan_results.scanned_at AND y.id > scan_results.id)`
|
||||
}
|
||||
|
||||
// groupOrder is the ORDER BY of the group page query.
|
||||
// It reads the aliases of the grouped subquery, which MySQL's only_full_group_by requires.
|
||||
func groupOrder(opts metadata.GroupListOptions) string {
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
//go:build pgintegration
|
||||
|
||||
package gormstore
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestPostgresSeverityFilter(t *testing.T) {
|
||||
store, _ := newPostgresStore(t)
|
||||
|
||||
for name, check := range map[string]func(*testing.T, *GORMStoreV2){
|
||||
"severity filter": checkSeverityFilter,
|
||||
"severity statements constant": checkSeverityFilterStatementsAreConstant,
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
require.NoError(t, store.db.Exec("TRUNCATE packages RESTART IDENTITY CASCADE").Error)
|
||||
check(t, store)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package gormstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func checkSeverityFilter(t *testing.T, store *GORMStoreV2) {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
for _, n := range []string{"crit", "high", "mod", "low", "clean", "fixed", "multi", "unscanned"} {
|
||||
seedAt(t, store, n, "1.0.0", 1, daysAgo(3))
|
||||
}
|
||||
scanAt(t, store, "crit", "1.0.0", daysAgo(2), "critical")
|
||||
scanAt(t, store, "high", "1.0.0", daysAgo(2), "high")
|
||||
scanAt(t, store, "mod", "1.0.0", daysAgo(2), "moderate")
|
||||
scanAt(t, store, "low", "1.0.0", daysAgo(2), "low")
|
||||
scanAt(t, store, "clean", "1.0.0", daysAgo(2))
|
||||
scanAt(t, store, "fixed", "1.0.0", daysAgo(2), "critical")
|
||||
scanAt(t, store, "fixed", "1.0.0", daysAgo(1)) // the newest scan decides
|
||||
scanAt(t, store, "multi", "1.0.0", daysAgo(2), "high", "low")
|
||||
|
||||
pick := func(opts metadata.GroupListOptions) []string {
|
||||
page, err := store.ListPackageGroups(ctx, opts)
|
||||
require.NoError(t, err)
|
||||
out := names(page.Packages)
|
||||
for i := range out {
|
||||
for j := i + 1; j < len(out); j++ {
|
||||
if out[j] < out[i] {
|
||||
out[i], out[j] = out[j], out[i]
|
||||
}
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
require.Equal(t, []string{"crit"}, pick(metadata.GroupListOptions{Severities: []string{"critical"}}))
|
||||
require.Equal(t, []string{"high", "multi"}, pick(metadata.GroupListOptions{Severities: []string{"high"}}))
|
||||
require.Equal(t, []string{"crit", "mod"}, pick(metadata.GroupListOptions{Severities: []string{"critical", "moderate"}}), "OR across severities")
|
||||
require.Equal(t, []string{"low", "multi"}, pick(metadata.GroupListOptions{Severities: []string{"low"}}))
|
||||
require.Equal(t, []string{"crit", "high", "low", "mod", "multi"},
|
||||
pick(metadata.GroupListOptions{Severities: metadata.Severities}), "every severity = every vulnerable package")
|
||||
require.Len(t, pick(metadata.GroupListOptions{}), 8, "no filter keeps everything")
|
||||
|
||||
paged, err := store.ListPackageGroups(ctx, metadata.GroupListOptions{Severities: []string{"high", "low"}, Page: 1, PageSize: 2})
|
||||
require.NoError(t, err)
|
||||
require.EqualValues(t, 3, paged.TotalGroups, "paging counts the filtered groups")
|
||||
require.Len(t, paged.Packages, 2)
|
||||
|
||||
require.Equal(t, []string{"crit"}, pick(metadata.GroupListOptions{Severities: []string{"critical"}, Query: "cr"}), "composes with search")
|
||||
require.Empty(t, pick(metadata.GroupListOptions{Severities: []string{"critical"}, Query: "high"}))
|
||||
}
|
||||
|
||||
func checkSeverityFilterStatementsAreConstant(t *testing.T, store *GORMStoreV2) {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
counter := attachCounter(store)
|
||||
measure := func() [2]int {
|
||||
var out [2]int
|
||||
counter.Reset()
|
||||
_, err := store.ListPackageGroups(ctx, metadata.GroupListOptions{Severities: []string{"critical", "high"}})
|
||||
require.NoError(t, err)
|
||||
out[0] = counter.Count()
|
||||
counter.Reset()
|
||||
_, err = store.ListPackageGroups(ctx, metadata.GroupListOptions{Severities: []string{"low"}, Page: 1, PageSize: 25})
|
||||
require.NoError(t, err)
|
||||
out[1] = counter.Count()
|
||||
return out
|
||||
}
|
||||
seedScanned(t, store, 0, 10)
|
||||
small := measure()
|
||||
seedScanned(t, store, 10, 90)
|
||||
large := measure()
|
||||
t.Logf("statements for 10 rows %v, for 100 rows %v", small, large)
|
||||
require.Equal(t, small, large)
|
||||
require.LessOrEqual(t, large[0], 1, "the filter is a subquery of the one list read")
|
||||
require.LessOrEqual(t, large[1], 3)
|
||||
}
|
||||
|
||||
func TestSeverityFilter(t *testing.T) { checkSeverityFilter(t, newTimeSeriesStore(t)) }
|
||||
func TestSeverityFilterStatementsAreConstant(t *testing.T) {
|
||||
checkSeverityFilterStatementsAreConstant(t, newTimeSeriesStore(t))
|
||||
}
|
||||
@@ -332,11 +332,25 @@ type GroupListOptions struct {
|
||||
Registry string // empty = every registry
|
||||
Query string // case-insensitive substring of name, version or release version
|
||||
SortBy string // one of the GroupSort* keys; empty = name
|
||||
SortDesc bool
|
||||
Page int // 1-based
|
||||
PageSize int // 0 = every group, unpaginated
|
||||
// Severities keeps rows whose latest scan holds a vulnerability of any listed
|
||||
// severity (SeverityCritical and the like); empty = no severity filter.
|
||||
Severities []string
|
||||
Page int // 1-based
|
||||
PageSize int // 0 = every group, unpaginated
|
||||
SortDesc bool
|
||||
}
|
||||
|
||||
// Severity filter values of GroupListOptions.
|
||||
const (
|
||||
SeverityCritical = "critical"
|
||||
SeverityHigh = "high"
|
||||
SeverityModerate = "moderate"
|
||||
SeverityLow = "low"
|
||||
)
|
||||
|
||||
// Severities lists the severity filter values, most severe first.
|
||||
var Severities = []string{SeverityCritical, SeverityHigh, SeverityModerate, SeverityLow}
|
||||
|
||||
// GroupPage is one page of groups, flattened to rows.
|
||||
type GroupPage struct {
|
||||
// Packages holds every version row of each group on the page, in group
|
||||
|
||||
Reference in New Issue
Block a user