Skip to content

eBPF-based security platform

tools/xtop: search tables by regular expressions, with terms that exclude

John Fastabend749fa6a259b1
diff --git a/Documentation/contribute/testing/test-coverage.rst b/Documentation/contribute/testing/test-coverage.rst
index 863e3726..28dd796d 100644
--- a/Documentation/contribute/testing/test-coverage.rst
+++ b/Documentation/contribute/testing/test-coverage.rst
@@ -993,7 +993,8 @@ findings and images of their SBOMs (``test/xtop-nodes``,
The unit tests of :src:`tools/xtop/test/` cover how xtop turns the rows
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 the
+status of a finding, the search of its tables and its ClickHouse client;
+``make -C tools/xtop tests`` type-checks the
program and runs them (:ref:`testing-xtop`).
Coverage by area
diff --git a/Documentation/operate/backend/xtop.rst b/Documentation/operate/backend/xtop.rst
index 82d6f93c..d605b250 100644
--- a/Documentation/operate/backend/xtop.rst
+++ b/Documentation/operate/backend/xtop.rst
@@ -64,6 +64,15 @@ A view queries when it opens, every minute after that, as often as
query that fails leaves the rows of the last one in place and says why
at the start of the summary line.
+``/`` searches a table; each view below says which fields. The search is
+terms separated by blanks, all of which a row must meet. A term is a
+regular expression, of JavaScript's syntax and ignoring case, that one of
+the fields must match; after a leading ``!``, none may. A term that is
+no regular expression is matched as text, and the search line says so.
+In SBOM, ``!^linux`` leaves out the findings of the packages whose names
+start with ``linux``, and ``high !^linux`` keeps the high ones of the
+rest. Enter keeps the search, Esc clears it.
+
Read the nodes
--------------
@@ -222,7 +231,9 @@ kernel release (:doc:`exposure`).
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.
+version, the binding of its image to an SBOM and its status. ``/``
+searches the advisory, package, severity, source, shield, status, the
+installed versions, and the names and images of the nodes it affects.
``t`` switches to the images: every image of ``sbom_images`` at its
newest scan, with its state (:doc:`sbom-scan`), ``stale`` when that scan
diff --git a/tools/xtop/src/App.tsx b/tools/xtop/src/App.tsx
index 610772be..177d52e7 100644
--- a/tools/xtop/src/App.tsx
+++ b/tools/xtop/src/App.tsx
@@ -31,7 +31,7 @@ const HINTS: Record<Focus, string> = {
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",
+ search: "regexes, all must match · !re drops matches · enter keep · esc clear",
};
export function App({ backend }: { backend: Backend }) {
diff --git a/tools/xtop/src/components/DataTable.tsx b/tools/xtop/src/components/DataTable.tsx
index 6aa0010a..957bee31 100644
--- a/tools/xtop/src/components/DataTable.tsx
+++ b/tools/xtop/src/components/DataTable.tsx
@@ -4,6 +4,7 @@
import { useEffect, useMemo, useRef, useState, type ReactNode } from "react";
import { Box, Text, measureElement, useInput, usePaste, type DOMElement } from "ink";
import { useMouse } from "../lib/useMouse.ts";
+import { parseSearch } from "../lib/search.ts";
export type SortDir = "asc" | "desc";
@@ -32,8 +33,8 @@ type Props<T> = {
tiebreak?: (a: T, b: T) => number;
/** Line above the table; receives the visible (filtered, sorted) rows. */
summary?: (rows: readonly T[], sortedBy: string) => ReactNode;
- /** Enables `/` search; returns whether a row matches the lowercased query. */
- matches?: (row: T, query: string) => boolean;
+ /** Enables `/` search (lib/search.ts) over the fields a row gives. */
+ searchFields?: (row: T) => readonly string[];
/** Search text to start with (e.g. when drilling into a group). */
initialQuery?: string;
/**
@@ -105,7 +106,7 @@ export function DataTable<T>({
initialSort,
tiebreak,
summary,
- matches,
+ searchFields,
initialQuery = "",
tabs,
startOnTabs = false,
@@ -127,17 +128,17 @@ export function DataTable<T>({
useEffect(() => onSearchingChange?.(searching), [searching, onSearchingChange]);
useEffect(() => () => onSearchingChange?.(false), [onSearchingChange]);
+ const search = useMemo(() => parseSearch(query), [query]);
const rows = useMemo(() => {
const col = columns.find((c) => c.id === sort.col) ?? columns[0]!;
const sign = sort.dir === "asc" ? 1 : -1;
- const q = query.trim().toLowerCase();
return input
- .filter((r) => !q || !matches || matches(r, q))
+ .filter((r) => !searchFields || search.test(searchFields(r)))
.sort((a, b) => sign * compare(col.sortKey(a), col.sortKey(b)) || (tiebreak?.(a, b) ?? 0));
- }, [input, columns, sort, query, matches, tiebreak]);
+ }, [input, columns, sort, search, searchFields, tiebreak]);
// Tabs, summary, search, header and scroll footer each take a line.
- const chrome = (tabs ? 1 : 0) + (summary ? 1 : 0) + (matches ? 1 : 0) + 2;
+ const chrome = (tabs ? 1 : 0) + (summary ? 1 : 0) + (searchFields ? 1 : 0) + 2;
const visible = Math.max(1, height - chrome);
const last = rows.length - 1;
@@ -209,7 +210,7 @@ export function DataTable<T>({
else if (c === "k") move(-1);
else if (c === "g") setCursor(0);
else if (c === "G") setCursor(last);
- else if (c === "/" && matches) setSearching(true);
+ else if (c === "/" && searchFields) setSearching(true);
}
}
},
@@ -233,7 +234,7 @@ export function DataTable<T>({
});
if (i >= 0) return i !== tabs.selected && tabs.onSelect(i);
}
- if (matches && e.y === headerY - 1) return setSearching(true);
+ if (searchFields && e.y === headerY - 1) return setSearching(true);
if (e.y === headerY) {
const i = headerRefs.current.findIndex((el) => {
if (!el) return false;
@@ -260,12 +261,13 @@ export function DataTable<T>({
<Box flexDirection="column">
{tabs && <Tabs labels={tabs.labels} selected={tabs.selected} focused={active && cursor === TABS ? tabFocus : null} tabRefs={tabRefs} />}
{summary && <Text wrap="truncate-end">{summary(rows, sortedBy)}</Text>}
- {matches && (
+ {searchFields && (
<Text wrap="truncate-end">
<Text color={searching ? "cyan" : "gray"}>/ </Text>
{query ? <Text>{query}</Text> : !searching && <Text dimColor>search</Text>}
{searching && <Text inverse> </Text>}
{query && !searching && <Text dimColor> esc clears</Text>}
+ {search.invalid.length > 0 && <Text color="yellow"> not a regex, taken as text: {search.invalid.join(" ")}</Text>}
</Text>
)}
<Box>
diff --git a/tools/xtop/src/components/NodesView.tsx b/tools/xtop/src/components/NodesView.tsx
index dfdc0c34..a0fab65e 100644
--- a/tools/xtop/src/components/NodesView.tsx
+++ b/tools/xtop/src/components/NodesView.tsx
@@ -27,6 +27,7 @@ import { NodeDetail } from "./NodeDetail.tsx";
import { HealthCell } from "./MiniBar.tsx";
import { ago } from "../lib/format.ts";
import { useRefreshing } from "../lib/useRefreshing.ts";
+import { literalSearch } from "../lib/search.ts";
import { STATUS_STYLE } from "./style.tsx";
export type NodesMode = "nodes" | "images";
@@ -155,7 +156,7 @@ const NODE_COLUMNS: readonly Column<FleetNode>[] = [
},
];
-const nodeMatches = (n: FleetNode, q: string) =>
+const nodeFields = (n: FleetNode) =>
[
n.name,
n.hostName,
@@ -168,7 +169,7 @@ const nodeMatches = (n: FleetNode, q: string) =>
n.failedCheck ? (n.log[n.failedCheck - 1] ?? "") : "",
...labelPairs(n.labels),
n.labelConflicts.length ? "label conflict" : "",
- ].some((s) => s.toLowerCase().includes(q));
+ ];
// ---- per-image table -------------------------------------------------------
@@ -243,8 +244,8 @@ const IMAGE_COLUMNS: readonly Column<ImageGroup>[] = [
},
];
-const imageMatches = (g: ImageGroup, q: string) =>
- [g.key, g.status, g.kernel ?? "mixed", ...g.roles].some((s) => s.toLowerCase().includes(q));
+const imageFields = (g: ImageGroup) =>
+ [g.key, g.status, g.kernel ?? "mixed", ...g.roles];
// ---- view ------------------------------------------------------------------
@@ -341,7 +342,7 @@ export function NodesView({ backend, mode, onModeChange, height, active, onClose
initialSort={{ col: "status", dir: "asc" }}
initialQuery={drill}
tiebreak={(a, b) => b.failedCheck - a.failedCheck || a.name.localeCompare(b.name)}
- matches={nodeMatches}
+ searchFields={nodeFields}
onSearchingChange={reportSearching}
onClose={onClose}
onOpen={(n) => showDetail(n.akName)}
@@ -375,12 +376,12 @@ export function NodesView({ backend, mode, onModeChange, height, active, onClose
active={active && !detail}
initialSort={{ col: "status", dir: "asc" }}
tiebreak={(a, b) => a.health - b.health || b.nodes - a.nodes}
- matches={imageMatches}
+ searchFields={imageFields}
onSearchingChange={reportSearching}
onClose={onClose}
onOpen={(g) => {
setOnTabs(false);
- setDrill(g.key);
+ setDrill(literalSearch(g.key));
onModeChange("nodes");
}}
summary={(rows, sortedBy) => {
diff --git a/tools/xtop/src/components/SbomView.tsx b/tools/xtop/src/components/SbomView.tsx
index 25563017..d886872a 100644
--- a/tools/xtop/src/components/SbomView.tsx
+++ b/tools/xtop/src/components/SbomView.tsx
@@ -10,6 +10,7 @@ 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 { literalSearch } from "../lib/search.ts";
import {
FINDING_STATUS_RANK,
IMAGE_STATES,
@@ -128,7 +129,7 @@ const FINDING_COLUMNS: readonly Column<Finding>[] = [
},
];
-const findingMatches = (f: Finding, q: string) =>
+const findingFields = (f: Finding) =>
[
f.vulnId,
f.package,
@@ -138,7 +139,7 @@ const findingMatches = (f: Finding, q: string) =>
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);
@@ -219,10 +220,8 @@ const IMAGE_COLUMNS: readonly Column<SbomImage>[] = [
},
];
-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),
- );
+const imageFields = (i: SbomImage) =>
+ [imageKey(i), i.imageRoot, i.state, i.sbomSha256, i.dbVersion, i.stale ? "stale" : ""];
// ---- view ------------------------------------------------------------------
@@ -299,12 +298,12 @@ export function SbomView({ backend, mode, onModeChange, height, active, onClose,
active={active}
initialSort={{ col: "state", dir: "asc" }}
tiebreak={(a, b) => b.nodes - a.nodes || imageKey(a).localeCompare(imageKey(b))}
- matches={imageMatches}
+ searchFields={imageFields}
onSearchingChange={reportSearching}
onClose={onClose}
onOpen={(i) => {
setOnTabs(false);
- setDrill(imageKey(i));
+ setDrill(literalSearch(imageKey(i)));
onModeChange("findings");
}}
summary={(rows, sortedBy) => {
@@ -344,7 +343,7 @@ export function SbomView({ backend, mode, onModeChange, height, active, onClose,
initialSort={{ col: "status", dir: "asc" }}
initialQuery={drill}
tiebreak={findingTiebreak}
- matches={findingMatches}
+ searchFields={findingFields}
onSearchingChange={reportSearching}
onClose={onClose}
onOpen={(f) => showDetail(keyOf(f))}
diff --git a/tools/xtop/src/components/ShieldsView.tsx b/tools/xtop/src/components/ShieldsView.tsx
index cb6e23cd..99bd0b88 100644
--- a/tools/xtop/src/components/ShieldsView.tsx
+++ b/tools/xtop/src/components/ShieldsView.tsx
@@ -124,7 +124,7 @@ const COLUMNS: readonly Column<Shield>[] = [
},
];
-const matches = (s: Shield, q: string) =>
+const shieldFields = (s: Shield) =>
[
s.id,
s.treeId,
@@ -134,7 +134,7 @@ const matches = (s: Shield, q: string) =>
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);
@@ -189,7 +189,7 @@ export function ShieldsView({ backend, height, active, onClose, onSearchingChang
active={active && !detail}
initialSort={{ col: "status", dir: "asc" }}
tiebreak={tiebreak}
- matches={matches}
+ searchFields={shieldFields}
footerHint="r refresh"
onSearchingChange={reportSearching}
onClose={onClose}
diff --git a/tools/xtop/src/lib/search.ts b/tools/xtop/src/lib/search.ts
new file mode 100644
index 00000000..7bd96923
--- /dev/null
+++ b/tools/xtop/src/lib/search.ts
@@ -0,0 +1,45 @@
+// SPDX-License-Identifier: BSD-2-Clause
+// Copyright (c) 2026 Authors of shirudo
+
+/**
+ * A table search: terms separated by blanks, each of which a row must meet.
+ * A term is a case-insensitive regular expression that one of the row's
+ * fields must match, or, after a leading `!`, that none of them may. A term
+ * that is not a valid expression is taken as plain text, and named in
+ * `invalid`.
+ */
+export type Search = {
+ test: (fields: readonly string[]) => boolean;
+ invalid: readonly string[];
+};
+
+const escapeRegExp = (text: string) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+
+export const parseSearch = (query: string): Search => {
+ const invalid: string[] = [];
+ const terms = query
+ .split(/\s+/)
+ .filter((term) => term && term !== "!")
+ .map((term) => {
+ const exclude = term.startsWith("!");
+ const pattern = exclude ? term.slice(1) : term;
+ try {
+ return { exclude, re: new RegExp(pattern, "i") };
+ } catch {
+ invalid.push(term);
+ return { exclude, re: new RegExp(escapeRegExp(pattern), "i") };
+ }
+ });
+ return {
+ test: (fields) => terms.every(({ exclude, re }) => fields.some((f) => re.test(f)) !== exclude),
+ invalid,
+ };
+};
+
+/** A search for the words of text as they are, such as a name to drill into. */
+export const literalSearch = (text: string) =>
+ text
+ .split(/\s+/)
+ .filter(Boolean)
+ .map((word) => escapeRegExp(word).replace(/^!/, "\\!"))
+ .join(" ");
diff --git a/tools/xtop/test/search.test.ts b/tools/xtop/test/search.test.ts
new file mode 100644
index 00000000..c28405d2
--- /dev/null
+++ b/tools/xtop/test/search.test.ts
@@ -0,0 +1,55 @@
+// SPDX-License-Identifier: BSD-2-Clause
+// Copyright (c) 2026 Authors of shirudo
+//
+// The search of every table: regular expressions, all of which a row must
+// meet, and terms that exclude.
+
+import { describe, expect, test } from "bun:test";
+import { literalSearch, parseSearch } from "../src/lib/search.ts";
+
+const kernel = ["CVE-2025-0001", "linux-modules-7.0.0-43-generic", "HIGH"];
+const openssl = ["CVE-2025-0002", "openssl", "MEDIUM"];
+const filter = (query: string) => [kernel, openssl].filter((row) => parseSearch(query).test(row));
+
+describe("parseSearch", () => {
+ test("an empty query keeps every row", () => {
+ expect(filter("")).toEqual([kernel, openssl]);
+ expect(filter(" ! ")).toEqual([kernel, openssl]);
+ });
+
+ test("a term is a regular expression that any field may match, ignoring case", () => {
+ expect(filter("^linux-")).toEqual([kernel]);
+ expect(filter("ssl$")).toEqual([openssl]);
+ expect(filter("cve-2025-000[12]")).toEqual([kernel, openssl]);
+ });
+
+ test("a term after ! drops the rows it matches", () => {
+ expect(filter("!^linux")).toEqual([openssl]);
+ expect(filter("!cve")).toEqual([]);
+ });
+
+ test("every term must hold", () => {
+ expect(filter("cve !linux")).toEqual([openssl]);
+ expect(filter("high medium")).toEqual([]);
+ });
+
+ test("a term that is no regular expression is plain text", () => {
+ const search = parseSearch("openssl (");
+ expect(search.invalid).toEqual(["("]);
+ expect(search.test(["openssl ("])).toBe(true);
+ expect(search.test(openssl)).toBe(false);
+ });
+});
+
+describe("literalSearch", () => {
+ test("finds the text as it is", () => {
+ const query = literalSearch("fleet-os 1.0+b1");
+ expect(query).toBe("fleet-os 1\\.0\\+b1");
+ expect(parseSearch(query).test(["fleet-os 1.0+b1"])).toBe(true);
+ expect(parseSearch(query).test(["fleet-os 1x00b1"])).toBe(false);
+ });
+
+ test("a word starting with ! is searched for, not excluded", () => {
+ expect(parseSearch(literalSearch("!x")).test(["!x"])).toBe(true);
+ });
+});