Scan images for known vulnerabilities (0.59.0)
CI / check (push) Successful in 13m2s
CI / build-and-push (push) Successful in 1m53s

The Images page knew what was running and whether it was current. It could not
say whether any of it was exploitable, which is the question people actually
have about a homelab full of images they pulled once and forgot.

Trivy runs as a throwaway container rather than being installed into
StackPilot's image, reusing the helper-container pattern backups already use for
volume contents. Three reasons: a 100 MB security tool and a vulnerability
database that changes weekly have no business in a release artifact, pinning
SCANNER_IMAGE is then a real version control, and the scanner updates itself by
pulling a newer tag. It gets the socket read-only so it inspects images the
daemon already has instead of pulling them again, and a named volume for its
database so the ~50 MB download happens once rather than per scan.

The number the UI leads with is "fixable", not the total. A base image with 300
unfixable low-severity CVEs is not a task and a page that shows 300 in red
teaches people to ignore it; three findings with a fixed version available are
something to do this afternoon. Counts are stored per severity, findings are
sorted worst-first and capped at 200 — every finding is counted, only the list
is trimmed, so the cap can never hide the severity distribution.

The failure mode this had to avoid is a security feature that reads as clean
when it is broken. A scanner that cannot run stores the error and *keeps the
previous counts* rather than resetting to zero, so a transient daemon problem
does not silently turn a bad image green. There is a test for exactly that, and
another for unparseable output. Staleness is handled the same way: the local
image id is recorded with the scan, and pulling the image marks the result stale
instead of presenting yesterday's numbers for today's bytes.

Sweeps are deliberately serial and singly-locked. Scanning is CPU- and IO-heavy,
and running eight at once on a homelab box would starve the very containers the
scan is meant to protect. docker-py is synchronous, so the scan itself goes to a
thread — otherwise a ten-minute scan blocks every other request on the loop.

Reading results is allowed for the read-only role, which the authorization
matrix made me justify in writing: CVE ids and package versions for images whose
tags and compose files that role can already see, and polling them is the
monitoring use case a read-only API token exists for. Running a scan stays
admin-only because it spends real CPU.

