mirror of
https://github.com/lukaszraczylo/gohoarder.git
synced 2026-11-26 06:37:07 +00:00
fix(ui): clearer hold reasons, aligned details and chart states
Render the hold reason as a sentence, pluralise counts, give the details grid a fixed rhythm, use distinct registry colours, label the plotted series, and show a note for a single day of history.
This commit is contained in:
@@ -56,6 +56,14 @@ describe('Insights', () => {
|
||||
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)
|
||||
|
||||
@@ -64,21 +64,26 @@
|
||||
<Card data-testid="daily-downloads">
|
||||
<CardHeader>
|
||||
<CardTitle as="h2">Daily downloads</CardTitle>
|
||||
<CardDescription>The last 30 days. A darker square is a busier day.</CardDescription>
|
||||
<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." />
|
||||
<CalendarHeatmap
|
||||
v-else
|
||||
:data="heatData"
|
||||
fit
|
||||
:start="heatStart"
|
||||
:end="heatEnd"
|
||||
label="Downloads per day over the last 30 days"
|
||||
:cell-title="(date: string, value: number | null) => `${date}: ${value ?? 0} downloads`"
|
||||
/>
|
||||
<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>
|
||||
@@ -95,6 +100,8 @@ import {
|
||||
BarChart,
|
||||
Button,
|
||||
CalendarHeatmap,
|
||||
DescriptionItem,
|
||||
DescriptionList,
|
||||
Callout,
|
||||
Card,
|
||||
CardContent,
|
||||
@@ -170,6 +177,15 @@ const heatError = ref<string | null>(null)
|
||||
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 ?? '')
|
||||
|
||||
|
||||
@@ -28,27 +28,31 @@
|
||||
<CardTitle as="h2">Details</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<DescriptionList variant="grid" :columns="3" data-testid="package-meta">
|
||||
<DescriptionItem term="Size">{{ row ? formatBytes(row.size) : 'Unknown' }}</DescriptionItem>
|
||||
<DescriptionItem term="Downloads">{{ row ? formatNumber(row.download_count) : 'Unknown' }}</DescriptionItem>
|
||||
<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="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="Expiry">{{ expiry }}</DescriptionItem>
|
||||
<DescriptionItem term="Last scanned">
|
||||
<RelativeTime v-if="report.scanned_at" :datetime="report.scanned_at" />
|
||||
<template v-else>Never</template>
|
||||
</DescriptionItem>
|
||||
</DescriptionList>
|
||||
<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>
|
||||
|
||||
|
||||
@@ -31,7 +31,7 @@
|
||||
/>
|
||||
<template v-else>
|
||||
<p class="m-0 mb-3 text-sm text-muted-foreground" data-testid="package-count">
|
||||
{{ rows.length }} of {{ packages.length }} package versions
|
||||
{{ rows.length }} of {{ plural(packages.length, 'package version') }}
|
||||
</p>
|
||||
<DataTable
|
||||
v-model:sort="sort"
|
||||
@@ -105,6 +105,7 @@ import {
|
||||
import PackageQuickView from './parts/PackageQuickView.vue'
|
||||
import VerdictBadge from './parts/VerdictBadge.vue'
|
||||
import { usePackageStore, type Package } from '../stores/packages'
|
||||
import { plural } from '@/lib/reason'
|
||||
import { displayVersion, formatBytes, formatNumber, withVersionPrefix } from '@/lib/format'
|
||||
import { filterPackages, packageRoute } from '@/lib/packages'
|
||||
import { faBoxOpen, faMagnifyingGlass, faRotateRight } from '@/lib/icons'
|
||||
|
||||
@@ -123,6 +123,7 @@ import VulnerabilityBadge from './VulnerabilityBadge.vue'
|
||||
import { usePackageStore, type Package, type VulnerabilityCounts } from '../stores/packages'
|
||||
import { displayVersion, withVersionPrefix } from '@/lib/format'
|
||||
import { packageRoute } from '@/lib/packages'
|
||||
import { humanReason } from '@/lib/reason'
|
||||
import { faCircleCheck, faRotateRight } from '@/lib/icons'
|
||||
import { NO_VULNERABILITIES, SEVERITY_LEVELS, formatSeverityName, type SeverityLevel } from '@/lib/severity'
|
||||
import { verdictOf } from '@/lib/verdict'
|
||||
@@ -221,7 +222,7 @@ const BASE_COLUMNS: DataTableColumn<Package>[] = [
|
||||
const SCANNED: DataTableColumn<Package> = { key: 'scanned', header: 'Last scanned', 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) => p.vulnerabilities?.reason ?? '' }, SCANNED]
|
||||
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]
|
||||
}
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -59,7 +59,7 @@
|
||||
<template #cell-state="{ row }">
|
||||
<StatusBadge :status="scannerState(row)" :label="STATE_LABELS[scannerState(row)]" :tones="STATE_TONES" />
|
||||
</template>
|
||||
<template #cell-version="{ row }">{{ row.version ? `v${row.version}` : 'Not reported' }}</template>
|
||||
<template #cell-version="{ row }">{{ scannerVersion(row) || 'Not applicable' }}</template>
|
||||
</DataTable>
|
||||
</CardContent>
|
||||
</Card>
|
||||
@@ -133,7 +133,7 @@ import AdminKeyDialog from './parts/AdminKeyDialog.vue'
|
||||
import { useAdminKey } from '@/lib/adminKey'
|
||||
import { formatBytes, formatDuration } from '@/lib/format'
|
||||
import { faRotateRight } from '@/lib/icons'
|
||||
import { describePolicy, scannerState, useSystem, type ScannerInfo } from '@/lib/system'
|
||||
import { describePolicy, scannerState, scannerVersion, useSystem, type ScannerInfo } from '@/lib/system'
|
||||
|
||||
const { info, error, load } = useSystem()
|
||||
const adminKey = useAdminKey()
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -71,7 +71,12 @@ const rows = computed<RegistryUsage[]>(() =>
|
||||
.map(([registry, r]) => ({ registry, count: r.count ?? 0, size: r.size ?? 0, downloads: r.downloads ?? 0 }))
|
||||
.sort((a, b) => b.size - a.size),
|
||||
)
|
||||
const donut = computed<DonutDatum[]>(() => rows.value.map((r) => ({ label: r.registry, value: r.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 },
|
||||
|
||||
@@ -56,6 +56,7 @@ 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'
|
||||
|
||||
@@ -63,5 +64,5 @@ 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(() => props.pkg?.vulnerabilities?.reason || VERDICT_MEANINGS[verdict.value])
|
||||
const explanation = computed(() => humanReason(props.pkg?.vulnerabilities?.reason) || VERDICT_MEANINGS[verdict.value])
|
||||
</script>
|
||||
|
||||
@@ -17,12 +17,12 @@
|
||||
<li
|
||||
v-for="scanner in info.security.scanners"
|
||||
:key="scanner.name"
|
||||
class="flex items-center justify-between gap-3 rounded-md border px-3 py-2"
|
||||
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 truncate text-sm font-medium">{{ scanner.name }}</span>
|
||||
<span class="block text-xs text-muted-foreground">{{ scanner.version ? `v${scanner.version}` : 'version not reported' }}</span>
|
||||
<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>
|
||||
@@ -44,7 +44,7 @@ import {
|
||||
LoadingState,
|
||||
StatusBadge,
|
||||
} from '@perfect-design/ui'
|
||||
import { scannerState, useSystem } from '@/lib/system'
|
||||
import { scannerState, scannerVersion, useSystem } from '@/lib/system'
|
||||
|
||||
const { info, error, load } = useSystem()
|
||||
|
||||
|
||||
@@ -130,7 +130,7 @@ describe('view smoke tests (strict mode throw, fixture data)', () => {
|
||||
await flushPromises()
|
||||
expect(problems).toEqual([])
|
||||
const sheet = document.body.querySelector('[data-slot="sheet-content"]')
|
||||
expect(sheet?.textContent).toContain('Package has 1 CRITICAL vulnerabilities')
|
||||
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()
|
||||
})
|
||||
|
||||
@@ -144,7 +144,7 @@ describe('view smoke tests (strict mode throw, fixture data)', () => {
|
||||
|
||||
const banner = wrapper.find('[data-testid="verdict-banner"]').text()
|
||||
expect(banner).toContain('Held: CVE-2026-0003 is HIGH')
|
||||
expect(banner).toContain('Blocks any CRITICAL.')
|
||||
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')
|
||||
@@ -188,7 +188,7 @@ describe('view smoke tests (strict mode throw, fixture data)', () => {
|
||||
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('Package has 1 CRITICAL vulnerabilities')
|
||||
expect(wrapper.text()).toContain('1 critical finding. Policy holds any critical finding.')
|
||||
})
|
||||
|
||||
it('Security opens on the tab named in the URL', async () => {
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { describePolicy, scannerState, type SystemInfo } from './system'
|
||||
import { describePolicy, scannerState, scannerVersion, type SystemInfo } from './system'
|
||||
|
||||
function security(over: Partial<SystemInfo['security']>): SystemInfo['security'] {
|
||||
return {
|
||||
@@ -48,3 +48,12 @@ describe('scannerState', () => {
|
||||
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('')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -34,6 +34,16 @@ export function scannerState(scanner: ScannerInfo): ScannerState {
|
||||
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
|
||||
|
||||
|
||||
@@ -37,7 +37,8 @@ describe('verdictBanner', () => {
|
||||
)
|
||||
expect(banner.type).toBe('danger')
|
||||
expect(banner.title).toBe('Held: CVE-2021-44906 is CRITICAL')
|
||||
expect(banner.body).toContain('Blocks any 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')
|
||||
})
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
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 {
|
||||
@@ -19,7 +20,7 @@ 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 = report.decision.reason
|
||||
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() }
|
||||
@@ -30,7 +31,7 @@ function heldBanner(report: PackageReport, policy: string): BannerContent {
|
||||
return {
|
||||
type: 'danger',
|
||||
title: `Held: ${listIds(blockers.map((b) => b.id))} ${verb} ${formatSeverityName(blockers[0].severity).toUpperCase()}`,
|
||||
body: `${policy} ${reason ? `${reason}. ` : ''}${clients}${fix}`.replace(/\s+/g, ' ').trim(),
|
||||
body: `${reason || policy} ${clients}${fix}`.replace(/\s+/g, ' ').trim(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -63,7 +64,7 @@ export function verdictBanner(report: PackageReport, policy: string, failClosed:
|
||||
return {
|
||||
type: 'success',
|
||||
title: 'Cleared: no finding reaches the block policy',
|
||||
body: n === 0 ? 'The scanners reported nothing. Clients are served this version.' : `${n} finding${n === 1 ? '' : 's'} below the block policy. Clients are served this version.`,
|
||||
body: n === 0 ? 'The scanners reported nothing. Clients are served this version.' : `${plural(n, 'finding')} below the block policy. Clients are served this version.`,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user