"use strict"; // adpanel:secret-strength-boot-check — pins for the boot strength checks on // the env secret overrides. Originally the three derived-HMAC overrides // (REMEMBER_LOGIN_SECRET, ACTION_TOKEN_SECRET, SSH_TERM_TOKEN_SECRET); the // sealing-key campaign added four more with the same floor and fail-fast // discipline (TOTP_SEALING_KEY, NODE_TOKEN_SEALING_KEY, // MONGO_ADMIN_SEALING_KEY, WEBHOOK_SEALING_KEY — each replaces the scrypt KDF // INPUT of an at-rest AES-256-GCM seal). The audit finding: SESSION_SECRET // exits at boot on a missing/short value, but these overrides were accepted // at ANY strength — and each one REPLACES a high-entropy SESSION_SECRET- // derived fallback (HMAC key or seal KDF input), so a weak override silently // weakens exactly the credentials that depend on it. It is strictly worse // than leaving the override unset. // // Contract locked here: // - One shared helper, called once per override, adjacent to the // SESSION_SECRET check in the boot-validation region — never a parallel // per-secret copy. // - Same 32-char floor as SESSION_SECRET (the Go sshterm consumer enforces // only >= 16 in cmd/sshterm/main.go; Node must not be the weaker link, // so it matches SESSION_SECRET instead). // - Violation (set, non-empty, < 32) → loud console.error naming the env // var + process.exit(1), mirroring the SESSION_SECRET fail-fast shape. // - Unset or empty override → derived fallback stays legal (behavior // unchanged); the `||`-fallback derivations at the consumption sites // must remain in place. // - The checks run in the module top-level boot region BEFORE listen() // (index.js executes top-to-bottom; the consuming consts are only USED // at request time, so before-listen placement is before every use). // - The boot ALTER failure log for users.totp_last_counter is console.warn // (matching the sibling column-check warns), not console.debug. const test = require("node:test"); const assert = require("node:assert"); const fs = require("node:fs"); const path = require("node:path"); const vm = require("node:vm"); const INDEX_JS = path.join(__dirname, "..", "index.js"); const indexSource = fs.readFileSync(INDEX_JS, "utf8"); function endIndexOfFunction(source, startMarker) { const start = source.indexOf(startMarker); assert.ok(start >= 0, `marker ${startMarker} not found`); const bodyStart = source.indexOf("{", start); let depth = 0; for (let i = bodyStart; i < source.length; i += 1) { if (source[i] === "{") depth += 1; else if (source[i] === "}") { depth -= 1; if (depth === 0) return i + 1; } } assert.fail(`unbalanced braces after marker ${startMarker}`); } test("one shared strength-check helper exists — no per-secret parallel copies", () => { const helperMarker = "function requireStrongSecretOverride(name)"; const first = indexSource.indexOf(helperMarker); assert.notStrictEqual(first, -1, "the shared helper must exist"); assert.strictEqual( indexSource.indexOf(helperMarker, first + 1), -1, "the helper must be defined exactly once — never forked into a second copy" ); }); test("all override names are routed through the shared check", () => { for (const name of [ "REMEMBER_LOGIN_SECRET", "ACTION_TOKEN_SECRET", "SSH_TERM_TOKEN_SECRET", "TOTP_SEALING_KEY", "NODE_TOKEN_SEALING_KEY", "MONGO_ADMIN_SEALING_KEY", "WEBHOOK_SEALING_KEY", ]) { const call = `requireStrongSecretOverride("${name}")`; assert.ok( indexSource.includes(call), `${name} must be checked through the shared helper` ); } }); test("the override floor equals the SESSION_SECRET floor (32 chars)", () => { const helper = indexSource.slice( indexSource.indexOf("function requireStrongSecretOverride(name)"), endIndexOfFunction(indexSource, "function requireStrongSecretOverride(name)") ); const overrideMatch = helper.match(/length\s*<\s*(\d+)/); assert.ok(overrideMatch, "the helper must enforce a length floor"); const overrideFloor = Number(overrideMatch[1]); const sessionCheckAt = indexSource.indexOf("if (!SESSION_SECRET || SESSION_SECRET.length < 32)"); assert.notStrictEqual(sessionCheckAt, -1, "the SESSION_SECRET boot check must still exist"); const sessionMatch = indexSource .slice(sessionCheckAt, sessionCheckAt + 120) .match(/SESSION_SECRET\.length\s*<\s*(\d+)/); assert.ok(sessionMatch, "the SESSION_SECRET check must enforce a length floor"); const sessionFloor = Number(sessionMatch[1]); assert.strictEqual( overrideFloor, sessionFloor, "the overrides must not be held to a weaker floor than SESSION_SECRET" ); assert.strictEqual(overrideFloor, 32, "the shared floor is 32 chars"); }); test("violation fails fast: loud error naming the env var, then exit(1)", () => { const helper = indexSource.slice( indexSource.indexOf("function requireStrongSecretOverride(name)"), endIndexOfFunction(indexSource, "function requireStrongSecretOverride(name)") ); assert.ok(helper.includes("console.error("), "the violation must log loudly"); assert.ok(helper.includes("${name}"), "the log must name the offending env var"); assert.ok(helper.includes("32+ chars"), "the log must state the required strength"); assert.ok(helper.includes("process.exit(1)"), "a violation must exit(1) at boot"); // Mirror discipline: the check must run BEFORE the log is skipped or the // process continues — the exit is unconditional inside the violation branch. const errorAt = helper.indexOf("console.error("); const exitAt = helper.indexOf("process.exit(1)"); assert.ok(errorAt > -1 && exitAt > errorAt, "the error precedes the exit"); }); test("unset or empty override stays legal — fallback behavior unchanged", () => { const helper = indexSource.slice( indexSource.indexOf("function requireStrongSecretOverride(name)"), endIndexOfFunction(indexSource, "function requireStrongSecretOverride(name)") ); // An empty-string env var is falsy in the `||`-fallback at the consumption // sites, so it must be treated exactly like unset — never exited on. assert.ok( helper.includes("override !== undefined && override !== \"\""), "the helper must only reject a SET, non-empty, too-short override" ); // The `||`-fallback derivations at the three consumption sites must remain: // this fix adds a boot check, it does not touch any default derivation. assert.ok( indexSource.includes("process.env.REMEMBER_LOGIN_SECRET ||"), "REMEMBER_LOGIN_SECRET keeps its derived fallback" ); assert.ok( indexSource.includes("process.env.ACTION_TOKEN_SECRET ||"), "ACTION_TOKEN_SECRET keeps its derived fallback" ); assert.ok( indexSource.includes("process.env.SSH_TERM_TOKEN_SECRET ||"), "SSH_TERM_TOKEN_SECRET keeps its derived fallback" ); // ...and the four sealing-key overrides keep their KDF-input ||-fallbacks // (TOTP's lives in utils/totp-secret-crypto.js, the node-token one in // utils/node-token-crypto.js; both are pinned in their own test files). assert.ok( indexSource.includes("process.env.MONGO_ADMIN_SEALING_KEY ||"), "MONGO_ADMIN_SEALING_KEY keeps its derived fallback at the wiring site" ); assert.ok( indexSource.includes("process.env.WEBHOOK_SEALING_KEY ||"), "WEBHOOK_SEALING_KEY keeps its derived fallback at the derivation site" ); // ...and each fallback is still the SESSION_SECRET-derived HMAC, not a // hardcoded constant. assert.ok( indexSource.includes('crypto.createHmac("sha256", process.env.SESSION_SECRET).update("adpanel-action-token-key-v1")'), "ACTION_TOKEN_SECRET fallback stays SESSION_SECRET-derived" ); assert.ok( indexSource.includes('crypto.createHmac("sha256", process.env.SESSION_SECRET).update("adpanel-ssh-term-token-key-v1")'), "SSH_TERM_TOKEN_SECRET fallback stays SESSION_SECRET-derived" ); assert.ok( indexSource.includes('crypto.createHmac("sha256", SESSION_SECRET).update("adpanel-remember-login-key-v1")'), "REMEMBER_LOGIN_SECRET fallback stays SESSION_SECRET-derived" ); }); test("the checks run in the boot-validation region, before listen() and before any use", () => { // index.js executes top-to-bottom: anything at module top level before the // listen() calls runs before the first request can be served. The checks // sit adjacent to the SESSION_SECRET check; the consuming sign*/derived // consts are only used at request time inside function bodies, so // before-listen placement is before every use. const sessionCheckAt = indexSource.indexOf("const SESSION_SECRET = process.env.SESSION_SECRET;"); const checksAt = indexSource.indexOf('requireStrongSecretOverride("REMEMBER_LOGIN_SECRET")'); const listenAt = indexSource.indexOf("httpServer.listen(LISTEN_HTTP_PORT, LISTEN_HOST"); assert.ok(sessionCheckAt > -1, "SESSION_SECRET boot check present"); assert.ok(checksAt > sessionCheckAt, "the override checks sit with the SESSION_SECRET boot check"); assert.ok(listenAt > -1, "the listen() call was found"); assert.ok(checksAt < listenAt, "the override checks run before listen()"); // The three names must not be captured by consts before the checks run // (i.e. no boot-time capture that the check could not influence): the // consumption sites are the `||` fallbacks plus request-time function // bodies — assert the checks are not placed after a listen call. const httpsListenAt = indexSource.indexOf("httpsServer.listen(HTTPS_PORT, HOST"); assert.ok(httpsListenAt > checksAt, "checks precede the HTTPS listener too"); }); function runHelperInSandbox(env, consoleStub) { const helper = indexSource.slice( indexSource.indexOf("function requireStrongSecretOverride(name)"), endIndexOfFunction(indexSource, "function requireStrongSecretOverride(name)") ); const context = vm.createContext({ process: { env, exit: (code) => { throw new Error(`__exit__:${code}`); } }, console: consoleStub, }); // Run the REAL helper body from index.js — no reimplementation in the test. return vm.runInContext(`${helper}\nrequireStrongSecretOverride`, context); } test("behavior: 32-char override passes, 31-char override exits(1) — for each of the seven", () => { const consoleStub = { error: () => {} }; for (const name of [ "REMEMBER_LOGIN_SECRET", "ACTION_TOKEN_SECRET", "SSH_TERM_TOKEN_SECRET", "TOTP_SEALING_KEY", "NODE_TOKEN_SEALING_KEY", "MONGO_ADMIN_SEALING_KEY", "WEBHOOK_SEALING_KEY", ]) { const ok = runHelperInSandbox({ [name]: "a".repeat(32) }, consoleStub); assert.doesNotThrow(() => ok(name), `32 chars must be accepted for ${name}`); const bad = runHelperInSandbox({ [name]: "a".repeat(31) }, consoleStub); assert.throws( () => bad(name), (err) => err.message === "__exit__:1", `31 chars must exit(1) for ${name}` ); // Unset and empty both keep the derived fallback — no exit. const unset = runHelperInSandbox({}, consoleStub); assert.doesNotThrow(() => unset(name), `unset must stay legal for ${name}`); const empty = runHelperInSandbox({ [name]: "" }, consoleStub); assert.doesNotThrow(() => empty(name), `empty override must stay legal for ${name}`); } }); test("behavior: the violation error names the env var and the 32+ requirement", () => { const logged = []; const consoleStub = { error: (...args) => logged.push(args.join(" ")) }; const bad = runHelperInSandbox({ ACTION_TOKEN_SECRET: "short" }, consoleStub); assert.throws(() => bad("ACTION_TOKEN_SECRET"), (err) => err.message === "__exit__:1"); assert.strictEqual(logged.length, 1, "exactly one loud error"); assert.ok(logged[0].includes("ACTION_TOKEN_SECRET"), "the log names the env var"); assert.ok(logged[0].includes("32+ chars"), "the log states the requirement"); assert.ok(logged[0].includes("leave it unset"), "the log offers the derived-fallback alternative"); }); test("the totp_last_counter ALTER failure is console.warn, matching the sibling column checks", () => { assert.ok( indexSource.includes("console.warn('[db] totp_last_counter column check:'"), "the TOTP ALTER failure must be console.warn" ); assert.strictEqual( indexSource.indexOf("console.debug('[db] totp_last_counter column check:'"), -1, "no console.debug may remain at the totp_last_counter site" ); // The message content is unchanged — only the channel moved. assert.ok( indexSource.includes("console.warn('[db] totp_last_counter column check:', err.message)"), "the warn keeps the exact prior message content" ); });