"use strict"; // adpanel:mongo-admin-sealing-key-override — pins for the MongoDB admin // credential seal's key-input override. The finding: the AES-256-GCM key that // seals config.adminAuth ({user, password}) was scrypt(SESSION_SECRET, // fixed-salt) via index.js getMongoAdminCredCipherKey with no independent key // env and no re-seal path, so rotating SESSION_SECRET made the sealed // credential undecryptable — it reads as "no credentials" and // ensureMongoAdminAuth re-bootstraps once, re-opening the risky legacy // unauthenticated-bootstrap window and losing the old credential. The fix // adds MONGO_ADMIN_SEALING_KEY, mirroring the TOTP_SEALING_KEY mechanics // (env override || derived fallback), with ONE hard invariant the pins below // lock: // // - Unset/empty override → the KDF input is process.env.SESSION_SECRET, // BYTE-IDENTICAL to the pre-override algorithm (same scryptSync through // deriveMongoAdminCipherKey, same MONGO_ADMIN_KDF_SALT, same 32-byte // length, same default params): every existing seal stays decryptable. // Proven by cross-decryption against an INDEPENDENTLY computed scrypt // key — GCM tag verification only succeeds under the exact key bytes, so // a successful authenticated open in BOTH directions is a key-equality // proof, not a circumstantial one (a param drift — cost, salt, length — // breaks the cross-open). // - Set override → different key material; seal/open roundtrips succeed // only under the same override. // - NO fallback: a seal minted under one input can never be opened under // the other (getMongoAdminCredentials returns null — reads as "bootstrap // needed"; the ledger-pinned fail-closed posture, untouched by this // change). A wrong/rotated key must never fall back to any other // derivation; a silent fallback would convert key rotation/tampering // into a MongoDB-admin impersonation primitive. // - Source pins: the boot check routes MONGO_ADMIN_SEALING_KEY through the // ONE shared requireStrongSecretOverride helper beside its siblings (same // 32-char floor, real helper body driven in a sandbox); the constraint // comment exists at BOTH the boot-check call and the wiring site; and the // pure module (utils/mongo-admin-credentials.js) keeps its stated // "no environment access" contract — the input is selected at exactly one // place, the index.js wiring site. // // Harness: index.js boots servers on require, so the credential helpers are // sliced out and evaluated in a scratch module — the same technique as // tests/mongo-admin-auth-hardening.test.js (loadCredentialHelpers). Each // derivation scenario writes a FRESH scratch module, which also gives a fresh // _mongoAdminCredKeyCache per scenario (the cache is module-scoped). const test = require("node:test"); const assert = require("node:assert"); const crypto = require("node:crypto"); const fs = require("node:fs"); const os = require("node:os"); const path = require("node:path"); const vm = require("node:vm"); const ROOT = path.join(__dirname, ".."); const INDEX_JS = path.join(ROOT, "index.js"); const CRED_MODULE = path.join(ROOT, "utils", "mongo-admin-credentials.js"); const ENC_PREFIX = "enc:v1:"; const SALT = "adpanel-mongo-admin-cred-v1"; const SESSION_SECRET = "adpanel-mongo-sealing-test-session-secret-0123456789abcdef"; const OVERRIDE = "mongo-admin-sealing-override-key-0123456789abcdef-zyxwvu"; const CRED = { user: "siteadmin", password: "admin-pass-0123456789" }; const indexSource = fs.readFileSync(INDEX_JS, "utf8"); if (!process.env.SESSION_SECRET || process.env.SESSION_SECRET.length < 32) { process.env.SESSION_SECRET = SESSION_SECRET; } 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}`); } let scratchCounter = 0; // Loads the REAL index.js credential helpers under the given env, as a fresh // scratch module (fresh key cache) each call. function freshHelpers(env) { delete process.env.SESSION_SECRET; delete process.env.MONGO_ADMIN_SEALING_KEY; for (const [name, value] of Object.entries(env || {})) { if (value !== undefined) process.env[name] = value; } const start = indexSource.indexOf("let _mongoAdminCredKeyCache = null;"); const end = indexSource.indexOf("async function installMongoDB("); assert.ok(start !== -1 && end !== -1 && start < end, "credential helper block not found in index.js"); const helperSrc = indexSource.slice(start, end); const modPath = path.join( os.tmpdir(), `adpanel-mongo-sealing-key-${process.pid}-${Date.now()}-${scratchCounter += 1}.js` ); fs.writeFileSync(modPath, [ "const crypto = require('node:crypto');", `const { deriveMongoAdminCipherKey, sealMongoSecret, openMongoSecret, isMongoSecretEnvelope } = require(${JSON.stringify(CRED_MODULE)});`, helperSrc, "module.exports = { getMongoAdminCredCipherKey, getMongoAdminCredentials, setMongoAdminCredentials };", ].join("\n"), { mode: 0o600 }); try { return require(modPath); } finally { fs.rmSync(modPath, { force: true }); } } // Independent envelope machinery — deliberately NOT the module under test, so // the cross-decryption pins below compare against a from-scratch AES-256-GCM // implementation of the documented envelope format. function sealWithKey(key, plaintext) { const iv = crypto.randomBytes(12); const cipher = crypto.createCipheriv("aes-256-gcm", key, iv, { authTagLength: 16 }); const ct = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]); return `${ENC_PREFIX}${iv.toString("base64")}:${cipher.getAuthTag().toString("base64")}:${ct.toString("base64")}`; } function openWithKey(key, envelope) { const [ivB64, tagB64, ctB64] = envelope.slice(ENC_PREFIX.length).split(":"); const decipher = crypto.createDecipheriv("aes-256-gcm", key, Buffer.from(ivB64, "base64"), { authTagLength: 16 }); decipher.setAuthTag(Buffer.from(tagB64, "base64")); return Buffer.concat([decipher.update(Buffer.from(ctB64, "base64")), decipher.final()]).toString("utf8"); } function derivedSessionKey() { // The pre-override algorithm, computed independently in the test. return crypto.scryptSync(SESSION_SECRET, SALT, 32); } test("unset override: the sealing key stays byte-identical to the pre-override derivation — scrypt(SESSION_SECRET, salt, 32)", () => { const helpers = freshHelpers({ SESSION_SECRET }); const expectedKey = derivedSessionKey(); // Direction 1: a manual envelope under the independently computed key must // open through the panel helpers — GCM verification only passes under the // exact key bytes, so this proves the wiring derived exactly that key. assert.deepEqual( helpers.getMongoAdminCredentials({ adminAuth: sealWithKey(expectedKey, JSON.stringify(CRED)) }), CRED, "helpers open an envelope sealed with the independent pre-override key" ); // Direction 2: the helpers' own seal must open under the independently // computed key — proving no other input (and no param drift) feeds the KDF. const config = {}; assert.strictEqual(helpers.setMongoAdminCredentials(config, CRED.user, CRED.password), true); assert.ok(config.adminAuth.startsWith(ENC_PREFIX), "the seal is a v1 envelope"); assert.deepEqual( JSON.parse(openWithKey(expectedKey, config.adminAuth)), CRED, "the independent pre-override key opens the helpers' seal" ); }); test("set override: seal+open roundtrip succeeds under the same override, with key material distinct from the SESSION_SECRET derivation", () => { const helpers = freshHelpers({ SESSION_SECRET, MONGO_ADMIN_SEALING_KEY: OVERRIDE }); const config = {}; assert.strictEqual(helpers.setMongoAdminCredentials(config, CRED.user, CRED.password), true, "roundtrip under the same override"); assert.deepEqual(helpers.getMongoAdminCredentials(config), CRED); // Distinct material: the override-sealed envelope must NOT open under the // scrypt(SESSION_SECRET) key — the decipher fails authentication. assert.throws( () => openWithKey(derivedSessionKey(), config.adminAuth), "the override key material differs from the SESSION_SECRET derivation" ); // And the KDF input is the OVERRIDE, not the session secret: an // independently computed scrypt(OVERRIDE, salt, 32) key opens the seal. const overrideKey = crypto.scryptSync(OVERRIDE, SALT, 32); assert.deepEqual( helpers.getMongoAdminCredentials({ adminAuth: sealWithKey(overrideKey, JSON.stringify(CRED)) }), CRED, "the helpers derive from the override input" ); }); test("fail-closed: a seal minted under one derivation can NEVER be opened under the other (no fallback)", () => { // Sealed under the derived key (override unset)… const sealer = freshHelpers({ SESSION_SECRET }); const sealedDerived = {}; assert.strictEqual(sealer.setMongoAdminCredentials(sealedDerived, CRED.user, CRED.password), true); // …an override-keyed panel must fail CLOSED — null ("bootstrap needed"), // never the credential. const opener = freshHelpers({ SESSION_SECRET, MONGO_ADMIN_SEALING_KEY: OVERRIDE }); assert.strictEqual( opener.getMongoAdminCredentials({ adminAuth: sealedDerived.adminAuth }), null, "derived-key seal under the override reads as bootstrap-needed (fail-closed, no fallback)" ); // And the reverse direction: sealed under the override… const sealedOverride = {}; assert.strictEqual(opener.setMongoAdminCredentials(sealedOverride, CRED.user, CRED.password), true); // …a derived-key panel must also fail closed. const derivedOpener = freshHelpers({ SESSION_SECRET }); assert.strictEqual( derivedOpener.getMongoAdminCredentials({ adminAuth: sealedOverride.adminAuth }), null, "override seal under the derived key reads as bootstrap-needed (fail-closed, no fallback)" ); }); test("empty-string override is treated exactly like unset, matching the boot check's `override !== \"\"` guard", () => { const unsetHelpers = freshHelpers({ SESSION_SECRET }); const sealed = {}; assert.strictEqual(unsetHelpers.setMongoAdminCredentials(sealed, CRED.user, CRED.password), true); const emptyHelpers = freshHelpers({ SESSION_SECRET, MONGO_ADMIN_SEALING_KEY: "" }); assert.deepEqual( emptyHelpers.getMongoAdminCredentials({ adminAuth: sealed.adminAuth }), CRED, "an empty override keeps the SESSION_SECRET-derived key" ); // Same proof in the encryption direction: the empty-override helpers' seal // opens under the independently computed pre-override key. const sealedEmpty = {}; assert.strictEqual(emptyHelpers.setMongoAdminCredentials(sealedEmpty, CRED.user, CRED.password), true); assert.deepEqual(JSON.parse(openWithKey(derivedSessionKey(), sealedEmpty.adminAuth)), CRED); }); test("the fail-closed open posture is untouched: a tampered envelope opens to null under either derivation", () => { const derived = freshHelpers({ SESSION_SECRET }); const override = freshHelpers({ SESSION_SECRET, MONGO_ADMIN_SEALING_KEY: OVERRIDE }); const tamper = (envelope) => { const [ivB64, tagB64, ctB64] = envelope.slice(ENC_PREFIX.length).split(":"); const tag = Buffer.from(tagB64, "base64"); tag[0] ^= 0xff; return `${ENC_PREFIX}${ivB64}:${tag.toString("base64")}:${ctB64}`; }; const sealedDerived = {}; const sealedOverride = {}; assert.strictEqual(derived.setMongoAdminCredentials(sealedDerived, CRED.user, CRED.password), true); assert.strictEqual(override.setMongoAdminCredentials(sealedOverride, CRED.user, CRED.password), true); assert.strictEqual(derived.getMongoAdminCredentials({ adminAuth: tamper(sealedOverride.adminAuth) }), null); assert.strictEqual(override.getMongoAdminCredentials({ adminAuth: tamper(sealedDerived.adminAuth) }), null); }); // ─── Source pins: boot-check wiring, constraint comments, module purity ─── test("source-pin: MONGO_ADMIN_SEALING_KEY is checked through the shared boot-check helper beside its siblings", () => { const callAt = indexSource.indexOf('requireStrongSecretOverride("MONGO_ADMIN_SEALING_KEY")'); assert.ok(callAt > -1, "MONGO_ADMIN_SEALING_KEY must be checked through the shared helper"); const totpCallAt = indexSource.indexOf('requireStrongSecretOverride("TOTP_SEALING_KEY")'); assert.ok(callAt > totpCallAt, "MONGO_ADMIN_SEALING_KEY sits beside the sibling calls"); const helperAt = indexSource.indexOf("function requireStrongSecretOverride(name)"); assert.ok(helperAt > -1, "the shared helper exists"); assert.strictEqual( indexSource.indexOf("function requireStrongSecretOverride(name)", helperAt + 1), -1, "the helper stays defined exactly once — the new override is a call, not a copy" ); assert.ok( indexSource.includes("adpanel:mongo-admin-sealing-key-override"), "the constraint comment exists at the boot-check site" ); }); test("source-pin: the real helper body enforces the 32-char floor on MONGO_ADMIN_SEALING_KEY (short → exit(1); unset/empty → legal)", () => { const helper = indexSource.slice( indexSource.indexOf("function requireStrongSecretOverride(name)"), endIndexOfFunction(indexSource, "function requireStrongSecretOverride(name)") ); const run = (env) => { const context = vm.createContext({ process: { env, exit: (code) => { throw new Error(`__exit__:${code}`); } }, console: { error: () => {} }, }); return vm.runInContext(`${helper}\nrequireStrongSecretOverride`, context); }; assert.doesNotThrow(() => run({ MONGO_ADMIN_SEALING_KEY: "a".repeat(32) })("MONGO_ADMIN_SEALING_KEY"), "32 chars must be accepted"); assert.throws(() => run({ MONGO_ADMIN_SEALING_KEY: "a".repeat(31) })("MONGO_ADMIN_SEALING_KEY"), (err) => err.message === "__exit__:1", "31 chars must exit(1)"); assert.doesNotThrow(() => run({})("MONGO_ADMIN_SEALING_KEY"), "unset must stay legal (keeps the derived key)"); assert.doesNotThrow(() => run({ MONGO_ADMIN_SEALING_KEY: "" })("MONGO_ADMIN_SEALING_KEY"), "empty must stay legal (keeps the derived key)"); }); test("source-pin: the boot advisory fires only when the override is ACTIVE, after the boot check", () => { const advisoryAt = indexSource.indexOf("[config] MONGO_ADMIN_SEALING_KEY override active"); assert.ok(advisoryAt > -1, "the boot advisory is present"); assert.ok( indexSource.includes("can no longer be decrypted, and the panel will re-bootstrap the MongoDB admin credential once (the previous credential is unrecoverable); set the override once and keep it stable"), "the advisory names the fail-closed re-bootstrap consequence" ); const gateAt = indexSource.lastIndexOf("if (process.env.MONGO_ADMIN_SEALING_KEY)", advisoryAt); assert.ok(gateAt > -1, "the advisory is gated on the override being set"); const bootCallAt = indexSource.indexOf('requireStrongSecretOverride("MONGO_ADMIN_SEALING_KEY")'); assert.ok(gateAt > bootCallAt, "the advisory runs after the strength check (a short override exits before any advisory)"); }); test("source-pin: the wiring site changes only the KDF input, carries the constraint comment, and stays the ONE input-selection site", () => { assert.strictEqual( indexSource.split("process.env.MONGO_ADMIN_SEALING_KEY || process.env.SESSION_SECRET").length - 1, 1, "exactly ONE derivation site in index.js — the ||-fallback replaces the bare SESSION_SECRET read" ); assert.ok( indexSource.includes('process.env.MONGO_ADMIN_SEALING_KEY || process.env.SESSION_SECRET || ""'), "the override || SESSION_SECRET fallback feeds the same scrypt input" ); assert.ok( indexSource.includes("adpanel:mongo-admin-sealing-key-override"), "the constraint comment exists at the wiring site" ); assert.ok( indexSource.includes("function getMongoAdminCredCipherKey()"), "the dedicated key function stays the single wiring point" ); }); test("source-pin: utils/mongo-admin-credentials.js keeps its pure contract — no environment access anywhere", () => { const moduleSource = fs.readFileSync(CRED_MODULE, "utf8"); assert.ok( !moduleSource.includes("process.env"), "the module stays pure (no I/O, no caching, no environment access) — the override is selected at the index.js wiring site only" ); assert.ok( moduleSource.includes('const MONGO_ADMIN_KDF_SALT = "adpanel-mongo-admin-cred-v1";'), "the mongo-admin-specific salt is pinned" ); assert.ok( moduleSource.includes("crypto.scryptSync(secret, MONGO_ADMIN_KDF_SALT, 32)"), "the KDF call keeps its salt and 32-byte length" ); assert.ok( moduleSource.includes("MONGO_ADMIN_SEALING_KEY"), "the module documents the override name chosen by the wiring site" ); });