Skip to content

eBPF-based security platform

tools/xtop: query as a user whose profile is read-only at level 2

John Fastabendd5791022be0e
diff --git a/Documentation/operate/backend/xtop.rst b/Documentation/operate/backend/xtop.rst
index b9cc4c4b..e946abac 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. 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
+per image. Every query is sent with ``readonly=1``, or without it to a user whose profile is read-only at another level and may not set it, 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
diff --git a/tools/xtop/src/lib/clickhouse.ts b/tools/xtop/src/lib/clickhouse.ts
index 847cabf7..81800404 100644
--- a/tools/xtop/src/lib/clickhouse.ts
+++ b/tools/xtop/src/lib/clickhouse.ts
@@ -37,27 +37,41 @@ export function configFromEnv(env: Record<string, string | undefined> = process.
};
}
+// The servers whose user is read-only by its profile at another level
+// than 1, readonly=2: such a user may not set readonly, and needs no one
+// to.
+const readOnlyByProfile = new WeakSet<ClickHouseConfig>();
+const READONLY_REFUSED = /Cannot modify 'readonly' setting in readonly mode/;
+
/** Runs one SELECT and returns its rows as objects keyed by column name. */
export async function queryRows<T>(
cfg: ClickHouseConfig,
sql: string,
fetchImpl: typeof fetch = fetch,
): Promise<T[]> {
- const url = new URL(cfg.url);
- url.searchParams.set("default_format", "JSONEachRow");
- url.searchParams.set("output_format_json_quote_64bit_integers", "0");
- url.searchParams.set("readonly", "1");
const headers: Record<string, string> = { "Content-Type": "text/plain" };
if (cfg.user) headers["X-ClickHouse-User"] = cfg.user;
if (cfg.password) headers["X-ClickHouse-Key"] = cfg.password;
- const res = await fetchImpl(url, {
- method: "POST",
- headers,
- body: sql,
- signal: AbortSignal.timeout(cfg.timeoutMs),
- });
- const text = await res.text();
+ const post = async () => {
+ const url = new URL(cfg.url);
+ url.searchParams.set("default_format", "JSONEachRow");
+ url.searchParams.set("output_format_json_quote_64bit_integers", "0");
+ if (!readOnlyByProfile.has(cfg)) url.searchParams.set("readonly", "1");
+ const res = await fetchImpl(url, {
+ method: "POST",
+ headers,
+ body: sql,
+ signal: AbortSignal.timeout(cfg.timeoutMs),
+ });
+ return { ok: res.ok, status: res.status, text: await res.text() };
+ };
+ let res = await post();
+ if (!res.ok && !readOnlyByProfile.has(cfg) && READONLY_REFUSED.test(res.text)) {
+ readOnlyByProfile.add(cfg);
+ res = await post();
+ }
+ const { text } = res;
if (!res.ok) throw new Error(`${res.status} ${text.trim().split("\n")[0]?.slice(0, 300) ?? ""}`);
return text
.split("\n")
diff --git a/tools/xtop/test/clickhouse.test.ts b/tools/xtop/test/clickhouse.test.ts
new file mode 100644
index 00000000..3b206a39
--- /dev/null
+++ b/tools/xtop/test/clickhouse.test.ts
@@ -0,0 +1,46 @@
+// SPDX-License-Identifier: BSD-2-Clause
+// Copyright (c) 2026 Authors of shirudo
+//
+// The requests of the ClickHouse client: read-only, also for a user whose
+// profile refuses the setting that says so.
+
+import { describe, expect, test } from "bun:test";
+import { queryRows, type ClickHouseConfig } from "../src/lib/clickhouse.ts";
+
+const config = (): ClickHouseConfig => ({ url: new URL("http://127.0.0.1:8123/"), timeoutMs: 1000 });
+
+const REFUSED = "Code: 164. DB::Exception: Cannot modify 'readonly' setting in readonly mode. (READONLY)";
+
+/** A server that answers each request with what answer makes of its URL. */
+const server = (answer: (url: URL) => Response) => {
+ const seen: URL[] = [];
+ const fetchImpl = (async (url: URL) => {
+ seen.push(url);
+ return answer(url);
+ }) as unknown as typeof fetch;
+ return { seen, fetchImpl };
+};
+
+describe("queryRows", () => {
+ test("sends readonly=1 and reads a row per line", async () => {
+ const { seen, fetchImpl } = server(() => new Response('{"a":1}\n{"a":2}\n'));
+ expect(await queryRows<{ a: number }>(config(), "SELECT 1", fetchImpl)).toEqual([{ a: 1 }, { a: 2 }]);
+ expect(seen.map((u) => u.searchParams.get("readonly"))).toEqual(["1"]);
+ });
+
+ test("leaves readonly to the profile of a user who may not set it", async () => {
+ const { seen, fetchImpl } = server((url) =>
+ url.searchParams.has("readonly") ? new Response(REFUSED, { status: 500 }) : new Response('{"a":1}\n'),
+ );
+ const cfg = config();
+ expect(await queryRows(cfg, "SELECT 1", fetchImpl)).toEqual([{ a: 1 }]);
+ expect(await queryRows(cfg, "SELECT 1", fetchImpl)).toEqual([{ a: 1 }]);
+ expect(seen.map((u) => u.searchParams.get("readonly"))).toEqual(["1", null, null]);
+ });
+
+ test("reports any other failure, with its first line", async () => {
+ const { seen, fetchImpl } = server(() => new Response("Code: 60. no such table\nstack", { status: 404 }));
+ expect(queryRows(config(), "SELECT 1", fetchImpl)).rejects.toThrow("404 Code: 60. no such table");
+ expect(seen.length).toBe(1);
+ });
+});