/** * Regression tests for the second security pass: where the server may be pointed, what an agent may send, and how the agent * scripts handle the token. * * - utils/networkGuard.ts: loopback, link-local (cloud metadata) and similar addresses are refused for the certificate check, * the WHOIS lookup and the port scanner; the connection goes to the address that was checked. * - the agent endpoint checks the token before reading a body, takes a large report, and trims rather than rejects. * - the Linux agent keeps the token off curl's command line and out of a fixed /tmp file; its systemd unit is locked down. * - the Windows installer gives the SYSTEM task's folder explicit permissions. * * Run with: npm test --workspace server */ import { test, describe, before, after } from "node:test"; import assert from "node:assert/strict"; import { mkdtempSync, mkdirSync, readFileSync, existsSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { fileURLToPath } from "node:url"; import { spawn, spawnSync } from "node:child_process"; import http from "node:http"; const dir = mkdtempSync(join(tmpdir(), "hm-hardening-test-")); process.env.DATABASE_PATH = join(dir, "test.sqlite"); process.env.SESSION_DIR = join(dir, "sessions"); process.env.CREDENTIALS_ENCRYPTION_KEY = "ab".repeat(32); const repoRoot = fileURLToPath(new URL("../../", import.meta.url)); const { classifyAddress, resolveTarget, BlockedTargetError } = await import("../src/utils/networkGuard.js"); const { fetchCertExpiry } = await import("../src/services/tlsCheck.js"); const { defaultDeps } = await import("../src/services/domainLookup.js"); const { resolveScanTarget } = await import("../src/services/portScan.js"); const { runMigrations } = await import("../src/db/migrate.js"); await runMigrations(); const blocked = (kind?: string) => (err: unknown) => err instanceof BlockedTargetError && (kind === undefined || err.kind === kind); // ─── Where the server may be pointed ──────────────────────────────────────── describe("networkGuard", () => { test("classifies addresses, including IPv4 wrapped in IPv6", () => { const expected: Record = { "127.0.0.1": "loopback", "127.9.9.9": "loopback", "::1": "loopback", "::ffff:127.0.0.1": "loopback", "0.0.0.0": "unspecified", "::": "unspecified", "169.254.169.254": "metadata", "::ffff:169.254.169.254": "metadata", "fd00:ec2::254": "metadata", "100.100.100.200": "metadata", "169.254.1.1": "link-local", "fe80::1": "link-local", "224.0.0.1": "multicast", "255.255.255.255": "multicast", "10.1.2.3": "private", "172.16.5.5": "private", "192.168.1.10": "private", "100.64.0.5": "private", "fd12:3456::1": "private", "::ffff:10.0.0.1": "private", "172.32.0.1": "public", "8.8.8.8": "public", "2606:4700::1111": "public", "::ffff:8.8.8.8": "public", }; for (const [ip, kind] of Object.entries(expected)) assert.equal(classifyAddress(ip), kind, ip); }); test("refuses what is never allowed, and resolves names before judging them", async () => { for (const host of ["127.0.0.1", "::1", "::ffff:127.0.0.1", "0.0.0.0", "169.254.169.254", "fe80::1", "fd00:ec2::254", "localhost"]) { await assert.rejects(() => resolveTarget(host, { allowPrivate: true }), blocked(), host); } }); test("private ranges: allowed when asked for, refused when not", async () => { assert.equal(await resolveTarget("192.168.1.10", { allowPrivate: true }), "192.168.1.10"); assert.equal(await resolveTarget("8.8.8.8", { allowPrivate: false }), "8.8.8.8"); await assert.rejects(() => resolveTarget("192.168.1.10", { allowPrivate: false }), blocked("private")); }); test("odd spellings of loopback don't get through (they're refused or don't resolve)", async () => { for (const host of ["2130706433", "0x7f000001", "127.1", "0177.0.0.1"]) { await assert.rejects(() => resolveTarget(host, { allowPrivate: true }), blocked(), host); } }); }); describe("certificate check", () => { test("won't connect to loopback, link-local or metadata addresses", async () => { for (const host of ["127.0.0.1", "localhost", "::1", "::ffff:127.0.0.1", "0.0.0.0", "169.254.169.254", "fd00:ec2::254", "100.100.100.200", "2130706433"]) { await assert.rejects(() => fetchCertExpiry(host, 443, 500), blocked(), host); } }); test("LAN and public hosts get past the check (and fail only on the connection)", async () => { // Nothing answers on these, so what comes back is a timeout or an unreachable error — never a refusal by the guard. for (const host of ["192.0.2.1", "10.255.255.1"]) { await assert.rejects( () => fetchCertExpiry(host, 443, 400), (err: unknown) => !(err instanceof BlockedTargetError), host, ); } }); }); describe("WHOIS server", () => { test("must look like a hostname and must be neither this machine, metadata nor private", async () => { for (const server of ["127.0.0.1", "localhost", "169.254.169.254", "10.0.0.1", "192.168.1.1"]) { await assert.rejects(() => defaultDeps.whoisQuery(server, "example.se"), blocked(), server); } for (const server of ["not a host", "evil.com/x", "a;b", "", "fd00::1", "[::1]"]) { await assert.rejects(() => defaultDeps.whoisQuery(server, "example.se"), /not a hostname/, JSON.stringify(server)); } }); }); describe("port scanner", () => { test("refuses loopback and the cloud metadata address, still scans the LAN", async () => { await assert.rejects(() => resolveScanTarget("127.0.0.1")); await assert.rejects(() => resolveScanTarget("169.254.169.254"), /metadata/); await assert.rejects(() => resolveScanTarget("8.8.8.8"), /private network/); assert.equal(await resolveScanTarget("192.168.1.10"), "192.168.1.10"); assert.equal(await resolveScanTarget("100.64.1.2"), "100.64.1.2"); }); }); // ─── Routes ───────────────────────────────────────────────────────────────── let port = 0; let server: http.Server; let operator = ""; /** Sends a path exactly as written, with a raw body. Resolves with the status and the reply text. */ function send(method: string, path: string, opts: { cookie?: string; token?: string; json?: object; raw?: string } = {}): Promise<{ status: number; text: string }> { return new Promise((resolve, reject) => { const payload = opts.raw ?? (opts.json ? JSON.stringify(opts.json) : undefined); const headers: Record = {}; if (opts.cookie) headers.cookie = opts.cookie; if (opts.token) headers.authorization = `Bearer ${opts.token}`; if (payload !== undefined) { headers["content-type"] = "application/json"; headers["content-length"] = String(Buffer.byteLength(payload)); } const req = http.request({ host: "127.0.0.1", port, method, path, headers }, (res) => { let text = ""; res.on("data", (c) => (text += c)); res.on("end", () => resolve({ status: res.statusCode ?? 0, text })); }); // The server may answer (and close) before it has taken the whole body; that's the point of some of these tests. req.on("error", (err) => (/EPIPE|ECONNRESET/.test(String(err)) ? undefined : reject(err))); if (payload !== undefined) req.write(payload); req.end(); }); } let agentToken = ""; let agentServerId = 0; before(async () => { const express = (await import("express")).default; const session = (await import("express-session")).default; const { db } = await import("../src/db/client.js"); const { users, servers } = await import("../src/db/schema.js"); const { generateApiToken } = await import("../src/services/tokens.js"); const { secretsRouter } = await import("../src/routes/secrets.js"); const { agentReportRouter } = await import("../src/routes/agentReport.js"); const { apiErrorHandler } = await import("../src/utils/apiErrorHandler.js"); await db.insert(users).values({ oidcSub: "op", email: "op@x", name: "Operator", role: "operator" }); const { token, prefix, hash } = generateApiToken(); agentToken = token; agentServerId = (await db.insert(servers).values({ name: "agent-host", apiTokenHash: hash, apiTokenPrefix: prefix }).returning())[0].id; // The same order index.ts uses: the agent endpoint first, then the app-wide JSON parser and sessions, then everything else. const app = express(); app.use("/api/agent/report", agentReportRouter); app.use(express.json()); app.use(session({ secret: "t", resave: false, saveUninitialized: true })); app.post("/login", (req, res) => { req.session.user = { sub: "op" } as never; res.json({}); }); app.use("/api/secrets", secretsRouter); app.use(apiErrorHandler); server = app.listen(0); port = (server.address() as { port: number }).port; operator = ((await fetch(`http://127.0.0.1:${port}/login`, { method: "POST" })).headers.get("set-cookie") as string).split(";")[0]; }); after(() => { server?.close(); try { rmSync(dir, { recursive: true, force: true }); } catch { // Windows keeps the SQLite file locked until the process exits. } }); describe("secrets: the certificate check can't be aimed at the server itself", () => { test("a blocked host is refused with a clear reason", async () => { for (const checkHost of ["127.0.0.1", "169.254.169.254", "localhost"]) { const res = await send("POST", "/api/secrets", { cookie: operator, json: { name: "probe", type: "ssl_certificate", checkHost, checkPort: 8080 } }); assert.equal(res.status, 400, `${checkHost}: ${res.text}`); assert.match(res.text, /can't be used/, checkHost); } }); test("with a typed-in expiry the secret is saved, and the check records why it wasn't done — it never connects", async () => { const res = await send("POST", "/api/secrets", { cookie: operator, json: { name: "manual", type: "ssl_certificate", checkHost: "127.0.0.1", checkPort: 8080, expiryDate: "2030-01-01" }, }); assert.equal(res.status, 201, res.text); assert.match(JSON.parse(res.text).secret.lastCheckError, /loopback/); }); }); // ─── The agent endpoint ───────────────────────────────────────────────────── describe("agent endpoint", () => { const report = (extra: object = {}) => ({ hostname: "agent-host", os_type: "linux", tasks: [], ...extra }); test("is mounted ahead of the app-wide JSON parser and the session store", () => { const index = readFileSync(join(repoRoot, "server/src/app.ts"), "utf8"); const agent = index.indexOf('app.use("/api/agent/report"'); assert.ok(agent > 0, "agent route not found in app.ts"); assert.ok(agent < index.indexOf("app.use(express.json())"), "the agent route must come before the 100 KB JSON parser"); assert.ok(agent < index.indexOf("session({"), "the agent route must come before the session store"); }); test("answers 401 without reading a body when the token is missing or wrong", async () => { const huge = JSON.stringify(report({ hostname: "x".repeat(3_000_000) })); assert.equal((await send("POST", "/api/agent/report", { raw: huge })).status, 401); assert.equal((await send("POST", "/api/agent/report", { token: "hlm_" + "0".repeat(48), raw: huge })).status, 401); assert.equal((await send("POST", "/api/agent/report", { token: "nonsense", json: report() })).status, 401); }); test("takes an ordinary report", async () => { const res = await send("POST", "/api/agent/report", { token: agentToken, json: report({ hostname: "web-1" }) }); assert.equal(res.status, 202, res.text); }); test("takes a big report (well past the 100 KB the rest of the API allows) from a real agent", async () => { const ports = Array.from({ length: 2500 }, (_, i) => ({ protocol: "tcp", port: 1000 + i, address: "0.0.0.0", process: "some-process-name" })); const body = JSON.stringify(report({ system: { listening_ports: ports } })); assert.ok(body.length > 150_000, `the test report should be larger than 100 KB, was ${body.length}`); const res = await send("POST", "/api/agent/report", { token: agentToken, raw: body }); assert.equal(res.status, 202, res.text); const { db } = await import("../src/db/client.js"); const row = await db.query.servers.findFirst({ where: (s, { eq }) => eq(s.id, agentServerId) }); assert.equal(JSON.parse(row!.listeningPorts!).length, 2500); }); test("a body over the limit is a 413, not a server error", async () => { const res = await send("POST", "/api/agent/report", { token: agentToken, raw: JSON.stringify(report({ hostname: "x".repeat(4_500_000) })) }); assert.equal(res.status, 413, res.text); assert.match(res.text, /payload_too_large/); }); test("malformed JSON is a 400", async () => { const res = await send("POST", "/api/agent/report", { token: agentToken, raw: "{not json" }); assert.equal(res.status, 400); assert.match(res.text, /invalid_json/); }); test("overlong text is trimmed instead of costing the host its whole report", async () => { const res = await send("POST", "/api/agent/report", { token: agentToken, json: report({ hostname: "h".repeat(300), system: { ip_addresses: Array.from({ length: 300 }, (_, i) => `10.0.${Math.floor(i / 250)}.${i % 250}`) }, tasks: [ { schedule_type: "cron", name: "n".repeat(600), command: "c".repeat(20_000), schedule_expression: "* * * * *" }, { schedule_type: "cron", name: "big-metadata", metadata: { blob: "m".repeat(60_000) } }, { schedule_type: "cron", name: "small-metadata", metadata: { user: "root" } }, ], }), }); assert.equal(res.status, 202, res.text); const { db } = await import("../src/db/client.js"); const row = await db.query.servers.findFirst({ where: (s, { eq }) => eq(s.id, agentServerId) }); assert.equal(row!.hostname!.length, 255); assert.equal(JSON.parse(row!.ipAddresses!).length, 200); const tasks = await db.query.scheduledTasks.findMany({ where: (t, { eq }) => eq(t.serverId, agentServerId) }); const long = tasks.find((t) => t.name.startsWith("nnn"))!; assert.equal(long.name.length, 500); assert.equal(long.command!.length, 8000); assert.equal(tasks.find((t) => t.name === "big-metadata")!.rawMetadata, null, "oversize metadata is dropped, the task kept"); assert.equal(tasks.find((t) => t.name === "small-metadata")!.rawMetadata, JSON.stringify({ user: "root" })); }); }); // ─── The Linux agent ──────────────────────────────────────────────────────── const agentScript = join(repoRoot, "agent/linux/report-tasks.sh"); const installScript = join(repoRoot, "agent/linux/install.sh"); const haveBash = spawnSync("bash", ["-c", "command -v curl"]).status === 0; const posix = (p: string) => p.replace(/\\/g, "/"); /** Runs a command without blocking this process (the fake server in these tests lives in it, so a blocking spawn would deadlock). */ function run(cmd: string, args: string[], env: NodeJS.ProcessEnv): Promise<{ status: number | null; stdout: string; stderr: string }> { return new Promise((resolve, reject) => { const child = spawn(cmd, args, { env }); let stdout = ""; let stderr = ""; const timer = setTimeout(() => child.kill(), 30_000); child.stdout.on("data", (c) => (stdout += c)); child.stderr.on("data", (c) => (stderr += c)); child.on("error", reject); child.on("close", (status) => { clearTimeout(timer); resolve({ status, stdout, stderr }); }); }); } describe("Linux agent", () => { test("both scripts are valid bash", { skip: !haveBash }, () => { for (const script of [agentScript, installScript]) { const r = spawnSync("bash", ["-n", posix(script)], { encoding: "utf8" }); assert.equal(r.status, 0, r.stderr); } }); test("the token never goes on a command line and nothing is written to a fixed /tmp path", () => { const text = readFileSync(agentScript, "utf8"); assert.doesNotMatch(text, /-H\s+"Authorization/, "the token must not be passed with -H"); assert.doesNotMatch(text, /\/tmp\/hlm/, "no fixed file name in /tmp"); assert.match(text, /mktemp -d/); assert.match(text, /trap 'rm -rf "\$HLM_TMPDIR"' EXIT/); assert.match(text, /curl .* -K -/, "curl should read its config (with the token) from stdin"); }); test("the systemd unit, as the installer writes it, is locked down and keeps what the agent needs", { skip: !haveBash }, async () => { // Run the installer's own heredoc, so a stray $, backtick or backslash in the unit shows up here exactly as it would on a server. const text = readFileSync(installScript, "utf8").replace(/\r\n/g, "\n"); const start = text.indexOf('cat > "$SYSTEMD_DIR/homelab-manager-agent.service" < 0 && end > start, "the unit's heredoc wasn't found in install.sh"); const out = mkdtempSync(join(tmpdir(), "hm-unit-")); try { writeFileSync(join(out, "render.sh"), `set -euo pipefail\nCONFIG_DIR=/etc\nINSTALL_DIR=/usr/local/bin\nSYSTEMD_DIR=$(cygpath -u "$OUT_DIR" 2>/dev/null || echo "$OUT_DIR")\n${text.slice(start, end)}`); const r = await run("bash", [posix(join(out, "render.sh"))], { ...process.env, OUT_DIR: posix(out) }); assert.equal(r.status, 0, r.stderr); assert.equal(r.stdout.trim(), "", "rendering the unit ran a command (a backtick or $( ) in the heredoc?)"); const rendered = readFileSync(join(out, "homelab-manager-agent.service"), "utf8"); const settings = new Map(); for (const line of rendered.split("\n").map((l) => l.trim()).filter((l) => l && !l.startsWith("#") && !l.startsWith("["))) { const eq = line.indexOf("="); assert.ok(eq > 0, `not a Key=Value line: ${JSON.stringify(line)}`); settings.set(line.slice(0, eq), line.slice(eq + 1)); } // The two intended expansions, and nothing else turned into something unexpected. assert.equal(settings.get("EnvironmentFile"), "/etc/homelab-manager-agent.env"); assert.equal(settings.get("ExecStart"), "/usr/local/bin/homelab-manager-agent.sh"); // The one step that runs outside the sandbox (+) is the package-manager question, which may fail without stopping the report (-), // and it hands its answer over through the unit's own private directory, which is where the script looks for it. assert.equal(settings.get("ExecStartPre"), "-+/usr/local/bin/homelab-manager-agent.sh --prepare"); assert.equal(rendered.split("\n").filter((l) => /^ExecStartPre=/.test(l.trim())).length, 1, "only that one step is outside the sandbox"); assert.equal(settings.get("RuntimeDirectory"), "homelab-manager-agent"); assert.equal(settings.get("RuntimeDirectoryMode"), "0700"); assert.ok(readFileSync(agentScript, "utf8").includes("/run/homelab-manager-agent/updates.json"), "the script looks where the unit leaves it"); assert.doesNotMatch(rendered, /[`\\]/); for (const [key, value] of Object.entries({ UMask: "0077", NoNewPrivileges: "yes", PrivateTmp: "yes", ProtectSystem: "strict", ProtectHome: "read-only", ProtectKernelTunables: "yes", ProtectKernelModules: "yes", ProtectKernelLogs: "yes", ProtectControlGroups: "yes", ProtectClock: "yes", ProtectHostname: "yes", MemoryDenyWriteExecute: "yes", RestrictSUIDSGID: "yes", RestrictRealtime: "yes", RestrictNamespaces: "yes", LockPersonality: "yes", DevicePolicy: "closed", })) { assert.equal(settings.get(key), value, key); } assert.equal(settings.get("RestrictAddressFamilies"), "AF_UNIX AF_INET AF_INET6 AF_NETLINK"); // Of root's powers only these three jobs are kept: read every user's crontab, switch user for `crontab -l -u`, and name the // program behind each socket. Tightening this further silently drops tasks or process names; loosening it undoes the point. assert.deepEqual( new Set((settings.get("CapabilityBoundingSet") ?? "").split(/\s+/)), new Set(["CAP_DAC_OVERRIDE", "CAP_DAC_READ_SEARCH", "CAP_SYS_PTRACE", "CAP_SETUID", "CAP_SETGID"]), ); // It has to keep seeing every process (that is how it names the program behind a listening port), real user IDs (for // crontab -l -u), and /dev/log (crontab writes to it each time the agent reads a crontab). for (const key of ["ProtectProc", "ProcSubset", "PrivateUsers", "PrivateDevices"]) assert.equal(settings.has(key), false, `${key} would break the agent`); } finally { try { rmSync(out, { recursive: true, force: true }); } catch { // best effort } } }); test("the update check can be run on its own, and what it leaves behind is read back through jq, not trusted", () => { const text = readFileSync(agentScript, "utf8"); assert.ok(text.includes("--prepare|--prepare-updates) MODE=prepare"), "the old name still works, for units written by an earlier installer"); assert.ok(text.includes("--check-updates|--check) MODE=check")); assert.ok(text.includes("use_prepared_updates || collect_updates"), "the report uses the prepared answer first and asks itself otherwise"); assert.ok(text.includes('find "$UPDATES_FILE" -mmin -10'), "an old answer isn't used"); assert.ok(text.includes("jq -ce 'select(type == \"object\""), "the file is re-shaped by jq, so the report only carries the four known fields"); assert.ok(text.includes('mv -f "$UPDATES_FILE.tmp" "$UPDATES_FILE"'), "written whole, then moved into place"); // disk and pool health need the devices, so they are read from the prepare step and handed over, re-shaped by jq like the updates assert.ok(text.includes("use_prepared_health")); assert.ok(text.includes("smartctl -j -H -A -n standby"), "a sleeping disk is not woken to be asked"); assert.ok(text.includes("zpool list -H -o name,health,capacity")); assert.ok(text.includes("systemctl list-units --state=failed")); assert.ok(text.includes("pacman -Qu")); // the two modes must not need a server address or a token assert.ok(text.includes('[[ "$MODE" == "report" && ( -z "$API_URL" || -z "$API_TOKEN" ) ]]')); }); test("self-update takes nothing on trust but a checksum, never runs inside the sandbox, and can not loop", () => { const text = readFileSync(agentScript, "utf8"); const body = text.slice(text.indexOf("self_update() {"), text.indexOf("# The answer --prepare left for this report")); assert.ok(body.length > 500, "self_update wasn't found"); assert.ok(body.includes("api_get \"/api/agent/report/update?version=$AGENT_VERSION\""), "it asks the server, with its token, whether it should"); assert.ok(body.includes("sha256sum") && body.includes("\"$got\" != \"$sha\""), "the download is checked against the checksum the server gave"); assert.ok(body.includes("bash -n \"$work/new.sh\"") && body.includes("#!/usr/bin/env bash") && body.includes("^AGENT_VERSION=$version"), "and must look like this script, parse, and say the version promised"); assert.ok(body.includes("(( version <= AGENT_VERSION ))"), "only ever to a newer version"); assert.ok(body.includes("mv -f \"$self.new\" \"$self\""), "put beside the old one and moved over it in one step"); assert.ok(body.includes("HLM_JUST_UPDATED"), "the new version doesn't update again straight away"); // it is only called from the prepare step (outside the sandbox) and from the manual check, never from the report const calls = text.split("\n").filter((l) => /(^|\s|&& )self_update(\s|$)/.test(l) && !l.includes("self_update()") && !l.trim().startsWith("#")); assert.equal(calls.length, 2, calls.join(" | ")); const reportBegins = text.indexOf("collect_cron\ncollect_systemd_timers"); assert.ok(reportBegins > 0 && text.indexOf("self_update", reportBegins) === -1, "not after the point where a report begins"); }); test("unit files are made readable by everyone (the umask above them is for the token file)", () => { const text = readFileSync(installScript, "utf8").replace(/\r\n/g, "\n"); assert.match(text, /chmod 644 "\$SYSTEMD_DIR\/homelab-manager-agent\.service" "\$SYSTEMD_DIR\/homelab-manager-agent\.timer"/); // ...and it comes after both files are written and before systemd is asked to read them. const chmodAt = text.indexOf('chmod 644 "$SYSTEMD_DIR'); assert.ok(chmodAt > text.indexOf("homelab-manager-agent.timer\" < { let fake: http.Server; let fakePort = 0; let seen: { authorization?: string; contentType?: string; body: string }[] = []; let work = ""; before(async () => { work = mkdtempSync(join(tmpdir(), "hm-agent-upload-")); fake = http.createServer((req, res) => { let body = ""; req.on("data", (c) => (body += c)); req.on("end", () => { seen.push({ authorization: req.headers.authorization, contentType: req.headers["content-type"], body }); res.writeHead(202, { "content-type": "application/json" }); res.end(JSON.stringify({ ok: true })); }); }); await new Promise((r) => fake.listen(0, "127.0.0.1", r)); fakePort = (fake.address() as { port: number }).port; // A curl that records its own arguments and then runs the real one — to prove what is, and isn't, on the command line. writeFileSync(join(work, "curl"), '#!/usr/bin/env bash\nprintf \'%s\\n\' "$@" >> "$ARGV_LOG"\nexec "$REAL_CURL" "$@"\n'); }); after(() => { fake?.close(); try { rmSync(work, { recursive: true, force: true }); } catch { // best effort } }); /** Runs the script's own post_report function (cut out of the real file) the way the script does. */ async function upload(token: string, payload: string) { seen = []; const argvLog = join(work, "argv.log"); const tmpRecord = join(work, "tmpdir.txt"); rmSync(argvLog, { force: true }); const harness = [ "set -euo pipefail", 'REAL_CURL=$(command -v curl); export REAL_CURL ARGV_LOG="$(cygpath -u "$ARGV_LOG_WIN" 2>/dev/null || echo "$ARGV_LOG_WIN")"', // A "C:/..." directory can't go in PATH on Windows bash (the colon splits it), so convert it the way bash itself would. 'SHIM_UNIX=$(cygpath -u "$SHIM_DIR" 2>/dev/null || echo "$SHIM_DIR")', 'chmod +x "$SHIM_UNIX/curl"; PATH="$SHIM_UNIX:$PATH"', 'source <(sed -n "/^# >>> post_report/,/^# <<< post_report/p" "$AGENT_SCRIPT")', "CURL_INSECURE_FLAG=()", 'HLM_TMPDIR=$(mktemp -d); printf "%s" "$HLM_TMPDIR" > "$TMP_RECORD"', "trap 'rm -rf \"$HLM_TMPDIR\"' EXIT", "response=$(post_report)", 'echo "HTTP=$response"', ].join("\n"); const r = await run("bash", ["-c", harness], { ...process.env, API_URL: `http://127.0.0.1:${fakePort}`, API_TOKEN: token, PAYLOAD: payload, SHIM_DIR: posix(work), AGENT_SCRIPT: posix(agentScript), ARGV_LOG_WIN: argvLog, TMP_RECORD: posix(tmpRecord), }); const argv = existsSync(argvLog) ? readFileSync(argvLog, "utf8") : ""; return { ...r, argv, tmpdir: existsSync(tmpRecord) ? readFileSync(tmpRecord, "utf8") : "" }; } test("an ordinary report arrives with the token as a header, and the token isn't in curl's arguments", async () => { const r = await upload("hlm_abc123", '{"hostname":"web-1","tasks":[]}'); assert.equal(r.status, 0, r.stderr); assert.match(r.stdout, /HTTP=202/); assert.equal(seen.length, 1); assert.equal(seen[0].authorization, "Bearer hlm_abc123"); assert.equal(seen[0].contentType, "application/json"); assert.equal(seen[0].body, '{"hostname":"web-1","tasks":[]}'); assert.ok(r.argv.length > 0, "the curl shim recorded nothing, so the test proves nothing"); assert.doesNotMatch(r.argv, /hlm_abc123/, "the token was on curl's command line"); assert.doesNotMatch(r.argv, /Authorization/i); }); test("a token with quotes, a backslash and a space arrives intact", async () => { const token = 'hlm_a"b\\c d'; const r = await upload(token, "{}"); assert.equal(r.status, 0, r.stderr); assert.equal(seen[0].authorization, `Bearer ${token}`); }); test("a large report goes through (it isn't limited by the length of a command line)", async () => { const payload = JSON.stringify({ tasks: [], padding: "p".repeat(600_000) }); const r = await upload("hlm_big", payload); assert.equal(r.status, 0, r.stderr); assert.equal(seen[0].body.length, payload.length); assert.doesNotMatch(r.argv, /ppppppppppppppppppppppppp/, "the payload was on curl's command line"); }); test("a token with a line break is refused and nothing is sent", async () => { const r = await upload("hlm_x\nX-Injected: yes", "{}"); assert.notEqual(r.status, 0); assert.match(r.stderr, /line break/); assert.equal(seen.length, 0); }); test("the private temporary directory is gone afterwards", async () => { const r = await upload("hlm_clean", "{}"); assert.equal(r.status, 0, r.stderr); assert.ok(r.tmpdir.length > 0); const gone = spawnSync("bash", ["-c", `test ! -e "${r.tmpdir}"`]); assert.equal(gone.status, 0, `${r.tmpdir} still exists`); }); }); }); // ─── The Windows installer ────────────────────────────────────────────────── const pwsh = process.platform === "win32" ? spawnSync("pwsh", ["-NoProfile", "-Command", "$PSVersionTable.PSVersion.Major"], { encoding: "utf8" }) : null; const havePwsh = pwsh?.status === 0; describe("Windows installer", { skip: !havePwsh }, () => { test("the folder the SYSTEM task runs from is writable only by SYSTEM and Administrators", () => { const work = mkdtempSync(join(tmpdir(), "hm-acl-")); const target = join(work, "HomelabManager"); mkdirSync(target); const script = ` $ErrorActionPreference = 'Stop' . '${join(repoRoot, "agent", "windows", "install.ps1").replace(/'/g, "''")}' $me = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value Protect-InstallDir '${target.replace(/'/g, "''")}' -ExtraGrants @("*\${me}:(OI)(CI)(F)") # lets this un-elevated test keep access to its own folder $file = Join-Path '${target.replace(/'/g, "''")}' 'homelab-manager-agent.ps1' Set-Content -Path $file -Value 'x' function Describe($p) { $acl = Get-Acl $p foreach ($rule in $acl.GetAccessRules($true, $true, [Security.Principal.SecurityIdentifier])) { '{0}|{1}' -f $rule.IdentityReference.Value, $rule.IsInherited } } 'DIR'; Describe '${target.replace(/'/g, "''")}' 'FILE'; Describe $file 'ME=' + $me `; const scriptFile = join(work, "check-acl.ps1"); writeFileSync(scriptFile, script); const r = spawnSync("pwsh", ["-NoProfile", "-NonInteractive", "-File", scriptFile], { encoding: "utf8" }); try { // No error output and a complete listing; the exit status is left out because PowerShell's -File status isn't reliable across hosts here. assert.equal(r.stderr.trim(), "", `PowerShell reported an error: ${r.stderr} ${r.stdout}`); assert.ok(r.stdout.includes("ME="), `the script did not finish: ${r.stdout}`); const lines = r.stdout.split(/\r?\n/).map((l) => l.trim()).filter(Boolean); const me = lines.find((l) => l.startsWith("ME="))!.slice(3); const part = (from: string, to: string | null) => lines.slice(lines.indexOf(from) + 1, to ? lines.indexOf(to) : lines.findIndex((l) => l.startsWith("ME="))).map((l) => l.split("|")); const dir = part("DIR", "FILE"); const file = part("FILE", null); const allowed = new Set(["S-1-5-18", "S-1-5-32-544", me]); assert.deepEqual(new Set(dir.map(([sid]) => sid)), allowed, `folder ACL: ${JSON.stringify(dir)}`); assert.ok(dir.every(([, inherited]) => inherited === "False"), "the folder must not inherit ProgramData's permissions"); assert.deepEqual(new Set(file.map(([sid]) => sid)), allowed, `file ACL: ${JSON.stringify(file)}`); for (const everyone of ["S-1-5-32-545" /* Users */, "S-1-5-11" /* Authenticated Users */, "S-1-1-0" /* Everyone */]) { assert.ok(!dir.some(([sid]) => sid === everyone) && !file.some(([sid]) => sid === everyone), `${everyone} has access`); } } finally { try { rmSync(work, { recursive: true, force: true }); } catch { // best effort } } }); });