"use strict"; // Tests for the MySQL localhost-twin rotation contract on // POST /api/settings/database/users/:username/password. // // Setup-created bookkeeping entries store no host property: they own BOTH the // user@'%' and the user@'localhost' MySQL accounts. MySQL matches local // connections (phpMyAdmin connects via 127.0.0.1) to the more-specific // 'user'@'localhost' account first, so a rotation that updates only the '%' // variant and treats a failed twin update as best-effort (the old behavior: a // console.warn, then "Password updated successfully" + updatedAt + save) // leaves the OLD password live on the localhost account — a silent orphan- // credential state while the panel records the rotation as done. // // Remediation contract locked here (the honest-failure taxonomy the sibling // DELETE route already applies to its secondary drop, where a failed // secondary drop fails the whole request and the entry stays for retry): // - a failed localhost twin sync returns a detailed 500 BEFORE any // updatedAt / saveDatabaseConfig bookkeeping, so the admin can retry and // bring both accounts back to the same password; // - the only exception is a twin that does not exist (MySQL ER_NO_SUCH_USER: // error 1396 / "Operation ALTER USER failed ...", the same signature // updateMySqlUserPassword matches at its '%' fallback) — nothing to sync, // the rotation is complete; // - the warn-and-continue behavior must be gone; // - every other case (entries WITH a stored host, non-MySQL branches, the // primary-update failure path, the success response) is unchanged. // // index.js boots servers on require, so the route-side contract is asserted // at source level (same technique as tests/db-mysql-scoping.test.js and // tests/pgadmin-recovery-hardening.test.js: slice the route between markers, // strip comments, assert on code only). 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, ""); } function extractFunction(name) { const start = indexSource.indexOf(`async function ${name}(`); assert.ok(start !== -1, `function ${name} not found in index.js`); const next = indexSource.indexOf("\nasync function ", start + 1); return indexSource.slice(start, next === -1 ? undefined : next); } const ROUTE_START_MARKER = 'app.post("/api/settings/database/users/:username/password"'; const NEXT_ROUTE_MARKER = 'app.delete("/api/settings/database/users/:username"'; const routeStart = indexSource.indexOf(ROUTE_START_MARKER); assert.ok(routeStart !== -1, "password route marker not found in index.js"); const routeEnd = indexSource.indexOf(NEXT_ROUTE_MARKER, routeStart); assert.ok(routeEnd > routeStart, "delete route marker must follow the password route in index.js"); // The password route body, comments stripped: only code can satisfy or // violate the assertions below. const routeBody = stripComments(indexSource.slice(routeStart, routeEnd)); // The mysql twin-sync block: from the setup-created condition (no stored // host) to the end of the mysql branch (the dbName assignment right after // the twin-sync block). const twinConditionIdx = routeBody.indexOf("hasOwnProperty.call(data.users[userIndex], 'host')"); assert.ok(twinConditionIdx !== -1, "setup-created twin-sync condition not found in the password route"); const mysqlBranchEndIdx = routeBody.indexOf("dbName = 'MySQL';", twinConditionIdx); assert.ok(mysqlBranchEndIdx > twinConditionIdx, "mysql branch end not found after the twin-sync condition"); const twinBlock = routeBody.slice(twinConditionIdx, mysqlBranchEndIdx); test("twin rotation: a failed localhost twin sync returns the honest-failure 500 before any bookkeeping", () => { assert.ok(twinBlock.includes("res.status(500).json"), "a twin-sync failure inside the mysql block must answer 500"); assert.ok(twinBlock.includes("was updated, but the matching"), "the 500 must state that the primary account WAS updated"); assert.ok(twinBlock.includes("'localhost' account could NOT be updated"), "the 500 must name the localhost twin that kept the old password"); assert.ok(twinBlock.includes("may still accept the previous password"), "the 500 must warn that local connections may still accept the old password"); assert.ok(twinBlock.includes("Retry the password change"), "the 500 must tell the admin how to recover"); // Ordered bookkeeping: the honest-failure return must precede the // updatedAt assignment / saveDatabaseConfig / success response, so a // partially-failed rotation is never recorded as done. const updatedAtIdx = routeBody.indexOf("data.users[userIndex].updatedAt"); assert.ok(updatedAtIdx !== -1, "success-path updatedAt bookkeeping must still exist"); const honestReturnIdx = routeBody.indexOf("was updated, but the matching"); assert.ok(honestReturnIdx !== -1 && honestReturnIdx < updatedAtIdx, "the honest-failure 500 must be returned before updatedAt is recorded"); assert.ok(routeBody.indexOf("saveDatabaseConfig(data)") > updatedAtIdx, "the config save must stay after the updatedAt bookkeeping on the success path"); }); test("twin rotation: a missing localhost twin (ER_NO_SUCH_USER 1396) is skipped, not failed", () => { // The detection must mirror the signature updateMySqlUserPassword itself // matches at its '%' fallback. const updBody = stripComments(extractFunction("updateMySqlUserPassword")); assert.ok(updBody.includes("1396") && updBody.includes("Operation ALTER USER failed"), "updateMySqlUserPassword must detect ER_NO_SUCH_USER via 1396 / Operation ALTER USER failed"); assert.ok(twinBlock.includes("1396"), "the twin-sync block must recognize the 1396 ER_NO_SUCH_USER signature"); assert.ok(twinBlock.includes("Operation ALTER USER failed"), "the twin-sync block must recognize the 'Operation ALTER USER failed' signature"); // The detection must precede and gate the honest-failure return: a twin // that does not exist is nothing to sync and must not fail the request. const detectionIdx = twinBlock.indexOf("1396"); const guardIdx = twinBlock.indexOf("!noSuchTwin"); const honestIdx = twinBlock.indexOf("res.status(500).json"); assert.ok(detectionIdx !== -1 && guardIdx !== -1 && honestIdx !== -1, "no-such-twin guard not found in the twin-sync block"); assert.ok(detectionIdx < guardIdx && guardIdx < honestIdx, "the no-such-twin detection must precede and gate the honest-failure return"); assert.ok(twinBlock.includes("account to sync for setup-created entry (skipped)"), "a missing twin is logged as skipped, not treated as a failure"); }); test("twin rotation: warn-and-continue is gone", () => { assert.ok(!routeBody.includes("Could not update password for"), "the old best-effort console.warn must not remain in the route"); // The twin outcome is captured — including a thrown error — and decides // the request's outcome instead of being fire-and-forget. assert.ok(twinBlock.includes("let localhostResult;"), "the twin outcome must be captured, not fire-and-forget"); assert.ok(twinBlock.includes("localhostResult = { ok: false, error:"), "a thrown twin-sync error must be captured into that outcome"); }); test("twin rotation: the ordinary paths are unchanged", () => { assert.ok(routeBody.includes("Password updated successfully in ${dbName}"), "the success response must be intact"); assert.ok(routeBody.includes("hasOwnProperty.call(data.users[userIndex], 'host')"), "the twin sync must stay limited to setup-created entries without a stored host"); assert.ok(twinBlock.includes("updateMySqlUserPassword(entryUsername, password, 'localhost')"), "the localhost twin update call itself is unchanged"); assert.ok(routeBody.includes("updateMySqlUserPassword(entryUsername, password, userHost)"), "the primary update is unchanged"); assert.ok(routeBody.includes("Failed to update ${dbName} password:"), "the primary-update failure path is unchanged"); assert.ok(routeBody.includes("updatePostgresUserPassword(entryUsername, password)"), "the PostgreSQL branch is unchanged"); assert.ok(routeBody.includes("updateMongoUserPassword(entryUsername, password)"), "the MongoDB branch is unchanged"); });