20 tests against a report shaped like Trivy's real output, covering the counting,
the fixable number, worst-first ordering, the cap, both failure paths, staleness,
and that two sweeps cannot overlap. Verified end to end through the API as well,
including that a failed rescan keeps its previous counts and shows the error.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
menzelj
2026-09-18 01:16:45 +02:00
co-authored by Claude Opus 5
parent 9247ff9621
commit a1cd14a1cd
13 changed files with 1114 additions and 9 deletions
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "stackpilot-frontend",
"private": true,
"version": "0.58.0",
"version": "0.59.0",
"type": "module",
"scripts": {
"dev": "vite",
+45
View File
@@ -18,12 +18,57 @@ export interface ImageRow {
update: UpdateStatus | null;
}
export interface ScanSummary {
image: string;
digest: string | null;
scanner: string;
critical: number;
high: number;
medium: number;
low: number;
unknown: number;
/** How many findings have a fixed version — the number worth acting on. */
fixable: number;
total: number;
scanned_at: string;
duration_ms: number;
error: string | null;
/** The image has been pulled since this scan ran. */
stale: boolean;
}
export interface Finding {
id: string;
severity: "critical" | "high" | "medium" | "low" | "unknown";
package: string | null;
installed: string | null;
fixed: string | null;
title: string | null;
url: string | null;
target: string;
}
export interface ScanDetail extends ScanSummary {
findings: Finding[];
}
const base = "/api/images";
export const imagesApi = {
list: () => api.get<ImageRow[]>(base).then((r) => r.data),
updates: () => api.get<Record<string, UpdateStatus>>(`${base}/updates`).then((r) => r.data),
check: () => api.post<Record<string, UpdateStatus>>(`${base}/check`).then((r) => r.data),
scans: () => api.get<ScanSummary[]>(`${base}/scans`).then((r) => r.data),
scanDetail: (image: string) =>
api.get<ScanDetail>(`${base}/scan`, { params: { image } }).then((r) => r.data),
scan: (image: string) =>
api.post<ScanSummary>(`${base}/scan`, { image }).then((r) => r.data),
scanAll: () =>
api.post<{ scanned: number; failed: number }>(`${base}/scan-all`).then((r) => r.data),
scanStatus: () =>
api
.get<{ active: boolean; done: number; total: number }>(`${base}/scan-status`)
.then((r) => r.data),
prune: (allUnused: boolean) =>
api
.post<{ ImagesDeleted: unknown[]; SpaceReclaimed: number }>(`${base}/prune`, null, {
@@ -0,0 +1,204 @@
import { useQuery } from "@tanstack/react-query";
import { createPortal } from "react-dom";
import { ShieldCheck, X, ExternalLink } from "lucide-react";
import { Badge, Button, Spinner } from "@/components/ui";
import { imagesApi, type Finding, type ScanSummary } from "@/api/images";
import { cn } from "@/lib/utils";
import { relativeTime } from "@/lib/utils";
/** Worst first, and coloured so the eye lands on what matters. */
const SEVERITY_TONE: Record<Finding["severity"], string> = {
critical: "bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300",
high: "bg-orange-100 text-orange-700 dark:bg-orange-900/40 dark:text-orange-300",
medium: "bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-300",
low: "bg-slate-100 text-slate-600 dark:bg-slate-700 dark:text-slate-300",
unknown: "bg-slate-100 text-slate-500 dark:bg-slate-700 dark:text-slate-400",
};
/**
* The compact summary that sits in the Images table.
*
* It leads with critical + high and with how many are *fixable*, because that
* is the number you can do something about — a base image with 300 unfixable
* low-severity CVEs is not a task, three fixable ones are.
*/
export function ScanBadge({
scan,
onOpen,
}: {
scan?: ScanSummary;
onOpen: () => void;
}) {
if (!scan) return <span className="text-xs text-slate-400">not scanned</span>;
if (scan.error) {
return (
<button onClick={onOpen} className="text-xs text-amber-500 hover:underline">
scan failed
</button>
);
}
if (scan.total === 0) {
return (
<button
onClick={onOpen}
className="inline-flex items-center gap-1 text-xs text-green-600 hover:underline dark:text-green-400"
>
<ShieldCheck className="h-3.5 w-3.5" /> clean
</button>
);
}
return (
<button onClick={onOpen} className="flex flex-wrap items-center gap-1 text-xs">
{scan.critical > 0 && (
<span className={cn("rounded-chip px-1.5 py-0.5 font-semibold", SEVERITY_TONE.critical)}>
{scan.critical} critical
</span>
)}
{scan.high > 0 && (
<span className={cn("rounded-chip px-1.5 py-0.5 font-semibold", SEVERITY_TONE.high)}>
{scan.high} high
</span>
)}
<span className="text-slate-400">
{scan.total} total
{scan.fixable > 0 && ` · ${scan.fixable} fixable`}
</span>
{scan.stale && <span className="text-amber-500">· stale</span>}
</button>
);
}
/** The full finding list for one image. */
export function ScanDetailDialog({
image,
onClose,
}: {
image: string;
onClose: () => void;
}) {
const { data, isLoading, error } = useQuery({
queryKey: ["image-scan", image],
queryFn: () => imagesApi.scanDetail(image),
retry: false,
});
return createPortal(
<div
className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4"
onClick={onClose}
>
<div
className="flex max-h-full w-full max-w-3xl flex-col overflow-hidden rounded-xl border border-slate-200 bg-card shadow-xl dark:border-slate-700 dark:bg-card-dark"
onClick={(e) => e.stopPropagation()}
>
<div className="flex items-start gap-3 border-b border-slate-200 p-4 dark:border-slate-700">
<div className="min-w-0 flex-1">
<h2 className="sp-heading text-lg">Vulnerabilities</h2>
<p className="break-all font-mono text-xs text-slate-500">{image}</p>
{data && !data.error && (
<p className="mt-1 text-xs text-slate-400">
scanned {relativeTime(data.scanned_at)} with {data.scanner} ·{" "}
{data.fixable} of {data.total} fixable
{data.stale && " · the image has been pulled since"}
</p>
)}
</div>
<button
onClick={onClose}
title="Close"
className="rounded-lg p-1.5 text-slate-500 hover:bg-slate-100 dark:hover:bg-slate-700"
>
<X className="h-4 w-4" />
</button>
</div>
<div className="min-h-0 flex-1 overflow-y-auto p-4">
{isLoading && <Spinner />}
{error && (
<p className="text-sm text-slate-500">
This image has not been scanned yet.
</p>
)}
{data?.error && (
<div className="rounded-lg border border-red-300 bg-red-50 p-3 text-sm text-red-700 dark:border-red-900/60 dark:bg-red-950/30 dark:text-red-300">
{data.error}
</div>
)}
{data && !data.error && data.findings.length === 0 && (
<p className="text-sm text-green-600 dark:text-green-400">
No known vulnerabilities.
</p>
)}
{data && data.findings.length > 0 && (
<table className="w-full text-left text-sm">
<thead className="text-xs uppercase text-slate-500">
<tr>
<th className="py-2 pr-3">Severity</th>
<th className="py-2 pr-3">CVE</th>
<th className="py-2 pr-3">Package</th>
<th className="py-2">Fix</th>
</tr>
</thead>
<tbody className="divide-y divide-slate-100 dark:divide-slate-700">
{data.findings.map((f) => (
<tr key={`${f.id}-${f.package}-${f.target}`}>
<td className="py-2 pr-3">
<span
className={cn(
"rounded-chip px-1.5 py-0.5 text-[11px] font-semibold",
SEVERITY_TONE[f.severity]
)}
>
{f.severity}
</span>
</td>
<td className="py-2 pr-3 font-mono text-xs">
{f.url ? (
<a
href={f.url}
target="_blank"
rel="noreferrer noopener"
className="inline-flex items-center gap-1 hover:underline"
>
{f.id} <ExternalLink className="h-3 w-3" />
</a>
) : (
f.id
)}
{f.title && (
<span className="block max-w-sm truncate font-sans text-[11px] text-slate-400">
{f.title}
</span>
)}
</td>
<td className="py-2 pr-3 font-mono text-xs text-slate-500">
{f.package}
{f.installed && (
<span className="block text-[11px] text-slate-400">{f.installed}</span>
)}
</td>
<td className="py-2">
{f.fixed ? (
<Badge status="running">{f.fixed}</Badge>
) : (
<span className="text-xs text-slate-400">no fix yet</span>
)}
</td>
</tr>
))}
</tbody>
</table>
)}
</div>
<div className="flex justify-end border-t border-slate-200 p-3 dark:border-slate-700">
<Button variant="ghost" onClick={onClose}>
Close
</Button>
</div>
</div>
</div>,
document.body
);
}
+45 -3
View File
@@ -1,10 +1,11 @@
import { Fragment, useMemo, useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { RefreshCw, ArrowUpCircle, CheckCircle2, HelpCircle, Eraser } from "lucide-react";
import { RefreshCw, ArrowUpCircle, CheckCircle2, HelpCircle, Eraser, ShieldAlert } from "lucide-react";
import { toast } from "sonner";
import { Button, Card, Spinner } from "@/components/ui";
import { ConfirmDialog } from "@/components/ui/ConfirmDialog";
import { imagesApi, type ImageRow } from "@/api/images";
import { ScanBadge, ScanDetailDialog } from "@/components/stacks/ScanFindings";
import { stacksApi } from "@/api/stacks";
import { groupByStack, type StackGroup } from "@/lib/stackGroups";
import { StackGroupHeader } from "@/components/ui/StackGroupHeader";
@@ -37,6 +38,8 @@ export function Images() {
function ImagesSection({ isAdmin }: { isAdmin: boolean }) {
const qc = useQueryClient();
const [checking, setChecking] = useState(false);
const [scanning, setScanning] = useState(false);
const [scanFor, setScanFor] = useState<string | null>(null);
const [pruneOpen, setPruneOpen] = useState(false);
const [pruneAll, setPruneAll] = useState(false);
const { data, isLoading } = useQuery({
@@ -64,6 +67,33 @@ function ImagesSection({ isAdmin }: { isAdmin: boolean }) {
[data, stackById]
);
// Cheap and cached; the scanning itself only happens on the buttons below.
const scans = useQuery({
queryKey: ["image-scans"],
queryFn: imagesApi.scans,
});
const scanByImage = useMemo(
() => new Map((scans.data ?? []).map((s) => [s.image, s])),
[scans.data]
);
const scanAll = async () => {
setScanning(true);
const t = toast.loading("Scanning images… this runs the scanner per image");
try {
const r = await imagesApi.scanAll();
await qc.invalidateQueries({ queryKey: ["image-scans"] });
toast.success(
`Scanned ${r.scanned} image(s)${r.failed ? `, ${r.failed} failed` : ""}`,
{ id: t }
);
} catch (e) {
toast.error(apiErrorMessage(e), { id: t });
} finally {
setScanning(false);
}
};
const check = async () => {
setChecking(true);
const t = toast.loading("Checking for updates…");
@@ -101,6 +131,9 @@ function ImagesSection({ isAdmin }: { isAdmin: boolean }) {
<Button variant="outline" onClick={() => setPruneOpen(true)}>
<Eraser className="h-4 w-4" /> Prune
</Button>
<Button variant="outline" onClick={scanAll} loading={scanning}>
<ShieldAlert className="h-4 w-4" /> Scan for CVEs
</Button>
<Button onClick={check} loading={checking}>
<RefreshCw className="h-4 w-4" /> Check updates
</Button>
@@ -119,6 +152,7 @@ function ImagesSection({ isAdmin }: { isAdmin: boolean }) {
<th className="p-3">Size</th>
<th className="p-3">Created</th>
<th className="p-3">Status</th>
<th className="p-3">Vulnerabilities</th>
</tr>
</thead>
<tbody>
@@ -126,7 +160,7 @@ function ImagesSection({ isAdmin }: { isAdmin: boolean }) {
<Fragment key={group.key}>
<StackGroupHeader
group={group}
colSpan={5}
colSpan={6}
meta={groupMeta(group)}
/>
{group.items.map((row) => (
@@ -145,13 +179,19 @@ function ImagesSection({ isAdmin }: { isAdmin: boolean }) {
<td className="p-3">
<UpdateBadge row={row} />
</td>
<td className="p-3">
<ScanBadge
scan={scanByImage.get(row.tag)}
onOpen={() => setScanFor(row.tag)}
/>
</td>
</tr>
))}
</Fragment>
))}
{data?.length === 0 && (
<tr>
<td colSpan={5} className="p-6 text-center text-sm text-slate-500">
<td colSpan={6} className="p-6 text-center text-sm text-slate-500">
No images.
</td>
</tr>
@@ -161,6 +201,8 @@ function ImagesSection({ isAdmin }: { isAdmin: boolean }) {
</Card>
)}
{scanFor && <ScanDetailDialog image={scanFor} onClose={() => setScanFor(null)} />}
{pruneOpen && (
<ConfirmDialog
title="Prune images"