eBPF-based security platform
tools/xtop: add the SBOM view
John Fastabend2b2f88601ce8
diff --git a/Documentation/contribute/testing/test-coverage.rst b/Documentation/contribute/testing/test-coverage.rstindex b9e6b704..554f5bd5 100644--- a/Documentation/contribute/testing/test-coverage.rst+++ b/Documentation/contribute/testing/test-coverage.rst@@ -980,16 +980,16 @@ ingest job on a single publication and on a walk over sealed segments,the SBOM scan job on a store that holds an image in every state, theSBOM put job into a ``file://`` and an ``s3://`` store, again and withanother SBOM, and what it refuses (``test/sbom-put``), and the queries-of :src:`tools/xtop/sql/nodes.sql` and :src:`tools/xtop/sql/shields.sql`,-with the names and types of their columns, over nodes healthy,-unhealthy, stale and without a tree or an image, and a tree with one-upatch deployed and one still rolling out (``test/xtop-nodes``,-``test/xtop-shields``).+of :src:`tools/xtop/sql/`, with the names and types of their columns,+over nodes healthy, unhealthy, stale and without a tree or an image, a+tree with one upatch deployed and one still rolling out, and the+findings and images of their SBOMs (``test/xtop-nodes``,+``test/xtop-shields``, ``test/xtop-sbom``).The unit tests of :src:`tools/xtop/test/` cover how xtop turns the rows-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 the+of those queries into nodes, shields, findings and images, the health+percent, the roll-up by image, the status and severity of a shield, the+status of a finding 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 ed1e4b3f..00b0e5c3 100644--- a/Documentation/contribute/testing/testing.rst+++ b/Documentation/contribute/testing/testing.rst@@ -1229,8 +1229,8 @@ 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`` and-``xtop-shields.expected`` have them.+shaped as ``tools/backend/test/xtop-nodes.expected``,+``xtop-shields.expected`` and ``xtop-sbom.expected`` have them... code-block:: console@@ -1238,11 +1238,10 @@ shaped as ``tools/backend/test/xtop-nodes.expected`` andThe target installs the locked packages, type-checks the program with``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.+the schema by the backend tests ``xtop-nodes``, ``xtop-shields`` and+``xtop-sbom``, which run the queries of :src:`tools/xtop/sql/` from their+``.sh`` scripts over the rows of ``test/xtop-nodes.setup.sql``, which the+other two ``.setup.sql`` link to.Write a test------------diff --git a/Documentation/operate/backend/index.rst b/Documentation/operate/backend/index.rstindex 392d86bb..6359f13b 100644--- a/Documentation/operate/backend/index.rst+++ b/Documentation/operate/backend/index.rst@@ -89,8 +89,8 @@ Files(:ref:`testing-backend`).* - :src:`tools/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`).+ ``latest`` and ``node_vulns``, of the upatches of the trees and+ their rollout, and of the SBOM findings and images (:doc:`xtop`)... toctree:::titlesonly:diff --git a/Documentation/operate/backend/xtop.rst b/Documentation/operate/backend/xtop.rstindex 232030ea..5a01abac 100644--- a/Documentation/operate/backend/xtop.rst+++ b/Documentation/operate/backend/xtop.rst@@ -5,8 +5,8 @@:page-type: How-to:audience: Operators, SecOps-Watch nodes and shields with xtop-=================================+Watch nodes, shields and SBOMs with xtop+========================================:src:`tools/xtop/` is a terminal view of the backend. It reads thebackend's ClickHouse over its HTTP interface, one query per view: Nodes@@ -14,8 +14,10 @@ sends :src:`tools/xtop/sql/nodes.sql`, over ``shirudo.node_status``,``shirudo.latest`` and ``shirudo.node_vulns``, and shows one row pernode, 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 on+and shows one row per upatch; SBOM sends :src:`tools/xtop/sql/sbom.sql`,+over ``shirudo.node_vulns``, and shows one row per finding, or, with+:src:`tools/xtop/sql/sbom-images.sql` over ``shirudo.sbom_images``, one+per image. 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@@ -169,3 +171,47 @@ repository, advisories, packages and images.The rollout counts the nodes whose newest record names the tree; a nodethat moved to another tree leaves it. Detector hits are not shown,because the backend takes in no metrics.++Read the SBOM findings+----------------------++SBOM has one row per finding, an advisory in a package, that+``node_vulns`` has on any node: from the SBOM of a node's image, as+:doc:`sbom-scan` matched it, or from ``kernel_vulns`` by the node's+kernel release (:doc:`exposure`).++.. list-table::+ :header-rows: 1++ * - Column+ - Value+ * - ``SEVERITY``, ``VULNERABILITY``+ - The advisory and its severity.+ * - ``PACKAGE``+ - ``kernel``, or the package of the SBOM, and the versions the+ nodes have installed.+ * - ``FIXED IN``+ - The first version without it; ``none yet`` when there is none.+ * - ``NODES``+ - The nodes it affects, of all the nodes in ``node_status``.+ * - ``SHIELD``+ - The upatch linked to the advisory, ``—`` when none is.+ * - ``STATUS``+ - ``no shield`` when no upatch is linked; ``shielded`` when it+ shields every affected node; ``pending`` while it is still+ coming to one; ``partial`` when it leaves some out, because the+ selector does, the module it attaches to is not loaded or it was+ withdrawn. The nodes it shields of those affected follow.++The summary line says when the findings come from a scan older than+``sbom_stale_seconds``. Enter on a finding shows its package, source and+shield, and every node it affects with its exposure, image, installed+version, the binding of its image to an SBOM and its status.++``t`` switches to the images: every image of ``sbom_images`` at its+newest scan, with its state (:doc:`sbom-scan`), ``stale`` when that scan+is older than ``sbom_stale_seconds``, the nodes that run it, its+findings with how many are critical and high, how long ago it was+scanned and the version of the matcher's database. An image a node runs+that has no SBOM in the store reads ``no_sbom``: store one with+:doc:`sbom-put`. Enter on an image shows its findings.diff --git a/tools/backend/test/xtop-sbom.expected b/tools/backend/test/xtop-sbom.expectednew file mode 100644index 00000000..407ac3de--- /dev/null+++ b/tools/backend/test/xtop-sbom.expected@@ -0,0 +1,8 @@+vuln_id package severity source fixed installed affected total upatch_id shielded pending idle withdrawn unshielded stale nodes+String String String String String Array(String) UInt64 UInt64 String UInt64 UInt64 UInt64 UInt64 UInt64 Bool Array(Tuple(String, String, String, String, String, String, String, String))+EXAMPLE-0101 linux CRITICAL kernel 7.4.5 ['7.4.2'] 4 5 xfs-fix 2 0 2 0 0 false [('node-a','000b23602ab98bfb','shielded','fleet-os','2026.11.1','7.4.2','verified','healthy'),('node-b','000b9d72e08380a1','shield_excludes_node','fleet-os','2026.11.1','7.4.2','declared','healthy'),('node-d','000b0d','shielded','fleet-os','2026.11.1','7.4.2','verified','unhealthy'),('node-e','000b0e','shield_excludes_node','fleet-os','2026.11.1','7.4.2','declared','stale')]+EXAMPLE-0202 openssl HIGH sbom 3.5.1-2 ['3.5.1-1'] 4 5 ssl-fix 0 4 0 0 0 false [('node-a','000b23602ab98bfb','shield_pending','fleet-os','2026.11.1','3.5.1-1','verified','healthy'),('node-b','000b9d72e08380a1','shield_pending','fleet-os','2026.11.1','3.5.1-1','declared','healthy'),('node-d','000b0d','shield_pending','fleet-os','2026.11.1','3.5.1-1','verified','unhealthy'),('node-e','000b0e','shield_pending','fleet-os','2026.11.1','3.5.1-1','declared','stale')]+image_id image_version image_root state sbom_format sbom_sha256 built_ms db_version stale vulns critical high nodes scanned+String String String String String String Int64 String UInt8 UInt64 UInt64 UInt64 UInt64 UInt8+fleet-os 2026.11.1 a3c3f1b0e4c2d7f09e3b6b2a8b1d5e7c4f6a9d0b2c8e1f3a5b7d9c0e2f4a6b8c ok cyclonedx-json 5b0e2c8a4f6d1e3b7a9c0d2e4f6a8b1c3d5e7f9a0b2c4d6e8f1a3b5c7d9e91d4 1793606400000 2 0 1 0 1 4 1+findings 2diff --git a/tools/backend/test/xtop-sbom.setup.sql b/tools/backend/test/xtop-sbom.setup.sqlnew file mode 120000index 00000000..49c04991--- /dev/null+++ b/tools/backend/test/xtop-sbom.setup.sql@@ -0,0 +1 @@+xtop-nodes.setup.sql\ No newline at end of filediff --git a/tools/backend/test/xtop-sbom.sh b/tools/backend/test/xtop-sbom.shnew file mode 100644index 00000000..d8626aef--- /dev/null+++ b/tools/backend/test/xtop-sbom.sh@@ -0,0 +1,25 @@+#!/bin/sh+# SPDX-License-Identifier: BSD-2-Clause+# Copyright (c) 2026 Authors of shirudo+#+# The two queries the SBOM view of tools/xtop sends, over the rows of+# xtop-nodes.setup.sql, with the names and types of their columns, which+# the view reads by name: the findings with the nodes they affect, and+# the images. The time of the scan changes from run to run and is left+# out.++xtop=$(dirname "$0")/../../xtop/sql++# query <file> <outer select>: run a query of the view inside a select+# that leaves out what changes.+query()+{+ {+ printf '%s\n' "$2 FROM ("+ sed '/^--/d' "$xtop/$1"+ printf '%s\n' ") FORMAT TSVWithNamesAndTypes"+ } | $CLICKHOUSE_CLIENT+}++query sbom.sql 'SELECT *'+query sbom-images.sql 'SELECT * EXCEPT (scanned_ms), scanned_ms > 0 AS scanned'diff --git a/tools/backend/test/xtop-sbom.sql b/tools/backend/test/xtop-sbom.sqlnew file mode 100644index 00000000..ec6aedc4--- /dev/null+++ b/tools/backend/test/xtop-sbom.sql@@ -0,0 +1,7 @@+-- SPDX-License-Identifier: BSD-2-Clause+-- Copyright (c) 2026 Authors of shirudo+--+-- Every finding of node_vulns is a row of the SBOM view; xtop-sbom.sh+-- prints the rows.++SELECT 'findings', uniqExact(vuln_id, package) FROM shirudo.node_vulns WHERE vuln_id != '';diff --git a/tools/xtop/sql/sbom-images.sql b/tools/xtop/sql/sbom-images.sqlnew file mode 100644index 00000000..f5470abc--- /dev/null+++ b/tools/xtop/sql/sbom-images.sql@@ -0,0 +1,87 @@+-- SPDX-License-Identifier: BSD-2-Clause+-- Copyright (c) 2026 Authors of shirudo+--+-- One row per image for the SBOM view of tools/xtop: the newest scan of+-- every image in sbom_images, its findings and the nodes that run it,+-- and, as no_sbom, every image a node runs that sbom_images does not+-- have. A node that reports no image root runs an image of its id and+-- version, as node_vulns reads it. Times are epoch milliseconds; a+-- no_sbom row has 0 for them.++WITH+running AS+(+ SELECT+ assumeNotNull(l.image_id) AS image_id,+ ifNull(l.image_version, '') AS image_version,+ ifNull(l.image_root, '') AS image_root,+ l.ak_name AS ak_name+ FROM shirudo.latest AS l+ WHERE l.image_id IS NOT NULL+),+findings AS+(+ SELECT+ sbom_sha256,+ scanned_at,+ uniq(vuln_id) AS vulns,+ uniqIf(vuln_id, severity = 'CRITICAL') AS critical,+ uniqIf(vuln_id, severity = 'HIGH') AS high+ FROM shirudo.sbom_vulns+ GROUP BY sbom_sha256, scanned_at+),+images AS+(+ SELECT image_id, image_version, image_root, state, sbom_format, sbom_sha256, built_at,+ scanned_at, db_version+ FROM shirudo.sbom_images FINAL+),+nodes AS+(+ SELECT i.image_id AS image_id, i.image_version AS image_version, i.image_root AS image_root,+ uniq(r.ak_name) AS nodes+ FROM images AS i+ INNER JOIN running AS r ON r.image_id = i.image_id AND r.image_version = i.image_version+ WHERE r.image_root = i.image_root OR r.image_root = ''+ GROUP BY image_id, image_version, image_root+)+SELECT+ i.image_id AS image_id,+ i.image_version AS image_version,+ i.image_root AS image_root,+ toString(i.state) AS state,+ i.sbom_format AS sbom_format,+ i.sbom_sha256 AS sbom_sha256,+ toInt64(toUnixTimestamp(i.built_at)) * 1000 AS built_ms,+ toInt64(toUnixTimestamp(i.scanned_at)) * 1000 AS scanned_ms,+ i.db_version AS db_version,+ ifNull(i.scanned_at < now() - toIntervalSecond((SELECT any(sbom_stale_seconds) FROM shirudo.settings FINAL)), false)+ AS stale,+ f.vulns AS vulns,+ f.critical AS critical,+ f.high AS high,+ n.nodes AS nodes+FROM images AS i+LEFT JOIN findings AS f ON f.sbom_sha256 = i.sbom_sha256 AND f.scanned_at = i.scanned_at+LEFT JOIN nodes AS n+ ON n.image_id = i.image_id AND n.image_version = i.image_version AND n.image_root = i.image_root+UNION ALL+SELECT+ r.image_id,+ r.image_version,+ r.image_root,+ 'no_sbom',+ '',+ '',+ toInt64(0),+ toInt64(0),+ '',+ false,+ toUInt64(0),+ toUInt64(0),+ toUInt64(0),+ uniq(r.ak_name)+FROM running AS r+LEFT ANTI JOIN images AS i ON i.image_id = r.image_id AND i.image_version = r.image_version+GROUP BY r.image_id, r.image_version, r.image_root+ORDER BY image_id, image_version, image_rootdiff --git a/tools/xtop/sql/sbom.sql b/tools/xtop/sql/sbom.sqlnew file mode 100644index 00000000..36ec6920--- /dev/null+++ b/tools/xtop/sql/sbom.sql@@ -0,0 +1,30 @@+-- SPDX-License-Identifier: BSD-2-Clause+-- Copyright (c) 2026 Authors of shirudo+--+-- One row per finding, an advisory in a package, over the nodes it+-- affects in node_vulns, for the SBOM view of tools/xtop: how many of+-- them the upatch linked to it shields, and every affected node with its+-- exposure. total is the number of nodes in node_status.++SELECT+ v.vuln_id AS vuln_id,+ v.package AS package,+ any(v.severity) AS severity,+ toString(any(v.source)) AS source,+ any(v.fixed) AS fixed,+ arraySort(groupUniqArray(v.installed)) AS installed,+ uniq(v.ak_name) AS affected,+ ifNull((SELECT uniq(ak_name) FROM shirudo.node_status), 0) AS total,+ anyIf(v.upatch_id, v.upatch_id != '') AS upatch_id,+ uniqIf(v.ak_name, v.exposure = 'shielded') AS shielded,+ uniqIf(v.ak_name, v.exposure = 'shield_pending') AS pending,+ uniqIf(v.ak_name, v.exposure IN ('shield_module_absent', 'shield_excludes_node')) AS idle,+ uniqIf(v.ak_name, v.exposure = 'shield_withdrawn') AS withdrawn,+ uniqIf(v.ak_name, v.exposure = 'exposed_no_shield') AS unshielded,+ max(v.sbom_stale) AS stale,+ arraySort(groupArray(tuple(v.node_id, v.ak_name, toString(v.exposure), v.image_id, v.image_version,+ v.installed, toString(v.binding), toString(v.status)))) AS nodes+FROM shirudo.node_vulns AS v+WHERE v.vuln_id != ''+GROUP BY v.vuln_id, v.package+ORDER BY vuln_id, packagediff --git a/tools/xtop/src/App.tsx b/tools/xtop/src/App.tsxindex 83120b23..610772be 100644--- a/tools/xtop/src/App.tsx+++ b/tools/xtop/src/App.tsx@@ -11,22 +11,25 @@ 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";+import { SbomView, type SbomMode } from "./components/SbomView.tsx";-type ViewId = "nodes" | "shields";+type ViewId = "nodes" | "shields" | "sbom";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" },+ { id: "sbom", label: "SBOM", title: "sbom · findings from shirudo.node_vulns, images from shirudo.sbom_images" },];const SIDEBAR_WIDTH = 16;type Focus = "menu" | "menu-open" | ViewId | "detail" | "search";const HINTS: Record<Focus, string> = {- menu: "j/k menu · l/enter open · 1 nodes · 2 shields · q quit",+ menu: "j/k menu · l/enter open · 1 nodes · 2 shields · 3 sbom · q quit","menu-open": "j/k menu · l/enter open · tab back to view · esc close view · 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",+ sbom: "j/k scroll · k past top → sort, then tabs · / search · enter finding nodes, image → findings · t images · r refresh · tab menu · esc close · q quit",detail: "esc back · q quit",search: "type to filter · enter keep · esc clear",};@@ -41,6 +44,7 @@ export function App({ backend }: { backend: Backend }) {const [detail, setDetail] = useState(false);// Kept while the app runs, so reopening Nodes keeps the toggle.const [nodesMode, setNodesMode] = useState<NodesMode>("nodes");+ const [sbomMode, setSbomMode] = useState<SbomMode>("findings");const open = (view: ViewId) => {setMenuCursor(MENU.findIndex((m) => m.id === view));@@ -132,6 +136,17 @@ export function App({ backend }: { backend: Backend }) {onSearchingChange={setSearching}onDetailChange={setDetail}/>+ ) : view.id === "sbom" ? (+ <SbomView+ backend={backend}+ mode={sbomMode}+ onModeChange={setSbomMode}+ height={viewLines}+ active={!menuFocused}+ onClose={close}+ onSearchingChange={setSearching}+ onDetailChange={setDetail}+ />) : (<ShieldsViewbackend={backend}diff --git a/tools/xtop/src/components/FindingDetail.tsx b/tools/xtop/src/components/FindingDetail.tsxnew file mode 100644index 00000000..1bc52727--- /dev/null+++ b/tools/xtop/src/components/FindingDetail.tsx@@ -0,0 +1,105 @@+// SPDX-License-Identifier: BSD-2-Clause+// Copyright (c) 2026 Authors of shirudo+//+// One finding: the advisory, its shield, and every node it affects with+// how exposed that node is.++import type { ReactNode } from "react";+import { Box, Text, useInput } from "ink";+import type { Exposure, Finding } from "../lib/sbom.ts";+import { FINDING_STATUS_STYLE, SeverityText } from "./style.tsx";++type Props = {+ /** null when the finding left node_vulns since it was opened. */+ finding: Finding | null;+ height: number;+ active: boolean;+ onClose: () => void;+};++const EXPOSURE_TEXT: Record<Exposure, { text: string; color?: string }> = {+ shielded: { text: "shielded", color: "green" },+ shield_pending: { text: "shield coming", color: "yellow" },+ shield_module_absent: { text: "module not loaded", color: "red" },+ shield_excludes_node: { text: "left out by selector", color: "red" },+ shield_withdrawn: { text: "shield withdrawn", color: "red" },+ exposed_no_shield: { text: "no shield", color: "red" },+ none: { text: "not affected" },+ unknown: { text: "unknown", color: "yellow" },+};++function Field({ name, children }: { name: string; children: ReactNode }) {+ return (+ <Box>+ <Box width={10} flexShrink={0}>+ <Text dimColor>{name}</Text>+ </Box>+ <Text wrap="truncate-end">{children}</Text>+ </Box>+ );+}++export function FindingDetail({ finding: f, height, active, onClose }: Props) {+ useInput(+ (input, key) => {+ if (key.escape || key.return || input === "h" || key.leftArrow) onClose();+ },+ { isActive: active },+ );++ if (!f)+ return (+ <Box flexDirection="column" height={height}>+ <Text color="yellow">the finding is no longer in node_vulns</Text>+ <Text dimColor>esc back</Text>+ </Box>+ );++ const style = FINDING_STATUS_STYLE[f.status];+ // Header, fields, the line before the nodes and the hint.+ const room = Math.max(1, height - 9);+ const shown = f.nodes.slice(0, room);+ return (+ <Box flexDirection="column" height={height} overflow="hidden">+ <Text>+ <Text bold>{f.vulnId}</Text> <SeverityText severity={f.severity} />+ <Text color={style.color}> {style.label}</Text>+ </Text>+ <Field name="package">+ {f.source === "kernel" ? "the kernel" : f.package} {f.installed.join(", ")}+ {f.fixed ? `, fixed in ${f.fixed}` : ", no fixed version yet"}+ </Field>+ <Field name="source">{f.source === "kernel" ? "kernel_vulns, by kernel release" : "the image's SBOM, by its scan"}</Field>+ <Field name="shield">{f.upatchId || "no upatch is linked to the advisory"}</Field>+ <Field name="nodes">+ {f.affected} of {f.total} affected · <Text color="green">{f.shielded} shielded</Text> · {f.pending} coming ·{" "}+ {f.idle} not taking it · {f.withdrawn} withdrawn · {f.unshielded} without one+ </Field>+ {f.stale && <Text color="red">an image's newest scan is older than sbom_stale_seconds</Text>}+ <Box marginTop={1} flexDirection="column">+ <Text dimColor>+ {"NODE".padEnd(14)}+ {"EXPOSURE".padEnd(22)}+ {"IMAGE".padEnd(22)}+ {"INSTALLED".padEnd(12)}+ {"BINDING".padEnd(14)}STATUS+ </Text>+ {shown.map((n) => {+ const e = EXPOSURE_TEXT[n.exposure];+ return (+ <Text key={n.akName} wrap="truncate-end">+ <Text bold>{n.name.padEnd(14)}</Text>+ <Text color={e.color}>{e.text.padEnd(22)}</Text>+ <Text color="cyan">{`${n.imageId} ${n.imageVersion}`.trim().padEnd(22)}</Text>+ {n.installed.padEnd(12)}+ <Text dimColor>{n.binding.padEnd(14)}</Text>+ {n.status}+ </Text>+ );+ })}+ {f.nodes.length > shown.length && <Text dimColor>and {f.nodes.length - shown.length} more</Text>}+ </Box>+ <Text dimColor>esc back</Text>+ </Box>+ );+}diff --git a/tools/xtop/src/components/SbomView.tsx b/tools/xtop/src/components/SbomView.tsxnew file mode 100644index 00000000..53ae0265--- /dev/null+++ b/tools/xtop/src/components/SbomView.tsx@@ -0,0 +1,367 @@+// SPDX-License-Identifier: BSD-2-Clause+// Copyright (c) 2026 Authors of shirudo+//+// What the SBOMs and kernels say is vulnerable on the nodes, one row per+// finding, or the images of the SBOM store and how far they are scanned.+// Enter on a finding shows its nodes; on an image, its findings.++import { useState } from "react";+import { Box, Text, useInput } from "ink";+import type { Backend } from "../lib/backend.ts";+import { ago } from "../lib/format.ts";+import { useRefreshing } from "../lib/useRefreshing.ts";+import {+ FINDING_STATUS_RANK,+ IMAGE_STATES,+ imageKey,+ type Finding,+ type FindingStatus,+ type ImageState,+ type ImagesReport,+ type SbomImage,+ type SbomReport,+} from "../lib/sbom.ts";+import { severityRank } from "../lib/shields.ts";+import { DataTable, Tabs, type Column } from "./DataTable.tsx";+import { FindingDetail } from "./FindingDetail.tsx";+import { FINDING_STATUS_STYLE, IMAGE_STATE_COLOR, SeverityText } from "./style.tsx";++export type SbomMode = "findings" | "images";++type Props = {+ backend: Backend;+ mode: SbomMode;+ onModeChange: (mode: SbomMode) => void;+ /** Lines available inside the panel. */+ height: number;+ active: boolean;+ onClose: () => void;+ onSearchingChange: (searching: boolean) => void;+ /** A finding's nodes are open. */+ onDetailChange?: (open: boolean) => void;+};++function FindingStatusCell({ f }: { f: Finding }) {+ const style = FINDING_STATUS_STYLE[f.status];+ return (+ <>+ <Text color={style.color}>{style.label}</Text>+ {f.status !== "no_shield" && f.status !== "shielded" && (+ <Text dimColor>+ {" "}+ {f.shielded}/{f.affected}+ </Text>+ )}+ </>+ );+}++// ---- findings --------------------------------------------------------------++const FINDING_COLUMNS: readonly Column<Finding>[] = [+ {+ id: "severity",+ title: "SEVERITY",+ width: 10,+ defaultDir: "asc",+ sortKey: (f) => severityRank(f.severity),+ render: (f) => <SeverityText severity={f.severity} />,+ },+ {+ id: "id",+ title: "VULNERABILITY",+ width: 18,+ defaultDir: "asc",+ sortKey: (f) => f.vulnId,+ render: (f) => <Text bold>{f.vulnId}</Text>,+ },+ {+ id: "package",+ title: "PACKAGE",+ defaultDir: "asc",+ sortKey: (f) => f.package,+ render: (f) => (+ <>+ <Text color={f.source === "kernel" ? "magenta" : "cyan"}>{f.source === "kernel" ? "kernel" : f.package}</Text>+ <Text dimColor> {f.installed.join(", ")}</Text>+ </>+ ),+ },+ {+ id: "fixed",+ title: "FIXED IN",+ width: 12,+ defaultDir: "asc",+ sortKey: (f) => f.fixed,+ render: (f) => (f.fixed ? <Text color="green">{f.fixed}</Text> : <Text dimColor>none yet</Text>),+ },+ {+ id: "nodes",+ title: "NODES",+ width: 9,+ align: "right",+ defaultDir: "desc",+ sortKey: (f) => f.affected,+ render: (f) => (+ <Text>+ <Text bold>{f.affected}</Text>+ <Text dimColor>/{f.total}</Text>+ </Text>+ ),+ },+ {+ id: "shield",+ title: "SHIELD",+ width: 14,+ defaultDir: "asc",+ sortKey: (f) => f.upatchId || "~",+ render: (f) => (f.upatchId ? <Text>{f.upatchId}</Text> : <Text dimColor>—</Text>),+ },+ {+ id: "status",+ title: "STATUS",+ width: 15,+ defaultDir: "asc",+ sortKey: (f) => FINDING_STATUS_RANK[f.status],+ render: (f) => <FindingStatusCell f={f} />,+ },+];++const findingMatches = (f: Finding, q: string) =>+ [+ f.vulnId,+ f.package,+ f.severity,+ f.source,+ f.upatchId,+ f.status,+ ...f.installed,+ ...f.nodes.flatMap((n) => [n.name, `${n.imageId} ${n.imageVersion}`]),+ ].some((s) => s.toLowerCase().includes(q));++const findingTiebreak = (a: Finding, b: Finding) =>+ severityRank(a.severity) - severityRank(b.severity) || b.affected - a.affected || a.vulnId.localeCompare(b.vulnId);++// ---- images ----------------------------------------------------------------++const STATE_RANK = Object.fromEntries(IMAGE_STATES.map((s, i) => [s, i])) as Record<ImageState, number>;++const IMAGE_COLUMNS: readonly Column<SbomImage>[] = [+ {+ id: "state",+ title: "STATE",+ width: 19,+ defaultDir: "asc",+ sortKey: (i) => STATE_RANK[i.state] * 2 + (i.stale ? 0 : 1),+ render: (i) => (+ <>+ <Text color={IMAGE_STATE_COLOR[i.state]}>{i.state}</Text>+ {i.stale && <Text color="red"> stale</Text>}+ </>+ ),+ },+ {+ id: "image",+ title: "IMAGE",+ defaultDir: "asc",+ sortKey: imageKey,+ render: (i) => (+ <>+ <Text color="cyan">{imageKey(i)}</Text>+ <Text dimColor> {i.imageRoot ? i.imageRoot.slice(0, 8) : "no root"}</Text>+ </>+ ),+ },+ {+ id: "nodes",+ title: "NODES",+ width: 6,+ align: "right",+ defaultDir: "desc",+ sortKey: (i) => i.nodes,+ render: (i) => <Text>{i.nodes}</Text>,+ },+ {+ id: "findings",+ title: "FINDINGS",+ width: 16,+ defaultDir: "desc",+ sortKey: (i) => i.critical * 1e6 + i.high * 1e3 + i.vulns,+ render: (i) =>+ i.state !== "ok" ? (+ <Text dimColor>—</Text>+ ) : (+ <>+ <Text>{i.vulns}</Text>+ {i.critical > 0 && <Text color="red"> {i.critical} crit</Text>}+ {i.high > 0 && <Text color="red"> {i.high} high</Text>}+ </>+ ),+ },+ {+ id: "scanned",+ title: "SCANNED",+ width: 8,+ align: "right",+ defaultDir: "desc",+ sortKey: (i) => i.scannedAt?.getTime() ?? 0,+ render: (i) =>+ i.scannedAt ? <Text color={i.stale ? "red" : undefined}>{ago(i.scannedAt)}</Text> : <Text dimColor>never</Text>,+ },+ {+ id: "db",+ title: "DATABASE",+ width: 21,+ defaultDir: "desc",+ sortKey: (i) => i.dbVersion,+ render: (i) => <Text dimColor>{i.dbVersion || "—"}</Text>,+ },+];++const imageMatches = (i: SbomImage, q: string) =>+ [imageKey(i), i.imageRoot, i.state, i.sbomSha256, i.dbVersion, i.stale ? "stale" : ""].some((s) =>+ s.toLowerCase().includes(q),+ );++// ---- view ------------------------------------------------------------------++export function SbomView({ backend, mode, onModeChange, height, active, onClose, onSearchingChange, onDetailChange }: Props) {+ const [reload, setReload] = useState(0);+ const findings = useRefreshing<SbomReport>(mode === "findings", reload, () => backend.getSbom());+ const images = useRefreshing<ImagesReport>(mode === "images", reload, () => backend.getSbomImages());+ const [searching, setSearching] = useState(false);+ // Set when drilling into an image; seeds the findings table's search.+ const [drill, setDrill] = useState("");+ const [onTabs, setOnTabs] = useState(false);+ const [detail, setDetail] = useState<string | null>(null);+ const keyOf = (f: Finding) => `${f.vulnId}\0${f.package}`;+ const detailFinding = detail ? (findings.data?.findings.find((f) => keyOf(f) === detail) ?? null) : null;++ const showDetail = (key: string | null) => {+ setDetail(key);+ onDetailChange?.(key !== null);+ };+ const reportSearching = (s: boolean) => {+ setSearching(s);+ onSearchingChange(s);+ };+ const switchTo = (m: SbomMode, fromTabs = false) => {+ setDrill("");+ setOnTabs(fromTabs);+ onModeChange(m);+ };+ const modes: SbomMode[] = ["findings", "images"];+ const tabs = {+ labels: ["findings", "images"],+ selected: modes.indexOf(mode),+ onSelect: (i: number) => switchTo(modes[i]!, true),+ };++ useInput(+ (input) => {+ if (input === "t") switchTo(mode === "findings" ? "images" : "findings");+ if (input === "r") setReload((r) => r + 1);+ },+ { isActive: active && !searching && !detail },+ );++ const tableHeight = Math.max(4, height);+ const query = mode === "findings" ? findings : images;+ if (!query.data)+ return (+ <Box flexDirection="column">+ <Tabs labels={tabs.labels} selected={tabs.selected} />+ {query.error ? <Text color="red">{mode} query failed: {query.error}</Text> : <Text dimColor>querying backend…</Text>}+ </Box>+ );+ const status = (generatedAt: Date) => (+ <>+ <Text dimColor> · as of {generatedAt.toTimeString().slice(0, 8)}</Text>+ {query.loading && <Text dimColor> · querying…</Text>}+ </>+ );+ const failed = query.error && <Text color="red">refresh failed: {query.error} · </Text>;++ if (mode === "images") {+ const report = images.data!;+ return (+ <DataTable+ tabs={tabs}+ startOnTabs={onTabs}+ footerHint="t findings · r refresh"+ rows={report.images}+ columns={IMAGE_COLUMNS}+ rowKey={(i) => `${imageKey(i)} ${i.imageRoot}`}+ height={tableHeight}+ active={active}+ initialSort={{ col: "state", dir: "asc" }}+ tiebreak={(a, b) => b.nodes - a.nodes || imageKey(a).localeCompare(imageKey(b))}+ matches={imageMatches}+ onSearchingChange={reportSearching}+ onClose={onClose}+ onOpen={(i) => {+ setOnTabs(false);+ setDrill(imageKey(i));+ onModeChange("findings");+ }}+ summary={(rows, sortedBy) => {+ const count = (s: ImageState) => rows.filter((i) => i.state === s).length;+ const bad = rows.filter((i) => i.state !== "ok" && i.state !== "no_sbom").length;+ return (+ <>+ {failed}+ <Text bold>{rows.length}</Text> images · <Text color="green">{count("ok")} scanned</Text> ·{" "}+ <Text color="red">{rows.filter((i) => i.stale).length} stale</Text> · <Text color="red">{bad} refused</Text> ·{" "}+ <Text color="yellow">{count("no_sbom")} without an SBOM</Text>+ <Text dimColor> · sorted by {sortedBy}</Text>+ {status(report.generatedAt)}+ </>+ );+ }}+ />+ );+ }++ const report = findings.data!;+ return (+ <Box flexDirection="column">+ {detail && <FindingDetail finding={detailFinding} 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+ key={`findings:${drill}`}+ tabs={tabs}+ startOnTabs={onTabs}+ footerHint="t images · r refresh"+ rows={report.findings}+ columns={FINDING_COLUMNS}+ rowKey={keyOf}+ height={tableHeight}+ active={active && !detail}+ initialSort={{ col: "status", dir: "asc" }}+ initialQuery={drill}+ tiebreak={findingTiebreak}+ matches={findingMatches}+ onSearchingChange={reportSearching}+ onClose={onClose}+ onOpen={(f) => showDetail(keyOf(f))}+ summary={(rows, sortedBy) => {+ const count = (s: FindingStatus) => rows.filter((f) => f.status === s).length;+ const stale = rows.some((f) => f.stale);+ return (+ <>+ {failed}+ <Text bold>{rows.length}</Text> findings · <Text color="red">{count("no_shield")} no shield</Text> ·{" "}+ <Text color="yellow">{count("partial")} partial</Text> · <Text color="yellow">{count("pending")} pending</Text> ·{" "}+ <Text color="green">{count("shielded")} shielded</Text>+ {stale && <Text color="red"> · from a stale scan</Text>}+ <Text dimColor> · sorted by {sortedBy}</Text>+ {status(report.generatedAt)}+ </>+ );+ }}+ />+ </Box>+ </Box>+ );+}diff --git a/tools/xtop/src/components/style.tsx b/tools/xtop/src/components/style.tsxindex 6ae872b2..87134b24 100644--- a/tools/xtop/src/components/style.tsx+++ b/tools/xtop/src/components/style.tsx@@ -3,6 +3,7 @@import { Text } from "ink";import type { NodeStatus } from "../lib/fleet.ts";+import type { FindingStatus, ImageState } from "../lib/sbom.ts";import type { ShieldStatus } from "../lib/shields.ts";export const STATUS_STYLE: Record<NodeStatus, { icon: string; color: string }> = {@@ -32,3 +33,19 @@ export function SeverityText({ severity }: { severity: string }) {</Text>);}++export const FINDING_STATUS_STYLE: Record<FindingStatus, { label: string; color: string }> = {+ no_shield: { label: "no shield", color: "red" },+ partial: { label: "partial", color: "yellow" },+ pending: { label: "pending", color: "yellow" },+ shielded: { label: "shielded", color: "green" },+};++export const IMAGE_STATE_COLOR: Record<ImageState, string> = {+ ok: "green",+ missing: "red",+ hash_mismatch: "red",+ parse_error: "red",+ unsupported_format: "red",+ no_sbom: "yellow",+};diff --git a/tools/xtop/src/lib/backend.ts b/tools/xtop/src/lib/backend.tsindex e210a960..095ccac3 100644--- a/tools/xtop/src/lib/backend.ts+++ b/tools/xtop/src/lib/backend.ts@@ -5,15 +5,32 @@import NODES_SQL from "../../sql/nodes.sql" with { type: "text" };import SHIELDS_SQL from "../../sql/shields.sql" with { type: "text" };+import SBOM_SQL from "../../sql/sbom.sql" with { type: "text" };+import SBOM_IMAGES_SQL from "../../sql/sbom-images.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";+import {+ EXPOSURES,+ IMAGE_STATES,+ findingStatus,+ type Exposure,+ type Finding,+ type ImageState,+ type ImagesReport,+ type SbomImage,+ type SbomReport,+} from "./sbom.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>;+ /** Every finding of shirudo.node_vulns, with the nodes it affects. */+ getSbom(): Promise<SbomReport>;+ /** Every image of shirudo.sbom_images, and those nodes run without an SBOM. */+ getSbomImages(): Promise<ImagesReport>;}/** A row of sql/nodes.sql. */@@ -134,6 +151,96 @@ export function toShield(r: ShieldRow): Shield {};}+/** A row of sql/sbom.sql. */+export type FindingRow = {+ vuln_id: string;+ package: string;+ severity: string;+ source: string;+ fixed: string;+ installed: string[];+ affected: number;+ total: number;+ upatch_id: string;+ shielded: number;+ pending: number;+ idle: number;+ withdrawn: number;+ unshielded: number;+ stale: boolean | number;+ /** (node_id, ak_name, exposure, image_id, image_version, installed, binding, status) */+ nodes: [string, string, string, string, string, string, string, string][];+};++export function toFinding(r: FindingRow): Finding {+ const f = {+ vulnId: r.vuln_id,+ package: r.package,+ severity: r.severity,+ source: r.source,+ fixed: r.fixed,+ installed: r.installed,+ affected: r.affected,+ total: r.total,+ upatchId: r.upatch_id,+ shielded: r.shielded,+ pending: r.pending,+ idle: r.idle,+ withdrawn: r.withdrawn,+ unshielded: r.unshielded,+ stale: Boolean(r.stale),+ nodes: r.nodes.map(([name, akName, exposure, imageId, imageVersion, installed, binding, status]) => ({+ name,+ akName,+ exposure: oneOf<Exposure>(EXPOSURES, exposure, "exposure"),+ imageId,+ imageVersion,+ installed,+ binding,+ status,+ })),+ };+ return { ...f, status: findingStatus(f) };+}++/** A row of sql/sbom-images.sql. */+export type ImageRow = {+ image_id: string;+ image_version: string;+ image_root: string;+ state: string;+ sbom_format: string;+ sbom_sha256: string;+ built_ms: number;+ scanned_ms: number;+ db_version: string;+ stale: boolean | number;+ vulns: number;+ critical: number;+ high: number;+ nodes: number;+};++export function toSbomImage(r: ImageRow): SbomImage {+ return {+ imageId: r.image_id,+ imageVersion: r.image_version,+ imageRoot: r.image_root,+ state: oneOf<ImageState>(IMAGE_STATES, r.state, "image state"),+ sbomFormat: r.sbom_format,+ sbomSha256: r.sbom_sha256,+ // A row without a scan, or a build time sbom-scan could not read, has 0.+ builtAt: r.built_ms ? new Date(r.built_ms) : null,+ scannedAt: r.scanned_ms ? new Date(r.scanned_ms) : null,+ dbVersion: r.db_version,+ stale: Boolean(r.stale),+ vulns: r.vulns,+ critical: r.critical,+ high: r.high,+ nodes: r.nodes,+ };+}+export class ClickHouseBackend implements Backend {constructor(private readonly cfg: ClickHouseConfig) {}@@ -145,4 +252,14 @@ export class ClickHouseBackend implements Backend {const rows = await queryRows<ShieldRow>(this.cfg, SHIELDS_SQL);return { generatedAt: new Date(), shields: rows.map(toShield) };}++ async getSbom(): Promise<SbomReport> {+ const rows = await queryRows<FindingRow>(this.cfg, SBOM_SQL);+ return { generatedAt: new Date(), findings: rows.map(toFinding) };+ }++ async getSbomImages(): Promise<ImagesReport> {+ const rows = await queryRows<ImageRow>(this.cfg, SBOM_IMAGES_SQL);+ return { generatedAt: new Date(), images: rows.map(toSbomImage) };+ }}diff --git a/tools/xtop/src/lib/sbom.ts b/tools/xtop/src/lib/sbom.tsnew file mode 100644index 00000000..e52cdd62--- /dev/null+++ b/tools/xtop/src/lib/sbom.ts@@ -0,0 +1,116 @@+// SPDX-License-Identifier: BSD-2-Clause+// Copyright (c) 2026 Authors of shirudo+//+// What the SBOMs of the images, and the kernels, say is vulnerable on the+// nodes, from node_vulns, and how far the SBOM store is scanned, from+// sbom_images.++/** node_vulns.exposure of one node. */+export type Exposure =+ | "shielded"+ | "shield_pending"+ | "shield_module_absent"+ | "shield_excludes_node"+ | "shield_withdrawn"+ | "exposed_no_shield"+ | "none"+ | "unknown";++export const EXPOSURES: readonly Exposure[] = [+ "shielded",+ "shield_pending",+ "shield_module_absent",+ "shield_excludes_node",+ "shield_withdrawn",+ "exposed_no_shield",+ "none",+ "unknown",+];++export type FindingNode = {+ name: string;+ akName: string;+ exposure: Exposure;+ imageId: string;+ imageVersion: string;+ installed: string;+ /** How the node's image was bound to an SBOM: verified, declared, ... */+ binding: string;+ /** The node's status in node_status. */+ status: string;+};++/**+ * no_shield when no upatch is linked to the advisory, shielded when it+ * shields every affected node, pending while it is still coming to one,+ * partial when it leaves some out.+ */+export type FindingStatus = "no_shield" | "partial" | "pending" | "shielded";++export const FINDING_STATUS_RANK: Record<FindingStatus, number> = { no_shield: 0, partial: 1, pending: 2, shielded: 3 };++export type Finding = {+ vulnId: string;+ package: string;+ severity: string;+ /** kernel for an advisory matched on the kernel release, sbom for one in an image's SBOM. */+ source: string;+ fixed: string;+ installed: string[];+ affected: number;+ /** Nodes in node_status. */+ total: number;+ upatchId: string;+ shielded: number;+ pending: number;+ /** Selector left the node out, or the module the shield attaches to is not loaded. */+ idle: number;+ withdrawn: number;+ unshielded: number;+ /** An image's newest scan is older than sbom_stale_seconds. */+ stale: boolean;+ nodes: FindingNode[];+ status: FindingStatus;+};++export type SbomReport = { generatedAt: Date; findings: Finding[] };++export type ImageState = "ok" | "missing" | "hash_mismatch" | "parse_error" | "unsupported_format" | "no_sbom";++export const IMAGE_STATES: readonly ImageState[] = [+ "parse_error",+ "hash_mismatch",+ "missing",+ "unsupported_format",+ "no_sbom",+ "ok",+];++export type SbomImage = {+ imageId: string;+ imageVersion: string;+ /** Empty for an image built without verity. */+ imageRoot: string;+ state: ImageState;+ sbomFormat: string;+ sbomSha256: string;+ builtAt: Date | null;+ scannedAt: Date | null;+ dbVersion: string;+ stale: boolean;+ vulns: number;+ critical: number;+ high: number;+ /** Nodes whose newest record names the image. */+ nodes: number;+};++export type ImagesReport = { generatedAt: Date; images: SbomImage[] };++export function findingStatus(f: Pick<Finding, "upatchId" | "affected" | "shielded" | "pending">): FindingStatus {+ if (!f.upatchId) return "no_shield";+ if (f.shielded >= f.affected) return "shielded";+ return f.pending ? "pending" : "partial";+}++export const imageKey = (i: Pick<SbomImage, "imageId" | "imageVersion">) => `${i.imageId} ${i.imageVersion}`;diff --git a/tools/xtop/test/sbom.test.ts b/tools/xtop/test/sbom.test.tsnew file mode 100644index 00000000..51476e01--- /dev/null+++ b/tools/xtop/test/sbom.test.ts@@ -0,0 +1,128 @@+// SPDX-License-Identifier: BSD-2-Clause+// Copyright (c) 2026 Authors of shirudo+//+// The rows of sql/sbom.sql and sql/sbom-images.sql as+// tools/backend/test/xtop-sbom.expected has them, turned into findings+// and images.++import { describe, expect, test } from "bun:test";+import { toFinding, toSbomImage, type FindingRow, type ImageRow } from "../src/lib/backend.ts";+import { findingStatus } from "../src/lib/sbom.ts";++const ROOT = "a3c3f1b0e4c2d7f09e3b6b2a8b1d5e7c4f6a9d0b2c8e1f3a5b7d9c0e2f4a6b8c";++function finding(over: Partial<FindingRow>): FindingRow {+ return {+ vuln_id: "EXAMPLE-0101",+ package: "linux",+ severity: "CRITICAL",+ source: "kernel",+ fixed: "7.4.5",+ installed: ["7.4.2"],+ affected: 4,+ total: 5,+ upatch_id: "xfs-fix",+ shielded: 2,+ pending: 0,+ idle: 2,+ withdrawn: 0,+ unshielded: 0,+ stale: false,+ nodes: [+ ["node-a", "000b23602ab98bfb", "shielded", "fleet-os", "2026.11.1", "7.4.2", "verified", "healthy"],+ ["node-b", "000b9d72e08380a1", "shield_excludes_node", "fleet-os", "2026.11.1", "7.4.2", "declared", "healthy"],+ ],+ ...over,+ };+}++function image(over: Partial<ImageRow>): ImageRow {+ return {+ image_id: "fleet-os",+ image_version: "2026.11.1",+ image_root: ROOT,+ state: "ok",+ sbom_format: "cyclonedx-json",+ sbom_sha256: "5b0e2c8a4f6d1e3b7a9c0d2e4f6a8b1c3d5e7f9a0b2c4d6e8f1a3b5c7d9e91d4",+ built_ms: 1_793_606_400_000,+ scanned_ms: 1_795_053_039_000,+ db_version: "2",+ stale: 0,+ vulns: 1,+ critical: 0,+ high: 1,+ nodes: 4,+ ...over,+ };+}++describe("toFinding", () => {+ test("a kernel finding the shield covers on some nodes is partial", () => {+ const f = toFinding(finding({}));+ expect(f.status).toBe("partial");+ expect(f.nodes[1]).toEqual({+ name: "node-b",+ akName: "000b9d72e08380a1",+ exposure: "shield_excludes_node",+ imageId: "fleet-os",+ imageVersion: "2026.11.1",+ installed: "7.4.2",+ binding: "declared",+ status: "healthy",+ });+ });++ test("a shield still coming is pending", () => {+ const f = toFinding(finding({ vuln_id: "EXAMPLE-0202", upatch_id: "ssl-fix", shielded: 0, pending: 4, idle: 0 }));+ expect(f.status).toBe("pending");+ });++ test("no linked upatch is no shield; one on every node shielded", () => {+ expect(toFinding(finding({ upatch_id: "", shielded: 0, idle: 0, unshielded: 4 })).status).toBe("no_shield");+ expect(toFinding(finding({ shielded: 4, idle: 0 })).status).toBe("shielded");+ });++ test("reads stale as a Bool or a number", () => {+ expect(toFinding(finding({ stale: 1 })).stale).toBe(true);+ expect(toFinding(finding({ stale: false })).stale).toBe(false);+ });++ test("refuses an exposure it does not know", () => {+ expect(() =>+ toFinding(finding({ nodes: [["n", "k", "patched", "", "", "", "verified", "healthy"]] })),+ ).toThrow(/unknown exposure/);+ });+});++describe("findingStatus", () => {+ test("ranks by what the shield does", () => {+ expect(findingStatus({ upatchId: "", affected: 2, shielded: 0, pending: 0 })).toBe("no_shield");+ expect(findingStatus({ upatchId: "u", affected: 2, shielded: 1, pending: 1 })).toBe("pending");+ expect(findingStatus({ upatchId: "u", affected: 2, shielded: 1, pending: 0 })).toBe("partial");+ expect(findingStatus({ upatchId: "u", affected: 2, shielded: 2, pending: 0 })).toBe("shielded");+ });+});++describe("toSbomImage", () => {+ test("a scanned image", () => {+ const i = toSbomImage(image({}));+ expect(i.state).toBe("ok");+ expect(i.stale).toBe(false);+ expect(i.builtAt?.getTime()).toBe(1_793_606_400_000);+ expect(i.scannedAt?.getTime()).toBe(1_795_053_039_000);+ expect(i.nodes).toBe(4);+ });++ test("an image nodes run without an SBOM has no times", () => {+ const i = toSbomImage(+ image({ image_root: "", state: "no_sbom", sbom_format: "", sbom_sha256: "", built_ms: 0, scanned_ms: 0, db_version: "", vulns: 0, high: 0, nodes: 1 }),+ );+ expect(i.state).toBe("no_sbom");+ expect(i.builtAt).toBeNull();+ expect(i.scannedAt).toBeNull();+ });++ test("refuses a state it does not know", () => {+ expect(() => toSbomImage(image({ state: "scanning" }))).toThrow(/unknown image state/);+ });+});