Files
Kelx/tests/mongo-admin-auth-hardening.test.js
2026-11-30 16:32:37 +00:00

423 lines
25 KiB
JavaScript

"use strict";
// Tests for audit finding H2: MongoDB user-management endpoints disabled
// authentication on the LIVE server during every operation — they stripped
// `authorization: enabled` from /etc/mongod.conf, restarted mongod, ran
// unauthenticated mongosh, then restored (restore living only in catch/then
// paths, so a panel crash mid-operation left mongod wide open forever).
//
// The remediation under test:
// - utils/mongo-admin-credentials.js — pure AES-256-GCM seal/open for the
// install-time admin credential (envelope enc:v1:iv:tag:ct, scrypt key
// from a mongo-admin-dedicated salt, fail-closed on any failure).
// - index.js get/setMongoAdminCredentials — sealed adminAuth in
// mongodb-config.json; plaintext never at rest, never in logs.
// - index.js runAuthenticatedMongosh — admin credential + connectionStatus
// gate prepended INSIDE the same 0600-staged script file (never argv);
// ADP_MONGO_AUTH_FAILED distinguishes stale-credential failures from
// operation failures.
// - index.js ensureMongoAdminAuth — one-time bootstrap for legacy installs;
// restoration of /etc/mongod.conf lives in a FINALLY path, not catch-only.
// - the three /api/settings/database/mongodb/users endpoints no longer
// rewrite mongod.conf or restart mongod at all.
// - startup self-heal re-enables authorization for legacy victims.
const test = require("node:test");
const assert = require("node:assert");
const fs = require("node:fs");
const os = require("node:os");
const path = require("node:path");
const crypto = require("node:crypto");
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 indexSource = fs.readFileSync(INDEX_JS, "utf8");
const cred = require(CRED_MODULE);
const {
MONGO_ADMIN_ENC_PREFIX,
MONGO_ADMIN_KDF_SALT,
deriveMongoAdminCipherKey,
isMongoSecretEnvelope,
sealMongoSecret,
openMongoSecret,
} = cred;
// ---------------------------------------------------------------------------
// Pure module: seal/open
// ---------------------------------------------------------------------------
const KEY_MATERIAL = "h2-test-session-secret";
test("H2: seal/open roundtrip restores the exact plaintext", () => {
for (const plaintext of ["simple", JSON.stringify({ user: "siteadmin", password: "p@ss w0rd/\\\"'" }), "x".repeat(4096)]) {
const envelope = sealMongoSecret(plaintext, KEY_MATERIAL);
assert.ok(typeof envelope === "string" && envelope.startsWith(MONGO_ADMIN_ENC_PREFIX), "seal must produce an envelope");
assert.equal(openMongoSecret(envelope, KEY_MATERIAL), plaintext);
}
});
test("H2: seal/open roundtrip works with a pre-derived key Buffer", () => {
const key = deriveMongoAdminCipherKey(KEY_MATERIAL);
assert.ok(Buffer.isBuffer(key) && key.length === 32, "derived key must be a 32-byte Buffer");
const envelope = sealMongoSecret("roundtrip-buffer", key);
assert.equal(openMongoSecret(envelope, key), "roundtrip-buffer");
// Same secret via string and via Buffer must yield the SAME key (salt is applied inside the module).
assert.deepEqual(deriveMongoAdminCipherKey(KEY_MATERIAL), key);
});
test("H2: tampered envelope fails closed to null", () => {
const envelope = sealMongoSecret("tamper-target", KEY_MATERIAL);
// Flip a character deep inside the ciphertext section.
const parts = envelope.slice(MONGO_ADMIN_ENC_PREFIX.length).split(":");
const ct = Buffer.from(parts[2], "base64").toString("hex");
const flipped = (parseInt(ct[0], 16) ^ 0x1).toString(16) + ct.slice(1);
const tampered = `${MONGO_ADMIN_ENC_PREFIX}${parts[0]}:${parts[1]}:${Buffer.from(flipped, "hex").toString("base64")}`;
assert.equal(openMongoSecret(tampered, KEY_MATERIAL), null);
// Truncated and swapped-tag variants too.
assert.equal(openMongoSecret(envelope.slice(0, envelope.length - 8), KEY_MATERIAL), null);
assert.equal(openMongoSecret(`${MONGO_ADMIN_ENC_PREFIX}${parts[1]}:${parts[0]}:${parts[2]}`, KEY_MATERIAL), null);
});
test("H2: wrong key material fails closed to null", () => {
const envelope = sealMongoSecret("wrong-key-target", KEY_MATERIAL);
assert.equal(openMongoSecret(envelope, "a-different-session-secret"), null);
assert.equal(openMongoSecret(envelope, deriveMongoAdminCipherKey("another-secret")), null);
assert.equal(openMongoSecret(envelope, null), null);
assert.equal(openMongoSecret(envelope, ""), null);
});
test("H2: envelope contains no plaintext in raw or base64 form", () => {
const secret = "SUPER-secret-plaintext-value-9f3a";
const envelope = sealMongoSecret(secret, KEY_MATERIAL);
assert.ok(!envelope.includes(secret), "raw plaintext must not appear in the envelope");
assert.ok(!envelope.includes(Buffer.from(secret).toString("base64")), "base64 plaintext must not appear in the envelope");
assert.ok(!envelope.includes(Buffer.from(secret).toString("base64url")), "base64url plaintext must not appear in the envelope");
});
test("H2: envelope format check accepts valid envelopes only", () => {
const envelope = sealMongoSecret("format-check", KEY_MATERIAL);
assert.equal(isMongoSecretEnvelope(envelope), true);
assert.equal(isMongoSecretEnvelope("enc:v1:"), false);
assert.equal(isMongoSecretEnvelope("garbage"), false);
assert.equal(isMongoSecretEnvelope("enc:v1:onlytwo:parts"), false);
assert.equal(isMongoSecretEnvelope("enc:v1::::"), false);
assert.equal(isMongoSecretEnvelope("enc:v1:a:b:c"), false, "invalid base64 segments must be rejected");
assert.equal(isMongoSecretEnvelope(null), false);
assert.equal(isMongoSecretEnvelope(undefined), false);
assert.equal(isMongoSecretEnvelope(42), false);
});
test("H2: seal/open fail closed on unusable inputs", () => {
assert.equal(sealMongoSecret("", KEY_MATERIAL), null, "empty plaintext must not seal");
assert.equal(sealMongoSecret("x", ""), null, "empty key material must not seal");
assert.equal(sealMongoSecret("x", null), null);
assert.equal(sealMongoSecret("x", Buffer.alloc(8).fill(1)), null, "short key Buffer must not seal");
assert.equal(openMongoSecret("", KEY_MATERIAL), null);
assert.equal(openMongoSecret("not-an-envelope", KEY_MATERIAL), null);
assert.equal(openMongoSecret(undefined, KEY_MATERIAL), null);
});
test("H2: dedicated salt — domain separation from webhook/node-token crypto", () => {
assert.notEqual(MONGO_ADMIN_KDF_SALT, "adpanel-webhook-secret-v1");
assert.notEqual(MONGO_ADMIN_KDF_SALT, "adpanel-node-token-v1");
// Same master secret must NOT yield the same AES key for another subsystem's salt.
const mongoKey = deriveMongoAdminCipherKey(KEY_MATERIAL);
const webhookKey = crypto.scryptSync(KEY_MATERIAL, "adpanel-webhook-secret-v1", 32);
assert.ok(!mongoKey.equals(webhookKey), "mongo-admin key must differ from webhook key for the same secret");
});
test("H2: mongo-admin-credentials module is pure (no I/O, no env access)", () => {
const src = fs.readFileSync(CRED_MODULE, "utf8");
const requires = src.match(/require\([^)]*\)/g) || [];
assert.equal(requires.length, 1, "only crypto may be required");
assert.ok(requires[0].includes("crypto"));
assert.ok(!src.includes("process.env"), "module must not read the environment");
assert.ok(!/\bfs\./.test(src), "module must not touch the filesystem");
assert.ok(!src.includes("child_process"), "module must not spawn processes");
assert.ok(!src.includes("console."), "module must not log (plaintext safety)");
});
// ---------------------------------------------------------------------------
// index.js source assertions
// ---------------------------------------------------------------------------
function endpointSlice() {
const start = indexSource.indexOf('app.post("/api/settings/database/mongodb/users", async');
const end = indexSource.indexOf('app.get("/api/settings/database/mongodb/users", async');
assert.ok(start !== -1 && end !== -1 && start < end, "mongodb user endpoints not found in index.js");
return indexSource.slice(start, end);
}
function bootstrapSlice(stripComments = false) {
const start = indexSource.indexOf("async function ensureMongoAdminAuth");
const end = indexSource.indexOf('app.post("/api/settings/database/mongodb/users", async');
assert.ok(start !== -1 && end !== -1 && start < end, "ensureMongoAdminAuth not found in index.js");
const slice = indexSource.slice(start, end);
return stripComments ? stripJsComments(slice) : slice;
}
// Removes JS comments so prose (e.g. "instead of --eval") cannot satisfy or
// violate code assertions.
function stripJsComments(src) {
return src.replace(/\/\*[\s\S]*?\*\//g, "").replace(/^\s*\/\/.*$/gm, "");
}
test("H2: the three mongodb user endpoints no longer touch mongod.conf or restart mongod", () => {
const slice = endpointSlice();
// The strip/restore machinery is gone: none of these may appear anywhere in
// the three endpoints (comments included), while it MUST remain in the
// one-time bootstrap only.
assert.ok(!/authorization/.test(slice), "endpoints must not reference authorization config at all");
assert.ok(!/bindIp/.test(slice), "endpoints must not rewrite bindIp");
assert.ok(!/runSystemctl/.test(slice), "endpoints must not manage the mongod service");
assert.ok(!/\/etc\/mongod\.conf/.test(slice), "endpoints must not read or write mongod.conf");
assert.ok(!/mongoConfPath/.test(slice), "endpoints must not keep mongod.conf paths");
assert.ok(!/\.replace\(/.test(slice), "endpoints must not rewrite config file content");
assert.ok(!/writeSystemFileWithPrivilegeFallback/.test(slice), "endpoints must not write system files");
assert.ok(!/requireActionTokenOr403[\s\S]*authorization:\s*enabled/.test(slice), "sanity");
});
test("H2: the three endpoints authenticate via ensureMongoAdminAuth + runAuthenticatedMongosh", () => {
const slice = endpointSlice();
assert.equal((slice.match(/ensureMongoAdminAuth\(config\)/g) || []).length, 3, "all three endpoints must bootstrap/resolve admin auth");
assert.equal((slice.match(/runAuthenticatedMongosh\(/g) || []).length, 3, "all three endpoints must run mongosh authenticated");
assert.equal((slice.match(/result\.authFailed/g) || []).length, 3, "all three endpoints must branch on auth failure");
assert.equal((slice.match(/stored credentials may be stale/g) || []).length, 6,
"each endpoint must answer the stale-credential 500 for both bootstrap and auth-preamble failures");
// Existing bookkeeping stays: bcrypt hashes, mutex, action tokens, response shapes.
assert.equal((slice.match(/bcrypt\.hash\(password, BCRYPT_ROUNDS\)/g) || []).length, 2, "create + password endpoints must keep hashing");
assert.ok(slice.includes("mongodbOperationMutex.tryAcquire()"), "mutex gating must stay");
assert.equal((slice.match(/db\.dropUser\(\$\{safeUsername\}\)/g) || []).length, 1, "delete endpoint keeps its staged username-only dropUser");
assert.ok(slice.includes("db.changeUserPassword(${safeUsername}, ${safePassword})"), "password endpoint keeps its eval");
assert.ok(slice.includes("buildMongoCreateUserEval(cleanUsername, password)"), "create endpoint keeps the least-privilege eval builder");
});
test("H2: bootstrap restoration is finally-guaranteed, not catch-only", () => {
const slice = bootstrapSlice();
const finallyIdx = slice.indexOf("} finally {");
assert.ok(finallyIdx !== -1, "ensureMongoAdminAuth must have a finally block");
// The re-enable logic (literal 'authorization: enabled' append, the restore
// write, and the restart) must live inside/after the finally, never in a
// catch-only path.
const firstAuthLiteral = slice.indexOf("authorization: enabled");
assert.ok(firstAuthLiteral > finallyIdx, "auth re-enable must first appear in the finally restoration path");
const restoreWrite = slice.indexOf("writeSystemFileWithPrivilegeFallback", finallyIdx);
assert.ok(restoreWrite !== -1, "finally must rewrite mongod.conf");
const restart = slice.indexOf("runSystemctl('restart')", finallyIdx);
assert.ok(restart > finallyIdx, "finally must restart mongod");
assert.ok(!slice.includes("Failed to restore config:"), "the old catch-only restore pattern must be gone");
assert.ok(slice.includes("bootstrapError"), "bootstrap failures must be tracked and surfaced");
assert.ok(slice.includes("return { ok: false"), "bootstrap must return structured errors");
});
test("H2: bootstrap is one-time, staged, and skips the server when credentials exist", () => {
const slice = bootstrapSlice();
const credIdx = slice.indexOf("getMongoAdminCredentials(config)");
const confReadIdx = slice.indexOf("fs.readFileSync");
assert.ok(credIdx !== -1 && confReadIdx !== -1 && credIdx < confReadIdx,
"existing sealed credentials must short-circuit before any server or conf access");
assert.ok(slice.includes("crypto.randomBytes(32).toString('base64url')"), "bootstrap must generate a fresh random admin password");
assert.ok(slice.includes("_mongoshRunScriptFile(\"mongosh\""), "bootstrap upsert must run through the 0600-staged script file");
assert.ok(!/--eval/.test(bootstrapSlice(true)), "bootstrap must never pass scripts via --eval");
assert.ok(slice.includes("setMongoAdminCredentials(config, adminUsername, adminPassword)"), "bootstrap must seal the new credential");
assert.ok(slice.includes("saveMongoDBConfig(config)"), "bootstrap must persist the sealed credential");
assert.ok(slice.includes("runAuthenticatedMongosh"), "bootstrap must verify the credential with an authenticated run");
assert.ok(slice.includes("connectionStatus"), "verification must rely on the connectionStatus gate");
});
test("H2: index.js wires the sealed credential helpers and setup-time sealing", () => {
assert.ok(indexSource.includes('require("./utils/mongo-admin-credentials")'), "credential module must be required");
assert.ok(indexSource.includes("let _mongoAdminCredKeyCache = null;"), "key cache variable must exist (mirrors webhook pattern)");
assert.ok(indexSource.includes("function getMongoAdminCredCipherKey()"), "dedicated key function must exist");
assert.ok(indexSource.includes("function getMongoAdminCredentials(config)"));
assert.ok(indexSource.includes("function setMongoAdminCredentials(config, user, password)"));
// Seal at setup success AND on admin password rotation (users[0]).
assert.equal((indexSource.match(/setMongoAdminCredentials\(config, cleanUsername, password\)/g) || []).length, 2,
"setup endpoint and admin-password rotation must both seal the credential");
});
test("H2: runAuthenticatedMongosh gates on connectionStatus and stages off-argv", () => {
const start = indexSource.indexOf("const MONGO_AUTH_FAILED_MARKER");
const end = indexSource.indexOf("// --- dedicated MySQL admin channel");
assert.ok(start !== -1 && end !== -1 && start < end, "runAuthenticatedMongosh block not found");
const slice = indexSource.slice(start, end);
assert.ok(slice.includes('"ADP_MONGO_AUTH_FAILED"'), "unique auth-failure marker must exist");
assert.ok(slice.includes("db.getSiblingDB('admin')"), "auth preamble must target the admin db");
assert.ok(slice.includes("db.auth("), "auth preamble must authenticate");
assert.ok(slice.includes("connectionStatus: 1"), "preamble must fail closed on connectionStatus");
assert.ok(slice.includes("authenticatedUsers"), "preamble must assert an authenticated session");
assert.ok(slice.includes("_mongoshRunScriptFile"), "staging must reuse the 0600 temp-file helper");
assert.ok(!/['"]-p['"]/.test(slice) && !/['"]-u['"]/.test(slice), "credentials must never travel as mongosh flags");
assert.ok(!/--eval/.test(slice), "credentials must never travel via --eval");
});
test("H2: startup self-heal repairs legacy auth-less mongod.conf, best-effort", () => {
const idx = indexSource.indexOf("// Self-heal legacy victims");
assert.ok(idx !== -1, "startup self-heal block must exist");
const slice = indexSource.slice(idx, idx + 4500);
assert.ok(slice.includes("loadMongoDBConfig()"), "self-heal must be gated on MongoDB being enabled");
assert.ok(slice.includes('which mongod'), "self-heal must be gated on mongod being installed");
assert.ok(slice.includes("'authorization: enabled'"), "self-heal must detect the missing security block");
assert.ok(slice.includes('["svc", "restart", "mongod"]'), "self-heal must restart via the privileged runner");
assert.ok(slice.includes("catch (healErr)"), "self-heal must be wrapped in its own try/catch");
});
// ---------------------------------------------------------------------------
// Functional: index.js credential helpers extracted into a scratch module
// (index.js boots servers on require, so slices are evaluated in isolation —
// same technique as tests/argv-secret-exposure.test.js).
// ---------------------------------------------------------------------------
process.env.SESSION_SECRET = process.env.SESSION_SECRET || "adpanel-h2-test-session-secret";
function loadCredentialHelpers() {
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-h2-cred-${process.pid}-${Date.now()}.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 });
}
}
test("H2: index.js credential helpers seal on set and open on get; failure reads as null", () => {
const helpers = loadCredentialHelpers();
const config = { enabled: true, users: [{ username: "siteadmin" }] };
assert.equal(helpers.getMongoAdminCredentials(config), null, "no adminAuth yet");
assert.equal(helpers.setMongoAdminCredentials(config, "siteadmin", "admin-pass-123"), true, "sealing must succeed");
assert.ok(isMongoSecretEnvelope(config.adminAuth), "stored value must be an envelope");
assert.ok(!config.adminAuth.includes("admin-pass-123"), "plaintext must never reach the config");
assert.deepEqual(helpers.getMongoAdminCredentials(config), { user: "siteadmin", password: "admin-pass-123" });
// Tampered / foreign envelopes fail closed.
const tampered = config.adminAuth.slice(0, -4) + "AAAA";
assert.equal(helpers.getMongoAdminCredentials({ adminAuth: tampered }), null);
assert.equal(helpers.getMongoAdminCredentials({ adminAuth: "garbage" }), null);
assert.equal(helpers.getMongoAdminCredentials({}), null);
assert.equal(helpers.getMongoAdminCredentials(null), null);
// Unusable payload shapes fail closed even when GCM opens.
const seal = (obj) => sealMongoSecret(JSON.stringify(obj), KEY_MATERIAL);
assert.equal(helpers.getMongoAdminCredentials({ adminAuth: seal({ password: "no-user" }) }), null);
assert.equal(helpers.getMongoAdminCredentials({ adminAuth: seal({ user: "" , password: "x" }) }), null);
});
// ---------------------------------------------------------------------------
// Functional: runAuthenticatedMongosh driven against a fake shell that
// records argv and the staged script, and only succeeds when the staged
// preamble carries the expected credential.
// ---------------------------------------------------------------------------
function loadMongoshHelpers() {
const start = indexSource.indexOf("function _mongoshRunScriptFile");
const end = indexSource.indexOf("// --- dedicated MySQL admin channel");
assert.ok(start !== -1 && end !== -1 && start < end, "mongosh helper block not found in index.js");
const helperSrc = indexSource.slice(start, end);
const modPath = path.join(os.tmpdir(), `adpanel-h2-mongosh-${process.pid}-${Date.now()}.js`);
fs.writeFileSync(modPath, [
"const fs = require('node:fs');",
"const os = require('node:os');",
"const path = require('node:path');",
"const { spawn } = require('node:child_process');",
helperSrc,
"module.exports = { _mongoshRunScriptFile, runAuthenticatedMongosh, MONGO_AUTH_FAILED_MARKER };",
].join("\n"), { mode: 0o600 });
try {
return require(modPath);
} finally {
fs.rmSync(modPath, { force: true });
}
}
test("H2: runAuthenticatedMongosh stages credentials in the 0600 script, never argv", async () => {
const { runAuthenticatedMongosh } = loadMongoshHelpers();
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "adpanel-h2-shell-"));
try {
const log = path.join(tmp, "mongosh-calls.jsonl");
const SECRET = "H2-admin-password-OFF-ARGV";
fs.writeFileSync(path.join(tmp, "fakeshell.js"), [
"#!/usr/bin/env node",
"const fs = require('node:fs');",
"const scriptPath = process.argv[process.argv.length - 1];",
"const script = fs.readFileSync(scriptPath, 'utf8');",
"fs.appendFileSync(process.env.ADP_H2_LOG, JSON.stringify({",
" argv: process.argv.slice(1),",
" script,",
" mode: fs.statSync(scriptPath).mode & 0o777,",
"}) + '\\n');",
"if (script.includes(JSON.stringify(process.env.ADP_H2_SECRET))) { console.log('AUTH_OK'); process.exit(0); }",
"console.log('ADP_MONGO_AUTH_FAILED'); process.exit(1);",
].join("\n"), { mode: 0o755 });
const opts = {
shellBin: path.join(tmp, "fakeshell.js"),
args: ["--port", "27017", "admin", "--quiet"],
timeoutMs: 5000,
};
const env = { ...process.env, ADP_H2_LOG: log, ADP_H2_SECRET: SECRET };
const savedEnv = { ADP_H2_LOG: process.env.ADP_H2_LOG, ADP_H2_SECRET: process.env.ADP_H2_SECRET };
process.env.ADP_H2_LOG = log;
process.env.ADP_H2_SECRET = SECRET;
try {
// Success: the staged preamble carries the expected credential.
const ok = await runAuthenticatedMongosh({ user: "siteadmin", password: SECRET }, "db.runCommand({ ping: 1 });", { ...opts, env });
assert.equal(ok.code, 0);
assert.equal(ok.authFailed, false);
// Auth failure: wrong credential resolves authFailed=true, distinct from op failure.
const bad = await runAuthenticatedMongosh({ user: "siteadmin", password: "wrong-password" }, "db.runCommand({ ping: 1 });", { ...opts, env });
assert.equal(bad.authFailed, true);
assert.equal(bad.code, 1);
// No credential: fails closed without spawning anything.
const none = await runAuthenticatedMongosh(undefined, "db.runCommand({ ping: 1 });", { ...opts, env });
assert.equal(none.authFailed, true);
assert.equal(none.code, 1);
} finally {
if (savedEnv.ADP_H2_LOG === undefined) delete process.env.ADP_H2_LOG; else process.env.ADP_H2_LOG = savedEnv.ADP_H2_LOG;
if (savedEnv.ADP_H2_SECRET === undefined) delete process.env.ADP_H2_SECRET; else process.env.ADP_H2_SECRET = savedEnv.ADP_H2_SECRET;
}
const calls = fs.readFileSync(log, "utf8").trim().split("\n").map((l) => JSON.parse(l));
assert.equal(calls.length, 2, "exactly two spawns: valid + invalid credential (missing credential must not spawn)");
const success = calls[0];
assert.ok(!success.argv.some((a) => a.includes(SECRET)), "admin password must never appear in argv");
assert.ok(!success.argv.includes("-u") && !success.argv.includes("-p"), "no credential flags on argv");
assert.ok(!success.argv.includes("--eval"), "staged file must replace --eval");
// The fake shell logs process.argv.slice(1): [scriptPath, ...callerArgs..., stagedPath].
assert.deepEqual(success.argv.slice(1, 5), ["--port", "27017", "admin", "--quiet"], "caller args preserved");
assert.equal(success.mode, 0o600, "staged script must be 0600");
assert.ok(success.script.includes("db.getSiblingDB('admin')"), "preamble authenticates on the admin db");
assert.ok(success.script.includes("db.auth("), "preamble carries db.auth");
assert.ok(success.script.includes("connectionStatus: 1"), "preamble fails closed on connectionStatus");
assert.ok(success.script.includes("ADP_MONGO_AUTH_FAILED"), "preamble prints the auth-failure marker");
assert.ok(success.script.includes(JSON.stringify(SECRET)), "password travels inside the 0600 file");
assert.ok(success.script.includes("db.runCommand({ ping: 1 });"), "caller script runs after the preamble");
const failure = calls[1];
assert.ok(!failure.script.includes(JSON.stringify(SECRET)), "the wrong password is staged instead");
assert.ok(failure.script.includes(JSON.stringify("wrong-password")));
// The staging directory is removed once the child exits.
const leftovers = fs.readdirSync(os.tmpdir()).filter((d) => d.startsWith("adpanel-mongosh-"));
assert.deepEqual(leftovers, [], "no staging directories may survive the run");
} finally {
fs.rmSync(tmp, { recursive: true, force: true });
}
});