eBPF-based security platform
tools/xtop: add the shields view
John Fastabend60d1fe6cfc11
diff --git a/Documentation/contribute/testing/test-coverage.rst b/Documentation/contribute/testing/test-coverage.rstindex e65b0ce7..fd99e680 100644--- a/Documentation/contribute/testing/test-coverage.rst+++ b/Documentation/contribute/testing/test-coverage.rst@@ -985,8 +985,9 @@ image, and a tree with one upatch deployed and one still rolling out(``test/xtop-nodes``, ``test/xtop-shields``).The unit tests of :src:`tools/xtop/test/` cover how xtop turns the rows-of that query into nodes, the health percent, the roll-up by image and-its ClickHouse client; ``make -C tools/xtop tests`` type-checks the+of those queries into nodes and shields, the health percent, the+roll-up by image, the status and severity of a shield and its+ClickHouse client; ``make -C tools/xtop tests`` type-checks theprogram and runs them (:ref:`testing-xtop`).Coverage by areadiff --git a/Documentation/contribute/testing/testing.rst b/Documentation/contribute/testing/testing.rstindex 51f27e54..a80e06f7 100644--- a/Documentation/contribute/testing/testing.rst+++ b/Documentation/contribute/testing/testing.rst@@ -1226,17 +1226,20 @@ Run the xtop tests:src:`tools/xtop/` is a Bun program. Its tests need ``bun`` on the hostand no ClickHouse: they feed its row mapping, roll-up and client rows-shaped as ``tools/backend/test/xtop-nodes.expected`` has them.+shaped as ``tools/backend/test/xtop-nodes.expected`` and+``xtop-shields.expected`` have them... code-block:: console$ make -C tools/xtop testsThe target installs the locked packages, type-checks the program with-``tsc`` and runs ``bun test``. The query itself is checked against the-schema by the backend test ``xtop-nodes``, which runs-:src:`tools/xtop/sql/nodes.sql` from ``test/xtop-nodes.sh`` over the-rows of ``test/xtop-nodes.setup.sql``.+``tsc`` and runs ``bun test``. The queries themselves are checked against+the schema by the backend tests ``xtop-nodes`` and ``xtop-shields``,+which run :src:`tools/xtop/sql/nodes.sql` and+:src:`tools/xtop/sql/shields.sql` from their ``.sh`` scripts over the+rows of ``test/xtop-nodes.setup.sql``, which ``xtop-shields.setup.sql``+links to.Write a test------------diff --git a/Documentation/operate/backend/index.rst b/Documentation/operate/backend/index.rstindex 0e67926a..bfb6b191 100644--- a/Documentation/operate/backend/index.rst+++ b/Documentation/operate/backend/index.rst@@ -85,8 +85,9 @@ Files- The SQL tests and their runner, ``test/run.sh``(:ref:`testing-backend`).* - :src:`tools/xtop/`- - A terminal view of the nodes over ``node_status``,- ``latest`` and ``node_vulns`` (:doc:`xtop`).+ - A terminal view of the nodes, over ``node_status``,+ ``latest`` and ``node_vulns``, and of the upatches of the trees+ and their rollout (:doc:`xtop`)... toctree:::titlesonly:diff --git a/Documentation/operate/backend/xtop.rst b/Documentation/operate/backend/xtop.rstindex 5b169088..232030ea 100644--- a/Documentation/operate/backend/xtop.rst+++ b/Documentation/operate/backend/xtop.rst@@ -5,15 +5,17 @@:page-type: How-to:audience: Operators, SecOps-Watch the nodes with xtop-=========================--:src:`tools/xtop/` is a terminal view of the backend. Its Nodes view-reads ``shirudo.node_status``, ``shirudo.latest`` and-``shirudo.node_vulns`` over the HTTP interface of the backend's-ClickHouse with one query, :src:`tools/xtop/sql/nodes.sql`, and shows-one row per node, or one per image. It only reads: every query is sent-with ``readonly=1``. It is a `Bun <https://bun.sh>`_ program built on+Watch nodes and shields with xtop+=================================++:src:`tools/xtop/` is a terminal view of the backend. It reads the+backend's ClickHouse over its HTTP interface, one query per view: Nodes+sends :src:`tools/xtop/sql/nodes.sql`, over ``shirudo.node_status``,+``shirudo.latest`` and ``shirudo.node_vulns``, and shows one row per+node, or one per image; Shields sends :src:`tools/xtop/sql/shields.sql`,+over the tree tables, ``shirudo.node_ops`` and ``shirudo.node_vulns``,+and shows one row per upatch. It only reads: every query is sent with+``readonly=1``. It is a `Bun <https://bun.sh>`_ program built onInk and React, and runs on an operator's host, never on a target.Build and run@@ -52,8 +54,8 @@ is enough.``X-ClickHouse-User`` and ``X-ClickHouse-Key`` headers. Withoutthem the server's default user answers.-The view queries when it opens, every minute after that, as often as-``node_status_mv`` recomputes the table, and when you press ``r``. A+A view queries when it opens, every minute after that, as often as+``node_status_mv`` recomputes its table, and when you press ``r``. Aquery that fails leaves the rows of the last one in place and says whyat the start of the summary line.@@ -119,3 +121,51 @@ nodes.Labels and detector hits are not shown: the keepalive carries no labels,and the collector of :src:`tools/backend/otelcol.yaml` takes in no mapsnapshot metrics.++Read the shields+----------------++Shields has one row per upatch of every tree the tree ingest job loaded+(:doc:`tree-ingest`), from its newest operation in ``shirudo.tree_ops``.++.. list-table::+ :header-rows: 1++ * - Column+ - Value+ * - ``STATUS``+ - ``pending`` while a node following the tree has not reached the+ newest operation, ``deployed`` once every one has, ``withdrawn``+ when that operation is a ``delete``.+ * - ``SHIELD``+ - The upatch id and the first eight digits of the manifest digest+ of its newest operation.+ * - ``SEVERITY``+ - The worst severity of the advisories in ``upatch_fixes`` for its+ newest ``add``, as ``kernel_vulns`` or ``sbom_vulns`` give it;+ ``—`` when neither knows them.+ * - ``TARGET``+ - What those advisories are in: ``kernel``, or the packages of an+ image's SBOM.+ * - ``IMAGES``+ - The first image, as id and version, of a node an advisory affects+ in ``node_vulns``, and ``+N`` for the others.+ * - ``ROLLOUT``+ - From the history of each node following the tree in ``node_ops``:+ the nodes that applied the newest operation over those it can+ apply on, all but the nodes its selector left out; ``…`` the nodes+ that have not reached it, ``✗`` those it reached whose module is+ not loaded.+ * - ``TREE``+ - The ``seq`` of the newest operation.++Enter on a shield shows its tree, its newest operation and how many it+has, when the backend loaded that operation's publication, the+repository, manifest digest and selector, the rollout in full, the+images, and per advisory its severity and how many affected nodes the+upatch shields. ``/`` searches the id, tree, status, severity, digest,+repository, advisories, packages and images.++The rollout counts the nodes whose newest record names the tree; a node+that moved to another tree leaves it. Detector hits are not shown,+because the backend takes in no metrics.diff --git a/tools/xtop/src/App.tsx b/tools/xtop/src/App.tsxindex b903d118..83120b23 100644--- a/tools/xtop/src/App.tsx+++ b/tools/xtop/src/App.tsx@@ -10,20 +10,23 @@ import { useMouse } from "./lib/useMouse.ts";import { Panel } from "./components/Panel.tsx";import { Sidebar, type MenuItem } from "./components/Sidebar.tsx";import { NodesView, type NodesMode } from "./components/NodesView.tsx";+import { ShieldsView } from "./components/ShieldsView.tsx";-type ViewId = "nodes";+type ViewId = "nodes" | "shields";const MENU: readonly (MenuItem & { id: ViewId; title: string })[] = [{ id: "nodes", label: "Nodes", title: "nodes · status from shirudo.node_status" },+ { id: "shields", label: "Shields", title: "shields · upatches of the trees in shirudo.tree_ops" },];const SIDEBAR_WIDTH = 16;-type Focus = "menu" | "menu-open" | "view" | "detail" | "search";+type Focus = "menu" | "menu-open" | ViewId | "detail" | "search";const HINTS: Record<Focus, string> = {- menu: "j/k menu · l/enter open · 1 nodes · q quit",+ menu: "j/k menu · l/enter open · 1 nodes · 2 shields · q quit","menu-open": "j/k menu · l/enter open · tab back to view · esc close view · q quit",- view: "j/k scroll · k past top → sort, then tabs · / search · enter node checks, image → nodes · t by image · r refresh · tab menu · esc close · q quit",+ nodes: "j/k scroll · k past top → sort, then tabs · / search · enter node checks, image → nodes · t by image · r refresh · tab menu · esc close · q quit",+ shields: "j/k scroll · k past top → sort · / search · enter details · r refresh · tab menu · esc close · q quit",detail: "esc back · q quit",search: "type to filter · enter keep · esc clear",};@@ -43,10 +46,12 @@ export function App({ backend }: { backend: Backend }) {setMenuCursor(MENU.findIndex((m) => m.id === view));setOpenView(view);setMenuFocused(false);+ setDetail(false);};const close = () => {setOpenView(null);setMenuFocused(true);+ setDetail(false);};const focus: Focus = searching@@ -57,7 +62,7 @@ export function App({ backend }: { backend: Backend }) {? "menu-open": detail? "detail"- : "view";+ : openView;const navActive = focus !== "search";useInput(@@ -116,16 +121,27 @@ export function App({ backend }: { backend: Backend }) {height={viewHeight}overflow="hidden">- <NodesView- backend={backend}- mode={nodesMode}- onModeChange={setNodesMode}- height={viewLines}- active={!menuFocused}- onClose={close}- onSearchingChange={setSearching}- onDetailChange={setDetail}- />+ {view.id === "nodes" ? (+ <NodesView+ backend={backend}+ mode={nodesMode}+ onModeChange={setNodesMode}+ height={viewLines}+ active={!menuFocused}+ onClose={close}+ onSearchingChange={setSearching}+ onDetailChange={setDetail}+ />+ ) : (+ <ShieldsView+ backend={backend}+ height={viewLines}+ active={!menuFocused}+ onClose={close}+ onSearchingChange={setSearching}+ onDetailChange={setDetail}+ />+ )}</Panel>)}</Box>diff --git a/tools/xtop/src/components/MiniBar.tsx b/tools/xtop/src/components/MiniBar.tsxnew file mode 100644index 00000000..748c412a--- /dev/null+++ b/tools/xtop/src/components/MiniBar.tsx@@ -0,0 +1,31 @@+// SPDX-License-Identifier: BSD-2-Clause+// Copyright (c) 2026 Authors of shirudo+//+// A share drawn in eighths of a cell, green to red.++import { Text } from "ink";++export const healthColor = (h: number) => (h >= 80 ? "green" : h >= 50 ? "yellow" : "red");+const EIGHTHS = ["", "▏", "▎", "▍", "▌", "▋", "▊", "▉"];++export function MiniBar({ value, width }: { value: number; width: number }) {+ const eighths = Math.round((Math.max(0, Math.min(100, value)) / 100) * width * 8);+ const full = Math.floor(eighths / 8);+ const partial = EIGHTHS[eighths % 8]!;+ return (+ <>+ <Text color={healthColor(value)}>{"█".repeat(full) + partial}</Text>+ <Text dimColor>{"░".repeat(width - full - (partial ? 1 : 0))}</Text>+ </>+ );+}++/** A bar and its percent. */+export function HealthCell({ health, bar }: { health: number; bar: number }) {+ return (+ <>+ <MiniBar value={health} width={bar} />+ <Text color={healthColor(health)}> {String(health).padStart(3)}%</Text>+ </>+ );+}diff --git a/tools/xtop/src/components/NodeDetail.tsx b/tools/xtop/src/components/NodeDetail.tsxindex b667fdb6..ac5dd4a9 100644--- a/tools/xtop/src/components/NodeDetail.tsx+++ b/tools/xtop/src/components/NodeDetail.tsx@@ -6,7 +6,7 @@import type { ReactNode } from "react";import { Box, Text, useInput } from "ink";import { imageLabel, type FleetNode } from "../lib/fleet.ts";-import { STATUS_STYLE } from "./style.ts";+import { STATUS_STYLE } from "./style.tsx";type Props = {/** null when the node left node_status since it was opened. */diff --git a/tools/xtop/src/components/NodesView.tsx b/tools/xtop/src/components/NodesView.tsxindex 0eaad957..33f61a75 100644--- a/tools/xtop/src/components/NodesView.tsx+++ b/tools/xtop/src/components/NodesView.tsx@@ -4,7 +4,7 @@// The fleet from shirudo.node_status: one row per node, or one per image// with its members rolled up. Enter on a node shows its check lines.-import { useEffect, useMemo, useRef, useState } from "react";+import { useMemo, useState } from "react";import { Box, Text, useInput } from "ink";import type { Backend } from "../lib/backend.ts";import {@@ -22,13 +22,13 @@ import {} from "../lib/fleet.ts";import { DataTable, Tabs, type Column } from "./DataTable.tsx";import { NodeDetail } from "./NodeDetail.tsx";-import { STATUS_STYLE } from "./style.ts";+import { HealthCell } from "./MiniBar.tsx";+import { ago } from "../lib/format.ts";+import { useRefreshing } from "../lib/useRefreshing.ts";+import { STATUS_STYLE } from "./style.tsx";export type NodesMode = "nodes" | "images";-/** node_status is recomputed once a minute; asking more often shows nothing new. */-const REFRESH_MS = 60_000;-type Props = {backend: Backend;mode: NodesMode;@@ -42,35 +42,6 @@ type Props = {onDetailChange?: (open: boolean) => void;};-const healthColor = (h: number) => (h >= 80 ? "green" : h >= 50 ? "yellow" : "red");-const EIGHTHS = ["", "▏", "▎", "▍", "▌", "▋", "▊", "▉"];--function MiniBar({ value, width }: { value: number; width: number }) {- const eighths = Math.round((Math.max(0, Math.min(100, value)) / 100) * width * 8);- const full = Math.floor(eighths / 8);- const partial = EIGHTHS[eighths % 8]!;- return (- <>- <Text color={healthColor(value)}>{"█".repeat(full) + partial}</Text>- <Text dimColor>{"░".repeat(width - full - (partial ? 1 : 0))}</Text>- </>- );-}--function HealthCell({ health, bar }: { health: number; bar: number }) {- return (- <>- <MiniBar value={health} width={bar} />- <Text color={healthColor(health)}> {String(health).padStart(3)}%</Text>- </>- );-}--const ago = (d: Date) => {- const s = Math.max(0, Math.round((Date.now() - d.getTime()) / 1000));- return s < 60 ? `${s}s` : s < 3600 ? `${Math.round(s / 60)}m` : s < 172800 ? `${Math.round(s / 3600)}h` : `${Math.round(s / 86400)}d`;-};-function StatusCell({ status }: { status: NodeStatus }) {return (<Text color={STATUS_STYLE[status].color}>@@ -247,37 +218,6 @@ const imageMatches = (g: ImageGroup, q: string) =>// ---- view -------------------------------------------------------------------type Query<T> = { data: T | null; error: string | null; loading: boolean };--/**- * Loads when enabled, again on every `reload` change and every REFRESH_MS.- * A failed refresh keeps the rows it had and reports the error beside them.- */-function useRefreshing<T>(enabled: boolean, reload: number, load: () => Promise<T>): Query<T> {- const [state, setState] = useState<Query<T>>({ data: null, error: null, loading: false });- const loadRef = useRef(load);- loadRef.current = load;- useEffect(() => {- if (!enabled) return;- let alive = true;- const run = () => {- setState((s) => ({ ...s, loading: true }));- loadRef.current().then(- (data) => alive && setState({ data, error: null, loading: false }),- (e: unknown) =>- alive && setState((s) => ({ ...s, error: e instanceof Error ? e.message : String(e), loading: false })),- );- };- run();- const id = setInterval(run, REFRESH_MS);- return () => {- alive = false;- clearInterval(id);- };- }, [enabled, reload]);- return state;-}-function HealthSummary({ health }: { health: number | null }) {if (health === null) return <Text dimColor>health —</Text>;return (diff --git a/tools/xtop/src/components/ShieldDetail.tsx b/tools/xtop/src/components/ShieldDetail.tsxnew file mode 100644index 00000000..1911072c--- /dev/null+++ b/tools/xtop/src/components/ShieldDetail.tsx@@ -0,0 +1,93 @@+// SPDX-License-Identifier: BSD-2-Clause+// Copyright (c) 2026 Authors of shirudo+//+// One upatch: its newest operation, what it fixes and how it rolled out.++import type { ReactNode } from "react";+import { Box, Text, useInput } from "ink";+import type { Shield } from "../lib/shields.ts";+import { SHIELD_STATUS_COLOR, SeverityText } from "./style.tsx";++type Props = {+ /** null when the upatch left tree_ops since it was opened. */+ shield: Shield | null;+ height: number;+ active: boolean;+ onClose: () => void;+};++function Field({ name, children }: { name: string; children: ReactNode }) {+ return (+ <Box>+ <Box width={12} flexShrink={0}>+ <Text dimColor>{name}</Text>+ </Box>+ <Text wrap="truncate-end">{children}</Text>+ </Box>+ );+}++export function ShieldDetail({ shield: s, height, active, onClose }: Props) {+ useInput(+ (input, key) => {+ if (key.escape || key.return || input === "h" || key.leftArrow) onClose();+ },+ { isActive: active },+ );++ if (!s)+ return (+ <Box flexDirection="column" height={height}>+ <Text color="yellow">the upatch is no longer in tree_ops</Text>+ <Text dimColor>esc back</Text>+ </Box>+ );++ const r = s.rollout;+ return (+ <Box flexDirection="column" height={height} overflow="hidden">+ <Text>+ <Text bold>{s.id}</Text>+ <Text color={SHIELD_STATUS_COLOR[s.status]}> {s.status}</Text>+ <Text dimColor> · tree {s.treeId}</Text>+ </Text>+ <Field name="newest op">+ {s.op} at #{s.seq}+ {s.ops > 1 ? `, ${s.ops} operations in all` : ""}+ {s.op === "delete" && s.addSeq ? `, last added at #${s.addSeq}` : ""}+ </Field>+ <Field name="published">{s.publishedAt ? s.publishedAt.toLocaleString() : "—"}</Field>+ <Field name="repository">{s.repository}</Field>+ <Field name="manifest">{s.manifestDigest}</Field>+ <Field name="selector">{s.selector}</Field>+ <Field name="rollout">+ <Text color="green">{r.applied} applied</Text>+ {" · "}+ <Text color={r.pending ? "yellow" : undefined}>{r.pending} not reached</Text>+ {" · "}+ {r.notSelected} left out by the selector+ {" · "}+ <Text color={r.noTarget ? "red" : undefined}>{r.noTarget} module not loaded</Text>+ <Text dimColor> · of {r.nodes} nodes following the tree</Text>+ </Field>+ <Field name="images">{s.images.length ? s.images.join(", ") : "—"}</Field>+ <Box marginTop={1} flexDirection="column">+ <Text dimColor>fixes{s.op === "delete" && s.addSeq ? ` (the add at #${s.addSeq})` : ""}</Text>+ {s.advisories.length === 0 && <Text dimColor>no advisory linked</Text>}+ {s.advisories.map((a) => (+ <Text key={a.id} wrap="truncate-end">+ <Text bold>{a.id}</Text> <SeverityText severity={a.severity} />{" "}+ <Text color={a.source === "kernel" ? "magenta" : "cyan"}>{a.source === "kernel" ? "kernel" : a.package || "?"}</Text>+ <Text dimColor> · </Text>+ <Text color="green">{a.shielded} shielded</Text>+ <Text dimColor> · </Text>+ <Text color={a.exposed ? "yellow" : undefined}>{a.exposed} not shielded</Text>+ </Text>+ ))}+ </Box>+ <Box marginTop={1}>+ <Text dimColor>esc back</Text>+ </Box>+ </Box>+ );+}diff --git a/tools/xtop/src/components/ShieldsView.tsx b/tools/xtop/src/components/ShieldsView.tsxnew file mode 100644index 00000000..5754932b--- /dev/null+++ b/tools/xtop/src/components/ShieldsView.tsx@@ -0,0 +1,214 @@+// SPDX-License-Identifier: BSD-2-Clause+// Copyright (c) 2026 Authors of shirudo+//+// Every upatch of every tree the backend has loaded, with what it fixes+// and how its newest operation rolled out. Enter shows one.++import { useState } from "react";+import { Box, Text, useInput } from "ink";+import type { Backend } from "../lib/backend.ts";+import { useRefreshing } from "../lib/useRefreshing.ts";+import {+ SHIELD_STATUS_RANK,+ severityRank,+ shieldTarget,+ targeted,+ type Rollout,+ type Shield,+ type ShieldStatus,+ type ShieldsReport,+} from "../lib/shields.ts";+import { DataTable, type Column } from "./DataTable.tsx";+import { MiniBar } from "./MiniBar.tsx";+import { ShieldDetail } from "./ShieldDetail.tsx";+import { SHIELD_STATUS_COLOR, SeverityText } from "./style.tsx";++type Props = {+ backend: Backend;+ /** Lines available inside the panel. */+ height: number;+ active: boolean;+ onClose: () => void;+ onSearchingChange: (searching: boolean) => void;+ /** A shield's detail is open. */+ onDetailChange?: (open: boolean) => void;+};++function RolloutCell({ r }: { r: Rollout }) {+ const of = targeted(r);+ if (!of) return <Text dimColor>—</Text>;+ return (+ <>+ <MiniBar value={(r.applied / of) * 100} width={6} />+ <Text> {`${r.applied}/${of}`.padEnd(5)}</Text>+ {r.pending > 0 && <Text color="yellow"> {r.pending}…</Text>}+ {r.noTarget > 0 && <Text color="red"> {r.noTarget}✗</Text>}+ </>+ );+}++const COLUMNS: readonly Column<Shield>[] = [+ {+ id: "status",+ title: "STATUS",+ width: 11,+ defaultDir: "asc",+ sortKey: (s) => SHIELD_STATUS_RANK[s.status],+ render: (s) => <Text color={SHIELD_STATUS_COLOR[s.status]}>{s.status}</Text>,+ },+ {+ id: "name",+ title: "SHIELD",+ defaultDir: "asc",+ sortKey: (s) => s.id,+ render: (s) => (+ <>+ <Text bold>{s.id}</Text>+ <Text dimColor> {s.manifestDigest.slice(0, 8)}</Text>+ </>+ ),+ },+ {+ id: "severity",+ title: "SEVERITY",+ width: 10,+ defaultDir: "asc",+ sortKey: (s) => severityRank(s.severity),+ render: (s) => <SeverityText severity={s.severity} />,+ },+ {+ id: "target",+ title: "TARGET",+ width: 16,+ defaultDir: "asc",+ sortKey: (s) => shieldTarget(s.advisories),+ render: (s) => {+ const t = shieldTarget(s.advisories);+ return t ? <Text color={t === "kernel" ? "magenta" : "cyan"}>{t}</Text> : <Text dimColor>—</Text>;+ },+ },+ {+ id: "images",+ title: "IMAGES",+ width: 22,+ defaultDir: "desc",+ sortKey: (s) => s.images.length,+ render: (s) =>+ s.images.length === 0 ? (+ <Text dimColor>—</Text>+ ) : (+ <>+ <Text color="cyan">{s.images[0]}</Text>+ {s.images.length > 1 && <Text dimColor> +{s.images.length - 1}</Text>}+ </>+ ),+ },+ {+ id: "rollout",+ title: "ROLLOUT",+ width: 20,+ defaultDir: "asc",+ sortKey: (s) => (targeted(s.rollout) ? s.rollout.applied / targeted(s.rollout) : 2),+ render: (s) => <RolloutCell r={s.rollout} />,+ },+ {+ id: "tree",+ title: "TREE",+ width: 6,+ align: "right",+ defaultDir: "asc",+ sortKey: (s) => s.seq,+ render: (s) => <Text color={s.op === "delete" ? "gray" : undefined}>#{s.seq}</Text>,+ },+];++const matches = (s: Shield, q: string) =>+ [+ s.id,+ s.treeId,+ s.status,+ s.severity,+ s.manifestDigest,+ s.repository,+ ...s.advisories.flatMap((a) => [a.id, a.package, a.source]),+ ...s.images,+ ].some((x) => x.toLowerCase().includes(q));++// Ties: worst severity first, then name.+const tiebreak = (a: Shield, b: Shield) => severityRank(a.severity) - severityRank(b.severity) || a.id.localeCompare(b.id);++export function ShieldsView({ backend, height, active, onClose, onSearchingChange, onDetailChange }: Props) {+ const [reload, setReload] = useState(0);+ const query = useRefreshing<ShieldsReport>(true, reload, () => backend.getShields());+ const [searching, setSearching] = useState(false);+ const [detail, setDetail] = useState<string | null>(null);+ const keyOf = (s: Shield) => `${s.treeId}\0${s.id}`;+ const detailShield = detail ? (query.data?.shields.find((s) => keyOf(s) === detail) ?? null) : null;++ const showDetail = (key: string | null) => {+ setDetail(key);+ onDetailChange?.(key !== null);+ };+ const reportSearching = (s: boolean) => {+ setSearching(s);+ onSearchingChange(s);+ };++ useInput(+ (input) => {+ if (input === "r") setReload((r) => r + 1);+ },+ { isActive: active && !searching && !detail },+ );++ if (!query.data)+ return query.error ? (+ <Text color="red">shields query failed: {query.error}</Text>+ ) : (+ <Text dimColor>querying backend…</Text>+ );+ const report = query.data;+ if (report.shields.length === 0)+ return <Text dimColor>no upatch in shirudo.tree_ops: load a tree with jobs/tree-ingest</Text>;+ const tableHeight = Math.max(4, height);+ const trees = new Set(report.shields.map((s) => s.treeId));++ return (+ <Box flexDirection="column">+ {detail && <ShieldDetail shield={detailShield} height={tableHeight} active={active} onClose={() => showDetail(null)} />}+ {/* Hidden, not unmounted, so the table keeps its cursor, sort and search. */}+ <Box flexDirection="column" display={detail ? "none" : "flex"}>+ <DataTable+ rows={report.shields}+ columns={COLUMNS}+ rowKey={keyOf}+ height={tableHeight}+ active={active && !detail}+ initialSort={{ col: "status", dir: "asc" }}+ tiebreak={tiebreak}+ matches={matches}+ footerHint="r refresh"+ onSearchingChange={reportSearching}+ onClose={onClose}+ onOpen={(s) => showDetail(keyOf(s))}+ summary={(rows, sortedBy) => {+ const count = (st: ShieldStatus) => rows.filter((s) => s.status === st).length;+ return (+ <>+ {query.error && <Text color="red">refresh failed: {query.error} · </Text>}+ <Text bold>{rows.length}</Text> shields · <Text color="green">{count("deployed")} deployed</Text> ·{" "}+ <Text color="yellow">{count("pending")} pending</Text> · <Text color="gray">{count("withdrawn")} withdrawn</Text>+ <Text dimColor>+ {" "}+ · {trees.size} tree{trees.size === 1 ? "" : "s"} · sorted by {sortedBy} · as of{" "}+ {report.generatedAt.toTimeString().slice(0, 8)}+ </Text>+ {query.loading && <Text dimColor> · querying…</Text>}+ </>+ );+ }}+ />+ </Box>+ </Box>+ );+}diff --git a/tools/xtop/src/components/style.ts b/tools/xtop/src/components/style.tsdeleted file mode 100644index be83ed1c..00000000--- a/tools/xtop/src/components/style.ts+++ /dev/null@@ -1,10 +0,0 @@-// SPDX-License-Identifier: BSD-2-Clause-// Copyright (c) 2026 Authors of shirudo--import type { NodeStatus } from "../lib/fleet.ts";--export const STATUS_STYLE: Record<NodeStatus, { icon: string; color: string }> = {- unhealthy: { icon: "✗", color: "red" },- stale: { icon: "○", color: "gray" },- healthy: { icon: "●", color: "green" },-};diff --git a/tools/xtop/src/lib/backend.ts b/tools/xtop/src/lib/backend.tsindex 78d1765c..e210a960 100644--- a/tools/xtop/src/lib/backend.ts+++ b/tools/xtop/src/lib/backend.ts@@ -4,12 +4,16 @@// What the views ask of the backend, and the client that asks ClickHouse.import NODES_SQL from "../../sql/nodes.sql" with { type: "text" };+import SHIELDS_SQL from "../../sql/shields.sql" with { type: "text" };import { queryRows, type ClickHouseConfig } from "./clickhouse.ts";import { STATUSES, TRUSTS, type FleetNode, type FleetReport, type NodeStatus, type Trust } from "./fleet.ts";+import { shieldStatus, worstSeverity, type Advisory, type Shield, type ShieldsReport } from "./shields.ts";export interface Backend {/** Every node of shirudo.node_status. */getFleet(): Promise<FleetReport>;+ /** Every upatch of every tree in shirudo.tree_ops. */+ getShields(): Promise<ShieldsReport>;}/** A row of sql/nodes.sql. */@@ -71,10 +75,74 @@ export function toFleetReport(rows: readonly NodeRow[]): FleetReport {return { generatedAt: updated ? new Date(updated) : new Date(), nodes: rows.map(toFleetNode) };}+/** A row of sql/shields.sql. */+export type ShieldRow = {+ tree_id: string;+ id: string;+ seq: number;+ op: string;+ add_seq: number;+ ops: number;+ manifest_digest: string;+ repository: string;+ selector: string;+ published_ms: number | null;+ /** (advisory, severity, package, source, shielded, exposed) */+ advisories: [string, string, string, string, number, number][];+ images: string[];+ nodes: number;+ applied: number;+ not_selected: number;+ no_target: number;+ pending: number;+};++export function toShield(r: ShieldRow): Shield {+ const op = oneOf<"add" | "delete">(["add", "delete"], r.op, "operation");+ const advisories: Advisory[] = r.advisories.map(([id, severity, pkg, source, shielded, exposed]) => ({+ id,+ severity,+ package: pkg,+ source: oneOf<Advisory["source"]>(["kernel", "sbom", ""], source, "advisory source"),+ shielded,+ exposed,+ }));+ const rollout = {+ nodes: r.nodes,+ applied: r.applied,+ notSelected: r.not_selected,+ noTarget: r.no_target,+ pending: r.pending,+ };+ return {+ treeId: r.tree_id,+ id: r.id,+ seq: r.seq,+ op,+ addSeq: r.add_seq,+ ops: r.ops,+ manifestDigest: r.manifest_digest,+ repository: r.repository,+ selector: r.selector,+ // A missing join reads as 0, not NULL.+ publishedAt: r.published_ms ? new Date(r.published_ms) : null,+ advisories,+ images: r.images,+ rollout,+ status: shieldStatus(op, rollout),+ severity: worstSeverity(advisories),+ };+}+export class ClickHouseBackend implements Backend {constructor(private readonly cfg: ClickHouseConfig) {}async getFleet(): Promise<FleetReport> {return toFleetReport(await queryRows<NodeRow>(this.cfg, NODES_SQL));}++ async getShields(): Promise<ShieldsReport> {+ const rows = await queryRows<ShieldRow>(this.cfg, SHIELDS_SQL);+ return { generatedAt: new Date(), shields: rows.map(toShield) };+ }}diff --git a/tools/xtop/src/lib/format.ts b/tools/xtop/src/lib/format.tsnew file mode 100644index 00000000..370ff7fa--- /dev/null+++ b/tools/xtop/src/lib/format.ts@@ -0,0 +1,8 @@+// SPDX-License-Identifier: BSD-2-Clause+// Copyright (c) 2026 Authors of shirudo++/** How long ago, in the largest unit that keeps it short: 8s, 3m, 5h, 2d. */+export const ago = (d: Date) => {+ const s = Math.max(0, Math.round((Date.now() - d.getTime()) / 1000));+ return s < 60 ? `${s}s` : s < 3600 ? `${Math.round(s / 60)}m` : s < 172800 ? `${Math.round(s / 3600)}h` : `${Math.round(s / 86400)}d`;+};diff --git a/tools/xtop/src/lib/shields.ts b/tools/xtop/src/lib/shields.tsnew file mode 100644index 00000000..7f1014cd--- /dev/null+++ b/tools/xtop/src/lib/shields.ts@@ -0,0 +1,94 @@+// SPDX-License-Identifier: BSD-2-Clause+// Copyright (c) 2026 Authors of shirudo+//+// The upatches of every tree the backend has loaded: what each fixes and+// how far its newest operation has rolled out.++/**+ * pending while a node following the tree has not reached the newest+ * operation, deployed once every one has, withdrawn when that operation+ * is a delete.+ */+export type ShieldStatus = "pending" | "deployed" | "withdrawn";++export const SHIELD_STATUS_RANK: Record<ShieldStatus, number> = { pending: 0, deployed: 1, withdrawn: 2 };++/** Worst first; a severity the scanner gave that is not listed sorts last. */+export const SEVERITIES = ["CRITICAL", "HIGH", "MEDIUM", "LOW"] as const;++export const severityRank = (s: string) => {+ const i = (SEVERITIES as readonly string[]).indexOf(s.toUpperCase());+ return i < 0 ? SEVERITIES.length : i;+};++export type Advisory = {+ id: string;+ /** Empty when neither kernel_vulns nor sbom_vulns knows the advisory. */+ severity: string;+ package: string;+ source: "kernel" | "sbom" | "";+ /** Nodes affected by it that this upatch shields. */+ shielded: number;+ /** Nodes affected by it that this upatch does not shield yet, or not at all. */+ exposed: number;+};++export type Rollout = {+ /** Nodes following the tree. */+ nodes: number;+ /** Applied the newest operation. */+ applied: number;+ /** Reached it; the selector left them out. */+ notSelected: number;+ /** Reached it; the module it attaches to is not loaded. */+ noTarget: number;+ /** Have not reached it. */+ pending: number;+};++export type Shield = {+ treeId: string;+ id: string;+ /** The newest operation of the upatch. */+ seq: number;+ op: "add" | "delete";+ /** The newest add, whose fixes the advisories are; 0 when there is none. */+ addSeq: number;+ /** Operations of the upatch in the tree. */+ ops: number;+ manifestDigest: string;+ repository: string;+ selector: string;+ /** When the backend first loaded the publication holding the newest operation. */+ publishedAt: Date | null;+ advisories: Advisory[];+ /** Images, as "id version", of the nodes an advisory affects. */+ images: string[];+ rollout: Rollout;+ status: ShieldStatus;+ /** The worst severity of its advisories, "" when none is known. */+ severity: string;+};++export type ShieldsReport = { generatedAt: Date; shields: Shield[] };++export function shieldStatus(op: Shield["op"], rollout: Rollout): ShieldStatus {+ if (op === "delete") return "withdrawn";+ return rollout.pending ? "pending" : "deployed";+}++export function worstSeverity(advisories: readonly Pick<Advisory, "severity">[]): string {+ return advisories+ .map((a) => a.severity)+ .filter((s) => s)+ .reduce((w, s) => (w === "" || severityRank(s) < severityRank(w) ? s : w), "");+}++/** What the vulnerable code is: the kernel, or the packages of an SBOM. */+export function shieldTarget(advisories: readonly Pick<Advisory, "package" | "source">[]): string {+ const names = advisories.map((a) => (a.source === "kernel" ? "kernel" : a.package)).filter((n) => n);+ return [...new Set(names)].sort().join(", ");+}++/** Nodes the newest operation can still apply on: all but those it left out. */+export const targeted = (r: Rollout) => r.nodes - r.notSelected;diff --git a/tools/xtop/src/lib/useRefreshing.ts b/tools/xtop/src/lib/useRefreshing.tsnew file mode 100644index 00000000..5bc7c1df--- /dev/null+++ b/tools/xtop/src/lib/useRefreshing.ts@@ -0,0 +1,38 @@+// SPDX-License-Identifier: BSD-2-Clause+// Copyright (c) 2026 Authors of shirudo++import { useEffect, useRef, useState } from "react";++/** The backend's views are recomputed once a minute; asking more often shows nothing new. */+const REFRESH_MS = 60_000;++export type Query<T> = { data: T | null; error: string | null; loading: boolean };++/**+ * Loads when enabled, again on every `reload` change and every REFRESH_MS.+ * A failed refresh keeps the rows it had and reports the error beside them.+ */+export function useRefreshing<T>(enabled: boolean, reload: number, load: () => Promise<T>): Query<T> {+ const [state, setState] = useState<Query<T>>({ data: null, error: null, loading: false });+ const loadRef = useRef(load);+ loadRef.current = load;+ useEffect(() => {+ if (!enabled) return;+ let alive = true;+ const run = () => {+ setState((s) => ({ ...s, loading: true }));+ loadRef.current().then(+ (data) => alive && setState({ data, error: null, loading: false }),+ (e: unknown) =>+ alive && setState((s) => ({ ...s, error: e instanceof Error ? e.message : String(e), loading: false })),+ );+ };+ run();+ const id = setInterval(run, REFRESH_MS);+ return () => {+ alive = false;+ clearInterval(id);+ };+ }, [enabled, reload]);+ return state;+}diff --git a/tools/xtop/test/fleet.test.ts b/tools/xtop/test/fleet.test.tsindex 749fdd79..822c8bfa 100644--- a/tools/xtop/test/fleet.test.ts+++ b/tools/xtop/test/fleet.test.ts@@ -1,8 +1,9 @@// SPDX-License-Identifier: BSD-2-Clause// Copyright (c) 2026 Authors of shirudo//-// The rows of sql/nodes.sql as tools/backend/test/xtop-nodes.expected has-// them, turned into nodes and rolled up by image.+// Rows shaped like those of sql/nodes.sql in+// tools/backend/test/xtop-nodes.expected, turned into nodes and rolled up+// by image.import { describe, expect, test } from "bun:test";import { toFleetNode, toFleetReport, type NodeRow } from "../src/lib/backend.ts";diff --git a/tools/xtop/test/shields.test.ts b/tools/xtop/test/shields.test.tsnew file mode 100644index 00000000..ddd7df5e--- /dev/null+++ b/tools/xtop/test/shields.test.ts@@ -0,0 +1,118 @@+// SPDX-License-Identifier: BSD-2-Clause+// Copyright (c) 2026 Authors of shirudo+//+// The rows of sql/shields.sql as tools/backend/test/xtop-shields.expected+// has them, turned into shields.++import { describe, expect, test } from "bun:test";+import { toShield, type ShieldRow } from "../src/lib/backend.ts";+import { severityRank, shieldStatus, shieldTarget, targeted, worstSeverity } from "../src/lib/shields.ts";++function row(over: Partial<ShieldRow>): ShieldRow {+ return {+ tree_id: "fleet-base",+ id: "xfs-fix",+ seq: 3,+ op: "add",+ add_seq: 3,+ ops: 3,+ manifest_digest: "b25c835b353ba101d51c4473d602764c2f8746a6e60342bcf49d510a868cb62a",+ repository: "oci://registry.example.com/shirudo/fleet-base",+ selector: '{"labels":{"role":["edge"]}}',+ published_ms: 1_795_053_774_291,+ advisories: [["EXAMPLE-0101", "CRITICAL", "linux", "kernel", 2, 2]],+ images: ["fleet-os 2026.11.1"],+ nodes: 4,+ applied: 2,+ not_selected: 2,+ no_target: 0,+ pending: 0,+ ...over,+ };+}++const SSL_FIX = row({+ id: "ssl-fix",+ seq: 4,+ add_seq: 4,+ ops: 1,+ selector: "{}",+ advisories: [["EXAMPLE-0202", "HIGH", "openssl", "sbom", 0, 4]],+ applied: 0,+ not_selected: 0,+ pending: 4,+});++describe("toShield", () => {+ test("maps a deployed kernel shield", () => {+ const s = toShield(row({}));+ expect(s.status).toBe("deployed");+ expect(s.severity).toBe("CRITICAL");+ expect(shieldTarget(s.advisories)).toBe("kernel");+ expect(s.rollout).toEqual({ nodes: 4, applied: 2, notSelected: 2, noTarget: 0, pending: 0 });+ expect(targeted(s.rollout)).toBe(2);+ expect(s.advisories[0]).toEqual({+ id: "EXAMPLE-0101",+ severity: "CRITICAL",+ package: "linux",+ source: "kernel",+ shielded: 2,+ exposed: 2,+ });+ expect(s.publishedAt?.getTime()).toBe(1_795_053_774_291);+ });++ test("maps a pending package shield", () => {+ const s = toShield(SSL_FIX);+ expect(s.status).toBe("pending");+ expect(s.severity).toBe("HIGH");+ expect(shieldTarget(s.advisories)).toBe("openssl");+ expect(targeted(s.rollout)).toBe(4);+ });++ test("a delete withdraws it, whatever the rollout", () => {+ expect(toShield(row({ op: "delete", seq: 5, pending: 3 })).status).toBe("withdrawn");+ });++ test("an upatch without fixes or a publication", () => {+ const s = toShield(row({ advisories: [], images: [], published_ms: 0 }));+ expect(s.severity).toBe("");+ expect(shieldTarget(s.advisories)).toBe("");+ expect(s.publishedAt).toBeNull();+ });++ test("refuses an operation or source it does not know", () => {+ expect(() => toShield(row({ op: "move" }))).toThrow(/unknown operation/);+ expect(() => toShield(row({ advisories: [["X", "LOW", "p", "rpm", 0, 0]] }))).toThrow(/unknown advisory source/);+ });+});++describe("helpers", () => {+ test("severity ranks worst first and unknown last", () => {+ expect(severityRank("CRITICAL")).toBeLessThan(severityRank("HIGH"));+ expect(severityRank("low")).toBe(3);+ expect(severityRank("NEGLIGIBLE")).toBe(4);+ });++ test("the worst severity of several advisories", () => {+ expect(worstSeverity([{ severity: "LOW" }, { severity: "" }, { severity: "HIGH" }])).toBe("HIGH");+ expect(worstSeverity([])).toBe("");+ });++ test("the target names each package once, the kernel as kernel", () => {+ expect(+ shieldTarget([+ { package: "openssl", source: "sbom" },+ { package: "linux", source: "kernel" },+ { package: "openssl", source: "sbom" },+ ]),+ ).toBe("kernel, openssl");+ });++ test("status follows the newest operation and the nodes not reached", () => {+ const r = { nodes: 2, applied: 1, notSelected: 0, noTarget: 0, pending: 1 };+ expect(shieldStatus("add", r)).toBe("pending");+ expect(shieldStatus("add", { ...r, pending: 0 })).toBe("deployed");+ expect(shieldStatus("delete", r)).toBe("withdrawn");+ });+});