Files
Kelx/tests/db-switch-strict-validation.test.js
2026-11-30 16:32:37 +00:00

255 lines
15 KiB
JavaScript

"use strict";
// Tests for the database-switch strict-validation remediation.
//
// checkDatabaseConnection() degraded to a warn-and-return-true pass-through
// when the engine's client binary (mongosh/psql) was missing on the panel
// host — a deliberate pre-M2 accommodation for remote engines the panel
// cannot locally verify. Two destructive callers blindly trusted that result:
// POST /api/settings/database/change-type and POST /api/settings/database/setup
// both DROP every previous engine account (dropRemovedDbAccounts) and then
// repoint the panel at the new engine. With the client binary missing, the
// panel therefore destroyed the old accounts and switched to an engine whose
// credentials were never validated — irreversible data loss plus a possibly
// dead panel.
//
// Remediation contract locked here:
// - checkDatabaseConnection(type, host, port, username, password, opts):
// strict mode (opts.strict) turns the ENOENT pass-through into a
// fail-closed `return false` for BOTH mongodb and postgresql (with a
// precise error naming the missing binary and host:port); non-strict
// callers keep the pre-M2 pass-through verbatim.
// - databaseClientBinaryMissing(type): actionable error string when
// mongosh/psql is absent on the panel host, null otherwise (mysql is the
// in-process mysql2 driver — no binary involved).
// - change-type: a PRE-TOKEN 400 guard (DB_CLIENT_BINARY_MISSING — body-only
// checks must never burn the 120s one-time action token, mirroring the
// endpoint's stated convention) AND { strict: true } at the destructive
// call site as a belt-and-suspenders backstop against future refactors.
// - setup: the same pre-token guard, but ONLY when the setup will drop the
// previous engine's accounts (willDropPrevious — a fresh setup keeps the
// pre-M2 pass-through so a remote engine can still be configured from a
// host without its client tooling), and { strict: willDropPreviousNow }
// at its single non-mysql call site — the flag derived from the
// AUTHORITATIVE post-mutex snapshot, so the validation gating the drop
// can never be stale relative to the config it drops. The two mysql-only
// validation calls (staged pre-commit and commit) stay strict-free: the
// mysql2 driver has no binary dependency.
//
// index.js boots servers on require, so the contract is asserted at source
// level (same technique as tests/db-mysql-scoping.test.js and
// tests/destructive-route-guards.test.js).
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 a default parameter like `opts = {}` in
// `function f(..., opts = {}) {` is not mistaken for the body (same depth
// counting approach as tests/destructive-route-guards.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 checkFn = stripComments(extractBlock(indexSource, "async function checkDatabaseConnection("));
// ---------------------------------------------------------------------------
// 1. checkDatabaseConnection: strict fail-closed ENOENT handling per engine
// ---------------------------------------------------------------------------
test("checkDatabaseConnection: signature accepts opts and the contract comment sits on the function", () => {
assert.ok(checkFn.includes("username, password, opts = {})"),
"checkDatabaseConnection must accept an opts argument");
});
test("checkDatabaseConnection: mongodb ENOENT fails closed under strict mode, keeps pass-through otherwise", () => {
const branch = stripComments(extractBlock(checkFn, "if (type === 'mongodb') {"));
const enoent = stripComments(extractBlock(branch, "if (res.errCode === 'ENOENT') {"));
assert.ok(enoent.includes("opts.strict"), "the mongosh ENOENT branch must consult opts.strict");
assert.match(enoent, /if \(opts\.strict\) \{[\s\S]*?return false;[\s\S]*?\}/,
"strict mode must fail closed (return false) when mongosh is missing");
assert.match(enoent, /console\.error\(`\[database\] mongosh is not installed[^`]*\$\{host\}:\$\{port\}/,
"strict mode must log a precise error naming the missing binary and host:port");
assert.ok(enoent.includes("console.warn") && enoent.includes("return true;"),
"non-strict mode must keep the pre-M2 warn + return true pass-through verbatim");
assert.ok(enoent.indexOf("return false;") < enoent.indexOf("return true;"),
"the strict return false must precede the pass-through so strict mode can never fall into it");
});
test("checkDatabaseConnection: postgresql ENOENT fails closed under strict mode, keeps pass-through otherwise", () => {
const branch = stripComments(extractBlock(checkFn, "if (type === 'postgresql') {"));
const enoent = stripComments(extractBlock(branch, "if (probe.errCode === 'ENOENT') {"));
assert.ok(enoent.includes("opts.strict"), "the psql ENOENT branch must consult opts.strict");
assert.match(enoent, /if \(opts\.strict\) \{[\s\S]*?return false;[\s\S]*?\}/,
"strict mode must fail closed (return false) when psql is missing");
assert.match(enoent, /console\.error\(`\[database\] psql is not installed[^`]*\$\{host\}:\$\{port\}/,
"strict mode must log a precise error naming the missing binary and host:port");
assert.ok(enoent.includes("console.warn") && enoent.includes("return true;"),
"non-strict mode must keep the pre-M2 warn + return true pass-through verbatim");
assert.ok(enoent.indexOf("return false;") < enoent.indexOf("return true;"),
"the strict return false must precede the pass-through so strict mode can never fall into it");
});
test("checkDatabaseConnection: the mysql branch has no binary pass-through (in-process driver)", () => {
const branch = stripComments(extractBlock(checkFn, "if (type === 'mysql') {"));
assert.ok(!branch.includes("ENOENT"), "mysql must never degrade to a missing-binary pass-through");
assert.ok(!branch.includes("opts.strict"), "the mysql branch must not branch on strict mode");
});
// ---------------------------------------------------------------------------
// 2. databaseClientBinaryMissing helper
// ---------------------------------------------------------------------------
test("databaseClientBinaryMissing: probes mongosh and psql with the repo's which/execSync pattern and returns actionable messages", () => {
const helper = stripComments(extractBlock(indexSource, "function databaseClientBinaryMissing(type)"));
assert.match(helper, /execSync\('which mongosh', \{ encoding: 'utf8', timeout: 5000, stdio: \['ignore', 'pipe', 'ignore'\] \}\)/,
"must probe mongosh with the repo's which/execSync pattern (cf. installMongoDB)");
assert.match(helper, /execSync\('which psql', \{ encoding: 'utf8', timeout: 5000, stdio: \['ignore', 'pipe', 'ignore'\] \}\)/,
"must probe psql with the repo's which/execSync pattern");
assert.ok(helper.includes("Install postgresql-client"), "the psql message must be actionable");
assert.ok(helper.includes("Install mongodb-mongosh"), "the mongosh message must be actionable");
assert.ok(helper.includes("verify the target connection before switching"),
"the messages must explain WHY the panel refuses (verification before switching)");
// Defined before both destructive endpoints, so every caller sees the helper.
const helperAt = indexSource.indexOf("function databaseClientBinaryMissing(");
const setupAt = indexSource.indexOf('app.post("/api/settings/database/setup"');
const changeAt = indexSource.indexOf('app.post("/api/settings/database/change-type"');
assert.ok(helperAt >= 0 && helperAt < setupAt && helperAt < changeAt,
"the helper must be declared before both destructive endpoints use it");
});
// ---------------------------------------------------------------------------
// 3. change-type: pre-token guard precedes the token gate; { strict: true }
// ---------------------------------------------------------------------------
test("change-type: pre-token DB_CLIENT_BINARY_MISSING guard precedes the token gate, and the destructive call passes { strict: true }", () => {
const route = extractRoute(
'app.post("/api/settings/database/change-type"',
'app.post("/api/settings/database/pgadmin/setup"'
);
const guardIdx = route.indexOf("databaseClientBinaryMissing(cleanType)");
const codeIdx = route.indexOf('code: "DB_CLIENT_BINARY_MISSING"');
const tokenIdx = route.indexOf('requireActionTokenOr403(req, res, "POST /api/settings/database/change-type")');
assert.ok(guardIdx > 0, "change-type must run databaseClientBinaryMissing(cleanType)");
assert.ok(codeIdx > guardIdx, "the guard must answer 400 with the DB_CLIENT_BINARY_MISSING code");
assert.ok(tokenIdx > guardIdx,
"the binary guard must run BEFORE requireActionTokenOr403 so a missing client cannot burn the one-time action token");
assert.match(route,
/if \(clientMissing\) return res\.status\(400\)\.json\(\{ error: clientMissing, code: "DB_CLIENT_BINARY_MISSING" \}\);/,
"the guard must actually reject the request (400), not merely compute");
assert.match(route,
/checkDatabaseConnection\(cleanType, cleanHost, cleanPort, cleanUsername, password, \{ strict: true \}\)/,
"the destructive connection check must pass { strict: true } so a skipped validation can never gate the account drop");
// Ordering inside the handler: the strict connection check (and therefore
// the destructive drop behind it) must come after the token gate.
const strictCallIdx = route.indexOf("checkDatabaseConnection(cleanType, cleanHost, cleanPort, cleanUsername, password, { strict: true })");
const dropIdx = route.indexOf("dropRemovedDbAccounts(existingConfig, removedUsers)");
assert.ok(strictCallIdx > tokenIdx, "the strict connection check must run after the token gate");
assert.ok(dropIdx > strictCallIdx, "the drop must run only after the strict connection check passed");
});
// ---------------------------------------------------------------------------
// 4. setup: willDropPrevious + conditional pre-token guard + strict call site
// ---------------------------------------------------------------------------
test("setup: willDropPrevious mirrors the drop block, guard is conditional and pre-token, non-mysql call passes { strict: willDropPreviousNow }", () => {
const route = extractRoute(
'app.post("/api/settings/database/setup"',
'app.post("/api/settings/database/disable"'
);
const willIdx = route.indexOf("const willDropPrevious = previousConfig.enabled && Array.isArray(previousConfig.users) && previousConfig.users.length > 0;");
assert.ok(willIdx > 0, "setup must compute willDropPrevious pre-token");
assert.ok(route.includes("if (existingConfig.enabled && Array.isArray(existingConfig.users) && existingConfig.users.length > 0) {"),
"the destructive drop block condition must still exist — keep willDropPrevious in sync with it");
const guardIdx = route.indexOf("databaseClientBinaryMissing(cleanType)");
const codeIdx = route.indexOf('code: "DB_CLIENT_BINARY_MISSING"');
const tokenIdx = route.indexOf('requireActionTokenOr403(req, res, "POST /api/settings/database/setup")');
assert.ok(guardIdx > willIdx, "the binary guard must run after willDropPrevious is computed");
assert.ok(codeIdx > guardIdx, "the guard must answer 400 with the DB_CLIENT_BINARY_MISSING code");
assert.ok(tokenIdx > guardIdx,
"the binary guard must run BEFORE requireActionTokenOr403 so a missing client cannot burn the one-time action token");
// The guard is conditional on willDropPrevious: a fresh setup (nothing to
// drop) keeps the pre-M2 pass-through for remote engines the panel cannot
// locally verify.
assert.match(route,
/if \(willDropPrevious\) \{\s*const clientMissing = databaseClientBinaryMissing\(cleanType\);\s*if \(clientMissing\) return res\.status\(400\)\.json\(\{ error: clientMissing, code: "DB_CLIENT_BINARY_MISSING" \}\);\s*\}/,
"the binary guard must fire only when the setup will drop the previous engine's accounts");
// The strict flag comes from the AUTHORITATIVE post-mutex snapshot, not the
// pre-token one: a config written between the pre-token read and the lock
// must never be dropped after a non-strict validation. The pre-token
// willDropPrevious only shapes the fast 400.
const strictCall = "checkDatabaseConnection(cleanType, connectionHost, cleanPort, cleanUsername, password, { strict: willDropPreviousNow })";
const strictCallIdx = route.indexOf(strictCall);
const hoistIdx = route.indexOf("const existingConfig = loadDatabaseConfig({ fresh: true });");
const nowIdx = route.indexOf("const willDropPreviousNow = ");
assert.ok(strictCallIdx !== -1 && hoistIdx !== -1 && nowIdx !== -1 &&
hoistIdx < nowIdx && nowIdx < strictCallIdx,
"the post-mutex snapshot must be loaded (and willDropPreviousNow derived) before the strict validation call");
assert.match(route,
new RegExp(strictCall.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")),
"the non-mysql validation call must pass { strict: willDropPreviousNow } from the post-mutex snapshot");
});
test("setup: the mysql staged/commit validation calls stay strict-free (mysql2 has no binary dependency)", () => {
const route = extractRoute(
'app.post("/api/settings/database/setup"',
'app.post("/api/settings/database/disable"'
);
assert.doesNotMatch(route, /checkDatabaseConnection\('mysql',[^\n]*\{[^}]*strict/,
"the mysql-only validation calls must not pass strict — the in-process driver is never binary-dependent");
assert.ok(route.includes("checkDatabaseConnection('mysql', connectionHost, cleanPort, cleanUsername, stagingPassword);"),
"the staged pre-commit mysql call must remain unchanged");
assert.ok(route.includes("checkDatabaseConnection('mysql', connectionHost, cleanPort, cleanUsername, password);"),
"the commit-time mysql call must remain unchanged");
});