Files
stack/packages/webui/tests/triage-snapshot.test.mjs

195 lines
11 KiB
JavaScript

// #1873 triage-host: the health snapshot keeps a fixed field list. States, times, counts and codes
// only; a failed system config check leaves no path, token or stderr text in it.
import { test } from "node:test";
import assert from "node:assert/strict";
import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, statSync, readdirSync } from "node:fs";
import { join } from "node:path";
import {
NOT_READ, SNAPSHOT_FIELDS, SYSTEM_CONFIG_CODES, ORG_CONFIG_CODES, ORG_READS_AT_ONCE, composeSnapshot, readSystemConfig, readOrgConfig,
runExitOnly, systemConfigCode, writeSnapshot, busFields, proxyFields,
} from "../src/triage-snapshot.mjs";
const scratch = () => mkdtempSync(join(process.env.TMPDIR, "ts-"));
const SECRET = "sk-ant-TRIAGESECRET0123456789";
const cliError = (message) => Object.assign(new Error(message), { name: "CliError", exitCode: 3 });
function assertClean(snapshot, ...needles) {
const text = JSON.stringify(snapshot);
for (const n of needles) assert.ok(!text.includes(n), `snapshot holds ${n}`);
assert.ok(!text.includes("mosaic-config"), "snapshot holds stderr text");
assert.ok(!/\/(home|mnt|tmp|srv)\//.test(text), "snapshot holds a host path");
}
test("a failed system config check (real validator, bad JSON) leaves no path, token or stderr text", async () => {
const dir = scratch();
const config = join(dir, `config-${SECRET}.json`);
writeFileSync(config, `{"configVersion": 1, "token": "${SECRET}",`);
const env = { PATH: process.env.PATH, HOME: dir, MOSAIC_CONFIG: config, LANG: "C.UTF-8" };
const systemConfig = await readSystemConfig({ env });
assert.notEqual(systemConfig, NOT_READ);
assert.equal(systemConfig.valid, false);
assert.ok(Number.isInteger(systemConfig.exit) && systemConfig.exit !== 0);
assert.ok(SYSTEM_CONFIG_CODES.includes(systemConfig.code), `code ${systemConfig.code} is on the fixed list`);
const snap = await composeSnapshot({ systemConfig: () => systemConfig });
assertClean(snap, SECRET, dir, config);
const file = writeSnapshot(dir, snap);
assertClean(readFileSync(file, "utf8"), SECRET, dir);
});
test("a missing config and an unsupported key are refused by code, never by the validator's words", async () => {
const dir = scratch();
const missing = await readSystemConfig({ env: { PATH: process.env.PATH, HOME: dir, MOSAIC_CONFIG: join(dir, "absent.json") } });
assert.deepEqual(missing, { valid: false, exit: 3, code: "config-not-found" });
const config = join(dir, "c.json");
writeFileSync(config, JSON.stringify({ configVersion: 1, [SECRET]: true }));
const odd = await readSystemConfig({ env: { PATH: process.env.PATH, HOME: dir, MOSAIC_CONFIG: config } });
assert.equal(odd.valid, false);
assert.ok(SYSTEM_CONFIG_CODES.includes(odd.code));
assertClean(await composeSnapshot({ systemConfig: () => odd }), SECRET, dir);
});
test("the stderr mapping keeps only a fixed code, whatever the line says", () => {
assert.equal(systemConfigCode(0, "anything"), null);
assert.equal(systemConfigCode(2, "mosaic-config: instance-root-mismatch: /home/x/.mosaic-dev is claimed"), "instance-root-mismatch");
assert.equal(systemConfigCode(3, "mosaic-config: configuration not found: /home/x/config.json"), "config-not-found");
assert.equal(systemConfigCode(2, `mosaic-config: ${SECRET}`), "config-invalid");
assert.equal(systemConfigCode(9, "/home/x/secret"), "config-check-failed");
assert.equal(systemConfigCode(2, "mosaic-config: not-a-code: x"), "config-invalid");
});
test("a child's stdout is never read and stderr only when asked", async () => {
const script = `process.stdout.write(${JSON.stringify(SECRET)}); process.stderr.write("line one ${SECRET}\\nline two"); process.exit(2)`;
const quiet = await runExitOnly([process.execPath, "-e", script], { env: { PATH: process.env.PATH } });
assert.deepEqual(quiet, { exit: 2, firstLine: "" });
const told = await runExitOnly([process.execPath, "-e", script], { env: { PATH: process.env.PATH }, stderr: true });
assert.equal(told.exit, 2);
assert.ok(!JSON.stringify(told).includes("line two"));
assert.equal(await runExitOnly([process.execPath, "-e", "setTimeout(() => {}, 10000)"], { env: {}, timeoutMs: 200 }), null);
assert.equal(await runExitOnly([join(scratch(), "absent")], { env: {} }), null);
});
test("a system config check that does not reach an exit says not read", async () => {
assert.equal(await readSystemConfig({ run: async () => null }), NOT_READ);
const snap = await composeSnapshot({ systemConfig: () => readSystemConfig({ run: async () => null }) });
assert.equal(snap.systemConfig, NOT_READ);
});
test("the org config check keeps its exit code only, and never runs for an id outside the pattern", async () => {
const calls = [];
const run = async (argv, opts) => { calls.push([argv.slice(-2), opts.stderr]); return { exit: 2, firstLine: SECRET }; };
assert.deepEqual(await readOrgConfig("alpha", { run }), { valid: false, exit: 2, code: "org-config-invalid" });
assert.deepEqual(calls, [[["validate", "alpha"], false]]);
assert.equal(await readOrgConfig("../etc", { run }), NOT_READ);
assert.equal(await readOrgConfig("--help", { run }), NOT_READ);
assert.equal(calls.length, 1);
assert.ok(ORG_CONFIG_CODES.includes("org-config-check-failed"));
});
test("the snapshot holds the fixed field list and nothing a reader adds", async () => {
const now = () => new Date("2026-11-16T12:00:00.000Z");
const snap = await composeSnapshot({
orgs: async () => [
{ id: "alpha", state: "active", root: "/home/x/orgs/alpha" },
{ id: "beta", state: "active", root: "/srv/beta" },
{ id: "gone", state: "archived", root: "/home/x/gone" },
{ id: "../bad", state: "active" },
],
busStatus: async (id) => {
if (id === "beta") throw cliError("stale bus host lock at /home/x/orgs/beta/bus.lock");
return { healthy: true, pid: 4242, boot: { ok: true, at: "2026-11-16T11:00:00.000Z", log: "/home/x/boot.log" }, root: "/home/x/orgs/alpha", socket: "/home/x/s.sock" };
},
processing: async (id) => (id === "alpha" ? { halted: false, invalid: false, reason: SECRET } : { nonsense: 1 }),
orgConfig: async () => ({ valid: true, exit: 0, code: null, stderr: SECRET }),
proxy: async () => ({ unit: { installed: true, active: "active", healthy: true, error: SECRET, path: "/home/x" }, init: { initialized: true, file: "/home/x" }, fence: { set: false, key: SECRET } }),
systemConfig: async () => ({ valid: true, exit: 0, code: null, path: "/home/x/config.json" }),
}, { now });
assert.deepEqual(Object.keys(snap), SNAPSHOT_FIELDS);
assert.deepEqual(snap, {
snapshotVersion: 1,
at: "2026-11-16T12:00:00.000Z",
console: { state: "answering", at: "2026-11-16T12:00:00.000Z" },
proxy: { initialized: true, installed: true, active: "active", healthy: true, fence: false },
systemConfig: { valid: true, exit: 0, code: null },
organizations: {
count: 2,
list: [
{ id: "alpha", bus: { state: "running", lastStart: { ok: true, at: "2026-11-16T11:00:00.000Z" } }, processing: { halted: false, invalid: false }, config: { valid: true, exit: 0, code: null } },
{ id: "beta", bus: { state: "dead", lastStart: null }, processing: NOT_READ, config: { valid: true, exit: 0, code: null } },
],
},
});
assertClean(snap, SECRET, "4242");
});
test("every failed or missing read says not read, and a read that hangs is cut off", async () => {
const hang = () => new Promise(() => {});
const snap = await composeSnapshot({
orgs: async () => [{ id: "alpha", state: "active" }],
busStatus: async () => { throw new Error("EACCES /home/x"); },
processing: hang,
orgConfig: async () => { throw new Error(SECRET); },
proxy: hang,
}, { timeoutMs: 100 });
assert.equal(snap.proxy, NOT_READ);
assert.equal(snap.systemConfig, NOT_READ);
assert.deepEqual(snap.organizations.list, [{ id: "alpha", bus: NOT_READ, processing: NOT_READ, config: NOT_READ }]);
assert.equal((await composeSnapshot({ orgs: async () => { throw new Error("x"); } })).organizations, NOT_READ);
assert.equal((await composeSnapshot({})).organizations, NOT_READ);
assertClean(snap, SECRET);
});
test("bus and proxy reads outside their shapes say not read; unknown unit states are unknown", () => {
assert.equal(busFields({ pid: 3 }), NOT_READ);
assert.deepEqual(busFields({ healthy: false, pid: 3 }), { state: "not-answering", lastStart: null });
assert.deepEqual(busFields({ healthy: false, pid: null, boot: { ok: false, at: "yesterday" } }), { state: "stopped", lastStart: null });
assert.equal(proxyFields({}), NOT_READ);
assert.equal(proxyFields({ unit: { installed: false, active: "rm -rf /", healthy: false } }).active, "unknown");
});
test("the snapshot file is one 0600 file, replaced whole", () => {
const dir = scratch();
mkdirSync(join(dir, "health"), { mode: 0o700 });
writeSnapshot(join(dir, "health"), { snapshotVersion: 1, n: 1 });
const file = writeSnapshot(join(dir, "health"), { snapshotVersion: 1, n: 2 });
assert.equal(statSync(file).mode & 0o777, 0o600);
assert.deepEqual(readdirSync(join(dir, "health")), ["snapshot.json"]);
assert.equal(JSON.parse(readFileSync(file, "utf8")).n, 2);
});
test("organizations are read at most ORG_READS_AT_ONCE at a time and listed in registry order", async () => {
let live = 0, most = 0;
const ids = Array.from({ length: 10 }, (_, i) => `org${i}`);
const slow = async () => { live++; most = Math.max(most, live); await new Promise((r) => setTimeout(r, 5)); live--; return { valid: true, exit: 0, code: null }; };
const snap = await composeSnapshot({ orgs: async () => ids.map((id) => ({ id, state: "active" })), orgConfig: slow });
assert.equal(ORG_READS_AT_ONCE, 4);
assert.equal(most, ORG_READS_AT_ONCE);
assert.deepEqual(snap.organizations.list.map((o) => o.id), ids);
assert.equal(snap.organizations.count, 10);
});
test("the organization reads share one deadline: forty hung organizations take one timeout, not ten", async () => {
let calls = 0;
const ids = Array.from({ length: 40 }, (_, i) => `org${i}`);
const hang = () => { calls++; return new Promise(() => {}); };
const began = Date.now();
const snap = await composeSnapshot({ orgs: async () => ids.map((id) => ({ id, state: "active" })), busStatus: hang, processing: hang, orgConfig: hang }, { timeoutMs: 200 });
const took = Date.now() - began;
assert.ok(took < 800, `took ${took} ms`);
assert.ok(calls < ids.length, `${calls} reads began`);
assert.equal(snap.organizations.count, 40);
assert.deepEqual(snap.organizations.list.map((o) => o.id), ids);
for (const o of snap.organizations.list) assert.deepEqual([o.bus, o.processing, o.config], [NOT_READ, NOT_READ, NOT_READ], o.id);
});
test("an organization begun late gets only what is left of the deadline", async () => {
const ids = ["a0", "a1", "a2", "a3", "a4"];
const hang = () => new Promise(() => {});
// Three readers hang; a3 answers after 300 ms, and the worker that read it starts a4 with 100 ms left.
const orgConfig = (id) => (id === "a3" ? new Promise((r) => setTimeout(() => r({ valid: true, exit: 0, code: null }), 300)) : hang());
const began = Date.now();
const snap = await composeSnapshot({ orgs: async () => ids.map((id) => ({ id, state: "active" })), orgConfig }, { timeoutMs: 400 });
const took = Date.now() - began;
assert.ok(took < 600, `took ${took} ms`);
assert.deepEqual(snap.organizations.list.map((o) => [o.id, o.config === NOT_READ ? "not read" : "read"]), [["a0", "not read"], ["a1", "not read"], ["a2", "not read"], ["a3", "read"], ["a4", "not read"]]);
});