"use strict"; // Tests for adpanel:heartbeat-fallback-scoped — the removal of the bearer-token // fallback behind POST /api/nodes/:id/heartbeat. // // The audited hole (Low, ops-deception): when the fleet master // (PANEL_HMAC_SECRET) was unresolvable, the heartbeat route fell back to // bearer-token authentication and then mutated node state — a single captured // daemon bearer token could keep a fake or dead node "online" for a full TTL // and repoint its api_port (where the panel later sends admin and server // traffic), with no replay bound at all. // // Re-verified scoping: utils/panel-hmac-secret.js auto-generates and persists // the master synchronously at boot, so "" only ever means a BROKEN install // (unwritable data dir / corrupt persisted file). Heartbeats never create // nodes (unknown id -> 401 before the branch), and first enrollment on a // healthy install bakes the per-node derived hmac_secret into config.yml, so // there is no legitimate flow that needs the bearer fallback. Hence the fix is // option (b) fail-closed: with the master unresolvable, EVERY heartbeat is // rejected with the endpoint's uniform 401 (the node lookup already happened, // so a distinguishable status would leak node-name validity) and a one-time // loud warn; nodes honestly show offline until the install is repaired. // // Locked in here: // 1. Unresolvable master: a heartbeat carrying the CORRECT daemon bearer // token is rejected 401 and issues NO state-mutating UPDATE (no // last_seen/port_ok/api_port write) — the captured-token replay is dead. // 2. Unresolvable master: the loud one-time warn fires exactly once (not // per request, not never). // 3. Unresolvable master: no credentials at all -> same 401 (unchanged). // 4. Resolvable master: a correctly signed envelope (derived per-node // secret, utils/node-hmac) is accepted 200 and persists health telemetry // without modifying the configured API port. // 5. Resolvable master: a bad signature and a bearer-only request (no // envelope) stay 401 — the HMAC-required branch is untouched. // 6. Source pin: the fallback branch cannot regain token comparison. const test = require("node:test"); const assert = require("node:assert"); const path = require("node:path"); const fs = require("node:fs"); const http = require("node:http"); const crypto = require("node:crypto"); const Module = require("node:module"); const express = require("express"); const ROOT = path.join(__dirname, ".."); const NODES_JS = path.join(ROOT, "nodes.js"); const { deriveNodeHmacSecret } = require(path.join(ROOT, "utils", "node-hmac.js")); const { heartbeatSignatureBase } = require(path.join(ROOT, "utils", "heartbeat-auth.js")); const NODE_TOKEN = "hb-fallback-scoped-node-token"; const NODE_ROW = { id: 41001, uuid: "hb-fallback-scoped-uuid", name: "hb-fallback-scoped-node", address: "127.0.0.1", ram_mb: 8192, disk_gb: 100, ports: JSON.stringify({ mode: "range", start: 25565, count: 10 }), token_id: "tok-hb-fallback", token: NODE_TOKEN, token_status: "active", created_at: Date.now(), api_port: 8080, sftp_port: 2022, max_upload_mb: 10240, port_ok: 1, last_seen: Date.now() - 10 * 60 * 1000, // stale — heartbeat is what refreshes it last_check: Date.now() - 10 * 60 * 1000, online: 1, build_config: null, }; function makeDbStub() { const queries = []; return { queries, async query(sql, params = []) { const normalized = String(sql).replace(/\s+/g, " ").trim(); queries.push({ sql: normalized, params }); if (/^SELECT \* FROM nodes WHERE/i.test(normalized)) return [NODE_ROW]; return []; }, pool: { async execute() { return [[]]; }, async query() { return [[]]; }, }, }; } // Loads a fresh nodes.js instance with the fleet master forced to // masterSecret ("" = unresolvable, the broken-install condition) and its own // isolated db stub. The real resolvePanelHmacSecret is bypassed so the test // never touches data/panel-hmac-secret.json. function loadNodesJs({ masterSecret }) { const dbStub = makeDbStub(); const fakePanelHmacSecret = { resolvePanelHmacSecret: () => ({ secret: masterSecret, source: masterSecret ? "env" : "", }), }; const originalLoad = Module._load; Module._load = function (request, parent, isMain) { if (parent && parent.filename === NODES_JS) { if (request === "./db") return dbStub; if (request === "./utils/panel-hmac-secret") return fakePanelHmacSecret; } return originalLoad.apply(this, arguments); }; try { delete require.cache[require.resolve(NODES_JS)]; const app = require(NODES_JS); return { app, dbStub }; } finally { Module._load = originalLoad; } } function signedEnvelopeHeaders(masterSecret, nodeId) { const nodeSecret = deriveNodeHmacSecret(masterSecret, nodeId); const ts = String(Date.now()); const nonce = crypto.randomBytes(16).toString("hex"); const sig = crypto .createHmac("sha256", nodeSecret) .update(heartbeatSignatureBase(nodeId, ts, nonce)) .digest("hex"); return { "x-node-ts": ts, "x-node-sign": sig, "x-node-nonce": nonce }; } function post(baseUrl, pathname, { headers = {}, body, raw } = {}) { // `raw` sends EXACT bytes (adpanel:heartbeat-body-binding v2 tests hash the // wire payload); `body` keeps the historical JSON.stringify behavior. const payload = raw !== undefined ? raw : body === undefined ? null : JSON.stringify(body); return new Promise((resolve, reject) => { const url = new URL(pathname, baseUrl); const req = http.request( url, { method: "POST", headers: { ...(payload !== null ? { "Content-Type": "application/json", "Content-Length": Buffer.byteLength(payload) } : {}), ...headers, }, }, (res) => { const chunks = []; res.on("data", (c) => chunks.push(c)); res.on("error", reject); res.on("end", () => { let json = null; try { json = JSON.parse(Buffer.concat(chunks).toString("utf8")); } catch { } resolve({ status: res.statusCode, json }); }); } ); req.on("error", reject); if (payload !== null) req.write(payload); req.end(); }); } const WARN_MARKER = "PANEL_HMAC_SECRET is unresolvable"; function captureWarns() { const warns = []; const orig = console.warn; console.warn = (...args) => { warns.push(args.join(" ")); }; return { warns, restore: () => { console.warn = orig; } }; } // --------------------------------------------------------------------------- // Instance A: unresolvable fleet master (broken install) // --------------------------------------------------------------------------- const broken = loadNodesJs({ masterSecret: "" }); const parentA = express(); parentA.use(broken.app); let baseUrlA = ""; let serverA = null; test.before(async () => { await new Promise((resolve) => { serverA = parentA.listen(0, "127.0.0.1", resolve); }); baseUrlA = `http://127.0.0.1:${serverA.address().port}`; }); test.after(() => new Promise((resolve) => serverA.close(resolve))); test("unresolvable master: correct bearer token on an established node is rejected and mutates nothing", async () => { const { queries } = broken.dbStub; queries.length = 0; // First request on this process: the one-time broken-install warn fires here. const capture = captureWarns(); let res; try { res = await post(baseUrlA, "/api/nodes/hb-fallback-scoped-uuid/heartbeat", { headers: { Authorization: `Bearer ${NODE_TOKEN}` }, body: { api_port: 39999 }, }); } finally { capture.restore(); } const hits = capture.warns.filter((w) => w.includes(WARN_MARKER)); assert.equal(hits.length, 1, "the broken install must be loud on its first rejected heartbeat"); assert.match(hits[0], /OFFLINE/, "the warn must state the honest operational impact"); assert.match(hits[0], /panel-hmac/, "the warn must point at the resolver's recovery guidance"); const { status, json } = res; assert.equal(status, 401, "a captured bearer token must not authenticate a heartbeat without the HMAC envelope"); assert.deepStrictEqual(json, { error: "authentication required" }, "uniform 401 body (no enumeration oracle)"); const updates = queries.filter((q) => /^UPDATE nodes SET/i.test(q.sql)); assert.equal(updates.length, 0, "no state-mutating write may run on the rejected fallback path"); }); test("unresolvable master: body-token heartbeat is rejected and mutates nothing too", async () => { const { queries } = broken.dbStub; queries.length = 0; const { status } = await post(baseUrlA, "/api/nodes/hb-fallback-scoped-uuid/heartbeat", { body: { token: NODE_TOKEN, api_port: 39999 }, }); assert.equal(status, 401); const updates = queries.filter((q) => /^UPDATE nodes SET/i.test(q.sql)); assert.equal(updates.length, 0); }); test("unresolvable master: no credentials -> same uniform 401 (legacy posture preserved)", async () => { const { status, json } = await post(baseUrlA, "/api/nodes/hb-fallback-scoped-uuid/heartbeat", { body: {}, }); assert.equal(status, 401); assert.deepStrictEqual(json, { error: "authentication required" }); }); test("unresolvable master: the broken-install warn does not repeat on later rejected heartbeats", async () => { const capture = captureWarns(); try { await post(baseUrlA, "/api/nodes/hb-fallback-scoped-uuid/heartbeat", { body: {} }); await post(baseUrlA, "/api/nodes/hb-fallback-scoped-uuid/heartbeat", { headers: { Authorization: `Bearer ${NODE_TOKEN}` }, body: {}, }); } finally { capture.restore(); } const hits = capture.warns.filter((w) => w.includes(WARN_MARKER)); assert.equal(hits.length, 0, "loud once per process, not spammy per request"); }); // --------------------------------------------------------------------------- // Instance B: resolvable fleet master (healthy install) — HMAC path unchanged // --------------------------------------------------------------------------- const healthy = loadNodesJs({ masterSecret: "healthy-fleet-master-for-heartbeat-tests" }); const parentB = express(); parentB.use(healthy.app); let baseUrlB = ""; let serverB = null; test.before(async () => { await new Promise((resolve) => { serverB = parentB.listen(0, "127.0.0.1", resolve); }); baseUrlB = `http://127.0.0.1:${serverB.address().port}`; }); test.after(() => new Promise((resolve) => serverB.close(resolve))); test("resolvable master: correctly signed heartbeat refreshes health without changing the configured API port", async () => { const { queries } = healthy.dbStub; queries.length = 0; const headers = signedEnvelopeHeaders("healthy-fleet-master-for-heartbeat-tests", NODE_ROW.uuid); const { status, json } = await post(baseUrlB, `/api/nodes/${NODE_ROW.uuid}/heartbeat`, { headers, body: { api_port: 39999 }, }); assert.equal(status, 200, "the healthy HMAC-signed path must keep working"); assert.equal(json && json.ok, true); assert.equal(json && json.online, true, "fresh liveness preserves an existing successful reachability result"); const updates = queries.filter((q) => /^UPDATE nodes SET/i.test(q.sql)); assert.equal(updates.length, 1, "exactly one liveness write"); assert.match(updates[0].sql, /last_seen = GREATEST\(COALESCE\(last_seen, 0\), \?\)/); assert.doesNotMatch(updates[0].sql, /port_ok|last_check|online|api_port/); }); test("a signed heartbeat does not override a failed outbound probe", async () => { const { queries } = healthy.dbStub; queries.length = 0; NODE_ROW.port_ok = 0; NODE_ROW.online = 0; try { const headers = signedEnvelopeHeaders("healthy-fleet-master-for-heartbeat-tests", NODE_ROW.uuid); const { status, json } = await post(baseUrlB, `/api/nodes/${NODE_ROW.uuid}/heartbeat`, { headers, body: {} }); assert.equal(status, 200); assert.equal(json.ok, true); assert.equal(json.port_ok, false); assert.equal(json.online, false); const updates = queries.filter((query) => /^UPDATE nodes SET/i.test(query.sql)); assert.equal(updates.length, 1); assert.ok(updates[0].params[0] > NODE_ROW.last_seen); assert.doesNotMatch(updates[0].sql, /port_ok|last_check|online|api_port/); } finally { NODE_ROW.port_ok = 1; NODE_ROW.online = 1; } }); test("resolvable master: bad signature and bearer-only requests stay rejected (HMAC-required branch untouched)", async () => { const bad = signedEnvelopeHeaders("healthy-fleet-master-for-heartbeat-tests", NODE_ROW.uuid); bad["x-node-sign"] = crypto.randomBytes(32).toString("hex"); const badRes = await post(baseUrlB, `/api/nodes/${NODE_ROW.uuid}/heartbeat`, { headers: bad, body: { api_port: 39999 }, }); assert.equal(badRes.status, 401, "a forged envelope must not authenticate"); const bearerOnly = await post(baseUrlB, `/api/nodes/${NODE_ROW.uuid}/heartbeat`, { headers: { Authorization: `Bearer ${NODE_TOKEN}` }, body: { api_port: 39999 }, }); assert.equal(bearerOnly.status, 401, "the long-lived bearer token alone must never authenticate on a healthy install"); }); // --------------------------------------------------------------------------- // adpanel:heartbeat-body-binding + adpanel:heartbeat-nonce-shared — route // level pins on a FRESH instance (own warn flags, own nonce cache, own DB // stub): the v2 envelope over the exact raw bytes, the one-byte-tamper // uniform 401, the transitional v1 warn, and the shared/local-fallback nonce // ledger. The pre-existing instances above stay byte-for-byte as pinned. // --------------------------------------------------------------------------- const HEALTHY_C = "healthy-fleet-master-for-heartbeat-v2-tests"; const instanceC = loadNodesJs({ masterSecret: HEALTHY_C }); const parentC = express(); parentC.use(instanceC.app); let baseUrlC = ""; let serverC = null; test.before(async () => { await new Promise((resolve) => { serverC = parentC.listen(0, "127.0.0.1", resolve); }); baseUrlC = `http://127.0.0.1:${serverC.address().port}`; }); test.after(() => new Promise((resolve) => serverC.close(resolve))); function sha256Hex(data) { return crypto.createHash("sha256").update(data).digest("hex"); } // Mock node-redis v4 client (sendCommand(string[])) with stateful SET NX, // following the injected clientOf/readyOf shape index.js hands the shared // stores (see utils/login-attack-redis.js). function mockHeartbeatRedis() { const commands = []; const keys = new Set(); return { commands, sendCommand(args) { const argv = args.map(String); commands.push(argv); if (argv[0] === "SET" && argv.includes("NX")) { if (keys.has(argv[1])) return Promise.resolve(null); keys.add(argv[1]); return Promise.resolve("OK"); } return Promise.resolve("OK"); }, }; } test("resolvable master: legacy v1 heartbeat still accepted and the unbound-body warn fires exactly once", async () => { const { queries } = instanceC.dbStub; queries.length = 0; const capture = captureWarns(); let res; try { res = await post(baseUrlC, `/api/nodes/${NODE_ROW.uuid}/heartbeat`, { headers: signedEnvelopeHeaders(HEALTHY_C, NODE_ROW.uuid), body: { api_port: 41001 }, }); } finally { capture.restore(); } assert.equal(res.status, 200, "the v1 envelope must remain accepted (transitional state)"); assert.equal(res.json && res.json.ok, true); const hits = capture.warns.filter((w) => w.includes("legacy v1 envelope")); assert.equal(hits.length, 1, "the v1 unbound-body warn must fire exactly once per process"); assert.match(hits[0], /x-node-body-hash/, "the warn must name the v2 marker the fleet should upgrade to"); assert.match(hits[0], /transitional/, "the warn must say v1 acceptance is transitional"); const second = captureWarns(); try { await post(baseUrlC, `/api/nodes/${NODE_ROW.uuid}/heartbeat`, { headers: signedEnvelopeHeaders(HEALTHY_C, NODE_ROW.uuid), body: {}, }); } finally { second.restore(); } assert.equal(second.warns.filter((w) => w.includes("legacy v1 envelope")).length, 0, "one-time per process, not per heartbeat"); }); test("resolvable master: a v2 heartbeat with a matching body hash is accepted without changing the configured API port", async () => { const { queries } = instanceC.dbStub; queries.length = 0; const payload = JSON.stringify({ api_port: 41222 }); const env = signedEnvelopeHeaders(HEALTHY_C, NODE_ROW.uuid); const headers = { ...env, "x-node-sign": crypto .createHmac("sha256", deriveNodeHmacSecret(HEALTHY_C, NODE_ROW.uuid)) .update(`heartbeat|${NODE_ROW.uuid}|${env["x-node-ts"]}|${env["x-node-nonce"]}|${sha256Hex(payload)}`) .digest("hex"), "x-node-body-hash": sha256Hex(payload), }; const { status, json } = await post(baseUrlC, `/api/nodes/${NODE_ROW.uuid}/heartbeat`, { headers, raw: Buffer.from(payload, "utf8"), }); assert.equal(status, 200, "a v2 envelope over the exact raw bytes must authenticate"); assert.equal(json && json.ok, true); const updates = queries.filter((q) => /^UPDATE nodes SET/i.test(q.sql)); assert.equal(updates.length, 1); assert.match(updates[0].sql, /last_seen = GREATEST\(COALESCE\(last_seen, 0\), \?\)/); assert.doesNotMatch(updates[0].sql, /api_port/); }); test("resolvable master: a v2 heartbeat whose body is tampered by one byte gets the uniform 401 and mutates nothing", async () => { const { queries } = instanceC.dbStub; queries.length = 0; const signedPayload = JSON.stringify({ api_port: 41333 }); const env = signedEnvelopeHeaders(HEALTHY_C, NODE_ROW.uuid); const headers = { ...env, "x-node-sign": crypto .createHmac("sha256", deriveNodeHmacSecret(HEALTHY_C, NODE_ROW.uuid)) .update(`heartbeat|${NODE_ROW.uuid}|${env["x-node-ts"]}|${env["x-node-nonce"]}|${sha256Hex(signedPayload)}`) .digest("hex"), "x-node-body-hash": sha256Hex(signedPayload), }; // One byte differs from the signed payload: the captured (ts, nonce, sign) // triple must be worthless against attacker-chosen body bytes. const tampered = Buffer.from(JSON.stringify({ api_port: 41334 }), "utf8"); const { status, json } = await post(baseUrlC, `/api/nodes/${NODE_ROW.uuid}/heartbeat`, { headers, raw: tampered, }); assert.equal(status, 401, "a one-byte body change must fail the v2 envelope"); assert.deepStrictEqual(json, { error: "authentication required" }, "same uniform 401 body as every other heartbeat rejection"); const updates = queries.filter((q) => /^UPDATE nodes SET/i.test(q.sql)); assert.equal(updates.length, 0, "no state-mutating write may run on a body-hash mismatch"); }); test("resolvable master: with the shared Redis nonce store wired, a replayed heartbeat is rejected cluster-wide", async () => { const redis = mockHeartbeatRedis(); instanceC.app.setHeartbeatSharedNonceDeps({ clientOf: () => redis, readyOf: () => true }); const env = signedEnvelopeHeaders(HEALTHY_C, NODE_ROW.uuid); const first = await post(baseUrlC, `/api/nodes/${NODE_ROW.uuid}/heartbeat`, { headers: env, body: { api_port: 41444 }, }); assert.equal(first.status, 200, "first-seen nonce accepted through the shared ledger"); const replay = await post(baseUrlC, `/api/nodes/${NODE_ROW.uuid}/heartbeat`, { headers: env, body: { api_port: 41444 }, }); assert.equal(replay.status, 401, "the shared ledger must reject the replay (any worker, not just this one)"); assert.deepStrictEqual(replay.json, { error: "authentication required" }); const sets = redis.commands.filter((c) => c[0] === "SET"); assert.equal(sets.length, 2, "both attempts consulted the shared store"); assert.match(sets[0][1], new RegExp(`^adpanel:heartbeat-nonce:${NODE_ROW.uuid}:${env["x-node-nonce"]}$`), "the key carries the node id and the nonce"); assert.ok(sets[0].includes("NX"), "SET must be NX"); const pxAt = sets[0].indexOf("PX"); assert.ok(pxAt !== -1 && Number(sets[0][pxAt + 1]) > 5 * 60 * 1000, "the TTL must exceed the drift window"); }); test("resolvable master: with Redis down, first-seen nonces are accepted via the local fallback and the warn fires once", async () => { instanceC.app.setHeartbeatSharedNonceDeps({ clientOf: () => ({ sendCommand: () => Promise.reject(new Error("connection down")) }), readyOf: () => true, }); const env = signedEnvelopeHeaders(HEALTHY_C, NODE_ROW.uuid); const capture = captureWarns(); let first; let replay; try { first = await post(baseUrlC, `/api/nodes/${NODE_ROW.uuid}/heartbeat`, { headers: env, body: { api_port: 41555 }, }); replay = await post(baseUrlC, `/api/nodes/${NODE_ROW.uuid}/heartbeat`, { headers: env, body: { api_port: 41555 }, }); } finally { capture.restore(); } assert.equal(first.status, 200, "heartbeats must keep flowing during a Redis outage"); assert.equal(replay.status, 401, "the per-process fallback must still reject same-worker replays"); const hits = capture.warns.filter((w) => w.includes("Shared Redis nonce store unavailable")); assert.equal(hits.length, 1, "the degraded-ledger warn must fire exactly once per process"); assert.match(hits[0], /1\/N/, "the warn must state the cluster impact"); }); // --------------------------------------------------------------------------- // Source pin: the fallback branch cannot quietly regain token authentication // --------------------------------------------------------------------------- test("source pin: the fallback branch is fail-closed and free of token comparison", () => { const source = fs.readFileSync(NODES_JS, "utf8"); assert.equal( (source.match(/adpanel:heartbeat-fallback-scoped/g) || []).length >= 2, true, "the constraint tag must document both the helper and the branch" ); const at = source.indexOf('app.post("/api/nodes/:id/heartbeat"'); assert.ok(at !== -1, "heartbeat route not found"); // Window widened from 5200: the route now also carries the v2 envelope // arguments (rawBody/sharedNonceStore) and the one-time warn hooks ahead of // the fallback branch. Every assertion below is unchanged. const route = source.slice(at, at + 9200); const elseAt = route.indexOf(" } else {"); assert.ok(elseAt !== -1, "the verifyHeartbeatEnvelope else-branch went missing"); const branch = route.slice(elseAt, route.indexOf("\n }\n", elseAt)); assert.doesNotMatch(branch, /safeCompare/, "the fallback must not compare bearer/body tokens"); assert.match(branch, /warnHeartbeatFallbackRejectedOnce\(\);/, "the rejection must be loud"); assert.match(branch, /return res\.status\(401\)\.json\(\{ error: "authentication required" \}\);/, "the rejection must use the endpoint's uniform 401 body"); assert.doesNotMatch(branch, /current\.last_seen|current\.port_ok|saveNodeHealth/, "the fallback must not mutate node state"); });