211 lines
12 KiB
JavaScript
211 lines
12 KiB
JavaScript
"use strict";
|
|
|
|
// Tests for the MongoDB setup hardening (authless re-setup window).
|
|
//
|
|
// installMongoDB used to provision like this: write an auth-DISABLED
|
|
// /etc/mongod.conf, restart mongod over whatever data directory existed, run
|
|
// an unauthenticated script that called dropAllUsers() and planted the panel's
|
|
// admin, and only THEN write the hardened config and restart again. Two
|
|
// consequences:
|
|
// - re-running setup on an already-enabled deployment restarted mongod
|
|
// authless over LIVE data: any local shell user could read and modify
|
|
// every database, and could plant a permanent root user in the window
|
|
// after dropAllUsers() wiped the real admin;
|
|
// - a panel crash (SIGKILL/power loss) inside the window left mongod
|
|
// authless AND boot-enabled indefinitely (the startup self-heal only
|
|
// repairs it on the next panel restart).
|
|
//
|
|
// Remediation contract locked here:
|
|
// - POST /api/settings/database/mongodb/setup refuses re-setup with 409
|
|
// MONGODB_ALREADY_ENABLED BEFORE the one-time action token is consumed
|
|
// (a 4xx must never burn the token) and before any lock/job acquisition.
|
|
// - installMongoDB writes ONLY the hardened config (authorization: enabled)
|
|
// and never starts mongod without it; the authless provisioning conf and
|
|
// its "auth disabled for user creation" stage are gone entirely.
|
|
// - the admin user is created through MongoDB's LOCALHOST EXCEPTION on an
|
|
// auth-enforcing server (first user on admin, unauthenticated loopback);
|
|
// dropAllUsers() is gone from the install path — the unauthenticated
|
|
// user-wipe primitive no longer exists.
|
|
// - when users already exist (localhost exception closed), the flow
|
|
// disambiguates by knowledge-of-credential: the submitted admin
|
|
// credential is verified (auth + connectionStatus). It proceeds ONLY on
|
|
// success (a prior attempt/crash left exactly this admin behind); it must
|
|
// NEVER strip authentication to take a data directory over.
|
|
// - boot start (svc enable) is arranged only AFTER the admin credential is
|
|
// created and verified, so a mid-install crash leaves mongod stopped or
|
|
// running with auth ON and no boot entry — never a half-provisioned
|
|
// server booting unattended.
|
|
|
|
const test = require("node:test");
|
|
const assert = require("node:assert");
|
|
const fs = require("node:fs");
|
|
const path = require("node:path");
|
|
|
|
const ROOT = path.join(__dirname, "..");
|
|
const indexSource = fs.readFileSync(path.join(ROOT, "index.js"), "utf8");
|
|
|
|
// Strip block comments and full-line // comments so prose cannot satisfy or
|
|
// violate assertions (same approach as tests/db-mysql-scoping.test.js).
|
|
function stripComments(src) {
|
|
return src
|
|
.replace(/\/\*[\s\S]*?\*\//g, "")
|
|
.replace(/^[ \t]*\/\/.*$/gm, "");
|
|
}
|
|
|
|
// Extract the { ... }-balanced block starting at the occurrence of
|
|
// startMarker. The body opener is the first `{` OUTSIDE any parentheses
|
|
// relative to the marker, so default parameter object literals cannot be
|
|
// mistaken for the body (same depth-counting technique as
|
|
// tests/db-switch-strict-validation.test.js).
|
|
function extractBlock(source, startMarker) {
|
|
const start = source.indexOf(startMarker);
|
|
assert.ok(start >= 0, `marker not found: ${startMarker}`);
|
|
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 found 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 source.slice(start, i + 1);
|
|
}
|
|
}
|
|
assert.fail(`unbalanced braces after marker: ${startMarker}`);
|
|
}
|
|
|
|
function extractRoute(routeMarker, nextRouteMarker) {
|
|
const start = indexSource.indexOf(routeMarker);
|
|
assert.ok(start >= 0, `route marker not found: ${routeMarker}`);
|
|
const end = indexSource.indexOf(nextRouteMarker, start);
|
|
assert.ok(end > start, `next route marker not found after route: ${nextRouteMarker}`);
|
|
return stripComments(indexSource.slice(start, end));
|
|
}
|
|
|
|
const installFn = stripComments(extractBlock(indexSource, "async function installMongoDB("));
|
|
const setupRoute = extractRoute(
|
|
'app.post("/api/settings/database/mongodb/setup"',
|
|
'app.post("/api/settings/database/mongodb/disable"'
|
|
);
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// 1. installMongoDB: hardened config from the first start, no authless stage
|
|
// ---------------------------------------------------------------------------
|
|
|
|
test("installMongoDB: the authless provisioning conf is gone; the only conf write carries authorization: enabled", () => {
|
|
assert.ok(!installFn.includes("auth disabled for user creation"),
|
|
"the authless provisioning stage must be gone");
|
|
assert.ok(installFn.includes("authorization: enabled"),
|
|
"the hardened mongod.conf template must live inside installMongoDB");
|
|
const firstConfWrite = installFn.indexOf("writeSystemFileWithPrivilegeFallback(mongoConfPath");
|
|
const secureWrite = installFn.indexOf("writeSystemFileWithPrivilegeFallback(mongoConfPath, secureConfig");
|
|
assert.ok(firstConfWrite !== -1, "installMongoDB must write the conf itself");
|
|
assert.equal(firstConfWrite, secureWrite,
|
|
"the FIRST conf write on the success path must be the hardened secureConfig");
|
|
const secureFlag = installFn.indexOf("secureConfWritten = true");
|
|
const firstStart = installFn.indexOf('["svc", "start", "mongod"]');
|
|
assert.ok(secureFlag !== -1 && firstStart !== -1, "conf write and start must both exist");
|
|
assert.ok(secureFlag < firstStart,
|
|
"the hardened conf must be on disk BEFORE mongod is ever started");
|
|
});
|
|
|
|
test("installMongoDB: no authless→authful restart remains (the enable-auth epilogue is gone)", () => {
|
|
assert.ok(!installFn.includes("Configuration updated with authentication enabled"),
|
|
"the write-secure-conf-and-restart epilogue must be gone");
|
|
assert.ok(!installFn.includes('["svc", "restart", "mongod"]'),
|
|
"the install path must never bounce mongod across an authless/authful boundary");
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// 2. Admin creation via the localhost exception — no user-wipe primitive
|
|
// ---------------------------------------------------------------------------
|
|
|
|
test("installMongoDB: dropAllUsers is gone; creation rides the localhost exception on an auth-enforcing server", () => {
|
|
assert.ok(!installFn.includes("dropAllUsers"),
|
|
"the unauthenticated user-wipe primitive must be gone from the install path");
|
|
assert.ok(indexSource.includes("LOCALHOST EXCEPTION") &&
|
|
indexSource.indexOf("LOCALHOST EXCEPTION") > indexSource.indexOf("async function installMongoDB("),
|
|
"the creation path must document that it rides the localhost exception");
|
|
const createScript = stripComments(extractBlock(installFn, "const createUserScript = `"));
|
|
assert.match(createScript, /db\.createUser\(\{[\s\S]*?role:\s*'root'[\s\S]*?db:\s*'admin'/,
|
|
"the created admin must hold root on the admin database");
|
|
assert.ok(!createScript.includes("drop"),
|
|
"the creation script must not drop anything");
|
|
});
|
|
|
|
test("installMongoDB: pre-existing users are never taken over by stripping auth — credential decides", () => {
|
|
// The auth-required rejection must not throw away the run inside the retry
|
|
// loop; it must fall through to the verify-based disambiguation.
|
|
assert.ok(installFn.includes("targetHasUsers = true;"),
|
|
"the localhost-exception rejection must be recorded, not retried blindly");
|
|
const disambiguation = stripComments(extractBlock(installFn, "if (!userCreated && targetHasUsers) {"));
|
|
assert.ok(disambiguation.includes("verifyScript"),
|
|
"disambiguation must authenticate with the SUBMITTED credential (auth + connectionStatus)");
|
|
assert.ok(disambiguation.includes("MONGO_VERIFY_OK=1"),
|
|
"disambiguation may only continue when the submitted credential actually authenticates");
|
|
assert.match(disambiguation, /already contains users and the submitted admin credential does not authenticate/,
|
|
"a foreign data directory must be refused with the remediation spelled out");
|
|
assert.ok(!/svc[^]*?restart[^]*?disabl/i.test(disambiguation),
|
|
"disambiguation must not restart mongod with authentication disabled");
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// 3. Boot start only for a fully provisioned, credential-verified server
|
|
// ---------------------------------------------------------------------------
|
|
|
|
test("installMongoDB: svc enable comes only after the admin credential verified", () => {
|
|
const enables = installFn.split('["svc", "enable", "mongod"]').length - 1;
|
|
assert.equal(enables, 1, "exactly one svc enable in the install path");
|
|
const enableIdx = installFn.indexOf('["svc", "enable", "mongod"]');
|
|
const verifyIdx = installFn.indexOf("MONGO_VERIFY_OK=1");
|
|
assert.ok(verifyIdx !== -1, "the credential verification marker must exist");
|
|
assert.ok(enableIdx > verifyIdx,
|
|
"boot start must be enabled only after the admin credential verified — a crash mid-install must never leave a half-provisioned mongod boot-enabled");
|
|
});
|
|
|
|
test("installMongoDB: failure cleanup restores the pre-install config on every post-snapshot failure path", () => {
|
|
// The takeover-refusal path (and any failure after the panel's hardened conf
|
|
// replaced the user's own) must put the machine back the way it found it:
|
|
// restore the snapshotted conf and bring the pre-install service back, not
|
|
// only when the live conf happens to be insecure.
|
|
assert.ok(installFn.includes('if (liveInsecure || (hadPreExistingConf && typeof preExistingConf === \'string\')) {'),
|
|
"the restore branch must run whenever a pre-install conf was snapshotted, not only for insecure live confs");
|
|
const restoreIdx = installFn.indexOf('if (liveInsecure || (hadPreExistingConf && typeof preExistingConf === \'string\')) {');
|
|
const restartIdx = installFn.indexOf('if (preInstallServiceActive) {', restoreIdx);
|
|
assert.ok(restoreIdx !== -1 && restartIdx !== -1,
|
|
"the restored pre-install service must be restarted when it was active before the install");
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// 4. The setup endpoint refuses re-setup before burning the action token
|
|
// ---------------------------------------------------------------------------
|
|
|
|
test("mongodb/setup: 409 MONGODB_ALREADY_ENABLED precedes the token gate and any lock/job acquisition", () => {
|
|
const guardIdx = setupRoute.indexOf("MONGODB_ALREADY_ENABLED");
|
|
assert.ok(guardIdx > 0, "re-setup must be refused with the MONGODB_ALREADY_ENABLED code");
|
|
assert.ok(setupRoute.includes("loadMongoDBConfig()"),
|
|
"the guard must consult the existing MongoDB config");
|
|
assert.match(setupRoute,
|
|
/if \(\w+\.enabled\) \{\s*return res\.status\(409\)\.json\(/,
|
|
"the guard must answer 409 when MongoDB is already enabled");
|
|
|
|
const tokenIdx = setupRoute.indexOf('requireActionTokenOr403(req, res, "POST /api/settings/database/mongodb/setup")');
|
|
assert.ok(tokenIdx !== -1, "the endpoint must still gate on the action token");
|
|
assert.ok(guardIdx < tokenIdx,
|
|
"the 409 must precede the token gate so a refused re-setup never burns the one-time token");
|
|
|
|
const mutexIdx = setupRoute.indexOf("mongodbOperationMutex.tryAcquire()");
|
|
const jobIdx = setupRoute.indexOf("createInstallJob('mongodb')");
|
|
assert.ok(mutexIdx > guardIdx && jobIdx > guardIdx,
|
|
"a refused re-setup must not occupy the install lock or create a job to poll");
|
|
|
|
// Both remediation paths must be spelled out in the admin-facing message.
|
|
assert.match(setupRoute, /Password action/, "the message must offer password rotation");
|
|
assert.match(setupRoute, /Disable[\s\S]*purge/i, "the message must offer the disable-and-purge path");
|
|
});
|