404 lines
19 KiB
JavaScript
404 lines
19 KiB
JavaScript
"use strict";
|
|
|
|
// Tests for adpanel:heartbeat-capture-integrated — the heartbeat v2 raw-body
|
|
// capture must live on the parser that ACTUALLY parses
|
|
// POST /api/nodes/:id/heartbeat in each deployment topology.
|
|
//
|
|
// The regression this pins (runtime-proven by the wired synthesis review):
|
|
// the v2 body-binding fix put the raw-body capture on nodes.js's OWN parser
|
|
// (express.json({ limit: "2mb", verify: captureHeartbeatRawBody })). That
|
|
// works standalone, but in INTEGRATED mode (index.js + app.use(nodesRouter))
|
|
// index.js's pre-auth JSON dispatch (its catch-all jsonParserDefault) parses
|
|
// the heartbeat FIRST and body-parser then sets the req._body sentinel —
|
|
// nodes.js's parser afterwards SKIPS without ever invoking verify
|
|
// (node_modules/body-parser/lib/types/json.js checks req._body before
|
|
// verify). req.heartbeatRawBody stayed undefined and every v2 heartbeat
|
|
// failed closed with the uniform 401 (body-unavailable). The fix exports the
|
|
// ONE capture implementation from nodes.js and index.js binds it onto a
|
|
// heartbeat-scoped parser ahead of its catch-all jsonParserDefault.
|
|
//
|
|
// Locked in here with the REAL express + body-parser over real HTTP:
|
|
// 1. Integrated ordering (index-style dispatch parser with the shared
|
|
// capture, then nodes.js mounted after): a v2 envelope over the exact
|
|
// wire bytes authenticates end-to-end (before the fix: 401).
|
|
// 2. Integrated ordering: the captured buffer is BYTE-IDENTICAL to the
|
|
// wire body (multi-byte UTF-8 + irregular spacing, so a
|
|
// re-serialization of req.body would NOT match) and the request is
|
|
// still parsed normally — one parse, one capture.
|
|
// 3. Standalone ordering (nodes.js's own parser parses): the capture still
|
|
// works — the export/rewiring did not break `node nodes.js`.
|
|
// 4. The body-parser contract the fix depends on: with an app-level parser
|
|
// WITHOUT capture followed by a parser WITH capture, the capture does
|
|
// NOT fire (A/B against capture-first on the same exported function).
|
|
// 5. Source pins: index.js's heartbeat mount is reachable BEFORE its
|
|
// catch-all jsonParserDefault, binds the shared export (no inlined
|
|
// second implementation), the path regex literal is character-identical
|
|
// to nodes.js HEARTBEAT_ROUTE_RE, and exactly ONE capture
|
|
// implementation exists in the codebase (one-true-home).
|
|
|
|
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 INDEX_JS = path.join(ROOT, "index.js");
|
|
|
|
const { deriveNodeHmacSecret } = require(path.join(ROOT, "utils", "node-hmac.js"));
|
|
|
|
const MASTER_INTEGRATED = "hb-rawbody-integrated-fleet-master";
|
|
const MASTER_STANDALONE = "hb-rawbody-standalone-fleet-master";
|
|
const NODE_TOKEN = "hb-rawbody-integrated-node-token";
|
|
const NODE_ROW = {
|
|
id: 42001,
|
|
uuid: "hb-rawbody-integrated-uuid",
|
|
name: "hb-rawbody-integrated-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-rawbody",
|
|
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,
|
|
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 its own isolated db stub, following
|
|
// tests/heartbeat-fallback-scoped.test.js. 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 sha256Hex(data) {
|
|
return crypto.createHash("sha256").update(data).digest("hex");
|
|
}
|
|
|
|
// v2 envelope: the signature base carries the sha256 of the EXACT wire bytes
|
|
// (see tests/heartbeat-fallback-scoped.test.js instance C for the format).
|
|
function signedV2Headers(masterSecret, nodeId, wireBytes) {
|
|
const nodeSecret = deriveNodeHmacSecret(masterSecret, nodeId);
|
|
const ts = String(Date.now());
|
|
const nonce = crypto.randomBytes(16).toString("hex");
|
|
const bodyHash = sha256Hex(wireBytes);
|
|
const sig = crypto
|
|
.createHmac("sha256", nodeSecret)
|
|
.update(`heartbeat|${nodeId}|${ts}|${nonce}|${bodyHash}`)
|
|
.digest("hex");
|
|
return { "x-node-ts": ts, "x-node-sign": sig, "x-node-nonce": nonce, "x-node-body-hash": bodyHash };
|
|
}
|
|
|
|
function post(baseUrl, pathname, { headers = {}, body, raw } = {}) {
|
|
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();
|
|
});
|
|
}
|
|
|
|
// The integrated deployment's dispatch, replicated with the same shape as
|
|
// index.js's pre-auth JSON dispatch (app.use middleware; heartbeat branch
|
|
// ahead of the catch-all jsonParserDefault) and wired THE WAY INDEX.JS NOW
|
|
// WIRES IT: the parser's verify is the ONE capture implementation exported
|
|
// from nodes.js (nodesRouter.captureHeartbeatRawBody), then nodesRouter is
|
|
// mounted after — exactly index.js's app.use(nodesRouter) ordering.
|
|
function buildIntegratedParent(nodesApp) {
|
|
const parent = express();
|
|
const jsonParserDefault = express.json({ limit: "1mb" });
|
|
const heartbeatJsonParserCapture = express.json({ limit: "2mb", verify: nodesApp.captureHeartbeatRawBody });
|
|
parent.use((req, res, next) => {
|
|
if (req._staticAsset || req.method === "GET" || req.method === "HEAD" || req.method === "OPTIONS") return next();
|
|
if (req.method === "POST" && /^\/api\/nodes\/[^/]+\/heartbeat$/.test(req.path || "")) {
|
|
return heartbeatJsonParserCapture(req, res, next);
|
|
}
|
|
return jsonParserDefault(req, res, next);
|
|
});
|
|
parent.use(nodesApp);
|
|
return parent;
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Instance I: integrated topology (dispatch parser with the shared capture,
|
|
// nodes.js mounted after). The route, gate, nonce store and v2 verifier are
|
|
// the REAL ones from nodes.js.
|
|
// ---------------------------------------------------------------------------
|
|
|
|
const integrated = loadNodesJs({ masterSecret: MASTER_INTEGRATED });
|
|
const parentI = buildIntegratedParent(integrated.app);
|
|
|
|
// Second parent over the same nodes.js instance: dispatch → stub handler →
|
|
// nodesRouter. The stub observes req[HEARTBEAT_RAW_BODY_PROP] directly, so
|
|
// the captured buffer itself can be compared to the wire bytes.
|
|
const parentStub = express();
|
|
const stubHeartbeatJsonParserCapture = express.json({ limit: "2mb", verify: integrated.app.captureHeartbeatRawBody });
|
|
parentStub.use((req, res, next) => {
|
|
if (req._staticAsset || req.method === "GET" || req.method === "HEAD" || req.method === "OPTIONS") return next();
|
|
if (req.method === "POST" && /^\/api\/nodes\/[^/]+\/heartbeat$/.test(req.path || "")) {
|
|
return stubHeartbeatJsonParserCapture(req, res, next);
|
|
}
|
|
return next();
|
|
});
|
|
parentStub.post("/api/nodes/:id/heartbeat", (req, res) => {
|
|
const buf = req[integrated.app.HEARTBEAT_RAW_BODY_PROP];
|
|
res.json({
|
|
capturedProp: buf === undefined ? null : "present",
|
|
len: Buffer.isBuffer(buf) ? buf.length : -1,
|
|
b64: Buffer.isBuffer(buf) ? buf.toString("base64") : null,
|
|
bodyApiPort: req.body && req.body.api_port,
|
|
});
|
|
});
|
|
parentStub.use(integrated.app);
|
|
|
|
let baseUrlI = "";
|
|
let serverI = null;
|
|
let baseUrlStub = "";
|
|
let serverStub = null;
|
|
|
|
test.before(async () => {
|
|
await new Promise((resolve) => { serverI = parentI.listen(0, "127.0.0.1", resolve); });
|
|
baseUrlI = `http://127.0.0.1:${serverI.address().port}`;
|
|
await new Promise((resolve) => { serverStub = parentStub.listen(0, "127.0.0.1", resolve); });
|
|
baseUrlStub = `http://127.0.0.1:${serverStub.address().port}`;
|
|
});
|
|
|
|
test.after(() => Promise.all([
|
|
new Promise((resolve) => serverI.close(resolve)),
|
|
new Promise((resolve) => serverStub.close(resolve)),
|
|
]));
|
|
|
|
test("integrated ordering: the dispatch parser with the shared capture lets a v2 envelope authenticate end-to-end", async () => {
|
|
const { queries } = integrated.dbStub;
|
|
queries.length = 0;
|
|
const wire = Buffer.from(JSON.stringify({ api_port: 42601 }), "utf8");
|
|
const headers = signedV2Headers(MASTER_INTEGRATED, NODE_ROW.uuid, wire);
|
|
const { status, json } = await post(baseUrlI, `/api/nodes/${NODE_ROW.uuid}/heartbeat`, { headers, raw: wire });
|
|
assert.equal(status, 200, "in integrated ordering the v2 envelope must authenticate (regression: uniform 401 body-unavailable)");
|
|
assert.equal(json && json.ok, true);
|
|
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("integrated ordering: the captured buffer is byte-identical to the wire body and the body is parsed normally", async () => {
|
|
// Valid JSON with irregular spacing and multi-byte UTF-8: a capture built
|
|
// from re-serialized req.body would NOT match these wire bytes.
|
|
const wire = Buffer.from('{ "api_port" :42700 , "pad":"µ—€" }', "utf8");
|
|
const { status, json } = await post(baseUrlStub, `/api/nodes/${NODE_ROW.uuid}/heartbeat`, { raw: wire });
|
|
assert.equal(status, 200);
|
|
assert.equal(json.capturedProp, "present", "the capture prop must be set by the integrated dispatch parser");
|
|
assert.equal(json.len, wire.length, `the capture must hold ${wire.length} wire bytes (not ${wire.length - 6} decoded chars)`);
|
|
const captured = Buffer.from(json.b64, "base64");
|
|
assert.ok(captured.equals(wire), "the captured buffer must be byte-identical to the sent body");
|
|
assert.equal(json.bodyApiPort, 42700, "the same parser must still deliver a parsed req.body (one parse, one capture)");
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Instance S: standalone topology (`node nodes.js` — no index.js dispatch).
|
|
// nodes.js's own 2mb parser with the same capture parses first.
|
|
// ---------------------------------------------------------------------------
|
|
|
|
const standalone = loadNodesJs({ masterSecret: MASTER_STANDALONE });
|
|
const parentS = express();
|
|
parentS.use(standalone.app);
|
|
|
|
let baseUrlS = "";
|
|
let serverS = null;
|
|
|
|
test.before(async () => {
|
|
await new Promise((resolve) => { serverS = parentS.listen(0, "127.0.0.1", resolve); });
|
|
baseUrlS = `http://127.0.0.1:${serverS.address().port}`;
|
|
});
|
|
|
|
test.after(() => new Promise((resolve) => serverS.close(resolve)));
|
|
|
|
test("standalone ordering: nodes.js's own parser still captures (v2 envelope authenticates end-to-end)", async () => {
|
|
const { queries } = standalone.dbStub;
|
|
queries.length = 0;
|
|
const wire = Buffer.from(JSON.stringify({ api_port: 42801 }), "utf8");
|
|
const headers = signedV2Headers(MASTER_STANDALONE, NODE_ROW.uuid, wire);
|
|
const { status, json } = await post(baseUrlS, `/api/nodes/${NODE_ROW.uuid}/heartbeat`, { headers, raw: wire });
|
|
assert.equal(status, 200, "standalone mode must keep working: the exported capture stays on nodes.js's own parser");
|
|
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, /port_ok|last_check|online|api_port/);
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// The body-parser contract the fix depends on (real express + body-parser):
|
|
// once an earlier parser set req._body, a LATER parser skips without ever
|
|
// invoking verify — so a capture on a later parser silently never fires.
|
|
// A/B on the SAME exported function and the same path: capture-first fires,
|
|
// capture-second does not.
|
|
// ---------------------------------------------------------------------------
|
|
|
|
const orderProbe = express();
|
|
const captureParser = express.json({ limit: "2mb", verify: integrated.app.captureHeartbeatRawBody });
|
|
const plainParser = express.json({ limit: "1mb" });
|
|
orderProbe.use((req, res, next) => {
|
|
const captureFirst = req.get("x-parser-order") === "capture-first";
|
|
const first = captureFirst ? captureParser : plainParser;
|
|
const second = captureFirst ? plainParser : captureParser;
|
|
return first(req, res, () => second(req, res, next));
|
|
});
|
|
orderProbe.post("/api/nodes/order-node/heartbeat", (req, res) => {
|
|
const buf = req[integrated.app.HEARTBEAT_RAW_BODY_PROP];
|
|
res.json({ capturedProp: buf === undefined ? null : "present" });
|
|
});
|
|
|
|
let baseUrlOrder = "";
|
|
let serverOrder = null;
|
|
|
|
test.before(async () => {
|
|
await new Promise((resolve) => { serverOrder = orderProbe.listen(0, "127.0.0.1", resolve); });
|
|
baseUrlOrder = `http://127.0.0.1:${serverOrder.address().port}`;
|
|
});
|
|
|
|
test.after(() => new Promise((resolve) => serverOrder.close(resolve)));
|
|
|
|
test("body-parser contract: an app-level parser WITHOUT capture followed by a parser WITH capture does NOT capture", async () => {
|
|
const wire = Buffer.from(JSON.stringify({ api_port: 42901 }), "utf8");
|
|
const skip = await post(baseUrlOrder, "/api/nodes/order-node/heartbeat", {
|
|
headers: { "x-parser-order": "capture-second" },
|
|
raw: wire,
|
|
});
|
|
assert.equal(skip.status, 200);
|
|
assert.equal(skip.json.capturedProp, null,
|
|
"req._body set by the first parser makes body-parser skip the second parser entirely — verify never runs (this is exactly how the integrated regression shipped)");
|
|
const control = await post(baseUrlOrder, "/api/nodes/order-node/heartbeat", {
|
|
headers: { "x-parser-order": "capture-first" },
|
|
raw: wire,
|
|
});
|
|
assert.equal(control.status, 200);
|
|
assert.equal(control.json.capturedProp, "present",
|
|
"control: the SAME exported capture fires when its parser is the first to parse — the function is fine, only the mount position matters");
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Source pins: mount order, the shared export, and the one-true-home.
|
|
// ---------------------------------------------------------------------------
|
|
|
|
test("source pin: index.js's heartbeat capture mount is reachable BEFORE its catch-all jsonParserDefault and binds the shared export", () => {
|
|
const src = fs.readFileSync(INDEX_JS, "utf8");
|
|
const constAt = src.indexOf('const heartbeatJsonParserCapture = express.json({ limit: "2mb", verify: nodesRouter.captureHeartbeatRawBody });');
|
|
assert.ok(constAt !== -1, "the heartbeat capture parser must exist and bind the ONE capture implementation exported from nodes.js");
|
|
const branchAt = src.indexOf("heartbeatJsonParserCapture(req, res, next)");
|
|
assert.ok(branchAt !== -1, "the dispatch chain must invoke the heartbeat parser");
|
|
const catchAllAt = src.indexOf("return jsonParserDefault(req, res, next);");
|
|
assert.ok(catchAllAt !== -1, "the dispatch chain's catch-all jsonParserDefault fall-through is expected");
|
|
assert.ok(branchAt < catchAllAt,
|
|
"the heartbeat mount must be reachable BEFORE the catch-all jsonParserDefault — dispatch order is mount order, and the capture must ride the parser that parses first");
|
|
assert.doesNotMatch(src, /function\s+captureHeartbeatRawBody\s*\(/,
|
|
"index.js must not inline a second capture implementation (one-true-home: nodes.js)");
|
|
assert.equal((src.match(/adpanel:heartbeat-capture-integrated/g) || []).length >= 2,
|
|
true, "the constraint tag must document both the parser const and the dispatch mount");
|
|
});
|
|
|
|
test("source pin: the index.js heartbeat path regex is character-identical to nodes.js HEARTBEAT_ROUTE_RE, and the export exists", () => {
|
|
const nodesSrc = fs.readFileSync(NODES_JS, "utf8");
|
|
const indexSrc = fs.readFileSync(INDEX_JS, "utf8");
|
|
// The exact source characters of the heartbeat matcher literal (both files
|
|
// must spell the ONE regex the route, the gate and the capture agree on).
|
|
const literal = "/^\\/api\\/nodes\\/[^/]+\\/heartbeat$/";
|
|
assert.ok(nodesSrc.includes(`const HEARTBEAT_ROUTE_RE = ${literal};`),
|
|
"nodes.js HEARTBEAT_ROUTE_RE went missing or drifted");
|
|
assert.ok(indexSrc.includes(`if (req.method === "POST" && ${literal}.test(req.path || ""))`),
|
|
"index.js's dispatch branch must use the exact HEARTBEAT_ROUTE_RE literal (lockstep, no divergent second regex)");
|
|
assert.match(nodesSrc, /module\.exports\.captureHeartbeatRawBody = captureHeartbeatRawBody;/,
|
|
"nodes.js must export the ONE capture implementation");
|
|
assert.match(nodesSrc, /module\.exports\.HEARTBEAT_RAW_BODY_PROP = HEARTBEAT_RAW_BODY_PROP;/,
|
|
"the capture prop name must travel with the capture so mount and verifier cannot drift");
|
|
});
|
|
|
|
test("source pin: exactly ONE captureHeartbeatRawBody implementation exists in the codebase (one-true-home)", () => {
|
|
const dirs = [ROOT, path.join(ROOT, "utils"), path.join(ROOT, "services"), path.join(ROOT, "routes")];
|
|
const holders = [];
|
|
for (const dir of dirs) {
|
|
for (const entry of fs.readdirSync(dir)) {
|
|
if (!entry.endsWith(".js")) continue;
|
|
const file = path.join(dir, entry);
|
|
const src = fs.readFileSync(file, "utf8");
|
|
if (/function\s+captureHeartbeatRawBody\s*\(/.test(src)) holders.push(file);
|
|
}
|
|
}
|
|
assert.deepEqual(holders, [NODES_JS],
|
|
"the capture implementation must exist exactly once — in nodes.js — and every topology binds that export");
|
|
});
|