Files
MUA-Mikes-Unraid-Agent/src/admin.test.ts
T
Mikei386andClaude Opus 5.5 b8d89ffd9c release: MUA 2026.11.20.r036
Read-only shell
- Accept a full command line (`command`) and parse it without /bin/sh:
  quotes, escapes, ~, pipes between allowed programs, ; && ||, globs in
  absolute paths; 2>&1 and 2>/dev/null are tolerated. Pipeline stages run
  with strictly single-quoted, pre-validated literals only.
- Per-program option policies that understand combined short flags,
  --opt=value and GNU abbreviations. Closes bypasses: ip abbreviations
  (ip a a / ip r d / ip link s), dmesg -c/-Tc/--console-level=, ss -tK/-D,
  date operands, sort -o, uniq output file, file -C.
- Block credential files (shadow, SSH private keys, mua.conf, admin token,
  /proc/*/environ, docker config.v2.json); redact password hashes, private
  PEM keys and WireGuard keys in output. MUA API key and admin token are
  never emitted by any tool.
- More diagnostic programs (echo, printf, sort, uniq, cut, tr, findmnt,
  sensors, zpool/zfs read verbs, mdcmd status, ...). grep without matches
  is reported as no_match instead of an error.

Process handling
- Spawn every child in its own process group; timeouts kill the whole
  tree. The MCP hard timeout kills exactly the processes of that call.
- Async jobs: command in its own file (exit no longer loses the exit
  code), new unraid_system_job_cancel, finished jobs pruned after 7 days.

Other
- Cache toolbox discovery briefly; validate and bound session IDs; /health
  shows version/port only with a valid token; constant-time admin token
  check; auto-granted tools are logged and shown in the WebGUI.
- Remove the legacy PHP server (mcp/), drop old packages from dist/, pin
  @types/bun.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 21:51:14 +01:00

95 lines
5.0 KiB
TypeScript

import { describe, expect, test } from "bun:test";
import { AdminTickets, ADMIN_TOOLS } from "./admin";
import { getToolRisk, toolByName } from "./tools";
import { parseConfig } from "./auth";
import { runLocal } from "./helpers";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { fileURLToPath } from "node:url";
describe("native administration approval boundary", () => {
const plan = { kind: "share" as const, spec: { action: "remove", name: "test" }, before: { config_sha256: "abc" } };
test("tickets are exact-kind, expiring and single use", () => {
const t = new AdminTickets(); const id = t.issue(plan, 1000);
expect(() => t.take(id, "docker", true, 1001)).toThrow();
expect(() => t.take(id, "share", false, 1001)).toThrow();
expect(t.take(id, "share", true, 1001)).toEqual(plan);
expect(() => t.take(id, "share", true, 1001)).toThrow();
const expired = t.issue(plan, 1000);
expect(() => t.take(expired, "share", true, 601000)).toThrow();
});
test("new writes are critical and not silently enabled", () => {
const cfg = parseConfig("MUA_ENABLED_TOOLS=unraid_system_shell_readonly\n");
for (const name of ["unraid_share_apply", "unraid_docker_template_apply"]) {
expect(getToolRisk(name)).toBe("critical");
expect(cfg.enabledTools).not.toContain(name);
}
expect(getToolRisk("unraid_share_preview")).toBe("active");
expect(getToolRisk("unraid_storage_diagnostics")).toBe("read");
for (const tool of ADMIN_TOOLS) expect(toolByName(tool.name)).toBeDefined();
});
test("existing template name example does not suggest an image path", () => {
expect(JSON.stringify(toolByName("unraid_docker_create")?.inputSchema)).not.toContain("linuxserver/sonarr");
});
test("a failed process cannot masquerade as normal tool output", async () => {
await expect(runLocal("synthetic_failure", "printf failure >&2; exit 17")).rejects.toThrow();
expect(await runLocal("synthetic_success", "printf ready")).toBe("ready");
});
});
test("actual MCP transport advertises new tools and marks failed commands as errors", async () => {
const root = mkdtempSync(`${tmpdir()}/mua-transport-`);
const token = crypto.randomUUID();
const child = Bun.spawn([process.execPath, fileURLToPath(new URL("./index.ts", import.meta.url))], {
env: { ...process.env, MUA_HOST: "127.0.0.1", MUA_PORT: "39871", MUA_CONFIG_PORT: "39872", MUA_API_KEY: token,
MUA_ENABLED_TOOLS: "all", MUA_MAX_REQUEST_BYTES: "16384", MUA_CONFIG_DIR: root, MUA_ADMIN_TOKEN_FILE: `${root}/admin.token`, MUA_AUDIT_LOG: `${root}/audit.log` },
stdout: "ignore", stderr: "ignore",
});
try {
let ready = false;
for (let i = 0; i < 50; i++) {
try { const r = await fetch("http://127.0.0.1:39871/health"); ready = r.ok; if (ready) break; } catch {}
await Bun.sleep(50);
}
expect(ready).toBe(true);
let session = ""; let id = 0;
const rpc = async (method: string, params: object) => {
const r = await fetch("http://127.0.0.1:39871/mcp", { method: "POST", headers: {
Authorization: `Bearer ${token}`, "Content-Type": "application/json", Accept: "application/json",
...(session ? { "Mcp-Session-Id": session } : {}),
}, body: JSON.stringify({ jsonrpc: "2.0", id: ++id, method, params }) });
if (r.headers.has("Mcp-Session-Id")) session = r.headers.get("Mcp-Session-Id")!;
return await r.json() as any;
};
const init = await rpc("initialize", { protocolVersion: "2025-03-26", capabilities: {}, clientInfo: { name: "isolated-test", version: "1" } });
expect(init.result.serverInfo.version).toBe(JSON.parse(await Bun.file(new URL("../package.json", import.meta.url)).text()).version);
const list = await rpc("tools/list", {});
expect(list.result.tools.some((t: { name: string }) => t.name === "unraid_share_apply")).toBe(true);
const fail = await rpc("tools/call", { name: "unraid_system_shell", arguments: { command: "exit 17" } });
expect(fail.result.isError).toBe(true);
expect(fail.result.structuredContent.exit_code).toBe(17);
const denied = await rpc("tools/call", { name: "unraid_share_apply", arguments: { approval_ticket: "invalid", confirm: true } });
expect(denied.result.isError).toBe(true);
// An oversized chunked upload must be rejected before its producer ends.
// Content-Length checks or trimming after req.text() are insufficient.
const abort = new AbortController();
const timer = setTimeout(() => abort.abort(), 2000);
try {
const oversized = await fetch("http://127.0.0.1:39871/mcp", {
method: "POST", headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" },
body: new ReadableStream<Uint8Array>({ start(controller) { controller.enqueue(new Uint8Array(16385)); } }),
signal: abort.signal,
});
expect(oversized.status).toBe(413);
await oversized.body?.cancel();
} finally {
clearTimeout(timer);
abort.abort();
}
} finally {
child.kill(); await child.exited;
rmSync(root, { recursive: true, force: true });
}
}, 15000);