Skip to content

eBPF-based security platform

tools/xtop: create a tree from the available shields

John Fastabend6211b1fe5cfd
diff --git a/Documentation/contribute/testing/test-coverage.rst b/Documentation/contribute/testing/test-coverage.rst
index 628853c0..3812fe2d 100644
--- a/Documentation/contribute/testing/test-coverage.rst
+++ b/Documentation/contribute/testing/test-coverage.rst
@@ -997,7 +997,8 @@ their SBOMs (``test/xtop-nodes``, ``test/xtop-shields``,
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, the search of its tables and its ClickHouse client;
+status of a finding, the commands that create a tree, the search of its
+tables and its ClickHouse client;
``make -C tools/xtop tests`` type-checks the
program and runs them (:ref:`testing-xtop`).
diff --git a/Documentation/contribute/testing/testing.rst b/Documentation/contribute/testing/testing.rst
index 8bf5804b..8c928ff7 100644
--- a/Documentation/contribute/testing/testing.rst
+++ b/Documentation/contribute/testing/testing.rst
@@ -707,6 +707,11 @@ the keepalives. The VM then shows in ``shirudo.node_status``, and
``make xtop`` builds :src:`tools/xtop/` and runs it with
``CLICKHOUSE_URL`` set to the stack's ClickHouse, unless the environment
names another.
+Once ``make vm`` has made a bundle, it also gives xtop the bundle's
+operator keys, the checkout's ``shirudo`` and tree ingest job, the
+stack's CA and its ClickHouse client, so that ``c`` in its shields view
+creates a tree in the stack's registry; ``shirudo/local-tree`` is the
+one the VMs follow.
Every ``make vm`` acts as the builder of :doc:`/operate/run/attest`:
before the guest first boots, :src:`testing/vm/tpm-builder.sh` creates
diff --git a/Documentation/operate/backend/xtop.rst b/Documentation/operate/backend/xtop.rst
index 783868fa..b5786ea1 100644
--- a/Documentation/operate/backend/xtop.rst
+++ b/Documentation/operate/backend/xtop.rst
@@ -19,7 +19,7 @@ and shows one row per upatch, or, with
``shirudo.shield_catalog``, one per shield available to append; 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 on
+per image. Every query is sent with ``readonly=1``, and it changes nothing unless it is given the operator's keys to create a tree with. It is a `Bun <https://bun.sh>`_ program built on
Ink and React, and runs on an operator's host, never on a target.
Build and run
@@ -208,6 +208,47 @@ 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.
+``c`` creates a tree. Type the tree's repository, a path under the
+registry of the shields such as ``shirudo/fleet-base``, and Enter; then
+``j`` and ``k`` move over the available shields and Space picks one, in
+the order the tree is to take them. ``n`` returns to the repository, Esc
+to the table. Below the shields are the commands that create it: one
+``bpm tree append`` per shield picked and the :doc:`tree-ingest` that
+loads the tree into the backend. The tree's id is the last name of the
+repository:
+
+.. code-block:: none
+
+ $ shirudo bpm tree append oci://<registry>/<namespace>/<package>:<version> --package-digest sha256:<digest> oci://<registry>/shirudo/fleet-base --tree-id fleet-base --keys-dir <keys>
+ $ tools/backend/jobs/tree-ingest --cert <keys>/cert.der oci://<registry>/shirudo/fleet-base
+
+Without ``XTOP_KEYS_DIR`` xtop only shows them, with the keys directory
+left to fill in, and stays a program that reads. With it, ``x`` runs
+them in order, without a shell and with xtop's environment, which is
+where ``bpm tree append`` and ``tree-ingest`` take their registry's CA
+and their ClickHouse client from. Each command shows ``✓`` and its last
+line, or ``✗`` and what it printed, and a failure stops the ones after
+it; ``x`` again runs from the command that failed. Once all have
+succeeded xtop returns to the table, which then lists the tree. xtop then signs with
+the operator's key: set the variable only on the operator's host.
+
+.. list-table::
+ :header-rows: 1
+
+ * - Variable
+ - Value
+ * - ``XTOP_KEYS_DIR``
+ - The operator's keys directory, with ``signing_key.pem`` and
+ ``cert.der``. Unset, xtop runs nothing.
+ * - ``SHIRUDO``
+ - The ``shirudo`` to run. Default ``shirudo``.
+ * - ``XTOP_TREE_INGEST``
+ - The tree ingest job. Default ``tools/backend/jobs/tree-ingest``,
+ from the directory xtop runs in.
+
+``make xtop`` sets all three, and the stack's CA and ClickHouse client,
+once ``make vm`` has made a bundle with operator keys.
+
Available
~~~~~~~~~
diff --git a/testing/Makefile b/testing/Makefile
index 1f6a0d2a..2a5a35a7 100644
--- a/testing/Makefile
+++ b/testing/Makefile
@@ -221,7 +221,7 @@ vm-sbom:
xtop:
+$(Q)$(MAKE) -s -C $(ROOT)/tools/xtop
- $(Q)$(ROOT)/testing/vm/stack.sh xtop
+ $(Q)TEST_VM_HOST_PRIVATE_DIR="$(TEST_VM_HOST_PRIVATE_DIR)" $(ROOT)/testing/vm/stack.sh xtop
# SHIELDS names Beefiles and directories of them, relative to the checkout
# root unless absolute; without it, every shield under upatches/.
diff --git a/testing/vm/stack.sh b/testing/vm/stack.sh
index 9da476ca..0e5a5b2e 100755
--- a/testing/vm/stack.sh
+++ b/testing/vm/stack.sh
@@ -180,6 +180,16 @@ xtop)
# and the others still have to get it.
flock -u 9
exec 9>&-
+ # With the operator keys of a bundle from make vm, xtop runs the
+ # commands that create a tree itself, against the stack.
+ keys=${TEST_VM_HOST_PRIVATE_DIR:-}/operator-keys/keys
+ if [ -s "$keys/signing_key.pem" ]; then
+ export XTOP_KEYS_DIR="$keys" XTOP_TREE_INGEST="$REPO/tools/backend/jobs/tree-ingest"
+ export SHIRUDO="${SHIRUDO:-$REPO/shirudo}"
+ export SHIRUDO_BUILD="${SHIRUDO_BUILD:-$REPO/tools/shirudo-build/shirudo-build}"
+ export BPM_OCI_CA_FILE="$W/ca.pem"
+ export CLICKHOUSE_CLIENT="docker exec -i $STACK_NAME-clickhouse clickhouse-client"
+ fi
CLICKHOUSE_URL=${CLICKHOUSE_URL:-http://$CLICKHOUSE/} exec "$REPO/tools/xtop/dist/xtop"
;;
*) echo "unknown stack command: $command" >&2; exit 2 ;;
diff --git a/tools/xtop/src/App.tsx b/tools/xtop/src/App.tsx
index 9b3ef3a3..a62f8845 100644
--- a/tools/xtop/src/App.tsx
+++ b/tools/xtop/src/App.tsx
@@ -28,7 +28,7 @@ const HINTS: Record<Focus, string> = {
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, then tabs · / search · enter details · t trees/available · r refresh · tab menu · esc close · q quit",
+ shields: "j/k scroll · k past top → sort, then tabs · / search · enter details · c create tree · t trees/available · 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: "regexes, all must match · !re drops matches · enter keep · esc clear",
diff --git a/tools/xtop/src/components/CreateTree.tsx b/tools/xtop/src/components/CreateTree.tsx
new file mode 100644
index 00000000..cb7d16b6
--- /dev/null
+++ b/tools/xtop/src/components/CreateTree.tsx
@@ -0,0 +1,162 @@
+// SPDX-License-Identifier: BSD-2-Clause
+// Copyright (c) 2026 Authors of shirudo
+//
+// A tree to create: its repository, the available shields to start it
+// with, and the commands that publish it, which xtop runs when it has the
+// operator's keys.
+
+import { useState } from "react";
+import { Box, Text, useInput } from "ink";
+import { createTreeCommands, type AvailableShield } from "../lib/shields.ts";
+import { run, type Operator } from "../lib/operator.ts";
+import { SeverityText } from "./style.tsx";
+
+type Props = {
+ shields: readonly AvailableShield[];
+ /** null when xtop was not given the keys: the commands are only shown. */
+ operator: Operator | null;
+ /** The tree is published and loaded. */
+ onCreated: () => void;
+ height: number;
+ active: boolean;
+ /** The repository field takes every key while it is edited. */
+ onEditingChange: (editing: boolean) => void;
+ onClose: () => void;
+};
+
+// Several at once when pasted.
+const REPOSITORY_CHARS = /^[a-z0-9._\/-]+$/;
+
+type Step = { state: "running" | "ok" | "failed"; output: string };
+
+const STEP_MARK = { running: "…", ok: "✓", failed: "✗" } as const;
+const STEP_COLOR = { running: "yellow", ok: "green", failed: "red" } as const;
+const FAILURE_LINES = 6;
+
+export function CreateTree({ shields, operator, onCreated, height, active, onEditingChange, onClose }: Props) {
+ const [repository, setRepository] = useState("");
+ const [editing, setEditingState] = useState(true);
+ const [cursor, setCursor] = useState(0);
+ const [picked, setPicked] = useState<readonly string[]>([]);
+
+ // One per command started, in order: a failure stops the rest.
+ const [steps, setSteps] = useState<readonly Step[]>([]);
+ const running = steps.some((s) => s.state === "running");
+
+ const runAll = async (commands: readonly string[][]) => {
+ // A retry leaves out what succeeded: an append run twice is two operations.
+ const done = steps.filter((s) => s.state === "ok");
+ for (const argv of commands.slice(done.length)) {
+ setSteps([...done, { state: "running", output: "" }]);
+ const result = await run(argv);
+ done.push({ state: result.ok ? "ok" : "failed", output: result.output });
+ setSteps([...done]);
+ if (!result.ok) return;
+ }
+ onCreated();
+ close();
+ };
+
+ const setEditing = (e: boolean) => {
+ setEditingState(e);
+ onEditingChange(e);
+ };
+ const close = () => {
+ onEditingChange(false);
+ onClose();
+ };
+
+ const chosen = picked.flatMap((id) => shields.find((s) => s.id === id) ?? []);
+ const commands = createTreeCommands(repository, chosen, operator);
+ const runnable = operator !== null && chosen.length > 0 && repository !== "";
+
+ useInput(
+ (input, key) => {
+ if (running) return;
+ if (editing) {
+ if (key.escape) return repository ? setEditing(false) : close();
+ if (key.return || key.tab || key.downArrow) return setEditing(false);
+ if (key.backspace || key.delete) return setRepository((r) => r.slice(0, -1));
+ if (REPOSITORY_CHARS.test(input)) {
+ setRepository((r) => r + input);
+ setSteps([]);
+ }
+ return;
+ }
+ if (key.escape || input === "h" || key.leftArrow) return close();
+ if (input === "n" || (cursor === 0 && (input === "k" || key.upArrow))) return setEditing(true);
+ if (input === "j" || key.downArrow) return setCursor((c) => Math.min(c + 1, shields.length - 1));
+ if (input === "k" || key.upArrow) return setCursor((c) => Math.max(c - 1, 0));
+ const id = shields[cursor]?.id;
+ if (input === "x" && runnable) return void runAll(commands);
+ if (id && (input === " " || key.return)) {
+ setSteps([]);
+ setPicked((p) => (p.includes(id) ? p.filter((x) => x !== id) : [...p, id]));
+ }
+ },
+ { isActive: active },
+ );
+
+ const listLines = Math.max(3, Math.min(shields.length, Math.floor((height - 6) / 2)));
+ const first = Math.max(0, Math.min(cursor - listLines + 1, shields.length - listLines));
+
+ return (
+ <Box flexDirection="column" height={height} overflow="hidden">
+ <Text bold>create tree</Text>
+ <Text>
+ <Text dimColor>repository </Text>
+ <Text inverse={editing}>{repository || (editing ? " " : "")}</Text>
+ {!repository && <Text dimColor> a path under the shields' registry, such as shirudo/fleet-base</Text>}
+ </Text>
+ <Box marginTop={1} flexDirection="column">
+ <Text dimColor>shields, appended in the order picked</Text>
+ {shields.slice(first, first + listLines).map((s, i) => {
+ const order = picked.indexOf(s.id);
+ return (
+ <Text key={s.id} inverse={!editing && first + i === cursor} wrap="truncate-end">
+ {order < 0 ? "[ ]" : `[${order + 1}]`} {s.id} <Text dimColor>{s.version}</Text> <SeverityText severity={s.severity} />
+ {s.trees.length > 0 && <Text dimColor> · in {s.trees.join(", ")}</Text>}
+ </Text>
+ );
+ })}
+ </Box>
+ <Box marginTop={1} flexDirection="column">
+ <Text dimColor>
+ {operator ? "x runs, with the keys of XTOP_KEYS_DIR" : "run, with the operator's keys directory for <keys>; xtop runs them when XTOP_KEYS_DIR names it"}
+ </Text>
+ {chosen.length === 0 ? (
+ <Text dimColor>pick a shield to see the commands</Text>
+ ) : (
+ commands.map((argv, i) => {
+ const step = steps[i];
+ const output = step?.output.split("\n") ?? [];
+ return (
+ <Box key={argv.join(" ")} flexDirection="column">
+ <Text wrap="wrap">
+ {step ? <Text color={STEP_COLOR[step.state]}>{STEP_MARK[step.state]}</Text> : "$"} {argv.join(" ")}
+ </Text>
+ {step?.state === "ok" && <Text dimColor wrap="truncate-end"> {output.at(-1)}</Text>}
+ {step?.state === "failed" &&
+ output.slice(-FAILURE_LINES).map((line, n) => (
+ <Text key={n} color="red" wrap="truncate-end">
+ {" "}
+ {line}
+ </Text>
+ ))}
+ </Box>
+ );
+ })
+ )}
+ </Box>
+ <Box marginTop={1}>
+ <Text dimColor>
+ {running
+ ? "running…"
+ : editing
+ ? "type the repository · enter shields · esc back"
+ : `j/k move · space pick · n repository${runnable ? " · x run" : ""} · esc back`}
+ </Text>
+ </Box>
+ </Box>
+ );
+}
diff --git a/tools/xtop/src/components/ShieldsView.tsx b/tools/xtop/src/components/ShieldsView.tsx
index f00d5075..e773cb44 100644
--- a/tools/xtop/src/components/ShieldsView.tsx
+++ b/tools/xtop/src/components/ShieldsView.tsx
@@ -28,6 +28,8 @@ import { ViewMessage } from "./ViewMessage.tsx";
import { MiniBar } from "./MiniBar.tsx";
import { ShieldDetail } from "./ShieldDetail.tsx";
import { AvailableDetail } from "./AvailableDetail.tsx";
+import { operatorFromEnv } from "../lib/operator.ts";
+import { CreateTree } from "./CreateTree.tsx";
import { SHIELD_STATUS_COLOR, SeverityText } from "./style.tsx";
/** The upatches of the trees, or the shields available to append. */
@@ -249,8 +251,9 @@ const availableTiebreak = (a: AvailableShield, b: AvailableShield) => b.exposed
export function ShieldsView({ backend, mode, onModeChange, height, active, onClose, onSearchingChange, onDetailChange }: Props) {
const [reload, setReload] = useState(0);
+ const [creating, setCreatingState] = useState(false);
const trees = useRefreshing<ShieldsReport>(mode === "trees", reload, () => backend.getShields());
- const available = useRefreshing<AvailableReport>(mode === "available", reload, () => backend.getAvailableShields());
+ const available = useRefreshing<AvailableReport>(mode === "available" || creating, reload, () => backend.getAvailableShields());
const [searching, setSearching] = useState(false);
const [onTabs, setOnTabs] = useState(false);
const [detail, setDetail] = useState<string | null>(null);
@@ -264,6 +267,10 @@ export function ShieldsView({ backend, mode, onModeChange, height, active, onClo
setSearching(s);
onSearchingChange(s);
};
+ const setCreating = (c: boolean) => {
+ setCreatingState(c);
+ onDetailChange?.(c);
+ };
const switchTo = (m: ShieldsMode, fromTabs = false) => {
setOnTabs(fromTabs);
showDetail(null);
@@ -280,22 +287,42 @@ export function ShieldsView({ backend, mode, onModeChange, height, active, onClo
(input) => {
if (input === "t") switchTo(mode === "trees" ? "available" : "trees");
if (input === "r") setReload((r) => r + 1);
+ if (input === "c" && mode === "trees") setCreating(true);
},
- { isActive: active && !searching && !detail },
+ { isActive: active && !searching && !detail && !creating },
);
const query = mode === "trees" ? trees : available;
const message = (color: string | undefined, text: ReactNode) => (
<Box flexDirection="column">
<Tabs labels={tabs.labels} selected={tabs.selected} />
- <ViewMessage active={active && !searching} onClose={onClose} color={color}>
+ <ViewMessage active={active && !searching} onClose={creating ? () => setCreating(false) : onClose} color={color}>
{text}
</ViewMessage>
</Box>
);
+ const tableHeight = Math.max(4, height);
+ if (creating) {
+ if (!available.data)
+ return available.error
+ ? message("red", `available query failed: ${available.error}`)
+ : message(undefined, "querying backend…");
+ if (available.data.shields.length === 0)
+ return message(undefined, "no shield in shirudo.shield_catalog to start a tree with: run make shields");
+ return (
+ <CreateTree
+ shields={available.data.shields}
+ operator={operatorFromEnv(process.env)}
+ onCreated={() => setReload((r) => r + 1)}
+ height={tableHeight}
+ active={active}
+ onEditingChange={reportSearching}
+ onClose={() => setCreating(false)}
+ />
+ );
+ }
if (!query.data)
return query.error ? message("red", `${mode} query failed: ${query.error}`) : message(undefined, "querying backend…");
- const tableHeight = Math.max(4, height);
const failed = query.error && <Text color="red">refresh failed: {query.error} · </Text>;
const status = (generatedAt: Date) => (
<>
@@ -348,7 +375,7 @@ export function ShieldsView({ backend, mode, onModeChange, height, active, onClo
const report = trees.data!;
if (report.shields.length === 0)
- return message(undefined, "no upatch in shirudo.tree_ops: load a tree with jobs/tree-ingest");
+ return message(undefined, "no upatch in shirudo.tree_ops: press c to create a tree, or load one with jobs/tree-ingest");
const detailShield = detail ? (report.shields.find((s) => keyOf(s) === detail) ?? null) : null;
const treeIds = new Set(report.shields.map((s) => s.treeId));
@@ -368,7 +395,7 @@ export function ShieldsView({ backend, mode, onModeChange, height, active, onClo
initialSort={{ col: "status", dir: "asc" }}
tiebreak={tiebreak}
searchFields={shieldFields}
- footerHint="t available · r refresh"
+ footerHint="c create tree · t available · r refresh"
onSearchingChange={reportSearching}
onClose={onClose}
onOpen={(s) => showDetail(keyOf(s))}
diff --git a/tools/xtop/src/lib/operator.ts b/tools/xtop/src/lib/operator.ts
new file mode 100644
index 00000000..4ade548c
--- /dev/null
+++ b/tools/xtop/src/lib/operator.ts
@@ -0,0 +1,41 @@
+// SPDX-License-Identifier: BSD-2-Clause
+// Copyright (c) 2026 Authors of shirudo
+//
+// What xtop needs to run an operator's commands itself: it does only
+// when XTOP_KEYS_DIR names the keys, and otherwise shows the commands.
+
+export type Operator = {
+ /** The directory of signing_key.pem and cert.der. */
+ keysDir: string;
+ shirudo: string;
+ treeIngest: string;
+};
+
+export const DEFAULT_SHIRUDO = "shirudo";
+export const DEFAULT_TREE_INGEST = "tools/backend/jobs/tree-ingest";
+
+export const operatorFromEnv = (env: Record<string, string | undefined>): Operator | null =>
+ env.XTOP_KEYS_DIR
+ ? {
+ keysDir: env.XTOP_KEYS_DIR,
+ shirudo: env.SHIRUDO || DEFAULT_SHIRUDO,
+ treeIngest: env.XTOP_TREE_INGEST || DEFAULT_TREE_INGEST,
+ }
+ : null;
+
+export type RunResult = { ok: boolean; output: string };
+
+/** Runs argv without a shell, and gives what it printed. */
+export async function run(argv: readonly string[]): Promise<RunResult> {
+ try {
+ const child = Bun.spawn([...argv], { stdin: "ignore", stdout: "pipe", stderr: "pipe" });
+ const [out, err, status] = await Promise.all([
+ new Response(child.stdout).text(),
+ new Response(child.stderr).text(),
+ child.exited,
+ ]);
+ return { ok: status === 0, output: (out + err).trim() || `exit status ${status}` };
+ } catch (e) {
+ return { ok: false, output: e instanceof Error ? e.message : String(e) };
+ }
+}
diff --git a/tools/xtop/src/lib/shields.ts b/tools/xtop/src/lib/shields.ts
index 847cec46..8e258063 100644
--- a/tools/xtop/src/lib/shields.ts
+++ b/tools/xtop/src/lib/shields.ts
@@ -4,6 +4,8 @@
// The upatches of every tree the backend has loaded: what each fixes and
// how far its newest operation has rolled out.
+import { DEFAULT_SHIRUDO, DEFAULT_TREE_INGEST, type Operator } from "./operator.ts";
+
/**
* pending while a node following the tree has not reached the newest
* operation, deployed once every one has, withdrawn when that operation
@@ -130,3 +132,33 @@ export const mostExposed = (advisories: readonly Pick<AvailableAdvisory, "expose
export const appendCommand = (s: Pick<AvailableShield, "reference" | "manifestDigest">) =>
`shirudo bpm tree append ${s.reference} --package-digest sha256:${s.manifestDigest} ` +
"oci://<registry>/<tree> --tree-id <tree-id>";
+
+const registryOf = (reference: string) => reference.match(/^oci:\/\/[^/]+/)?.[0] ?? "oci://<registry>";
+
+/**
+ * The commands, as argument lists, that start a tree at repository, a path
+ * under the registry of the first shield, with the shields in the order
+ * given, then load it into the backend. The tree's id is the last name of
+ * the path. Without an operator the keys directory is left to fill in.
+ */
+export function createTreeCommands(
+ repository: string,
+ shields: readonly Pick<AvailableShield, "reference" | "manifestDigest">[],
+ operator: Operator | null,
+): string[][] {
+ const { keysDir, shirudo, treeIngest } = operator ?? {
+ keysDir: "<keys>",
+ shirudo: DEFAULT_SHIRUDO,
+ treeIngest: DEFAULT_TREE_INGEST,
+ };
+ const path = repository.replace(/^\/+|\/+$/g, "");
+ const tree = `${shields[0] ? registryOf(shields[0].reference) : "oci://<registry>"}/${path || "<tree>"}`;
+ const treeId = path.split("/").pop() || "<tree-id>";
+ return [
+ ...shields.map((s) => [
+ shirudo, "bpm", "tree", "append", s.reference, "--package-digest", `sha256:${s.manifestDigest}`,
+ tree, "--tree-id", treeId, "--keys-dir", keysDir,
+ ]),
+ [treeIngest, ...(shirudo === DEFAULT_SHIRUDO ? [] : ["--shirudo", shirudo]), "--cert", `${keysDir}/cert.der`, tree],
+ ];
+}
diff --git a/tools/xtop/test/shields.test.ts b/tools/xtop/test/shields.test.ts
index fa0411b9..dd6f1b6c 100644
--- a/tools/xtop/test/shields.test.ts
+++ b/tools/xtop/test/shields.test.ts
@@ -4,10 +4,12 @@
// The rows of sql/shields.sql as tools/backend/test/xtop-shields.expected
// has them, turned into shields.
+import { operatorFromEnv } from "../src/lib/operator.ts";
import { describe, expect, test } from "bun:test";
import { toAvailableShield, toShield, type AvailableRow, type ShieldRow } from "../src/lib/backend.ts";
import {
appendCommand,
+ createTreeCommands,
mostExposed,
severityRank,
shieldStatus,
@@ -191,3 +193,34 @@ describe("appendCommand", () => {
);
});
});
+
+describe("createTreeCommands", () => {
+ const shield = { reference: "oci://registry.example.com/shields/rpl-detector:1.0.2", manifestDigest: "ab".repeat(32) };
+ const tree = "oci://registry.example.com/shirudo/fleet-base";
+
+ test("appends each shield to the tree under the shields' registry, then loads it", () => {
+ expect(createTreeCommands("/shirudo/fleet-base/", [shield], null).map((c) => c.join(" "))).toEqual([
+ `shirudo bpm tree append ${shield.reference} --package-digest sha256:${shield.manifestDigest} ` +
+ `${tree} --tree-id fleet-base --keys-dir <keys>`,
+ `tools/backend/jobs/tree-ingest --cert <keys>/cert.der ${tree}`,
+ ]);
+ });
+
+ test("leaves the tree to fill in while it has no repository", () => {
+ expect(createTreeCommands("", [shield], null)[0]!.slice(7)).toEqual([
+ "oci://registry.example.com/<tree>", "--tree-id", "<tree-id>", "--keys-dir", "<keys>",
+ ]);
+ });
+
+ test("names the operator's keys and programs", () => {
+ const operator = operatorFromEnv({ XTOP_KEYS_DIR: "/keys", SHIRUDO: "/bin/shirudo", XTOP_TREE_INGEST: "/jobs/tree-ingest" });
+ const [append, ingest] = createTreeCommands("shirudo/fleet-base", [shield], operator);
+ expect(append!.slice(0, 2)).toEqual(["/bin/shirudo", "bpm"]);
+ expect(append!.slice(-2)).toEqual(["--keys-dir", "/keys"]);
+ expect(ingest).toEqual(["/jobs/tree-ingest", "--shirudo", "/bin/shirudo", "--cert", "/keys/cert.der", tree]);
+ });
+
+ test("xtop runs nothing without XTOP_KEYS_DIR", () => {
+ expect(operatorFromEnv({ SHIRUDO: "/bin/shirudo" })).toBeNull();
+ });
+});