188 lines
11 KiB
JavaScript
188 lines
11 KiB
JavaScript
"use strict";
|
|
|
|
// Tests for the phpMyAdmin/database disable orphan remediation.
|
|
//
|
|
// POST /api/settings/database/disable used to write
|
|
// { enabled: false, config: null, users: [] } while only blocking the
|
|
// phpMyAdmin web UI — the panel-provisioned MySQL/PostgreSQL/MongoDB accounts
|
|
// themselves were never dropped. The users array is the panel's ONLY record
|
|
// of which accounts it provisioned, so the wipe left live, password-known,
|
|
// remotely reachable accounts (a setup-created entry owns BOTH 'user'@'%'
|
|
// and 'user'@'localhost') that the panel could never list or revoke again:
|
|
// the exact bug class the drop-outcome taxonomy (dropRemovedDbAccounts /
|
|
// classifyDbDropResult) exists to prevent, violating its stated invariant.
|
|
//
|
|
// Remediation contract locked here:
|
|
// - PRE-TOKEN 409 guard: when the configured engine's host is remote, the
|
|
// strictly-local drop tooling cannot revoke anything, so disable refuses
|
|
// with REMOTE_DROP_CONFIRMATION_REQUIRED until the admin re-submits with
|
|
// confirmOrphan: true (mirrors setup / change-type / delete-user; the 409
|
|
// must never burn the one-time action token).
|
|
// - Drop-before-wipe ordering: disablePhpMyAdminWebServer() first (fail
|
|
// closed on web access), then dropRemovedDbAccounts(currentData,
|
|
// currentData.users) — ALL bookkept accounts including the setup
|
|
// administrator, the same deliberate teardown allowance as /setup and
|
|
// /change-type — and ONLY then the bookkeeping wipe. A failed LOCAL drop
|
|
// aborts with 500 BEFORE saveDatabaseConfig, so every account stays
|
|
// listed and retryable (absent-idempotent drops make retries converge).
|
|
// - Confirmed remote orphans ride back as a warnings array on the success
|
|
// response, mirroring setup/change-type.
|
|
// - Client: togglePhpmyadmin sends confirmOrphan, branches on the 409 code
|
|
// with a recursive re-send, and surfaces data.warnings.
|
|
//
|
|
// index.js boots servers on require, so the contract is asserted at source
|
|
// level (same technique as tests/db-switch-strict-validation.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");
|
|
const settingsSource = fs.readFileSync(path.join(ROOT, "public", "js", "settings.js"), "utf8");
|
|
|
|
// Strip block comments and full-line // comments so prose cannot satisfy or
|
|
// violate assertions (same approach as tests/db-switch-strict-validation.test.js).
|
|
function stripComments(src) {
|
|
return src
|
|
.replace(/\/\*[\s\S]*?\*\//g, "")
|
|
.replace(/^[ \t]*\/\/.*$/gm, "");
|
|
}
|
|
|
|
function extractRoute(source, routeMarker, nextRouteMarker) {
|
|
const start = source.indexOf(routeMarker);
|
|
assert.ok(start >= 0, `route marker not found: ${routeMarker}`);
|
|
const end = source.indexOf(nextRouteMarker, start);
|
|
assert.ok(end > start, `next route marker not found after route: ${nextRouteMarker}`);
|
|
return source.slice(start, end);
|
|
}
|
|
|
|
const disableRoute = stripComments(extractRoute(
|
|
indexSource,
|
|
'app.post("/api/settings/database/disable"',
|
|
'app.post("/api/settings/database/users"'
|
|
));
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// 1. Pre-token remote-orphan confirmation guard
|
|
// ---------------------------------------------------------------------------
|
|
|
|
test("disable: remote-host disable requires confirmOrphan via a 409 that precedes the token gate", () => {
|
|
const guardIdx = disableRoute.indexOf("preDisableRemoteOrphans");
|
|
const codeIdx = disableRoute.indexOf('code: "REMOTE_DROP_CONFIRMATION_REQUIRED"');
|
|
const tokenIdx = disableRoute.indexOf('requireActionTokenOr403(req, res, "POST /api/settings/database/disable")');
|
|
|
|
assert.ok(guardIdx > 0, "disable must compute the remote-orphan list pre-token");
|
|
assert.ok(codeIdx > guardIdx, "the guard must answer 409 with REMOTE_DROP_CONFIRMATION_REQUIRED");
|
|
assert.ok(tokenIdx > guardIdx,
|
|
"the orphan guard must run BEFORE requireActionTokenOr403 so the 409 cannot burn the one-time action token");
|
|
assert.match(disableRoute, /res\.status\(409\)\.json\(/,
|
|
"the guard must answer 409, not a plain 400/500");
|
|
|
|
// The guard must reuse the drop taxonomy (not re-derive its own host logic)
|
|
// and only fire when there is something that can actually be orphaned.
|
|
assert.ok(disableRoute.includes("DB_DROP_CAPABLE_TYPES.includes(preDisableData.config?.type)"),
|
|
"the guard must key off DB_DROP_CAPABLE_TYPES");
|
|
assert.ok(disableRoute.includes("!isLocalDbConfigHost(preDisableData.config?.host)"),
|
|
"the guard must only fire for remote (non-local) configured hosts");
|
|
assert.match(disableRoute, /preDisableRemoteOrphans\.length > 0 && req\.body\?\.confirmOrphan !== true/,
|
|
"a remote host with zero bookkept users needs no confirmation");
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// 2. Drop-before-wipe ordering (the orphan invariant itself)
|
|
// ---------------------------------------------------------------------------
|
|
|
|
test("disable: all bookkept accounts are dropped AFTER the web UI is blocked and BEFORE bookkeeping is wiped", () => {
|
|
const webIdx = disableRoute.indexOf("disablePhpMyAdminWebServer()");
|
|
const dropIdx = disableRoute.indexOf("dropRemovedDbAccounts(currentData, currentData.users)");
|
|
const wipeIdx = disableRoute.indexOf("users: [], disabledAt: Date.now()");
|
|
const saveIdx = disableRoute.indexOf("saveDatabaseConfig(data)");
|
|
|
|
assert.ok(webIdx > 0, "disable must still block the phpMyAdmin web server");
|
|
assert.ok(dropIdx > webIdx, "the account drop must run after the web server is blocked");
|
|
assert.ok(wipeIdx > dropIdx,
|
|
"the users:[] wipe must come AFTER the drop — wiping first is the orphan bug");
|
|
assert.ok(saveIdx > wipeIdx, "the wipe must be persisted after the drop succeeded");
|
|
|
|
// dropRemovedDbAccounts receives the FULL users array: the setup
|
|
// administrator is dropped deliberately on teardown (same allowance as
|
|
// /setup and /change-type). A filtered subset here would leave the admin
|
|
// (and its 'user'@'%' variant) live and untracked.
|
|
assert.ok(disableRoute.includes("dropRemovedDbAccounts(currentData, currentData.users)"),
|
|
"the drop must cover every bookkept account, not a filtered subset");
|
|
});
|
|
|
|
test("disable: a failed local drop aborts with 500 BEFORE the wipe, keeping every account listed and retryable", () => {
|
|
const dropIdx = disableRoute.indexOf("dropRemovedDbAccounts(currentData, currentData.users)");
|
|
const failureIdx = disableRoute.indexOf("dropOutcome.failures.length > 0");
|
|
const failureReturnIdx = disableRoute.indexOf("return res.status(500).json({ error: `Disable aborted: could not drop");
|
|
const wipeIdx = disableRoute.indexOf("users: [], disabledAt: Date.now()");
|
|
|
|
assert.ok(failureIdx > dropIdx, "the drop outcome must be classified after dropRemovedDbAccounts returns");
|
|
assert.ok(failureReturnIdx > failureIdx, "a failed drop must answer 500 with an explicit abort error");
|
|
assert.ok(failureReturnIdx < wipeIdx,
|
|
"the abort return must precede the bookkeeping wipe — erasing entries on failure orphans the credential unrevokably");
|
|
|
|
// Post-mutex snapshot: the drop decisions must key off a fresh authoritative
|
|
// read taken inside the lock, never the pre-token read (which only shapes
|
|
// the fast 409 and can be stale).
|
|
const snapshotIdx = disableRoute.indexOf("const currentData = loadDatabaseConfig({ fresh: true });");
|
|
assert.ok(snapshotIdx > 0 && snapshotIdx > disableRoute.indexOf('requireActionTokenOr403(req, res, "POST /api/settings/database/disable")'),
|
|
"the authoritative config read must happen after the token gate (under the mutex)");
|
|
assert.ok(dropIdx > snapshotIdx, "the drop must consume the post-mutex snapshot");
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// 3. Confirmed remote orphans surface as warnings, wipe still converges
|
|
// ---------------------------------------------------------------------------
|
|
|
|
test("disable: confirmed remote orphans ride back as a warnings array on the success response", () => {
|
|
const warningsIdx = disableRoute.indexOf("disableDropWarnings = dropOutcome.warnings;");
|
|
const responseIdx = disableRoute.indexOf("warnings: disableDropWarnings");
|
|
|
|
assert.ok(warningsIdx > 0, "the drop warnings must be captured");
|
|
assert.ok(responseIdx > warningsIdx,
|
|
"the success response must carry the warnings so the admin learns which accounts stay live on the remote server");
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// 4. Helper ordering: dropRemovedDbAccounts is defined before the route uses it
|
|
// ---------------------------------------------------------------------------
|
|
|
|
test("dropRemovedDbAccounts is declared before the disable route consumes it", () => {
|
|
const helperAt = indexSource.indexOf("async function dropRemovedDbAccounts(");
|
|
const routeAt = indexSource.indexOf('app.post("/api/settings/database/disable"');
|
|
assert.ok(helperAt >= 0 && helperAt < routeAt,
|
|
"the teardown helper must be defined before the disable route");
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// 5. Client contract: confirmOrphan round-trip and warning surfacing
|
|
// ---------------------------------------------------------------------------
|
|
|
|
test("settings.js: the disable toggle sends confirmOrphan, re-sends after the 409, and surfaces warnings", () => {
|
|
const fnStart = settingsSource.indexOf("async function togglePhpmyadmin(enabled, confirmOrphan)");
|
|
assert.ok(fnStart > 0, "togglePhpmyadmin must thread a confirmOrphan parameter");
|
|
const fnEnd = settingsSource.indexOf("phpmyadminToggle.addEventListener('change'", fnStart);
|
|
assert.ok(fnEnd > fnStart, "could not bound togglePhpmyadmin body");
|
|
const fn = stripComments(settingsSource.slice(fnStart, fnEnd));
|
|
|
|
assert.ok(fn.includes("body: JSON.stringify({ confirmOrphan: confirmOrphan === true })"),
|
|
"the disable request must carry confirmOrphan in a JSON body");
|
|
assert.ok(fn.includes("'Content-Type': 'application/json'"),
|
|
"the disable request must declare its JSON content type");
|
|
|
|
assert.match(fn,
|
|
/res\.status === 409 && data\.code === 'REMOTE_DROP_CONFIRMATION_REQUIRED' && confirmOrphan !== true/,
|
|
"the client must branch on the 409 orphan-confirmation code");
|
|
assert.ok(fn.includes("return await togglePhpmyadmin(false, true);"),
|
|
"confirming must re-send with confirmOrphan: true");
|
|
|
|
assert.ok(fn.includes("Array.isArray(data.warnings) ? data.warnings : []"),
|
|
"the client must read the warnings array");
|
|
assert.ok(fn.includes("progress.finish(true, doneMessage);"),
|
|
"the computed message must actually be surfaced through progress.finish, not computed and dropped");
|
|
});
|