Dockhand vulnerability scans: warn about critical findings, with a setting to turn it off
Reads what Dockhand's scans have already stored (never starts one) every 15 minutes and raises a warning per Docker host with critical findings. Unknown counts and stale readings are held, not treated as clean. Settings -> Notifications has a switch (on by default); the Docker page shows counts, scan coverage and the critical findings; /metrics and docs updated. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
65214f6f0f
commit
5a2b320175
25 files changed
+8527
-12
No files matched your search
@@ -0,0 +1,149 @@
|
||||
/**
|
||||
* Keeps what Dockhand's vulnerability scans say up to date: every fifteen minutes each Dockhand integration is asked, for each of its Docker hosts, how many findings its stored scans
|
||||
* add up to (and the critical ones, with the containers that use the image), and that is stored. Pages and alerts are built from what is stored, so none of them talks to Dockhand.
|
||||
*
|
||||
* Nothing here starts a scan: Dockhand scans when it is told to (by hand, after a pull, or for a whole host), and this only reads what it kept. So an image that was never scanned is
|
||||
* not known to be clean — the page says how many of a host's images have a scan — and an environment whose summary could not be read is *unknown*, never *none*.
|
||||
*
|
||||
* What is raised is **critical** findings only (a host with one or more is a warning), and only while the setting for it is on (Settings → Notifications). Dockhand can also notify
|
||||
* about vulnerabilities itself; if both are switched on you hear twice.
|
||||
*/
|
||||
import { and, eq, notInArray } from "drizzle-orm";
|
||||
import { db } from "../db/client.js";
|
||||
import { dockhandVulnerabilities, integrations } from "../db/schema.js";
|
||||
import { createDockhandAdapter, type DockhandEnvironmentVulns, type DockhandVulnFinding } from "../integrations/dockhand/adapter.js";
|
||||
import { loadIntegrationConfig } from "../integrations/loadIntegration.js";
|
||||
import { getInternalFlag, setInternalFlag } from "./settingsStore.js";
|
||||
|
||||
export const SYNC_INTERVAL_MS = 15 * 60_000;
|
||||
/** After this long without a good read, what is stored is no longer believed. */
|
||||
export const STALE_AFTER_MS = 45 * 60_000;
|
||||
const STATUS_FLAG = "dockerVulnSync";
|
||||
|
||||
export interface DockerVulnSyncStatus {
|
||||
/** The last read that worked (kept when a later one failed). */
|
||||
at: string;
|
||||
ok: boolean;
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
async function readStatuses(): Promise<Record<string, DockerVulnSyncStatus>> {
|
||||
try {
|
||||
const raw = await getInternalFlag(STATUS_FLAG);
|
||||
return raw ? (JSON.parse(raw) as Record<string, DockerVulnSyncStatus>) : {};
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
export async function dockerVulnSyncStatuses(): Promise<Record<number, DockerVulnSyncStatus>> {
|
||||
return Object.fromEntries(Object.entries(await readStatuses()).map(([k, v]) => [Number(k), v]));
|
||||
}
|
||||
|
||||
export const isDockerVulnFresh = (status: DockerVulnSyncStatus | undefined, nowMs: number) => !!status && status.ok && nowMs - Date.parse(status.at) <= STALE_AFTER_MS;
|
||||
|
||||
export type StateRow = typeof dockhandVulnerabilities.$inferSelect;
|
||||
|
||||
export const findingsOf = (row: Pick<StateRow, "findings">): DockhandVulnFinding[] => {
|
||||
try {
|
||||
const v = JSON.parse(row.findings);
|
||||
return Array.isArray(v) ? (v as DockhandVulnFinding[]) : [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
};
|
||||
|
||||
/** Writes down one read, replacing the last one for this integration (a host Dockhand no longer lists is dropped). */
|
||||
export async function storeRead(integrationId: number, environments: DockhandEnvironmentVulns[], now: Date = new Date()): Promise<void> {
|
||||
for (const e of environments) {
|
||||
const values = {
|
||||
environmentName: e.environmentName,
|
||||
critical: e.summary?.critical ?? null,
|
||||
high: e.summary?.high ?? null,
|
||||
medium: e.summary?.medium ?? null,
|
||||
low: e.summary?.low ?? null,
|
||||
imagesScanned: e.summary?.imagesScanned ?? null,
|
||||
totalImages: e.summary?.totalImages ?? null,
|
||||
findings: JSON.stringify(e.critical),
|
||||
updatedAt: now.toISOString(),
|
||||
};
|
||||
await db.insert(dockhandVulnerabilities).values({ integrationId, environmentId: e.environmentId, ...values }).onConflictDoUpdate({ target: [dockhandVulnerabilities.integrationId, dockhandVulnerabilities.environmentId], set: values });
|
||||
}
|
||||
const ids = environments.map((e) => e.environmentId);
|
||||
await db.delete(dockhandVulnerabilities).where(ids.length > 0 ? and(eq(dockhandVulnerabilities.integrationId, integrationId), notInArray(dockhandVulnerabilities.environmentId, ids)) : eq(dockhandVulnerabilities.integrationId, integrationId));
|
||||
}
|
||||
|
||||
/** Reads one Dockhand's scans and stores them. Never throws: how it went is the answer, and what was stored is left alone when it failed. */
|
||||
export async function syncDockerVulns(integrationId: number, now: Date = new Date(), read?: (config: Record<string, unknown>) => Promise<{ environments: DockhandEnvironmentVulns[] }>): Promise<DockerVulnSyncStatus> {
|
||||
let status: DockerVulnSyncStatus;
|
||||
try {
|
||||
const loaded = await loadIntegrationConfig(integrationId);
|
||||
if (!loaded || loaded.integration.type !== "dockhand") throw new Error("not a Dockhand integration");
|
||||
const result = await (read ? read(loaded.config) : createDockhandAdapter(loaded.config as never).readVulnerabilities());
|
||||
await storeRead(integrationId, result.environments, now);
|
||||
status = { at: now.toISOString(), ok: true, error: null };
|
||||
} catch (err) {
|
||||
const previous = (await readStatuses())[String(integrationId)];
|
||||
status = { at: previous?.at ?? now.toISOString(), ok: false, error: err instanceof Error ? err.message : String(err) };
|
||||
console.error(`[docker-vulns] couldn't read integration ${integrationId}:`, status.error);
|
||||
}
|
||||
try {
|
||||
const all = await readStatuses();
|
||||
all[String(integrationId)] = status;
|
||||
await setInternalFlag(STATUS_FLAG, JSON.stringify(all));
|
||||
} catch (err) {
|
||||
console.error("[docker-vulns] couldn't record the result:", err);
|
||||
}
|
||||
return status;
|
||||
}
|
||||
|
||||
export async function syncAllDockerVulns(now: Date = new Date()): Promise<Record<number, DockerVulnSyncStatus>> {
|
||||
const rows = await db.select({ id: integrations.id }).from(integrations).where(and(eq(integrations.type, "dockhand"), eq(integrations.enabled, true)));
|
||||
const out: Record<number, DockerVulnSyncStatus> = {};
|
||||
for (const r of rows) out[r.id] = await syncDockerVulns(r.id, now);
|
||||
return out;
|
||||
}
|
||||
|
||||
export async function forgetDockerVulns(integrationId: number): Promise<void> {
|
||||
const all = await readStatuses();
|
||||
if (String(integrationId) in all) {
|
||||
delete all[String(integrationId)];
|
||||
await setInternalFlag(STATUS_FLAG, JSON.stringify(all));
|
||||
}
|
||||
}
|
||||
|
||||
// ─── What is wrong ──────────────────────────────────────────────────────────
|
||||
|
||||
export interface DockerVulnProblem {
|
||||
key: string;
|
||||
message: string;
|
||||
severity: "warning";
|
||||
}
|
||||
|
||||
/** Pure: a warning for each Docker host whose stored scans have critical findings. A host whose summary is unknown says nothing. */
|
||||
export function dockerVulnProblems(integrationId: number, rows: Pick<StateRow, "environmentId" | "environmentName" | "critical" | "high" | "findings">[]): DockerVulnProblem[] {
|
||||
const out: DockerVulnProblem[] = [];
|
||||
for (const r of [...rows].sort((a, b) => a.environmentName.localeCompare(b.environmentName))) {
|
||||
if (r.critical === null || r.critical <= 0) continue;
|
||||
const findings = findingsOf(r);
|
||||
const images = [...new Set(findings.map((f) => f.imageName))];
|
||||
const fixable = findings.filter((f) => f.fixedVersion).length;
|
||||
const where = images.length === 0 ? "" : ` in ${images.length === 1 ? "1 image" : `${images.length}${findings.length >= r.critical ? "" : "+"} images`}: ${images.slice(0, 3).join(", ")}${images.length > 3 ? ` and ${images.length - 3} more` : ""}`;
|
||||
out.push({
|
||||
key: `docker-vuln:${integrationId}:${r.environmentId}`,
|
||||
severity: "warning",
|
||||
message: `${r.environmentName}: ${r.critical} critical ${r.critical === 1 ? "vulnerability" : "vulnerabilities"}${where}${findings.length > 0 ? ` (${fixable} of the first ${findings.length} ${fixable === 1 ? "has" : "have"} a fix)` : ""}`,
|
||||
});
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
let timer: ReturnType<typeof setInterval> | null = null;
|
||||
|
||||
export function initDockerVulnSync(): void {
|
||||
if (timer) return;
|
||||
const pass = () => void syncAllDockerVulns().catch((err) => console.error("[docker-vulns] pass failed:", err));
|
||||
timer = setInterval(pass, SYNC_INTERVAL_MS);
|
||||
setTimeout(pass, 27_000);
|
||||
console.log(`[docker-vulns] reading Dockhand's vulnerability scans every ${SYNC_INTERVAL_MS / 60000} minutes`);
|
||||
}
|
||||
Reference in new issue
Block a user