523 lines
29 KiB
JavaScript
523 lines
29 KiB
JavaScript
"use strict";
|
|
|
|
// Tests for audit finding M2: the GENERIC user-management API (the
|
|
// type-agnostic /api/settings/database/users* endpoints, reached whenever
|
|
// loadDatabaseConfig().config.type === 'mongodb', i.e. the Switch-Database
|
|
// path) was non-functional and insecure:
|
|
// - createMongoUser / createMongoUserLegacy / updateMongoUserPassword /
|
|
// updateMongoUserPasswordLegacy / deleteMongoUser spawned mongosh with NO
|
|
// credentials, so against the auth-enabled server the panel installs every
|
|
// call failed with "requires authentication";
|
|
// - deleteMongoUser passed its eval script via --eval, whose argv is
|
|
// world-readable via /proc/<pid>/cmdline (the last remaining --eval spawn);
|
|
// - checkDatabaseConnection returned true unconditionally for everything
|
|
// except mysql, so the setup/switch flows never validated mongodb or
|
|
// postgresql credentials.
|
|
//
|
|
// Remediation contract locked here:
|
|
// - every primary generic function resolves the sealed admin credential via
|
|
// ensureMongoAdminAuth and runs its (unchanged) operation script through
|
|
// runAuthenticatedMongosh — admin auth + connectionStatus gate staged in
|
|
// the SAME 0600 file, never argv; res.authFailed maps to the
|
|
// stale-credential error;
|
|
// - the ENOENT fallbacks to the legacy `mongo` shell authenticate too: the
|
|
// legacy variants reuse the same staged preamble (db.getSiblingDB('admin')
|
|
// .auth(...) + connectionStatus) via runAuthenticatedMongosh's shellBin
|
|
// override;
|
|
// - deleteMongoUser no longer spawns the shell with --eval at all;
|
|
// - ensureMongoAdminAuth guards its one-time bootstrap with a one-flight
|
|
// pending-promise latch (the generic endpoints hold only
|
|
// dbConfigOperationMutex, so two first-ever calls could otherwise
|
|
// bootstrap concurrently) and never takes the non-reentrant
|
|
// mongodbOperationMutex the dedicated endpoints already hold;
|
|
// - checkDatabaseConnection performs real checks for mongodb (staged auth
|
|
// preamble with the PROVIDED credentials) and postgresql (psql with
|
|
// PGPASSWORD in the child env, never argv), keeps the mysql logic
|
|
// unchanged, and fails closed for any other type; a missing client binary
|
|
// degrades to the previous pass-through with a warning.
|
|
//
|
|
// index.js boots servers on require, so the index-side contract is asserted
|
|
// at source level and the behavior is verified functionally by slicing the
|
|
// functions into a vm sandbox with stubbed channels (same technique as
|
|
// tests/db-mysql-scoping.test.js).
|
|
|
|
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 { EventEmitter } = require("node:events");
|
|
|
|
const ROOT = path.join(__dirname, "..");
|
|
const INDEX_JS = path.join(ROOT, "index.js");
|
|
const priv = require(path.join(ROOT, "utils", "db-user-privileges"));
|
|
|
|
const indexSource = fs.readFileSync(INDEX_JS, "utf8");
|
|
|
|
// Strip comments so prose cannot satisfy or violate code assertions (same
|
|
// approach as tests/db-mysql-scoping.test.js).
|
|
function stripComments(src) {
|
|
return src
|
|
.replace(/\/\*[\s\S]*?\*\//g, "")
|
|
.replace(/^[ \t]*\/\/.*$/gm, "");
|
|
}
|
|
|
|
function endIndexOfFunction(source, startMarker) {
|
|
const start = source.indexOf(startMarker);
|
|
assert.ok(start >= 0, `marker ${startMarker} not found`);
|
|
// The body opener is the first `{` OUTSIDE the parameter list, so a default
|
|
// parameter object literal (e.g. the `opts = {}` on checkDatabaseConnection)
|
|
// cannot be mistaken for the start of the body (same depth-counting
|
|
// technique as tests/db-switch-strict-validation.test.js).
|
|
let parenDepth = 0;
|
|
let bodyStart = -1;
|
|
for (let i = source.indexOf("(", start); i < source.length; i += 1) {
|
|
if (source[i] === "(") parenDepth += 1;
|
|
else if (source[i] === ")") parenDepth -= 1;
|
|
else if (source[i] === "{" && parenDepth === 0) { bodyStart = i; break; }
|
|
}
|
|
assert.ok(bodyStart >= 0, `no body brace after marker ${startMarker}`);
|
|
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}`);
|
|
}
|
|
|
|
function extractFunction(name, marker) {
|
|
const startMarker = marker || `async function ${name}(`;
|
|
const end = endIndexOfFunction(indexSource, startMarker);
|
|
return indexSource.slice(indexSource.indexOf(startMarker), end);
|
|
}
|
|
|
|
const STALE_ERROR =
|
|
"MongoDB admin authentication failed; stored credentials may be stale — re-run MongoDB setup.";
|
|
|
|
const PRIMARY_GENERIC = ["createMongoUser", "updateMongoUserPassword", "deleteMongoUser"];
|
|
const LEGACY_GENERIC = ["createMongoUserLegacy", "updateMongoUserPasswordLegacy", "deleteMongoUserLegacy"];
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Source assertions: the five generic functions authenticate through the H2
|
|
// infrastructure and the delete path keeps no argv leak.
|
|
// ---------------------------------------------------------------------------
|
|
|
|
test("M2: the three primary generic MongoDB functions bootstrap auth and run authenticated", () => {
|
|
for (const name of PRIMARY_GENERIC) {
|
|
const body = stripComments(extractFunction(name));
|
|
assert.ok(body.includes("loadMongoDBConfig()"), `${name} must load the MongoDB config`);
|
|
assert.ok(body.includes("await ensureMongoAdminAuth(config)"), `${name} must resolve/bootstrap the sealed admin credential`);
|
|
assert.ok(body.includes("if (!authResult.ok)"), `${name} must fail closed when the bootstrap fails`);
|
|
assert.ok(body.includes("return { ok: false, error: authResult.error };"), `${name} must surface the bootstrap error`);
|
|
assert.ok(body.includes("runAuthenticatedMongosh(authResult.auth,"), `${name} must run its script through the authenticated runner`);
|
|
assert.ok(body.includes("if (res.authFailed)"), `${name} must branch on the staged preamble's auth failure`);
|
|
assert.ok(body.includes("MONGO_GENERIC_AUTH_FAILED_ERROR"), `${name} must map auth failure to the stale-credential error`);
|
|
assert.ok(/res\.errCode === 'ENOENT'[\s\S]*?Legacy\(/.test(body), `${name} must keep its ENOENT fallback to the legacy shell`);
|
|
// The fallback inherits the resolved credential so the legacy shell
|
|
// authenticates too.
|
|
assert.ok(/Legacy\(username, password, authResult\.auth, port\);/.test(body) || /Legacy\(username, authResult\.auth, port\);/.test(body),
|
|
`${name} must hand the resolved admin credential to its legacy fallback`);
|
|
// Scripts keep their username-only / least-privilege shape: nothing may
|
|
// travel on argv.
|
|
assert.ok(!/--eval/.test(body), `${name} must not use --eval`);
|
|
assert.ok(!/['"]-p['"]/.test(body) && !/['"]-u['"]/.test(body), `${name} must not pass credential flags`);
|
|
}
|
|
});
|
|
|
|
test("M2: the legacy fallbacks authenticate with the staged preamble (legacy shell)", () => {
|
|
for (const name of LEGACY_GENERIC) {
|
|
const body = stripComments(extractFunction(name));
|
|
assert.ok(body.includes("runAuthenticatedMongosh(adminAuth,"), `${name} must run authenticated`);
|
|
assert.ok(body.includes('shellBin: "mongo"'), `${name} must target the legacy shell via the runner's shellBin override`);
|
|
assert.ok(body.includes("if (res.authFailed)"), `${name} must branch on the staged preamble's auth failure`);
|
|
assert.ok(body.includes("MONGO_GENERIC_AUTH_FAILED_ERROR"), `${name} must map auth failure to the stale-credential error`);
|
|
assert.ok(!/--eval/.test(body), `${name} must not use --eval`);
|
|
assert.ok(!/spawn\(/.test(body), `${name} must not spawn the shell directly`);
|
|
}
|
|
});
|
|
|
|
test("M2: deleteMongoUser no longer leaks its script via --eval argv", () => {
|
|
for (const name of ["deleteMongoUser", "deleteMongoUserLegacy"]) {
|
|
const body = stripComments(extractFunction(name));
|
|
assert.ok(body.includes("dropUser(${safeUsername})"), `${name} keeps its username-only dropUser script`);
|
|
assert.ok(!/--eval/.test(body), `${name} must not use --eval`);
|
|
assert.ok(!/spawn\(/.test(body), `${name} must go through the staged-script runner, not spawn`);
|
|
}
|
|
// Index-wide: the two delete-user spawns were the last shell spawns carrying
|
|
// --eval; none may remain (comments stripped so prose cannot satisfy this).
|
|
const stripped = stripComments(indexSource);
|
|
assert.equal((stripped.match(/spawn\("(?:mongosh|mongo)"/g) || []).length, 0,
|
|
"no direct mongosh/mongo spawn may remain — everything goes through the staged runner");
|
|
});
|
|
|
|
test("M2: the stale-credential message is defined once and used by all six paths", () => {
|
|
const def = indexSource.indexOf('const MONGO_GENERIC_AUTH_FAILED_ERROR = "MongoDB admin authentication failed; stored credentials may be stale — re-run MongoDB setup.";');
|
|
assert.ok(def !== -1, "the stale-credential error constant must exist verbatim");
|
|
for (const name of [...PRIMARY_GENERIC, ...LEGACY_GENERIC]) {
|
|
const body = stripComments(extractFunction(name));
|
|
assert.ok(body.includes("MONGO_GENERIC_AUTH_FAILED_ERROR"), `${name} must reuse the constant`);
|
|
}
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Source assertions: checkDatabaseConnection does real checks.
|
|
// ---------------------------------------------------------------------------
|
|
|
|
test("M2: checkDatabaseConnection validates mongodb credentials via the staged preamble", () => {
|
|
const body = stripComments(extractFunction("checkDatabaseConnection"));
|
|
assert.ok(body.includes("if (type === 'mongodb')"), "mongodb must have its own branch");
|
|
assert.ok(body.includes("runAuthenticatedMongosh("), "mongodb check must run through the authenticated runner");
|
|
assert.ok(body.includes('{ user: String(username || ""), password: String(password || "") }'),
|
|
"mongodb check must authenticate with the PROVIDED credentials");
|
|
assert.ok(body.includes('"--host", host, "--port", String(port), "--quiet"'), "mongodb check must target host/port");
|
|
assert.ok(body.includes("res.code === 0 && !res.authFailed"), "mongodb check must require success AND an authenticated session");
|
|
assert.ok(body.includes("mongosh not found"), "missing mongosh must degrade to the previous pass-through with a warning");
|
|
assert.ok(!/only mysql supported for now/.test(body), "the unconditional skip must be gone");
|
|
});
|
|
|
|
test("M2: checkDatabaseConnection validates postgresql via psql with PGPASSWORD in env", () => {
|
|
const body = stripComments(extractFunction("checkDatabaseConnection"));
|
|
assert.ok(body.includes('if (type === \'postgresql\')'), "postgresql must have its own branch");
|
|
assert.ok(body.includes('spawn("psql"'), "postgresql check must drive the psql client");
|
|
assert.ok(body.includes('"-h", host, "-p", String(port), "-U", username, "-d", "postgres", "-c", "SELECT 1"'),
|
|
"psql must be invoked with -h/-p/-U/-d/-c and no password-bearing argument");
|
|
assert.ok(body.includes("PGPASSWORD: password"), "the password must travel in PGPASSWORD (child env)");
|
|
assert.ok(body.includes("psql not found"), "missing psql must degrade to the previous pass-through with a warning");
|
|
assert.ok(!/postgresql:\/\//.test(body), "no connection-string construction (password would land on argv)");
|
|
});
|
|
|
|
test("M2: checkDatabaseConnection keeps the mysql logic and fails closed otherwise", () => {
|
|
const body = stripComments(extractFunction("checkDatabaseConnection"));
|
|
// The mysql path is preserved in full: same client call, timeout, logs and
|
|
// connection teardown.
|
|
for (const line of [
|
|
"connection = await mysql.createConnection({",
|
|
"host: host,",
|
|
"port: port,",
|
|
"user: username,",
|
|
"password: password,",
|
|
"connectTimeout: 5000",
|
|
"console.log(`[database] Connection successful!`);",
|
|
"console.error(`[database] Connection failed: ${err.message}`);",
|
|
"if (connection) await connection.end();",
|
|
]) {
|
|
assert.ok(body.includes(line), `mysql branch must keep: ${line}`);
|
|
}
|
|
assert.ok(body.includes("if (type === 'mysql')"), "mysql must keep its own branch");
|
|
// Unknown types fail closed (callers validate the type, but never wave an
|
|
// unverifiable connection through).
|
|
assert.ok(body.includes("No connection check implemented for type"), "unknown types must be logged");
|
|
const returnsFalse = (body.match(/return false;/g) || []).length;
|
|
assert.equal(returnsFalse, 6, "mongodb, postgresql, their strict-mode ENOENT paths, mysql-failure and the fail-closed tail must return false");
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Source assertions: the one-flight bootstrap latch in ensureMongoAdminAuth.
|
|
// ---------------------------------------------------------------------------
|
|
|
|
test("M2: ensureMongoAdminAuth gates its one-time bootstrap with a one-flight latch", () => {
|
|
const latchIdx = indexSource.indexOf("let _mongoAdminBootstrapInFlight = null;");
|
|
const wrapStart = indexSource.indexOf("async function ensureMongoAdminAuth(config)");
|
|
const bootStart = indexSource.indexOf("async function _bootstrapMongoAdminAuth(config)");
|
|
assert.ok(latchIdx !== -1 && wrapStart !== -1 && bootStart !== -1, "latch, wrapper and bootstrap body must exist");
|
|
assert.ok(latchIdx < wrapStart && wrapStart < bootStart, "latch must be declared before the wrapper, wrapper before the bootstrap body");
|
|
|
|
const wrapEnd = endIndexOfFunction(indexSource, "async function ensureMongoAdminAuth(config)");
|
|
const wrapper = stripComments(indexSource.slice(wrapStart, wrapEnd));
|
|
assert.ok(wrapper.includes("getMongoAdminCredentials(config)"), "sealed credentials must short-circuit before the latch");
|
|
assert.ok(wrapper.indexOf("return { ok: true, auth: existing };") < wrapper.indexOf("if (_mongoAdminBootstrapInFlight)"),
|
|
"the steady-state path must skip the latch entirely");
|
|
assert.ok(wrapper.includes("if (_mongoAdminBootstrapInFlight)"), "a pending bootstrap must be awaited, not duplicated");
|
|
assert.ok(wrapper.includes("_bootstrapMongoAdminAuth(config)"), "the bootstrap must run through the latched helper");
|
|
assert.ok(/finally\s*\{\s*_mongoAdminBootstrapInFlight = null;\s*\}/.test(wrapper), "the latch must be released in finally");
|
|
|
|
const bootEnd = endIndexOfFunction(indexSource, "async function _bootstrapMongoAdminAuth(config)");
|
|
const boot = stripComments(indexSource.slice(bootStart, bootEnd));
|
|
assert.ok(!boot.includes("mongodbOperationMutex") && !wrapper.includes("mongodbOperationMutex"),
|
|
"the latch must be a pending promise, NOT the non-reentrant mongo mutex (the dedicated endpoints already hold it)");
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Functional: the generic functions + checkDatabaseConnection are sliced out
|
|
// of index.js into a vm sandbox and driven against stubbed channels, so the
|
|
// AUTHENTICATION WIRING is verified, not just the source shape.
|
|
// ---------------------------------------------------------------------------
|
|
|
|
const ADMIN_AUTH = { user: "adpadmin", password: "admin-secret" };
|
|
const MONGO_CONFIG = { enabled: true, port: "27019", users: [{ username: "adpadmin" }] };
|
|
|
|
function fakeChild({ exitCode = 0, stderrText = "", errCode = null } = {}) {
|
|
const child = new EventEmitter();
|
|
child.stderr = new EventEmitter();
|
|
child.kill = () => { };
|
|
process.nextTick(() => {
|
|
if (errCode) child.emit("error", Object.assign(new Error("spawn ENOENT"), { code: errCode }));
|
|
else {
|
|
if (stderrText) child.stderr.emit("data", Buffer.from(stderrText));
|
|
child.emit("close", exitCode);
|
|
}
|
|
});
|
|
return child;
|
|
}
|
|
|
|
function buildModule(overrides = {}) {
|
|
const state = { runnerCalls: [], spawnCalls: [], ensureCalls: [], loadCalls: [] };
|
|
|
|
const sliceStart = indexSource.indexOf("const MONGO_GENERIC_AUTH_FAILED_ERROR =");
|
|
const genericEnd = endIndexOfFunction(indexSource, "async function deleteMongoUserLegacy");
|
|
const cdcStart = indexSource.indexOf("async function checkDatabaseConnection(type, host, port, username, password, opts = {})");
|
|
const cdcEnd = endIndexOfFunction(indexSource, "async function checkDatabaseConnection(type, host, port, username, password, opts = {})");
|
|
assert.ok(sliceStart !== -1 && genericEnd > sliceStart && cdcStart !== -1 && cdcEnd > cdcStart, "slices not found");
|
|
const slice = indexSource.slice(sliceStart, genericEnd) + "\n" + indexSource.slice(cdcStart, cdcEnd);
|
|
|
|
const sandbox = {
|
|
module: { exports: {} },
|
|
console: { log() { }, warn() { }, error() { } },
|
|
buildMongoCreateUserEval: priv.buildMongoCreateUserEval,
|
|
loadMongoDBConfig: (config) => {
|
|
state.loadCalls.push(config);
|
|
return overrides.config || MONGO_CONFIG;
|
|
},
|
|
ensureMongoAdminAuth: async (config) => {
|
|
state.ensureCalls.push(config);
|
|
if (overrides.ensureMongoAdminAuth) return overrides.ensureMongoAdminAuth(config);
|
|
return { ok: true, auth: ADMIN_AUTH };
|
|
},
|
|
validatePort: (p) => {
|
|
const n = parseInt(String(p), 10);
|
|
return Number.isInteger(n) && n >= 1 && n <= 65535 ? n : null;
|
|
},
|
|
runAuthenticatedMongosh: (auth, script, opts) => {
|
|
state.runnerCalls.push({ auth, script, opts });
|
|
if (overrides.runner) return overrides.runner(auth, script, opts, state.runnerCalls.length);
|
|
return { code: 0, stdout: "", stderr: "", errCode: undefined, authFailed: false };
|
|
},
|
|
spawn: (cmd, args, opts) => {
|
|
state.spawnCalls.push({ cmd, args, opts });
|
|
return overrides.spawn
|
|
? overrides.spawn(cmd, args, opts)
|
|
: fakeChild();
|
|
},
|
|
mysql: overrides.mysql || {
|
|
createConnection: async () => ({ end: async () => { } }),
|
|
},
|
|
process: { env: {} },
|
|
setTimeout,
|
|
clearTimeout,
|
|
// Faithful mirror of index.js's stripLogControlChars
|
|
// (adpanel:log-email-control-chars): the sliced functions' console lines
|
|
// strip the interpolated account username.
|
|
stripLogControlChars: (value) => String(value || "").replace(/[\x00-\x1f\x7f]/g, ""),
|
|
};
|
|
vm.createContext(sandbox);
|
|
vm.runInContext(
|
|
slice +
|
|
"\nmodule.exports = { createMongoUser, createMongoUserLegacy, updateMongoUserPassword, " +
|
|
"updateMongoUserPasswordLegacy, deleteMongoUser, deleteMongoUserLegacy, " +
|
|
"checkDatabaseConnection, MONGO_GENERIC_AUTH_FAILED_ERROR };",
|
|
sandbox
|
|
);
|
|
return { mod: sandbox.module.exports, state };
|
|
}
|
|
|
|
test("M2 (functional): createMongoUser runs the scoped create script through the authenticated runner", async () => {
|
|
const { mod, state } = buildModule();
|
|
const result = await mod.createMongoUser("alice", "password123");
|
|
assert.ok(result.ok, "creation must succeed on the happy path");
|
|
assert.equal(state.ensureCalls.length, 1, "exactly one ensureMongoAdminAuth per call");
|
|
assert.deepEqual(state.ensureCalls[0], MONGO_CONFIG, "the MongoDB config feeds the auth bootstrap");
|
|
|
|
const call = state.runnerCalls[0];
|
|
assert.deepEqual(call.auth, ADMIN_AUTH, "the sealed admin credential must reach the runner");
|
|
assert.equal(call.script, priv.buildMongoCreateUserEval("alice", "password123"),
|
|
"the operation script must be the unchanged least-privilege builder output");
|
|
assert.deepEqual(call.opts.args, ["--port", "27019", "admin", "--quiet"], "runner must target the configured port");
|
|
assert.ok(!JSON.stringify(call.opts).includes("password123"), "the new password must only travel inside the staged script");
|
|
});
|
|
|
|
test("M2 (functional): update/delete keep their exact scripts, authenticated", async () => {
|
|
const { mod, state } = buildModule();
|
|
assert.ok((await mod.updateMongoUserPassword("bob", "password123")).ok);
|
|
assert.ok((await mod.deleteMongoUser("bob")).ok);
|
|
|
|
assert.equal(state.runnerCalls[0].script, `db.getSiblingDB('admin').changeUserPassword("bob", "password123")`);
|
|
assert.equal(state.runnerCalls[1].script, `db.getSiblingDB('admin').dropUser("bob")`);
|
|
for (const call of state.runnerCalls) {
|
|
assert.deepEqual(call.auth, ADMIN_AUTH);
|
|
assert.deepEqual(call.opts.args, ["--port", "27019", "admin", "--quiet"]);
|
|
}
|
|
});
|
|
|
|
test("M2 (functional): ENOENT falls back to the legacy shell, which authenticates too", async () => {
|
|
const { mod, state } = buildModule({
|
|
runner: (auth, script, opts, n) => (n === 1
|
|
? { code: 1, stdout: "", stderr: "spawn mongosh ENOENT", errCode: "ENOENT", authFailed: false }
|
|
: { code: 0, stdout: "", stderr: "", errCode: undefined, authFailed: false }),
|
|
});
|
|
const result = await mod.createMongoUser("alice", "password123");
|
|
assert.ok(result.ok, "the legacy fallback must still create the user");
|
|
|
|
assert.equal(state.runnerCalls.length, 2, "mongosh attempt + legacy fallback");
|
|
const legacy = state.runnerCalls[1];
|
|
assert.equal(legacy.opts.shellBin, "mongo", "the fallback must target the legacy shell");
|
|
assert.deepEqual(legacy.auth, ADMIN_AUTH, "the legacy shell must receive the admin credential for its staged preamble");
|
|
assert.equal(legacy.script, priv.buildMongoCreateUserEval("alice", "password123"), "same least-privilege script");
|
|
assert.deepEqual(legacy.opts.args, ["--port", "27019", "admin"], "legacy invocation keeps its db address");
|
|
});
|
|
|
|
test("M2 (functional): all six paths authenticate and map stale credentials to the re-setup error", async () => {
|
|
const { mod } = buildModule({
|
|
runner: () => ({ code: 1, stdout: "ADP_MONGO_AUTH_FAILED", stderr: "", errCode: undefined, authFailed: true }),
|
|
});
|
|
for (const call of [
|
|
() => mod.createMongoUser("alice", "password123"),
|
|
() => mod.updateMongoUserPassword("alice", "password123"),
|
|
() => mod.deleteMongoUser("alice"),
|
|
]) {
|
|
const r = await call();
|
|
assert.deepEqual(r, { ok: false, error: STALE_ERROR }, "auth failure must map to the stale-credential error");
|
|
}
|
|
|
|
// The legacy variants enforce the same contract when driven directly.
|
|
const direct = buildModule({
|
|
runner: () => ({ code: 1, stdout: "ADP_MONGO_AUTH_FAILED", stderr: "", errCode: undefined, authFailed: true }),
|
|
});
|
|
for (const call of [
|
|
() => direct.mod.createMongoUserLegacy("alice", "password123", ADMIN_AUTH, "27017"),
|
|
() => direct.mod.updateMongoUserPasswordLegacy("alice", "password123", ADMIN_AUTH, "27017"),
|
|
() => direct.mod.deleteMongoUserLegacy("alice", ADMIN_AUTH, "27017"),
|
|
]) {
|
|
const r = await call();
|
|
assert.deepEqual(r, { ok: false, error: STALE_ERROR });
|
|
}
|
|
});
|
|
|
|
test("M2 (functional): a failed bootstrap surfaces its error and never spawns a shell", async () => {
|
|
const { mod, state } = buildModule({
|
|
ensureMongoAdminAuth: async () => ({ ok: false, error: "Cannot read /etc/mongod.conf: EACCES" }),
|
|
});
|
|
for (const call of [
|
|
() => mod.createMongoUser("alice", "password123"),
|
|
() => mod.updateMongoUserPassword("alice", "password123"),
|
|
() => mod.deleteMongoUser("alice"),
|
|
]) {
|
|
const r = await call();
|
|
assert.deepEqual(r, { ok: false, error: "Cannot read /etc/mongod.conf: EACCES" });
|
|
}
|
|
assert.equal(state.runnerCalls.length, 0, "no shell may run without a resolved admin credential");
|
|
});
|
|
|
|
test("M2 (hijack fix): createUser against an existing user is a refusal, never a success", async () => {
|
|
// createUser cannot set a new password for an existing user. Treating its
|
|
// "already exists" error as success used to append bookkeeping for a live
|
|
// account whose current (unknown-to-the-panel) credential stays valid —
|
|
// presented to the admin as a panel-issued user.
|
|
const stdoutVariant = buildModule({
|
|
runner: () => ({ code: 1, stdout: 'MongoServerError: User "alice@admin" already exists', stderr: "", errCode: undefined, authFailed: false }),
|
|
});
|
|
const r1 = await stdoutVariant.mod.createMongoUser("alice", "password123");
|
|
// deepEqual, not deepStrictEqual: results cross the vm context boundary.
|
|
assert.deepEqual(r1, { ok: false, accountExists: true, error: "MongoDB user 'alice' already exists on the admin database" });
|
|
|
|
const stderrVariant = buildModule({
|
|
runner: () => ({ code: 1, stdout: "", stderr: 'User "alice@admin" already exists', errCode: undefined, authFailed: false }),
|
|
});
|
|
const r2 = await stderrVariant.mod.createMongoUser("alice", "password123");
|
|
assert.equal(r2.ok, false, "stderr-reported duplicates must be refused too");
|
|
assert.equal(r2.accountExists, true);
|
|
|
|
const legacyVariant = buildModule({
|
|
runner: (auth, script, opts, n) => (n === 1
|
|
? { code: 1, stdout: "", stderr: "spawn mongosh ENOENT", errCode: "ENOENT", authFailed: false }
|
|
: { code: 1, stdout: "", stderr: 'User "alice@admin" already exists', errCode: undefined, authFailed: false }),
|
|
});
|
|
const r3 = await legacyVariant.mod.createMongoUser("alice", "password123");
|
|
assert.equal(r3.accountExists, true, "the legacy shell path must refuse as well");
|
|
|
|
// A genuine failure that is NOT a duplicate keeps the generic error shape:
|
|
const otherError = buildModule({
|
|
runner: () => ({ code: 1, stdout: "", stderr: "command createUser requires authentication", errCode: undefined, authFailed: false }),
|
|
});
|
|
const r4 = await otherError.mod.createMongoUser("alice", "password123");
|
|
assert.equal(r4.ok, false);
|
|
assert.equal(r4.accountExists, undefined, "only duplicate-user errors carry the accountExists flag");
|
|
});
|
|
|
|
test("M2 (functional): invalid input fails closed before any auth bootstrap", async () => {
|
|
const { mod, state } = buildModule();
|
|
const r = await mod.createMongoUser("bad name", "password123");
|
|
assert.deepEqual(r, { ok: false, error: "Invalid username or password" });
|
|
assert.equal(state.ensureCalls.length, 0, "validation must precede the bootstrap");
|
|
assert.equal(state.runnerCalls.length, 0);
|
|
});
|
|
|
|
test("M2 (functional): checkDatabaseConnection(mongodb) authenticates the provided credentials", async () => {
|
|
const { mod, state } = buildModule();
|
|
assert.equal(await mod.checkDatabaseConnection("mongodb", "127.0.0.1", 27017, "siteadmin", "site-password"), true);
|
|
|
|
const call = state.runnerCalls[0];
|
|
assert.deepEqual(call.auth, { user: "siteadmin", password: "site-password" }, "the PROVIDED credentials must be checked");
|
|
assert.deepEqual(call.opts.args, ["--host", "127.0.0.1", "--port", "27017", "--quiet"]);
|
|
assert.equal(call.script, "db.runCommand({ ping: 1 });");
|
|
assert.equal(state.spawnCalls.length, 0, "the mongodb check must not spawn directly");
|
|
|
|
const bad = buildModule({
|
|
runner: () => ({ code: 1, stdout: "ADP_MONGO_AUTH_FAILED", stderr: "", errCode: undefined, authFailed: true }),
|
|
});
|
|
assert.equal(await bad.mod.checkDatabaseConnection("mongodb", "127.0.0.1", 27017, "siteadmin", "wrong-pass"), false,
|
|
"wrong credentials must fail the check");
|
|
|
|
const missing = buildModule({
|
|
runner: () => ({ code: 1, stdout: "", stderr: "Could not connect", errCode: "ENOENT", authFailed: false }),
|
|
});
|
|
assert.equal(await missing.mod.checkDatabaseConnection("mongodb", "127.0.0.1", 27017, "siteadmin", "site-password"), true,
|
|
"a missing mongosh binary degrades to the previous pass-through");
|
|
});
|
|
|
|
test("M2 (functional): checkDatabaseConnection(postgresql) uses PGPASSWORD env, never argv", async () => {
|
|
const ok = buildModule({ spawn: () => fakeChild({ exitCode: 0 }) });
|
|
assert.equal(await ok.mod.checkDatabaseConnection("postgresql", "127.0.0.1", 5432, "siteadmin", "pg-password"), true);
|
|
const call = ok.state.spawnCalls[0];
|
|
assert.equal(call.cmd, "psql");
|
|
assert.deepEqual(call.args, ["-h", "127.0.0.1", "-p", "5432", "-U", "siteadmin", "-d", "postgres", "-c", "SELECT 1"]);
|
|
assert.equal(call.opts.env.PGPASSWORD, "pg-password", "the password must reach the client via PGPASSWORD");
|
|
assert.ok(!call.args.join(" ").includes("pg-password"), "the password must never appear on argv");
|
|
|
|
const bad = buildModule({ spawn: () => fakeChild({ exitCode: 2, stderrText: "psql: FATAL: password authentication failed" }) });
|
|
assert.equal(await bad.mod.checkDatabaseConnection("postgresql", "127.0.0.1", 5432, "siteadmin", "pg-password"), false,
|
|
"a rejected credential must fail the check");
|
|
|
|
const missing = buildModule({ spawn: () => fakeChild({ errCode: "ENOENT" }) });
|
|
assert.equal(await missing.mod.checkDatabaseConnection("postgresql", "127.0.0.1", 5432, "siteadmin", "pg-password"), true,
|
|
"a missing psql binary degrades to the previous pass-through");
|
|
});
|
|
|
|
test("M2 (functional): checkDatabaseConnection(mysql) keeps its channel and semantics", async () => {
|
|
const calls = [];
|
|
const mysqlStub = {
|
|
createConnection: async (opts) => {
|
|
calls.push(opts);
|
|
if (opts.password === "wrong") throw new Error("Access denied for user");
|
|
return { end: async () => { } };
|
|
},
|
|
};
|
|
const { mod, state } = buildModule({ mysql: mysqlStub });
|
|
assert.equal(await mod.checkDatabaseConnection("mysql", "127.0.0.1", 3306, "root", "good"), true);
|
|
assert.equal(await mod.checkDatabaseConnection("mysql", "127.0.0.1", 3306, "root", "wrong"), false);
|
|
assert.deepEqual(calls[0], { host: "127.0.0.1", port: 3306, user: "root", password: "good", connectTimeout: 5000 },
|
|
"the mysql client call must be unchanged");
|
|
assert.equal(state.runnerCalls.length, 0, "mysql must not touch the mongosh runner");
|
|
assert.equal(state.spawnCalls.length, 0, "mysql must not spawn anything");
|
|
});
|
|
|
|
test("M2 (functional): unknown database types fail closed", async () => {
|
|
const { mod, state } = buildModule();
|
|
assert.equal(await mod.checkDatabaseConnection("redis", "127.0.0.1", 6379, "u", "p"), false,
|
|
"an unverifiable connection must not pass");
|
|
assert.equal(state.runnerCalls.length, 0);
|
|
assert.equal(state.spawnCalls.length, 0);
|
|
});
|