Publish optional native HTTPS and explicit Unraid WebGUI PEM reuse from 1677894. Synchronize all release versions and TXZ/manifest/checksum, use transport-aware authenticated local post-install readiness, preserve r033, and document operator-only installation/trust/renewal. Verified 68 source tests, 31 extracted-r034 transport tests, 52 PHP checks and all 7 release/archive/hook gates; final independent fresh-context AI review passed without blocking security/logic findings. No production installation or configuration changes.
597 lines
34 KiB
TypeScript
597 lines
34 KiB
TypeScript
import { afterAll, beforeAll, expect, test } from "bun:test";
|
|
import { chmodSync, mkdtempSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
import { tmpdir } from "node:os";
|
|
import { join } from "node:path";
|
|
import { connect } from "node:net";
|
|
import { request } from "node:https";
|
|
import { tlsOptions } from "./tls";
|
|
|
|
// All listeners, certificates, tokens and tool data in this suite are synthetic.
|
|
let root: string;
|
|
let cert: string;
|
|
let key: string;
|
|
const testToken = "synthetic-mua-transport-test";
|
|
const expectedVersion = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
|
|
|
|
function openssl(...args: string[]) {
|
|
const result = Bun.spawnSync(["openssl", ...args], { stdout: "pipe", stderr: "pipe" });
|
|
if (result.exitCode !== 0) throw new Error(result.stderr.toString());
|
|
}
|
|
|
|
beforeAll(() => {
|
|
root = mkdtempSync(join(tmpdir(), "mua-tls-test-"));
|
|
cert = join(root, "server.pem");
|
|
key = join(root, "server.key");
|
|
openssl("req", "-x509", "-newkey", "ec", "-pkeyopt", "ec_paramgen_curve:P-256", "-nodes",
|
|
"-days", "2", "-subj", "/CN=localhost", "-addext", "subjectAltName=DNS:localhost,IP:127.0.0.1",
|
|
"-keyout", key, "-out", cert);
|
|
chmodSync(key, 0o600);
|
|
mkdirSync(join(root, "bin"));
|
|
writeFileSync(join(root, "bin/docker"), "#!/bin/sh\nprintf '[]'\n", { mode: 0o755 });
|
|
});
|
|
afterAll(() => rmSync(root, { recursive: true, force: true }));
|
|
|
|
test("same-path combined PEM uses one in-memory snapshot for certificate and key", () => {
|
|
const bundle = join(root, "snapshot-bundle.pem");
|
|
writeFileSync(bundle, readFileSync(key, "utf8") + readFileSync(cert, "utf8"), { mode: 0o600 });
|
|
const options = tlsOptions({ enabled: true, certFile: bundle, keyFile: bundle })!;
|
|
// Compare identity without printing either secret buffer on a test failure.
|
|
expect(options.cert === options.key).toBe(true);
|
|
});
|
|
|
|
function unraidBundle(keyFirst: boolean) {
|
|
const dir = mkdtempSync(join(root, "unraid-bundle-"));
|
|
const generatedCert = join(dir, "generated-cert.pem");
|
|
const generatedKey = join(dir, "generated-key.pem");
|
|
const bundle = join(dir, "selected-webgui-bundle.pem");
|
|
const publicCert = join(dir, "webgui-public.pem");
|
|
openssl("req", "-x509", "-newkey", "rsa:2048", "-sha256", "-nodes", "-days", "2",
|
|
"-subj", "/CN=localhost", "-addext", "basicConstraints=critical,CA:FALSE",
|
|
"-addext", "keyUsage=critical,digitalSignature,keyEncipherment", "-addext", "extendedKeyUsage=serverAuth",
|
|
"-addext", "subjectAltName=DNS:localhost,IP:127.0.0.1", "-keyout", generatedKey, "-out", generatedCert);
|
|
const certPEM = readFileSync(generatedCert, "utf8");
|
|
const keyPEM = readFileSync(generatedKey, "utf8");
|
|
writeFileSync(bundle, keyFirst ? keyPEM + certPEM : certPEM + keyPEM, { mode: 0o600 });
|
|
// Retain no separate server key. Only extract the public leaf for client trust.
|
|
rmSync(generatedCert);
|
|
rmSync(generatedKey);
|
|
openssl("x509", "-in", bundle, "-out", publicCert);
|
|
return { dir, bundle, publicCert };
|
|
}
|
|
|
|
// Bun 1.3.14's node:https client rejects a trusted self-signed CA:FALSE leaf
|
|
// even with separate server files. OpenSSL/curl/Python/Node verify it correctly;
|
|
// use curl here rather than weakening validation or turning the leaf into a CA.
|
|
async function bundleRequest(port: number, path: string, publicCert: string, body?: unknown, token?: string) {
|
|
const config = [
|
|
`url = ${JSON.stringify(`https://127.0.0.1:${port}${path}`)}`,
|
|
`cacert = ${JSON.stringify(publicCert)}`,
|
|
...(body ? ['request = "POST"', 'header = "Content-Type: application/json"',
|
|
'header = "Accept: application/json, text/event-stream"', `data = ${JSON.stringify(JSON.stringify(body))}`] : []),
|
|
...(token ? [`header = ${JSON.stringify(`Authorization: Bearer ${token}`)}`] : []),
|
|
].join("\n") + "\n";
|
|
const result = Bun.spawnSync(["curl", "--noproxy", "*", "--silent", "--show-error", "--max-time", "3",
|
|
"--write-out", "\n%{http_code}", "--config", "-"],
|
|
{ stdin: Buffer.from(config), stdout: "pipe", stderr: "pipe" });
|
|
if (result.exitCode !== 0) throw new Error("Verified HTTPS bundle request failed");
|
|
const text = result.stdout.toString();
|
|
const split = text.lastIndexOf("\n");
|
|
return { status: Number(text.slice(split + 1)), data: JSON.parse(text.slice(0, split)) };
|
|
}
|
|
|
|
for (const keyFirst of [true, false]) {
|
|
test(`Unraid combined PEM (${keyFirst ? "key" : "certificate"} first) supports verified TLS and authenticated MCP`, async () => {
|
|
const fixture = unraidBundle(keyFirst);
|
|
const original = readFileSync(fixture.bundle);
|
|
const publicPEM = readFileSync(fixture.publicCert);
|
|
expect(publicPEM.includes("PRIVATE KEY")).toBe(false);
|
|
expect(readdirSync(fixture.dir).sort()).toEqual(["selected-webgui-bundle.pem", "webgui-public.pem"]);
|
|
const app = await start(tlsConfig(fixture.bundle, fixture.bundle));
|
|
try {
|
|
const health = await bundleRequest(app.port, "/health", fixture.publicCert);
|
|
expect(health.status).toBe(200);
|
|
expect(health.data.version).toBe(expectedVersion);
|
|
const rpc = async (id: number, method: string, params: unknown = {}) => bundleRequest(app.port, "/mcp",
|
|
fixture.publicCert, { jsonrpc: "2.0", id, method, params }, testToken);
|
|
const initialized = await rpc(1, "initialize", { protocolVersion: "2025-03-26", capabilities: {},
|
|
clientInfo: { name: "unraid-bundle-test", version: "1" } });
|
|
expect(initialized.data.result.serverInfo.name).toBeDefined();
|
|
expect(initialized.data.result.serverInfo.version).toBe(expectedVersion);
|
|
expect((await rpc(2, "tools/list")).data.result.tools.some((t: any) => t.name === "unraid_system_shell_readonly")).toBe(true);
|
|
const called = await rpc(3, "tools/call", { name: "unraid_system_shell_readonly",
|
|
arguments: { program: "ls", args: ["-ld", fixture.dir] } });
|
|
expect(called.data.result.isError).toBeUndefined();
|
|
expect(JSON.parse(called.data.result.content[0].text).exit_code).toBe(0);
|
|
expect((await bundleRequest(app.port, "/mcp", fixture.publicCert, { method: "ping" })).status).toBe(401);
|
|
// An unrelated CA and a wrong hostname both fail while verification stays enabled.
|
|
await expect(bundleRequest(app.port, "/health", cert)).rejects.toThrow();
|
|
const peer = Bun.spawnSync(["openssl", "s_client", "-connect", `127.0.0.1:${app.port}`,
|
|
"-servername", "localhost", "-verify_hostname", "localhost", "-verify_return_error",
|
|
"-CAfile", fixture.publicCert, "-showcerts"], { stdin: new Uint8Array(), stdout: "pipe", stderr: "pipe" });
|
|
expect(peer.exitCode).toBe(0);
|
|
expect(peer.stdout.includes("PRIVATE KEY")).toBe(false);
|
|
const wrongName = Bun.spawnSync(["openssl", "s_client", "-connect", `127.0.0.1:${app.port}`,
|
|
"-verify_hostname", "other.example.invalid", "-verify_return_error", "-CAfile", fixture.publicCert],
|
|
{ stdin: new Uint8Array(), stdout: "pipe", stderr: "pipe" });
|
|
expect(wrongName.exitCode).not.toBe(0);
|
|
expect(wrongName.stderr.toString().includes("hostname mismatch")).toBe(true);
|
|
const admin = readFileSync(join(app.dir, "admin.token"), "utf8").trim();
|
|
const saved = await fetch(`http://127.0.0.1:${app.configPort}/config`, { method: "POST",
|
|
headers: { "X-MUA-Admin-Token": admin, "Content-Type": "application/json" },
|
|
body: JSON.stringify({ tls: { enabled: true, certFile: fixture.bundle, keyFile: fixture.bundle } }) });
|
|
expect(saved.status).toBe(200);
|
|
expect((await saved.text()).includes("PRIVATE KEY")).toBe(false);
|
|
expect(readFileSync(fixture.bundle).equals(original)).toBe(true);
|
|
for (const name of readdirSync(app.dir)) {
|
|
expect(readFileSync(join(app.dir, name)).includes("-----BEGIN PRIVATE KEY-----")).toBe(false);
|
|
}
|
|
} finally { await app.stop(); }
|
|
expect(((await app.stdout) + (await app.stderr)).includes("PRIVATE KEY")).toBe(false);
|
|
}, 10_000);
|
|
}
|
|
|
|
for (const part of ["certificate", "key"]) {
|
|
test(`same-path PEM with only ${part} fails closed without private material in logs`, async () => {
|
|
const bundle = join(root, `incomplete-${part}.pem`);
|
|
writeFileSync(bundle, readFileSync(part === "certificate" ? cert : key), { mode: 0o600 });
|
|
const app = await start(tlsConfig(bundle, bundle));
|
|
try {
|
|
const exit = await Promise.race([app.child.exited, Bun.sleep(1000).then(() => "still-running")]);
|
|
expect(exit).not.toBe("still-running");
|
|
expect(exit).not.toBe(0);
|
|
expect(await tcpReady(app.port)).toBe(false);
|
|
expect(((await app.stdout) + (await app.stderr)).includes("PRIVATE KEY")).toBe(false);
|
|
} finally { await app.stop(); }
|
|
}, 10_000);
|
|
}
|
|
|
|
test("replacing the selected Unraid bundle requires restart and refreshed public-only trust", async () => {
|
|
const fixture = unraidBundle(true);
|
|
const replacement = unraidBundle(false);
|
|
const dir = mkdtempSync(join(root, "bundle-service-"));
|
|
const port = await freePort();
|
|
const configPort = await freePort();
|
|
const wrapper = join(dir, "daemon");
|
|
const quote = (s: string) => "'" + s.replaceAll("'", "'\\''") + "'";
|
|
const command = process.env.MUA_TEST_BINARY ? quote(process.env.MUA_TEST_BINARY) : `${quote(process.execPath)} ${quote(join(import.meta.dir, "index.ts"))}`;
|
|
writeFileSync(wrapper, `#!/bin/sh\nexec ${command} "$@"\n`, { mode: 0o755 });
|
|
writeFileSync(join(dir, "tls.conf"), tlsConfig(fixture.bundle, fixture.bundle));
|
|
const env = { ...process.env, MUA_BINARY: wrapper, MUA_CONFIG_DIR: dir, MUA_HOST: "127.0.0.1",
|
|
MUA_PORT: String(port), MUA_CONFIG_PORT: String(configPort), MUA_PIDFILE: join(dir, "mua.pid"),
|
|
MUA_LOGFILE: join(dir, "mua.log"), MUA_ADMIN_TOKEN_FILE: join(dir, "admin.token"),
|
|
MUA_AUDIT_LOG: join(dir, "audit.log"), MUA_API_KEY: testToken, MUA_ENABLED_TOOLS: "none" };
|
|
const service = (action: string) => Bun.spawnSync(["bash", join(import.meta.dir, "../scripts/rc.mua"), action],
|
|
{ env, stdout: "pipe", stderr: "pipe" });
|
|
try {
|
|
expect(service("start").exitCode).toBe(0);
|
|
expect((await bundleRequest(port, "/health", fixture.publicCert)).status).toBe(200);
|
|
renameSync(replacement.bundle, fixture.bundle); // Same configured path, new self-signed leaf/key.
|
|
expect((await bundleRequest(port, "/health", fixture.publicCert)).status).toBe(200);
|
|
await expect(bundleRequest(port, "/health", replacement.publicCert)).rejects.toThrow();
|
|
expect(service("restart").exitCode).toBe(0);
|
|
const ping = await bundleRequest(port, "/mcp", replacement.publicCert,
|
|
{ jsonrpc: "2.0", id: 1, method: "ping" }, testToken);
|
|
expect(ping.status).toBe(200);
|
|
expect(ping.data.result).toEqual({});
|
|
await expect(bundleRequest(port, "/health", fixture.publicCert)).rejects.toThrow();
|
|
writeFileSync(fixture.bundle, "invalid synthetic bundle");
|
|
expect(service("restart").exitCode).not.toBe(0);
|
|
expect((await bundleRequest(port, "/health", replacement.publicCert)).status).toBe(200);
|
|
} finally { service("stop"); }
|
|
}, 15_000);
|
|
|
|
async function freePort(): Promise<number> {
|
|
const probe = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch: () => new Response() });
|
|
const port = probe.port!;
|
|
await probe.stop(true);
|
|
return port;
|
|
}
|
|
|
|
async function tcpReady(port: number): Promise<boolean> {
|
|
return new Promise((resolve) => {
|
|
const socket = connect({ host: "127.0.0.1", port });
|
|
socket.setTimeout(100);
|
|
socket.once("connect", () => { socket.destroy(); resolve(true); });
|
|
socket.once("error", () => { socket.destroy(); resolve(false); });
|
|
socket.once("timeout", () => { socket.destroy(); resolve(false); });
|
|
});
|
|
}
|
|
|
|
async function start(tlsConfig: string | null, overrides: Record<string, string> = {}) {
|
|
const dir = mkdtempSync(join(root, "instance-"));
|
|
if (tlsConfig !== null) writeFileSync(join(dir, "tls.conf"), tlsConfig);
|
|
const port = await freePort();
|
|
const configPort = await freePort();
|
|
const entry = process.env.MUA_TEST_BINARY;
|
|
const child = Bun.spawn(entry ? [entry] : [process.execPath, join(import.meta.dir, "index.ts")], {
|
|
env: { ...process.env, MUA_TLS_ENABLED: undefined, MUA_TLS_CERT_FILE: undefined,
|
|
MUA_TLS_KEY_FILE: undefined, MUA_CONFIG_DIR: dir, MUA_PORT: String(port),
|
|
MUA_HOST: "127.0.0.1", MUA_CONFIG_PORT: String(configPort),
|
|
MUA_API_KEY: testToken, MUA_ENABLED_TOOLS: "unraid_system_shell_readonly",
|
|
MUA_ADMIN_TOKEN_FILE: join(dir, "admin.token"), MUA_AUDIT_LOG: join(dir, "audit.log"),
|
|
MUA_BINARY: join(dir, "no-update-binary"), PATH: join(root, "bin") + ":" + process.env.PATH,
|
|
...overrides }, stdout: "pipe", stderr: "pipe",
|
|
});
|
|
const stdout = new Response(child.stdout).text();
|
|
const stderr = new Response(child.stderr).text();
|
|
const deadline = performance.now() + 5000;
|
|
while (performance.now() < deadline && child.exitCode === null) {
|
|
if (await tcpReady(port) && await tcpReady(configPort)) break;
|
|
await Bun.sleep(20);
|
|
}
|
|
return { child, dir, port, configPort, stdout, stderr, async stop() {
|
|
child.kill();
|
|
await child.exited;
|
|
} };
|
|
}
|
|
|
|
function httpsJson(port: number, path: string, body?: unknown, token?: string, ca = readFileSync(cert)):
|
|
Promise<{ status: number; data: any; headers: Record<string, unknown> }> {
|
|
return new Promise((resolve, reject) => {
|
|
const req = request({ hostname: "127.0.0.1", port, path, method: body ? "POST" : "GET",
|
|
ca, rejectUnauthorized: true, headers: {
|
|
...(body ? { "Content-Type": "application/json", Accept: "application/json, text/event-stream" } : {}),
|
|
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
|
}, timeout: 2000 }, (res) => {
|
|
let text = "";
|
|
res.setEncoding("utf8");
|
|
res.on("data", (part) => { text += part; });
|
|
res.on("end", () => {
|
|
try { resolve({ status: res.statusCode!, data: JSON.parse(text), headers: res.headers }); }
|
|
catch (error) { reject(error); }
|
|
});
|
|
});
|
|
req.on("error", reject);
|
|
req.on("timeout", () => req.destroy(new Error("HTTPS test timed out")));
|
|
if (body) req.write(JSON.stringify(body));
|
|
req.end();
|
|
});
|
|
}
|
|
|
|
test("local status authenticates admin token and reports actual HTTPS without PEM material", async () => {
|
|
const app = await start(tlsConfig());
|
|
try {
|
|
const url = `http://127.0.0.1:${app.configPort}/status`;
|
|
expect((await fetch(url)).status).toBe(401);
|
|
const token = readFileSync(join(app.dir, "admin.token"), "utf8").trim();
|
|
const response = await fetch(url, { headers: { "X-MUA-Admin-Token": token } });
|
|
expect(response.status).toBe(200);
|
|
const status = await response.json() as any;
|
|
expect(status.status).toBe("ok");
|
|
expect(status.version).toBe(expectedVersion);
|
|
expect(status.scheme).toBe("https");
|
|
expect(status.port).toBe(app.port);
|
|
expect(JSON.stringify(status)).not.toContain("PRIVATE KEY");
|
|
expect(JSON.stringify(status)).not.toContain(testToken);
|
|
} finally { await app.stop(); }
|
|
}, 10_000);
|
|
|
|
test("--check-config validates certificates and exits without opening listeners", async () => {
|
|
const dir = mkdtempSync(join(root, "preflight-"));
|
|
const port = await freePort();
|
|
writeFileSync(join(dir, "tls.conf"), tlsConfig());
|
|
const entry = process.env.MUA_TEST_BINARY;
|
|
const child = Bun.spawn(entry ? [entry, "--check-config"] : [process.execPath, join(import.meta.dir, "index.ts"), "--check-config"], {
|
|
env: { ...process.env, MUA_CONFIG_DIR: dir, MUA_PORT: String(port), MUA_HOST: "127.0.0.1",
|
|
MUA_CONFIG_PORT: String(await freePort()), MUA_ADMIN_TOKEN_FILE: join(dir, "admin.token") }, stdout: "pipe", stderr: "pipe",
|
|
});
|
|
try {
|
|
const exit = await Promise.race([child.exited, Bun.sleep(500).then(() => "still-running")]);
|
|
expect(exit).toBe(0);
|
|
expect(await tcpReady(port)).toBe(false);
|
|
expect(await new Response(child.stderr).text()).toBe("");
|
|
} finally { child.kill(); await child.exited; }
|
|
}, 5000);
|
|
|
|
test("SysV health uses local authenticated status even when MCP requires HTTPS", async () => {
|
|
const app = await start(tlsConfig());
|
|
try {
|
|
const result = Bun.spawnSync(["bash", join(import.meta.dir, "../scripts/rc.mua"), "health"], {
|
|
env: { ...process.env, MUA_CONFIG_PORT: String(app.configPort), MUA_ADMIN_TOKEN_FILE: join(app.dir, "admin.token"),
|
|
http_proxy: "http://127.0.0.1:1", no_proxy: "", NO_PROXY: "" },
|
|
stdout: "pipe", stderr: "pipe",
|
|
});
|
|
expect(result.exitCode).toBe(0);
|
|
const status = JSON.parse(result.stdout.toString());
|
|
expect(status.scheme).toBe("https");
|
|
expect(status.status).toBe("ok");
|
|
expect(result.stdout.toString()).not.toContain(readFileSync(join(app.dir, "admin.token"), "utf8").trim());
|
|
} finally { await app.stop(); }
|
|
}, 10_000);
|
|
|
|
test("WebGUI renders HTTPS settings and active endpoint through the local config server", async () => {
|
|
const app = await start(tlsConfig());
|
|
try {
|
|
const html = renderWebGUI(app);
|
|
expect(html.includes(`https://127.0.0.1:${app.port}/mcp`)).toBe(true);
|
|
expect(html).toContain('name="tls_cert_file"');
|
|
expect(html).toContain('name="tls_key_file"');
|
|
expect(html).toContain('name="tls_enabled"');
|
|
expect(html).toContain(cert);
|
|
expect(html).not.toContain(readFileSync(key, "utf8").trim());
|
|
} finally { await app.stop(); }
|
|
}, 10_000);
|
|
|
|
test("SysV restart preflights bad renewed certificates before stopping a healthy HTTPS listener", async () => {
|
|
const dir = mkdtempSync(join(root, "service-"));
|
|
const port = await freePort();
|
|
const configPort = await freePort();
|
|
const wrapper = join(dir, "daemon");
|
|
const quote = (s: string) => "'" + s.replaceAll("'", "'\\''") + "'";
|
|
const command = process.env.MUA_TEST_BINARY ? quote(process.env.MUA_TEST_BINARY) : `${quote(process.execPath)} ${quote(join(import.meta.dir, "index.ts"))}`;
|
|
writeFileSync(wrapper, `#!/bin/sh\nexec ${command} "$@"\n`, { mode: 0o755 });
|
|
writeFileSync(join(dir, "tls.conf"), tlsConfig());
|
|
const env = { ...process.env, MUA_BINARY: wrapper, MUA_CONFIG_DIR: dir, MUA_HOST: "127.0.0.1",
|
|
MUA_PORT: String(port), MUA_CONFIG_PORT: String(configPort), MUA_PIDFILE: join(dir, "mua.pid"),
|
|
MUA_LOGFILE: join(dir, "mua.log"), MUA_ADMIN_TOKEN_FILE: join(dir, "admin.token"),
|
|
MUA_AUDIT_LOG: join(dir, "audit.log"), MUA_API_KEY: testToken, MUA_ENABLED_TOOLS: "none" };
|
|
const service = (action: string) => Bun.spawnSync(["bash", join(import.meta.dir, "../scripts/rc.mua"), action],
|
|
{ env, stdout: "pipe", stderr: "pipe" });
|
|
try {
|
|
expect(service("start").exitCode).toBe(0);
|
|
expect((await httpsJson(port, "/health")).status).toBe(200);
|
|
writeFileSync(join(dir, "tls.conf"), tlsConfig(cert, join(root, "absent-renewal.key")));
|
|
expect(service("restart").exitCode).not.toBe(0);
|
|
expect((await httpsJson(port, "/health")).status).toBe(200);
|
|
const renewedCert = join(dir, "renewed.pem");
|
|
const renewedKey = join(dir, "renewed.key");
|
|
openssl("req", "-x509", "-newkey", "ec", "-pkeyopt", "ec_paramgen_curve:P-256", "-nodes", "-days", "2",
|
|
"-subj", "/CN=localhost", "-addext", "subjectAltName=DNS:localhost,IP:127.0.0.1", "-keyout", renewedKey, "-out", renewedCert);
|
|
writeFileSync(join(dir, "tls.conf"), tlsConfig(renewedCert, renewedKey));
|
|
expect(service("restart").exitCode).toBe(0);
|
|
expect((await httpsJson(port, "/health", undefined, undefined, readFileSync(renewedCert))).status).toBe(200);
|
|
await expect(httpsJson(port, "/health")).rejects.toThrow();
|
|
} finally { service("stop"); }
|
|
}, 10_000);
|
|
|
|
test("WebGUI enforces CSRF and saves TLS separately, with clear invalid-certificate errors", async () => {
|
|
const app = await start("");
|
|
try {
|
|
const html = renderWebGUI(app);
|
|
const csrf = /name="mua_csrf" value="([a-f0-9]+)"/.exec(html)![1];
|
|
const fields = { action: "save_tls", tls_enabled: "on", tls_cert_file: cert, tls_key_file: key };
|
|
expect(renderWebGUI(app, { ...fields, mua_csrf: "invalid" }).includes("Sicherheitsprüfung fehlgeschlagen")).toBe(true);
|
|
expect(readFileSync(join(app.dir, "tls.conf"), "utf8")).toBe("");
|
|
const saved = renderWebGUI(app, { ...fields, mua_csrf: csrf });
|
|
expect(saved.includes("TLS-Einstellungen geprüft und gespeichert")).toBe(true);
|
|
expect(saved.includes("noch nicht aktiv")).toBe(true);
|
|
const content = readFileSync(join(app.dir, "tls.conf"), "utf8");
|
|
const invalid = renderWebGUI(app, { ...fields, tls_key_file: join(root, "missing.key"), mua_csrf: csrf });
|
|
expect(invalid.includes("PEM-Datei fehlt")).toBe(true);
|
|
expect(readFileSync(join(app.dir, "tls.conf"), "utf8")).toBe(content);
|
|
} finally { await app.stop(); }
|
|
}, 10_000);
|
|
|
|
test("TLS environment overrides take precedence and prevent conflicting WebGUI saves", async () => {
|
|
const app = await start(tlsConfig(join(root, "absent.pem")), { MUA_TLS_ENABLED: "false" });
|
|
try {
|
|
expect((await fetch(`http://127.0.0.1:${app.port}/health`)).status).toBe(200);
|
|
const token = readFileSync(join(app.dir, "admin.token"), "utf8").trim();
|
|
const url = `http://127.0.0.1:${app.configPort}/config`;
|
|
const before = readFileSync(join(app.dir, "tls.conf"), "utf8");
|
|
const result = await fetch(url, { method: "POST", headers: { "X-MUA-Admin-Token": token,
|
|
"Content-Type": "application/json" }, body: JSON.stringify({ tls: { enabled: true, certFile: cert, keyFile: key } }) });
|
|
expect(result.status).toBe(400);
|
|
expect(readFileSync(join(app.dir, "tls.conf"), "utf8")).toBe(before);
|
|
expect(renderWebGUI(app).includes("WebGUI-Änderung gesperrt")).toBe(true);
|
|
} finally { await app.stop(); }
|
|
}, 10_000);
|
|
|
|
test("invalid TLS admin input never alters persisted TLS or permissions", async () => {
|
|
const app = await start("");
|
|
try {
|
|
const token = readFileSync(join(app.dir, "admin.token"), "utf8").trim();
|
|
for (const tls of [null, [], { enabled: "true", certFile: cert, keyFile: key },
|
|
{ enabled: true, certFile: cert, keyFile: join(root, "absent.key") },
|
|
{ enabled: false, certFile: cert + "\nMUA_TLS_ENABLED=true", keyFile: key }]) {
|
|
const response = await fetch(`http://127.0.0.1:${app.configPort}/config`, { method: "POST",
|
|
headers: { "X-MUA-Admin-Token": token, "Content-Type": "application/json" }, body: JSON.stringify({ tls }) });
|
|
expect(response.status).toBe(400);
|
|
expect(readFileSync(join(app.dir, "tls.conf"), "utf8")).toBe("");
|
|
}
|
|
expect((await fetch(`http://127.0.0.1:${app.port}/health`)).status).toBe(200);
|
|
} finally { await app.stop(); }
|
|
}, 10_000);
|
|
|
|
test("admin restart rejects invalid renewed TLS before spawning the service script", async () => {
|
|
const app = await start(tlsConfig(), { MUA_RC_SCRIPT: join(root, "no-such-service-script") });
|
|
try {
|
|
writeFileSync(join(app.dir, "tls.conf"), tlsConfig(cert, join(root, "missing.key")));
|
|
const token = readFileSync(join(app.dir, "admin.token"), "utf8").trim();
|
|
const response = await fetch(`http://127.0.0.1:${app.configPort}/restart`, { method: "POST",
|
|
headers: { "X-MUA-Admin-Token": token } });
|
|
expect(response.status).toBe(400);
|
|
expect((await httpsJson(app.port, "/health")).status).toBe(200);
|
|
} finally { await app.stop(); }
|
|
}, 10_000);
|
|
|
|
test("native HTTPS sends intermediate certificates for a privately issued full chain", async () => {
|
|
const dir = mkdtempSync(join(root, "chain-"));
|
|
const intermediate = join(dir, "intermediate.pem");
|
|
const intermediateKey = join(dir, "intermediate.key");
|
|
const intermediateCSR = join(dir, "intermediate.csr");
|
|
openssl("req", "-new", "-newkey", "ec", "-pkeyopt", "ec_paramgen_curve:P-256", "-nodes",
|
|
"-subj", "/CN=MUA synthetic intermediate", "-keyout", intermediateKey, "-out", intermediateCSR);
|
|
const extensions = join(dir, "extensions.cnf");
|
|
writeFileSync(extensions, "[ca]\nbasicConstraints=critical,CA:TRUE,pathlen:0\nkeyUsage=critical,keyCertSign,cRLSign\n[server]\nbasicConstraints=critical,CA:FALSE\nkeyUsage=critical,digitalSignature\nextendedKeyUsage=serverAuth\nsubjectAltName=DNS:localhost,IP:127.0.0.1\n");
|
|
openssl("x509", "-req", "-in", intermediateCSR, "-CA", cert, "-CAkey", key, "-set_serial", "2",
|
|
"-days", "2", "-extfile", extensions, "-extensions", "ca", "-out", intermediate);
|
|
const leafKey = join(dir, "leaf.key");
|
|
const leafCSR = join(dir, "leaf.csr");
|
|
const leaf = join(dir, "leaf.pem");
|
|
openssl("req", "-new", "-newkey", "ec", "-pkeyopt", "ec_paramgen_curve:P-256", "-nodes",
|
|
"-subj", "/CN=localhost", "-keyout", leafKey, "-out", leafCSR);
|
|
openssl("x509", "-req", "-in", leafCSR, "-CA", intermediate, "-CAkey", intermediateKey, "-set_serial", "3",
|
|
"-days", "1", "-extfile", extensions, "-extensions", "server", "-out", leaf);
|
|
const chain = join(dir, "fullchain.pem");
|
|
writeFileSync(chain, readFileSync(leaf, "utf8") + readFileSync(intermediate, "utf8"));
|
|
const app = await start(tlsConfig(chain, leafKey));
|
|
try { expect((await httpsJson(app.port, "/health")).status).toBe(200); }
|
|
finally { await app.stop(); }
|
|
}, 10_000);
|
|
|
|
function renderWebGUI(app: { port: number; configPort: number; dir: string }, post?: Record<string, string>) {
|
|
const result = Bun.spawnSync(["php", "-r", '$_SERVER["REQUEST_METHOD"]=$argc>2?"POST":"GET"; $_SERVER["SERVER_ADDR"]="127.0.0.1"; $var=["csrf_token"=>"synthetic"]; if($argc>2) $_POST=json_decode($argv[2],true); require $argv[1];',
|
|
join(import.meta.dir, "../scripts/mua.page"), ...(post ? [JSON.stringify(post)] : [])], {
|
|
env: { ...process.env, MUA_PORT: String(app.port), MUA_CONFIG_PORT: String(app.configPort),
|
|
MUA_ADMIN_TOKEN_FILE: join(app.dir, "admin.token"), MUA_PIDFILE: join(app.dir, "pid"),
|
|
http_proxy: "http://127.0.0.1:1", no_proxy: "", NO_PROXY: "" },
|
|
stdout: "pipe", stderr: "pipe",
|
|
});
|
|
if (result.exitCode !== 0 || result.stderr.length) throw new Error(result.stderr.toString());
|
|
return result.stdout.toString();
|
|
}
|
|
|
|
function tlsConfig(certFile = cert, keyFile = key) {
|
|
return `MUA_TLS_ENABLED=true\nMUA_TLS_CERT_FILE=${certFile}\nMUA_TLS_KEY_FILE=${keyFile}\n`;
|
|
}
|
|
|
|
test("native HTTPS serves health with a verified certificate and authenticated MCP tool call", async () => {
|
|
const app = await start(tlsConfig());
|
|
try {
|
|
const health = await httpsJson(app.port, "/health");
|
|
expect(health.status).toBe(200);
|
|
expect(health.data.auth).toBe("required");
|
|
const init = await httpsJson(app.port, "/mcp", { jsonrpc: "2.0", id: 1, method: "initialize",
|
|
params: { protocolVersion: "2025-03-26", capabilities: {}, clientInfo: { name: "tls-test", version: "1" } } }, testToken);
|
|
expect(init.status).toBe(200);
|
|
expect(init.data.result.serverInfo.name).toBeDefined();
|
|
expect(init.headers["mcp-session-id"]).toBeTruthy();
|
|
const list = await httpsJson(app.port, "/mcp", { jsonrpc: "2.0", id: 2, method: "tools/list" }, testToken);
|
|
expect(list.data.result.tools.map((tool: any) => tool.name)).toEqual(["unraid_files_inventory", "unraid_system_shell_readonly"]);
|
|
const result = await httpsJson(app.port, "/mcp", { jsonrpc: "2.0", id: 3, method: "tools/call",
|
|
params: { name: "unraid_system_shell_readonly", arguments: { program: "ls", args: ["-ld", app.dir] } } }, testToken);
|
|
expect(result.data.result.isError).toBeUndefined();
|
|
expect(JSON.parse(result.data.result.content[0].text).exit_code).toBe(0);
|
|
expect((await httpsJson(app.port, "/mcp", { method: "ping" })).status).toBe(401);
|
|
expect((await httpsJson(app.port, "/mcp", { method: "ping" }, "incorrect")).status).toBe(401);
|
|
const blocked = await httpsJson(app.port, "/mcp", { jsonrpc: "2.0", id: 4, method: "tools/call",
|
|
params: { name: "unraid_system_shell", arguments: { command: "must-not-execute" } } }, testToken);
|
|
expect(blocked.data.result.isError).toBe(true);
|
|
expect(blocked.data.result.content[0].text).toContain("Tool disabled");
|
|
} finally { await app.stop(); }
|
|
}, 10_000);
|
|
|
|
test("local admin stages validated TLS without changing auth or the active listener", async () => {
|
|
const app = await start("");
|
|
try {
|
|
const authFile = join(app.dir, "mua.conf");
|
|
const authContents = "# synthetic existing credentials and permissions\nMUA_API_KEY=synthetic\nMUA_ENABLED_TOOLS=none\n";
|
|
writeFileSync(authFile, authContents);
|
|
const admin = readFileSync(join(app.dir, "admin.token"), "utf8").trim();
|
|
const url = `http://127.0.0.1:${app.configPort}/config`;
|
|
const before = await fetch(url, { headers: { "X-MUA-Admin-Token": admin } });
|
|
expect((await before.json() as any).transport.scheme).toBe("http");
|
|
const response = await fetch(url, { method: "POST", headers: { "X-MUA-Admin-Token": admin,
|
|
"Content-Type": "application/json" }, body: JSON.stringify({ tls: { enabled: true, certFile: cert, keyFile: key } }) });
|
|
expect(response.status).toBe(200);
|
|
const result = await response.json() as any;
|
|
expect(result.transport.scheme).toBe("http");
|
|
expect(result.transport.tls.enabled).toBe(true);
|
|
expect(result.transport.restartRequired).toBe(true);
|
|
expect(readFileSync(authFile, "utf8")).toBe(authContents);
|
|
expect(readFileSync(join(app.dir, "tls.conf"), "utf8")).toContain("MUA_TLS_ENABLED=true");
|
|
expect((await fetch(`http://127.0.0.1:${app.port}/health`)).status).toBe(200);
|
|
} finally { await app.stop(); }
|
|
}, 10_000);
|
|
|
|
for (const [name, config] of [
|
|
["missing certificate", () => tlsConfig(join(root, "absent.pem"))],
|
|
["missing key", () => tlsConfig(cert, join(root, "absent.key"))],
|
|
["unset paths", () => "MUA_TLS_ENABLED=true\n"],
|
|
["relative path", () => tlsConfig("relative.pem")],
|
|
["invalid boolean", () => "MUA_TLS_ENABLED=tru\n"],
|
|
["duplicate enable flag", () => tlsConfig() + "MUA_TLS_ENABLED=false\n"],
|
|
["malformed PEM", () => {
|
|
const path = join(root, "malformed.pem");
|
|
writeFileSync(path, "SYNTHETIC-SECRET-MUST-NOT-APPEAR");
|
|
return tlsConfig(path);
|
|
}],
|
|
["mismatched key", () => {
|
|
const path = join(root, "other.key");
|
|
openssl("genpkey", "-algorithm", "EC", "-pkeyopt", "ec_paramgen_curve:P-256", "-out", path);
|
|
return tlsConfig(cert, path);
|
|
}],
|
|
["encrypted key", () => {
|
|
const path = join(root, "encrypted.key");
|
|
openssl("pkey", "-in", key, "-aes-256-cbc", "-passout", "pass:synthetic-test-passphrase", "-out", path);
|
|
return tlsConfig(cert, path);
|
|
}],
|
|
["expired certificate", () => {
|
|
const csr = join(root, "expired.csr");
|
|
const path = join(root, "expired.pem");
|
|
openssl("req", "-new", "-key", key, "-subj", "/CN=expired-test", "-out", csr);
|
|
const caConfig = join(root, "expiry-ca.cnf");
|
|
writeFileSync(join(root, "expiry-index"), "");
|
|
writeFileSync(join(root, "expiry-serial"), "01\n");
|
|
writeFileSync(caConfig, `[ca]\ndefault_ca=test\n[test]\ndatabase=${join(root, "expiry-index")}\nserial=${join(root, "expiry-serial")}\nnew_certs_dir=${root}\ndefault_md=sha256\npolicy=policy\n[policy]\ncommonName=supplied\n`);
|
|
openssl("ca", "-selfsign", "-batch", "-config", caConfig, "-keyfile", key, "-in", csr,
|
|
"-startdate", "20200101000000Z", "-enddate", "20200102000000Z", "-out", path);
|
|
return tlsConfig(path);
|
|
}],
|
|
["unreadable key", () => {
|
|
const path = join(root, "unreadable.key");
|
|
writeFileSync(path, "not-readable", { mode: 0o000 });
|
|
return tlsConfig(cert, path);
|
|
}],
|
|
] as const) {
|
|
test(`configured HTTPS fails closed for ${name}, without secret output`, async () => {
|
|
const app = await start(config());
|
|
try {
|
|
const exit = await Promise.race([app.child.exited, Bun.sleep(1000).then(() => "still-running")]);
|
|
expect(exit).not.toBe("still-running");
|
|
expect(exit).not.toBe(0);
|
|
expect(await tcpReady(app.port)).toBe(false);
|
|
expect(await tcpReady(app.configPort)).toBe(false);
|
|
const logs = (await app.stdout) + (await app.stderr);
|
|
expect(logs).toContain("kein HTTP-Fallback");
|
|
expect(logs).not.toContain("SYNTHETIC-SECRET-MUST-NOT-APPEAR");
|
|
expect(logs).not.toContain("BEGIN PRIVATE KEY");
|
|
expect(logs).not.toContain("synthetic-test-passphrase");
|
|
} finally { await app.stop(); }
|
|
}, 10_000);
|
|
}
|
|
|
|
test("HTTP remains the default, including Bearer, tool dispatch and local admin protection", async () => {
|
|
const app = await start(null);
|
|
try {
|
|
const base = `http://127.0.0.1:${app.port}`;
|
|
expect((await fetch(base + "/health")).status).toBe(200);
|
|
expect((await fetch(base + "/mcp", { method: "POST", body: "{}" })).status).toBe(401);
|
|
const rpc = async (message: unknown) => (await fetch(base + "/mcp", { method: "POST",
|
|
headers: { Authorization: `Bearer ${testToken}`, "Content-Type": "application/json" }, body: JSON.stringify(message) })).json() as Promise<any>;
|
|
expect((await rpc({ id: 1, method: "initialize", params: {} })).result.serverInfo).toBeDefined();
|
|
const called = await rpc({ id: 2, method: "tools/call", params: { name: "unraid_system_shell_readonly",
|
|
arguments: { program: "ls", args: ["-ld", app.dir] } } });
|
|
expect(called.result.isError).toBeUndefined();
|
|
expect(JSON.parse(called.result.content[0].text).exit_code).toBe(0);
|
|
expect((await fetch(`http://127.0.0.1:${app.configPort}/config`)).status).toBe(401);
|
|
} finally { await app.stop(); }
|
|
}, 10_000);
|
|
|
|
test("HTTPS rejects plaintext and untrusted clients; OpenSSL verifies TLS 1.2/1.3, not TLS 1.1", async () => {
|
|
const app = await start(tlsConfig());
|
|
try {
|
|
await expect(fetch(`http://127.0.0.1:${app.port}/health`, { signal: AbortSignal.timeout(1500) })).rejects.toThrow();
|
|
await expect(httpsJson(app.port, "/health", undefined, undefined, Buffer.from(""))).rejects.toThrow();
|
|
for (const protocol of ["-tls1_2", "-tls1_3", "-tls1_1"]) {
|
|
const result = Bun.spawnSync(["openssl", "s_client", "-connect", `127.0.0.1:${app.port}`,
|
|
"-CAfile", cert, "-verify_return_error", "-verify_ip", "127.0.0.1", "-brief", "-cipher", "DEFAULT:@SECLEVEL=0", protocol],
|
|
{ stdin: new Uint8Array(), stdout: "pipe", stderr: "pipe" });
|
|
if (protocol === "-tls1_1") {
|
|
expect(result.exitCode).not.toBe(0);
|
|
expect(result.stderr.toString()).toContain("alert protocol version");
|
|
} else {
|
|
expect(result.exitCode).toBe(0);
|
|
expect(result.stderr.toString()).toContain("Verification: OK");
|
|
expect(result.stderr.toString()).toContain(protocol === "-tls1_2" ? "TLSv1.2" : "TLSv1.3");
|
|
}
|
|
}
|
|
const wrongName = Bun.spawnSync(["openssl", "s_client", "-connect", `127.0.0.1:${app.port}`,
|
|
"-CAfile", cert, "-verify_return_error", "-verify_hostname", "incorrect.example.invalid", "-brief"],
|
|
{ stdin: new Uint8Array(), stdout: "pipe", stderr: "pipe" });
|
|
expect(wrongName.exitCode).not.toBe(0);
|
|
expect(wrongName.stderr.toString()).toContain("hostname mismatch");
|
|
} finally { await app.stop(); }
|
|
}, 10_000);
|