478 lines
24 KiB
JavaScript
478 lines
24 KiB
JavaScript
"use strict";
|
|
|
|
const test = require("node:test");
|
|
const assert = require("node:assert");
|
|
const crypto = require("crypto");
|
|
|
|
const {
|
|
deriveNodeHmacSecret,
|
|
probeSignatureBase,
|
|
signPanelProbeRequest,
|
|
applyVersionSignatureBase,
|
|
signPanelApplyVersionRequest,
|
|
} = require("./node-hmac");
|
|
const {
|
|
BODY_HASH_HEADER,
|
|
createNonceCache,
|
|
createSharedHeartbeatNonceStore,
|
|
heartbeatBodySha256,
|
|
HEARTBEAT_NONCE_KEY_PREFIX,
|
|
heartbeatSignatureBase,
|
|
NONCE_TTL_MS,
|
|
verifyHeartbeatEnvelope,
|
|
} = require("./heartbeat-auth");
|
|
|
|
const MASTER = "fleet-master-secret-value";
|
|
const NODE_ID = "8.8.8.8-node-9f1c";
|
|
|
|
function hmacHex(secret, base) {
|
|
return crypto.createHmac("sha256", secret).update(base).digest("hex");
|
|
}
|
|
|
|
test("probe signature base matches the daemon envelope (uuid|probe|purpose|admin|ts|nonce)", () => {
|
|
assert.strictEqual(
|
|
probeSignatureBase(NODE_ID, "stats", "1700000000000", "abc123"),
|
|
`${NODE_ID}|probe|stats|admin|1700000000000|abc123`
|
|
);
|
|
assert.strictEqual(
|
|
probeSignatureBase(NODE_ID, "info", "1700000000000", ""),
|
|
`${NODE_ID}|probe|info|admin|1700000000000`
|
|
);
|
|
});
|
|
|
|
test("signPanelProbeRequest produces a verifiable signature over the derived secret", () => {
|
|
const secret = deriveNodeHmacSecret(MASTER, NODE_ID);
|
|
assert.match(secret, /^[0-9a-f]{64}$/);
|
|
|
|
const probe = signPanelProbeRequest(secret, NODE_ID, "stats");
|
|
assert.ok(probe, "probe signing failed");
|
|
assert.match(probe.nonce, /^[0-9a-f]{32}$/);
|
|
assert.strictEqual(probe.headers["x-panel-role"], "admin");
|
|
assert.strictEqual(probe.headers["x-panel-nonce"], probe.nonce);
|
|
|
|
const base = `${NODE_ID}|probe|stats|admin|${probe.headers["x-panel-ts"]}|${probe.nonce}`;
|
|
assert.strictEqual(probe.headers["x-panel-sign"], hmacHex(secret, base));
|
|
});
|
|
|
|
test("signPanelProbeRequest fails closed on blank inputs", () => {
|
|
assert.strictEqual(signPanelProbeRequest("", NODE_ID, "stats"), null);
|
|
assert.strictEqual(signPanelProbeRequest("secret", " ", "stats"), null);
|
|
assert.strictEqual(signPanelProbeRequest("secret", NODE_ID, ""), null);
|
|
});
|
|
|
|
function signedHeartbeatHeaders(secret, nodeId, { ts, nonce } = {}) {
|
|
const t = ts || String(Date.now());
|
|
const n = nonce || crypto.randomBytes(16).toString("hex");
|
|
const sig = hmacHex(secret, heartbeatSignatureBase(nodeId, t, n));
|
|
return { "x-node-ts": t, "x-node-sign": sig, "x-node-nonce": n };
|
|
}
|
|
|
|
// adpanel:heartbeat-body-binding — v2 signing helper: the body hash is sha256
|
|
// over the EXACT raw bytes (as the daemon would compute on the wire) and is
|
|
// both the x-node-body-hash header and the fourth base segment.
|
|
function signedHeartbeatV2Headers(secret, nodeId, rawBody, { ts, nonce, bodyHash } = {}) {
|
|
const t = ts || String(Date.now());
|
|
const n = nonce || crypto.randomBytes(16).toString("hex");
|
|
const hash = bodyHash || heartbeatBodySha256(rawBody);
|
|
const sig = hmacHex(secret, heartbeatSignatureBase(nodeId, t, n, hash));
|
|
return { "x-node-ts": t, "x-node-sign": sig, "x-node-nonce": n, [BODY_HASH_HEADER]: hash };
|
|
}
|
|
|
|
test("verifyHeartbeatEnvelope accepts a correctly signed heartbeat", async () => {
|
|
const secret = deriveNodeHmacSecret(MASTER, NODE_ID);
|
|
const cache = createNonceCache();
|
|
const headers = signedHeartbeatHeaders(secret, NODE_ID);
|
|
const verdict = await verifyHeartbeatEnvelope(headers, { secret, nodeId: NODE_ID, nonceCache: cache });
|
|
assert.deepStrictEqual(verdict, { ok: true, envelope: "v1", nonceScope: "local" });
|
|
});
|
|
|
|
test("verifyHeartbeatEnvelope rejects replays of an identical heartbeat", async () => {
|
|
const secret = deriveNodeHmacSecret(MASTER, NODE_ID);
|
|
const cache = createNonceCache();
|
|
const headers = signedHeartbeatHeaders(secret, NODE_ID);
|
|
assert.strictEqual((await verifyHeartbeatEnvelope(headers, { secret, nodeId: NODE_ID, nonceCache: cache })).ok, true);
|
|
const replay = await verifyHeartbeatEnvelope(headers, { secret, nodeId: NODE_ID, nonceCache: cache });
|
|
assert.strictEqual(replay.ok, false);
|
|
assert.strictEqual(replay.reason, "replayed");
|
|
});
|
|
|
|
test("verifyHeartbeatEnvelope rejects expired timestamps", async () => {
|
|
const secret = deriveNodeHmacSecret(MASTER, NODE_ID);
|
|
const cache = createNonceCache();
|
|
const staleTs = String(Date.now() - 6 * 60 * 1000);
|
|
const headers = signedHeartbeatHeaders(secret, NODE_ID, { ts: staleTs });
|
|
const verdict = await verifyHeartbeatEnvelope(headers, { secret, nodeId: NODE_ID, nonceCache: cache });
|
|
assert.strictEqual(verdict.reason, "expired");
|
|
});
|
|
|
|
test("verifyHeartbeatEnvelope rejects unsigned, nonce-less and forged requests", async () => {
|
|
const secret = deriveNodeHmacSecret(MASTER, NODE_ID);
|
|
const cache = createNonceCache();
|
|
const ctx = { secret, nodeId: NODE_ID, nonceCache: cache };
|
|
|
|
assert.strictEqual((await verifyHeartbeatEnvelope({}, ctx)).reason, "missing-signature");
|
|
assert.strictEqual((await verifyHeartbeatEnvelope({ "x-node-ts": String(Date.now()) }, ctx)).reason, "missing-signature");
|
|
|
|
const t = String(Date.now());
|
|
const sig = hmacHex(secret, heartbeatSignatureBase(NODE_ID, t, ""));
|
|
assert.strictEqual(
|
|
(await verifyHeartbeatEnvelope({ "x-node-ts": t, "x-node-sign": sig }, ctx)).reason,
|
|
"nonce-required"
|
|
);
|
|
|
|
const wrongNode = signedHeartbeatHeaders(secret, "some-other-node-uuid");
|
|
assert.strictEqual((await verifyHeartbeatEnvelope(wrongNode, ctx)).reason, "bad-signature");
|
|
|
|
const forged = signedHeartbeatHeaders("wrong-secret", NODE_ID);
|
|
assert.strictEqual((await verifyHeartbeatEnvelope(forged, ctx)).reason, "bad-signature");
|
|
});
|
|
|
|
test("verifyHeartbeatEnvelope rejects separator-smuggling nonces", async () => {
|
|
const secret = deriveNodeHmacSecret(MASTER, NODE_ID);
|
|
const cache = createNonceCache();
|
|
const t = String(Date.now());
|
|
const evil = "aaaaaaaaaaaaaaaa|x-node-sign-forged";
|
|
const headers = {
|
|
"x-node-ts": t,
|
|
"x-node-nonce": evil,
|
|
"x-node-sign": hmacHex(secret, heartbeatSignatureBase(NODE_ID, t, evil)),
|
|
};
|
|
const verdict = await verifyHeartbeatEnvelope(headers, { secret, nodeId: NODE_ID, nonceCache: cache });
|
|
assert.strictEqual(verdict.reason, "bad-nonce");
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// adpanel:heartbeat-body-binding — envelope v2 pins
|
|
//
|
|
// The v1 base does not bind the request body, so one captured (ts, nonce,
|
|
// sign) triple is valid for ANY body inside the drift window (repoint
|
|
// api_port, flip port_ok, refresh last_seen). v2 appends the sha256 of the
|
|
// EXACT raw bytes as the fourth base segment, declared via the
|
|
// x-node-body-hash header. The verifier hashes the raw bytes as received and
|
|
// fails closed (same 401 shape as every other rejection, at the route) on a
|
|
// tampered body or a v2 request without captured raw bytes — never against a
|
|
// re-serialization.
|
|
// ---------------------------------------------------------------------------
|
|
|
|
const HB_BODY = Buffer.from('{"api_port":39999,"token":"tok"}', "utf8");
|
|
|
|
test("heartbeatSignatureBase v2 appends the body hash as the fourth segment (v1 base unchanged)", () => {
|
|
const hash = heartbeatBodySha256(HB_BODY);
|
|
assert.strictEqual(
|
|
heartbeatSignatureBase(NODE_ID, "1700000000000", "abc123def456ghi0", hash),
|
|
`heartbeat|${NODE_ID}|1700000000000|abc123def456ghi0|${hash}`
|
|
);
|
|
// The legacy 3-arg form is byte-identical to the pre-v2 base.
|
|
assert.strictEqual(
|
|
heartbeatSignatureBase(NODE_ID, "1700000000000", "abc123def456ghi0"),
|
|
`heartbeat|${NODE_ID}|1700000000000|abc123def456ghi0`
|
|
);
|
|
});
|
|
|
|
test("heartbeatBodySha256 hashes the exact raw bytes (byte-level pin)", () => {
|
|
// Independently computed sha256 of '{"api_port":39999,"token":"tok"}'.
|
|
assert.strictEqual(
|
|
heartbeatBodySha256(HB_BODY),
|
|
crypto.createHash("sha256").update(HB_BODY).digest("hex")
|
|
);
|
|
// One byte differs -> a different hash (the tamper pin below relies on it).
|
|
const oneByteFlipped = Buffer.from(HB_BODY);
|
|
oneByteFlipped[1] ^= 0x01;
|
|
assert.notStrictEqual(heartbeatBodySha256(oneByteFlipped), heartbeatBodySha256(HB_BODY));
|
|
// Strings are hashed as UTF-8 bytes; anything else -> null (fail closed).
|
|
assert.strictEqual(heartbeatBodySha256('{"a":1}'), heartbeatBodySha256(Buffer.from('{"a":1}', "utf8")));
|
|
assert.strictEqual(heartbeatBodySha256(undefined), null);
|
|
assert.strictEqual(heartbeatBodySha256(null), null);
|
|
assert.strictEqual(heartbeatBodySha256({ api_port: 1 }), null, "objects must never be hashed — that is re-serialization");
|
|
});
|
|
|
|
test("verifyHeartbeatEnvelope accepts a v2 heartbeat whose body hash matches the raw bytes", async () => {
|
|
const secret = deriveNodeHmacSecret(MASTER, NODE_ID);
|
|
const cache = createNonceCache();
|
|
const headers = signedHeartbeatV2Headers(secret, NODE_ID, HB_BODY);
|
|
const verdict = await verifyHeartbeatEnvelope(headers, { secret, nodeId: NODE_ID, nonceCache: cache, rawBody: HB_BODY });
|
|
assert.deepStrictEqual(verdict, { ok: true, envelope: "v2", nonceScope: "local" });
|
|
});
|
|
|
|
test("verifyHeartbeatEnvelope rejects a v2 heartbeat whose body was tampered by one byte", async () => {
|
|
const secret = deriveNodeHmacSecret(MASTER, NODE_ID);
|
|
const cache = createNonceCache();
|
|
const headers = signedHeartbeatV2Headers(secret, NODE_ID, HB_BODY);
|
|
const tampered = Buffer.from(HB_BODY);
|
|
tampered[tampered.length - 3] = tampered[tampered.length - 3] ^ 0x01; // one byte flips
|
|
const verdict = await verifyHeartbeatEnvelope(headers, { secret, nodeId: NODE_ID, nonceCache: cache, rawBody: tampered });
|
|
assert.strictEqual(verdict.ok, false, "a one-byte body change must fail the envelope (same uniform 401 at the route)");
|
|
assert.strictEqual(verdict.reason, "body-hash-mismatch");
|
|
// The captured triple must ALSO be worthless against a different body even
|
|
// with a fresh nonce ledger: the signature covers the original hash.
|
|
const replayWithOtherBody = await verifyHeartbeatEnvelope(headers, { secret, nodeId: NODE_ID, nonceCache: createNonceCache(), rawBody: Buffer.from('{"api_port":1234}', "utf8") });
|
|
assert.strictEqual(replayWithOtherBody.reason, "body-hash-mismatch");
|
|
});
|
|
|
|
test("verifyHeartbeatEnvelope fails closed when a v2 request has no captured raw bytes", async () => {
|
|
const secret = deriveNodeHmacSecret(MASTER, NODE_ID);
|
|
const cache = createNonceCache();
|
|
const headers = signedHeartbeatV2Headers(secret, NODE_ID, HB_BODY);
|
|
// Raw capture missing (parser did not run / property absent) — v2 must
|
|
// NEVER fall back to re-serialized JSON.
|
|
for (const rawBody of [undefined, null, { api_port: 39999 }]) {
|
|
const verdict = await verifyHeartbeatEnvelope(headers, { secret, nodeId: NODE_ID, nonceCache: cache, rawBody });
|
|
assert.strictEqual(verdict.ok, false);
|
|
assert.strictEqual(verdict.reason, "body-unavailable");
|
|
}
|
|
});
|
|
|
|
test("verifyHeartbeatEnvelope rejects malformed v2 body-hash headers", async () => {
|
|
const secret = deriveNodeHmacSecret(MASTER, NODE_ID);
|
|
const cache = createNonceCache();
|
|
const base = { "x-node-ts": String(Date.now()), "x-node-nonce": "abcdef0123456789" };
|
|
for (const bad of ["not-a-hash", crypto.randomBytes(16).toString("hex"), "zzzz", `${heartbeatBodySha256(HB_BODY)}extra`]) {
|
|
const sig = hmacHex(secret, heartbeatSignatureBase(NODE_ID, base["x-node-ts"], base["x-node-nonce"], bad));
|
|
const verdict = await verifyHeartbeatEnvelope(
|
|
{ ...base, "x-node-sign": sig, [BODY_HASH_HEADER]: bad },
|
|
{ secret, nodeId: NODE_ID, nonceCache: cache, rawBody: HB_BODY }
|
|
);
|
|
assert.strictEqual(verdict.reason, "bad-body-hash", `malformed hash ${JSON.stringify(bad)} must be rejected pre-signature`);
|
|
}
|
|
// An EMPTY header value is indistinguishable from an absent marker, so it
|
|
// takes the v1 path — and a signature minted over the v2 base then fails as
|
|
// bad-signature (no cross-version confusion in either direction).
|
|
const v2Sig = hmacHex(secret, heartbeatSignatureBase(NODE_ID, base["x-node-ts"], base["x-node-nonce"], heartbeatBodySha256(HB_BODY)));
|
|
const emptyMarker = await verifyHeartbeatEnvelope(
|
|
{ ...base, "x-node-sign": v2Sig, [BODY_HASH_HEADER]: "" },
|
|
{ secret, nodeId: NODE_ID, nonceCache: cache, rawBody: HB_BODY }
|
|
);
|
|
assert.strictEqual(emptyMarker.reason, "bad-signature");
|
|
});
|
|
|
|
test("verifyHeartbeatEnvelope still accepts the legacy v1 envelope unchanged (transitional state)", async () => {
|
|
const secret = deriveNodeHmacSecret(MASTER, NODE_ID);
|
|
const cache = createNonceCache();
|
|
const headers = signedHeartbeatHeaders(secret, NODE_ID);
|
|
// No x-node-body-hash header, no rawBody option: the pre-v2 contract.
|
|
const verdict = await verifyHeartbeatEnvelope(headers, { secret, nodeId: NODE_ID, nonceCache: cache });
|
|
assert.strictEqual(verdict.ok, true);
|
|
assert.strictEqual(verdict.envelope, "v1");
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// adpanel:heartbeat-nonce-shared — cluster-shared nonce ledger pins
|
|
//
|
|
// The per-process cache is 1/N effective under PM2 cluster; the shared store
|
|
// is the authoritative arbiter (SET NX PX, key carries the node id, TTL >
|
|
// drift window) with the per-process cache as write-through fallback. The
|
|
// Redis client is mocked following the injected clientOf/readyOf shape of
|
|
// utils/login-attack-redis.js (node-redis v4: sendCommand(string[])).
|
|
// ---------------------------------------------------------------------------
|
|
|
|
function mockRedisClient() {
|
|
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); // NX lost: replay
|
|
keys.add(argv[1]);
|
|
return Promise.resolve("OK");
|
|
}
|
|
return Promise.resolve("OK");
|
|
},
|
|
};
|
|
}
|
|
|
|
function failingRedisClient() {
|
|
return {
|
|
sendCommand() {
|
|
return Promise.reject(new Error("connection down"));
|
|
},
|
|
};
|
|
}
|
|
|
|
test("nonce replay is rejected via the shared store (replayed once per cluster, not per worker)", async () => {
|
|
const secret = deriveNodeHmacSecret(MASTER, NODE_ID);
|
|
const cache = createNonceCache();
|
|
const redis = mockRedisClient();
|
|
const shared = createSharedHeartbeatNonceStore({ clientOf: () => redis, readyOf: () => true });
|
|
const ctx = { secret, nodeId: NODE_ID, nonceCache: cache, sharedNonceStore: shared };
|
|
const headers = signedHeartbeatHeaders(secret, NODE_ID);
|
|
|
|
const first = await verifyHeartbeatEnvelope(headers, ctx);
|
|
assert.deepStrictEqual(first, { ok: true, envelope: "v1", nonceScope: "shared" });
|
|
const replay = await verifyHeartbeatEnvelope(headers, ctx);
|
|
assert.strictEqual(replay.ok, false);
|
|
assert.strictEqual(replay.reason, "replayed", "the shared ledger must reject the replay, not just this worker's cache");
|
|
// Write-through: the local fallback cache also saw the nonce.
|
|
assert.strictEqual(cache.record(headers["x-node-nonce"], Date.now()), false, "shared verdicts must write through to the local fallback cache");
|
|
});
|
|
|
|
test("shared nonce keys carry the node id, the nonce, NX and the drift-window TTL", async () => {
|
|
const secret = deriveNodeHmacSecret(MASTER, NODE_ID);
|
|
const cache = createNonceCache();
|
|
const redis = mockRedisClient();
|
|
const shared = createSharedHeartbeatNonceStore({ clientOf: () => redis, readyOf: () => true });
|
|
const nonce = "0123456789abcdef0123456789abcdef";
|
|
const headers = signedHeartbeatHeaders(secret, NODE_ID, { nonce });
|
|
await verifyHeartbeatEnvelope(headers, { secret, nodeId: NODE_ID, nonceCache: cache, sharedNonceStore: shared });
|
|
|
|
const setCmds = redis.commands.filter((c) => c[0] === "SET");
|
|
assert.strictEqual(setCmds.length, 1);
|
|
const cmd = setCmds[0];
|
|
assert.strictEqual(cmd[1], `${HEARTBEAT_NONCE_KEY_PREFIX}${NODE_ID}:${nonce}`, "the key must be namespaced per mechanism and carry the node id + nonce");
|
|
assert.strictEqual(cmd[2], "1");
|
|
assert.ok(cmd.includes("NX"), "SET must be NX (first-seen wins, replays lose)");
|
|
const pxAt = cmd.indexOf("PX");
|
|
assert.ok(pxAt !== -1, "the TTL must be PX (milliseconds)");
|
|
assert.strictEqual(Number(cmd[pxAt + 1]), NONCE_TTL_MS, "TTL = drift window + margin (the local cache's NONCE_TTL_MS)");
|
|
assert.ok(Number(cmd[pxAt + 1]) > 5 * 60 * 1000, "TTL must exceed the 5-minute drift window");
|
|
});
|
|
|
|
test("Redis outage falls back to the per-process cache: first-seen accepted, replays rejected locally", async () => {
|
|
const secret = deriveNodeHmacSecret(MASTER, NODE_ID);
|
|
const cache = createNonceCache();
|
|
const shared = createSharedHeartbeatNonceStore({ clientOf: () => failingRedisClient(), readyOf: () => true });
|
|
const ctx = { secret, nodeId: NODE_ID, nonceCache: cache, sharedNonceStore: shared };
|
|
const headers = signedHeartbeatHeaders(secret, NODE_ID);
|
|
|
|
const first = await verifyHeartbeatEnvelope(headers, ctx);
|
|
assert.strictEqual(first.ok, true, "heartbeats must keep flowing during a Redis outage");
|
|
assert.strictEqual(first.nonceScope, "local-fallback", "the route warns once on this scope");
|
|
const replay = await verifyHeartbeatEnvelope(headers, ctx);
|
|
assert.strictEqual(replay.ok, false);
|
|
assert.strictEqual(replay.reason, "replayed", "the local fallback must still catch same-worker replays");
|
|
});
|
|
|
|
test("shared store degrades on a not-ready or absent client (never throws, never hangs)", async () => {
|
|
const secret = deriveNodeHmacSecret(MASTER, NODE_ID);
|
|
const cache = createNonceCache();
|
|
const headers = signedHeartbeatHeaders(secret, NODE_ID);
|
|
// clientOf returns null (Redis never configured) and readyOf false.
|
|
const unwired = createSharedHeartbeatNonceStore({ clientOf: () => null, readyOf: () => false });
|
|
const verdict = await verifyHeartbeatEnvelope(headers, { secret, nodeId: NODE_ID, nonceCache: cache, sharedNonceStore: unwired });
|
|
assert.strictEqual(verdict.ok, true);
|
|
assert.strictEqual(verdict.nonceScope, "local-fallback");
|
|
// A store whose record throws must degrade, not reject the verifier.
|
|
const throwing = { record: () => { throw new Error("boom"); } };
|
|
const cache2 = createNonceCache();
|
|
const verdict2 = await verifyHeartbeatEnvelope(signedHeartbeatHeaders(secret, NODE_ID), { secret, nodeId: NODE_ID, nonceCache: cache2, sharedNonceStore: throwing });
|
|
assert.strictEqual(verdict2.ok, true);
|
|
assert.strictEqual(verdict2.nonceScope, "local-fallback");
|
|
// A slow client must not hold the heartbeat longer than the op timeout.
|
|
const slow = createSharedHeartbeatNonceStore({
|
|
clientOf: () => ({ sendCommand: () => new Promise(() => {}) }),
|
|
readyOf: () => true,
|
|
opTimeoutMs: 20,
|
|
});
|
|
const started = Date.now();
|
|
const verdict3 = await verifyHeartbeatEnvelope(signedHeartbeatHeaders(secret, NODE_ID), { secret, nodeId: NODE_ID, nonceCache: createNonceCache(), sharedNonceStore: slow });
|
|
assert.ok(Date.now() - started < 1000, "the hard op timeout bounds the shared-store dial");
|
|
assert.strictEqual(verdict3.ok, true);
|
|
assert.strictEqual(verdict3.nonceScope, "local-fallback");
|
|
});
|
|
|
|
test("v2 heartbeats also ride the shared nonce ledger", async () => {
|
|
const secret = deriveNodeHmacSecret(MASTER, NODE_ID);
|
|
const redis = mockRedisClient();
|
|
const shared = createSharedHeartbeatNonceStore({ clientOf: () => redis, readyOf: () => true });
|
|
const ctx = { secret, nodeId: NODE_ID, nonceCache: createNonceCache(), sharedNonceStore: shared, rawBody: HB_BODY };
|
|
const headers = signedHeartbeatV2Headers(secret, NODE_ID, HB_BODY);
|
|
const first = await verifyHeartbeatEnvelope(headers, ctx);
|
|
assert.deepStrictEqual(first, { ok: true, envelope: "v2", nonceScope: "shared" });
|
|
const replay = await verifyHeartbeatEnvelope(headers, ctx);
|
|
assert.strictEqual(replay.reason, "replayed");
|
|
});
|
|
|
|
test("nonce cache entries expire after the TTL", () => {
|
|
const cache = createNonceCache();
|
|
const now = Date.now();
|
|
assert.strictEqual(cache.record("n1".padEnd(16, "0"), now), true);
|
|
assert.strictEqual(cache.record("n1".padEnd(16, "0"), now), false);
|
|
// After the TTL the entry is gone: a nonce may be reused in a later window.
|
|
assert.strictEqual(cache.record("n1".padEnd(16, "0"), now + 7 * 60 * 1000), true);
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Panel -> node apply-version signing (POST /v1/servers/<name>/apply-version)
|
|
//
|
|
// The daemon dispatches this endpoint before bearer-token auth, so the
|
|
// envelope is the request's only authentication. The signed base MUST stay
|
|
// byte-identical to the daemon's verifyPanelSignature:
|
|
// <name>|<providerId>|<versionId>|<url>|<ts>|<nonce>
|
|
// The fixed literals below are shared with apply_version_signature_compat_test.go
|
|
// on the Go side — if either implementation drifts, one of the two suites
|
|
// fails against them.
|
|
// ---------------------------------------------------------------------------
|
|
|
|
const APPLY_FIXTURE = {
|
|
name: "srv-1",
|
|
providerId: "papermc",
|
|
versionId: "1.21.4",
|
|
url: "https://example.com/server.jar",
|
|
ts: "1700000000000",
|
|
nonce: "0123456789abcdef0123456789abcdef",
|
|
};
|
|
|
|
test("apply-version signature base matches the daemon envelope (name|provider|version|url|ts|nonce)", () => {
|
|
const f = APPLY_FIXTURE;
|
|
assert.strictEqual(
|
|
applyVersionSignatureBase(f.name, f.providerId, f.versionId, f.url, f.ts, f.nonce),
|
|
`${f.name}|${f.providerId}|${f.versionId}|${f.url}|${f.ts}|${f.nonce}`
|
|
);
|
|
// Absent provider/version fields are bound as empty segments — the daemon's
|
|
// Go zero values for the pruned backward-compat body.
|
|
assert.strictEqual(
|
|
applyVersionSignatureBase(f.name, "", "", f.url, f.ts, f.nonce),
|
|
`${f.name}|||${f.url}|${f.ts}|${f.nonce}`
|
|
);
|
|
// Legacy (nonce-less) form for daemons predating nonce-authenticated
|
|
// signatures.
|
|
assert.strictEqual(
|
|
applyVersionSignatureBase(f.name, f.providerId, f.versionId, f.url, f.ts, ""),
|
|
`${f.name}|${f.providerId}|${f.versionId}|${f.url}|${f.ts}`
|
|
);
|
|
});
|
|
|
|
test("signPanelApplyVersionRequest produces a verifiable signature with no role header", () => {
|
|
const f = APPLY_FIXTURE;
|
|
const secret = deriveNodeHmacSecret(MASTER, NODE_ID);
|
|
const signed = signPanelApplyVersionRequest(secret, f.name, f.providerId, f.versionId, f.url);
|
|
assert.ok(signed, "apply-version signing failed");
|
|
assert.match(signed.nonce, /^[0-9a-f]{32}$/);
|
|
// Unlike reinstall/node-admin, the daemon's apply-version verifier reads
|
|
// only ts/sign/nonce — pin the envelope to exactly that.
|
|
assert.strictEqual(signed.headers["x-panel-role"], undefined);
|
|
assert.strictEqual(signed.headers["x-panel-ts"], signed.headers["x-panel-ts"]);
|
|
const base = `${f.name}|${f.providerId}|${f.versionId}|${f.url}|${signed.headers["x-panel-ts"]}|${signed.nonce}`;
|
|
assert.strictEqual(signed.headers["x-panel-sign"], hmacHex(secret, base));
|
|
});
|
|
|
|
test("signPanelApplyVersionRequest legacy form signs the nonce-less base", () => {
|
|
const f = APPLY_FIXTURE;
|
|
const secret = deriveNodeHmacSecret(MASTER, NODE_ID);
|
|
const signed = signPanelApplyVersionRequest(secret, f.name, f.providerId, f.versionId, f.url, { legacy: true });
|
|
assert.ok(signed, "legacy apply-version signing failed");
|
|
assert.strictEqual(signed.nonce, "");
|
|
assert.strictEqual(signed.headers["x-panel-nonce"], undefined);
|
|
const base = `${f.name}|${f.providerId}|${f.versionId}|${f.url}|${signed.headers["x-panel-ts"]}`;
|
|
assert.strictEqual(signed.headers["x-panel-sign"], hmacHex(secret, base));
|
|
});
|
|
|
|
test("signPanelApplyVersionRequest signs empty provider/version bindings for pruned bodies", () => {
|
|
const f = APPLY_FIXTURE;
|
|
const secret = deriveNodeHmacSecret(MASTER, NODE_ID);
|
|
const signed = signPanelApplyVersionRequest(secret, f.name, "", "", f.url);
|
|
assert.ok(signed, "pruned apply-version signing failed");
|
|
const base = `${f.name}|||${f.url}|${signed.headers["x-panel-ts"]}|${signed.nonce}`;
|
|
assert.strictEqual(signed.headers["x-panel-sign"], hmacHex(secret, base));
|
|
});
|
|
|
|
test("signPanelApplyVersionRequest fails closed on blank inputs", () => {
|
|
const f = APPLY_FIXTURE;
|
|
assert.strictEqual(signPanelApplyVersionRequest("", f.name, "p", "v", f.url), null);
|
|
assert.strictEqual(signPanelApplyVersionRequest(" ", f.name, "p", "v", f.url), null);
|
|
assert.strictEqual(signPanelApplyVersionRequest("secret", " ", "p", "v", f.url), null);
|
|
assert.strictEqual(signPanelApplyVersionRequest("secret", f.name, "p", "v", " "), null);
|
|
});
|