283 lines
15 KiB
JavaScript
283 lines
15 KiB
JavaScript
"use strict";
|
|
|
|
// Tests for the engine-teardown step-up gates (change-type / disable /
|
|
// mongodb disable).
|
|
//
|
|
// POST /api/settings/database/setup, /pgadmin/setup, /pgadmin/disable,
|
|
// /mongodb/setup and /verify-install all required the destructive-action
|
|
// step-up (fresh current password or TOTP, or a live grace grant minted by an
|
|
// earlier verification), but the most destructive operations in the same tab
|
|
// did not:
|
|
// - POST /api/settings/database/change-type DROPS every previous engine
|
|
// account (dropRemovedDbAccounts, setup administrator included) before
|
|
// repointing the panel;
|
|
// - POST /api/settings/database/disable drops every bookkept account and
|
|
// then erases the panel's ONLY record of them;
|
|
// - POST /api/settings/database/mongodb/disable purges packages, the data
|
|
// directory and firewall rules.
|
|
// With only the admin session + one-time action token (both harvestable from
|
|
// a single GET /api/settings/database response), a hijacked admin session —
|
|
// stolen cookie or XSS, the exact threat the step-up exists to stop — could
|
|
// mass-destroy all database accounts with zero re-auth, while a LESS
|
|
// destructive sibling (/setup) still demanded a fresh credential.
|
|
//
|
|
// Remediation contract locked here:
|
|
// - Each of the three routes mounts sessionRevoke2faRateLimiter (the
|
|
// credential-bearing step-up budget; non-credential requests are skipped
|
|
// by its own skip rules, so grace-authorized calls are never counted).
|
|
// - Each loads the acting user (findUserByEmail) and re-checks admin, then
|
|
// runs requireDatabaseInstallStepUp AFTER requireActionTokenOr403 (same
|
|
// ordering as /setup and /pgadmin/disable: a failed verification must
|
|
// not leave the request half-authorized — the client recovers a burned
|
|
// one-time token via its token-retry re-mint) and BEFORE the operation
|
|
// mutex (a rejected request must never occupy the lock).
|
|
// - The pre-token 400/409 guards keep their positions BEFORE the token
|
|
// gate, so a step-up challenge or an orphan confirmation never burns
|
|
// the one-time action token (locked by db-switch-strict-validation and
|
|
// db-disable-revoke-before-wipe; re-asserted here for change-type's
|
|
// orphan guard).
|
|
// - Client: saveDbTypeChange, togglePhpmyadmin's disable branch and
|
|
// disableMongoDB mint the grace grant BEFORE the destructive request via
|
|
// the shared install-verification modal (confirmDatabaseInstallBeforeSetup),
|
|
// mirroring disablePgAdmin — so the normal flow is challenged once and
|
|
// the request itself rides the live grant.
|
|
//
|
|
// 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 full-line // comments FIRST, then block comments, so prose cannot
|
|
// satisfy or violate assertions (same approach as
|
|
// tests/db-switch-strict-validation.test.js). The order matters for the
|
|
// mongodb/disable slice: its lock comment contains the prose "/mongodb/*",
|
|
// and block-comment-first stripping would treat that "/*" as an opener and
|
|
// swallow the code that follows it.
|
|
function stripComments(src) {
|
|
return src
|
|
.replace(/^[ \t]*\/\/.*$/gm, "")
|
|
.replace(/\/\*[\s\S]*?\*\//g, "");
|
|
}
|
|
|
|
// Slice a route registration to the NEXT app.* registration so family checks
|
|
// only ever see the route's own body (several of these handlers are far too
|
|
// long for a fixed character window).
|
|
function routeSliceOf(source, marker) {
|
|
const start = source.indexOf(marker);
|
|
assert.ok(start >= 0, `route marker not found: ${marker}`);
|
|
let end = source.length;
|
|
for (const kind of ["app.post(", "app.delete(", "app.get(", "app.put("]) {
|
|
const at = source.indexOf(kind, start + marker.length);
|
|
if (at >= 0 && at < end) end = at;
|
|
}
|
|
return source.slice(start, end);
|
|
}
|
|
|
|
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 changeTypeRoute = stripComments(extractRoute(
|
|
indexSource,
|
|
'app.post("/api/settings/database/change-type"',
|
|
'app.post("/api/settings/database/pgadmin/setup"'
|
|
));
|
|
const disableRoute = stripComments(extractRoute(
|
|
indexSource,
|
|
'app.post("/api/settings/database/disable"',
|
|
'app.post("/api/settings/database/users"'
|
|
));
|
|
const mongoDisableRoute = stripComments(extractRoute(
|
|
indexSource,
|
|
'app.post("/api/settings/database/mongodb/disable"',
|
|
'app.post("/api/settings/database/mongodb/users"'
|
|
));
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// 1. Route signature: the credential-bearing step-up limiter is mounted
|
|
// ---------------------------------------------------------------------------
|
|
|
|
function assertLimiterMounted(route, label) {
|
|
assert.match(
|
|
route,
|
|
new RegExp(`app\\.post\\("[^"]*", sessionRevoke2faRateLimiter, async \\(req, res\\) => \\{`),
|
|
`${label} must mount sessionRevoke2faRateLimiter — the per-session and per-account step-up budgets are what stop a hijacked session from brute-forcing the verification`
|
|
);
|
|
}
|
|
|
|
test("change-type: sessionRevoke2faRateLimiter is mounted", () => {
|
|
assertLimiterMounted(changeTypeRoute, "change-type");
|
|
});
|
|
|
|
test("disable: sessionRevoke2faRateLimiter is mounted", () => {
|
|
assertLimiterMounted(disableRoute, "disable");
|
|
});
|
|
|
|
test("mongodb disable: sessionRevoke2faRateLimiter is mounted", () => {
|
|
assertLimiterMounted(mongoDisableRoute, "mongodb disable");
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// 2. Gate ordering: admin re-check -> action token -> step-up -> mutex
|
|
// ---------------------------------------------------------------------------
|
|
|
|
function assertStepUpGateOrder(route, label, opts = {}) {
|
|
const adminIdx = route.indexOf("if (!(await isAdmin(req)))");
|
|
const userIdx = route.indexOf("const currentUser = await findUserByEmail(req.session.user);");
|
|
const adminRecheckIdx = route.indexOf("if (!currentUser || !currentUser.admin)");
|
|
const tokenGate = String(opts.tokenGate || "");
|
|
const tokenIdx = route.indexOf(`requireActionTokenOr403(req, res, "${tokenGate}")`);
|
|
const stepUpIdx = route.indexOf("requireDatabaseInstallStepUp(req, res, currentUser");
|
|
const mutexIdx = route.indexOf(opts.mutexMarker);
|
|
const okReturnIdx = route.indexOf("if (!stepUp.ok) return;", stepUpIdx);
|
|
|
|
assert.ok(userIdx > adminIdx, `${label} must load the acting user after the session admin check`);
|
|
assert.ok(adminRecheckIdx > userIdx, `${label} must re-check admin on the DB user record (session flag alone is not the truth)`);
|
|
assert.ok(tokenIdx > 0, `${label} must gate on its one-time action token`);
|
|
assert.ok(stepUpIdx > tokenIdx,
|
|
`${label} step-up must come AFTER the token gate (same ordering as /setup and /pgadmin/disable: a failed verification must not leave the request half-authorized; the client re-mints a burned token on retry)`);
|
|
assert.ok(okReturnIdx > stepUpIdx && okReturnIdx < mutexIdx,
|
|
`${label} must fail closed BETWEEN the step-up call and the mutex — a rejected request must never occupy the operation lock`);
|
|
|
|
// The step-up must run on the freshly loaded user record and carry a
|
|
// specific subject (it lands in the security log line and the grace
|
|
// consumption log).
|
|
const stepUpCall = route.slice(stepUpIdx, okReturnIdx);
|
|
assert.match(stepUpCall, /requireDatabaseInstallStepUp\(req, res, currentUser, "[^"]+"\)/,
|
|
`${label} must pass a subject string for the audit log`);
|
|
assert.ok(route.includes("if (!stepUp.ok) return;"),
|
|
`${label} must fail closed when the step-up is not satisfied`);
|
|
}
|
|
|
|
test("change-type: admin re-check, token gate, step-up, then the config mutex", () => {
|
|
assertStepUpGateOrder(changeTypeRoute, "change-type", {
|
|
tokenGate: "POST /api/settings/database/change-type",
|
|
mutexMarker: "dbConfigOperationMutex.tryAcquire()",
|
|
});
|
|
assert.match(changeTypeRoute, /requireDatabaseInstallStepUp\(req, res, currentUser, "phpMyAdmin database type change"\)/,
|
|
"change-type must log under the database-type-change subject");
|
|
});
|
|
|
|
test("disable: admin re-check, token gate, step-up, then the config mutex", () => {
|
|
assertStepUpGateOrder(disableRoute, "disable", {
|
|
tokenGate: "POST /api/settings/database/disable",
|
|
mutexMarker: "dbConfigOperationMutex.tryAcquire()",
|
|
});
|
|
assert.match(disableRoute, /requireDatabaseInstallStepUp\(req, res, currentUser, "phpMyAdmin disable"\)/,
|
|
"disable must log under the phpMyAdmin-disable subject (mirrors pgAdmin4 disable)");
|
|
});
|
|
|
|
test("mongodb disable: admin re-check, token gate, step-up, then the mongo mutex", () => {
|
|
assertStepUpGateOrder(mongoDisableRoute, "mongodb disable", {
|
|
tokenGate: "POST /api/settings/database/mongodb/disable",
|
|
mutexMarker: "mongodbOperationMutex.tryAcquire()",
|
|
});
|
|
assert.match(mongoDisableRoute, /requireDatabaseInstallStepUp\(req, res, currentUser, "MongoDB disable"\)/,
|
|
"mongodb disable must log under the MongoDB-disable subject (mirrors pgAdmin4 disable)");
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// 3. Pre-token guards keep their positions (no token burn on 400/409/challenge)
|
|
// ---------------------------------------------------------------------------
|
|
|
|
test("change-type: the orphan 409 and binary 400 still precede the token gate, so confirmOrphan retries never burn the token", () => {
|
|
const orphanIdx = changeTypeRoute.indexOf("REMOTE_DROP_CONFIRMATION_REQUIRED");
|
|
const binaryIdx = changeTypeRoute.indexOf("DB_CLIENT_BINARY_MISSING");
|
|
const tokenIdx = changeTypeRoute.indexOf('requireActionTokenOr403(req, res, "POST /api/settings/database/change-type")');
|
|
const stepUpIdx = changeTypeRoute.indexOf("requireDatabaseInstallStepUp(req, res, currentUser");
|
|
|
|
assert.ok(orphanIdx > 0 && orphanIdx < tokenIdx, "the orphan guard must stay pre-token");
|
|
assert.ok(binaryIdx > 0 && binaryIdx < tokenIdx, "the binary guard must stay pre-token");
|
|
assert.ok(stepUpIdx > tokenIdx, "the step-up gate sits after the token gate — its 403 challenge may burn the token, which is exactly what the client's token-retry re-mint recovers");
|
|
});
|
|
|
|
test("disable: the orphan 409 still precedes the token gate", () => {
|
|
const orphanIdx = disableRoute.indexOf("REMOTE_DROP_CONFIRMATION_REQUIRED");
|
|
const tokenIdx = disableRoute.indexOf('requireActionTokenOr403(req, res, "POST /api/settings/database/disable")');
|
|
assert.ok(orphanIdx > 0 && orphanIdx < tokenIdx, "the orphan guard must stay pre-token");
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// 4. The whole destructive route family is now step-up covered
|
|
// ---------------------------------------------------------------------------
|
|
|
|
test("every destructive /api/settings/database route family member requires the install step-up", () => {
|
|
const family = [
|
|
"verify-install",
|
|
"setup",
|
|
"disable",
|
|
"change-type",
|
|
"pgadmin/setup",
|
|
"pgadmin/disable",
|
|
"mongodb/setup",
|
|
"mongodb/disable",
|
|
];
|
|
for (const route of family) {
|
|
const slice = stripComments(routeSliceOf(indexSource, `app.post("/api/settings/database/${route}"`));
|
|
const hasGate = slice.includes("requireDatabaseInstallStepUp(req, res, currentUser") ||
|
|
slice.includes("requireDestructiveActionStepUp(req, res, currentUser");
|
|
assert.ok(hasGate, `${route} must require a destructive-action step-up`);
|
|
const limiter = slice.includes("sessionRevoke2faRateLimiter");
|
|
assert.ok(limiter, `${route} must mount sessionRevoke2faRateLimiter`);
|
|
}
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// 5. Client contract: the grace grant is minted BEFORE the destructive request
|
|
// ---------------------------------------------------------------------------
|
|
|
|
test("settings.js: saveDbTypeChange verifies through the shared modal before POSTing change-type", () => {
|
|
const fnStart = settingsSource.indexOf("async function saveDbTypeChange(confirmOrphan)");
|
|
assert.ok(fnStart > 0, "saveDbTypeChange must exist");
|
|
const fnEnd = settingsSource.indexOf("async function togglePhpmyadmin(", fnStart);
|
|
assert.ok(fnEnd > fnStart, "could not bound saveDbTypeChange body");
|
|
const fn = stripComments(settingsSource.slice(fnStart, fnEnd));
|
|
|
|
const verifyIdx = fn.indexOf("window.confirmDatabaseInstallBeforeSetup('phpmyadmin')");
|
|
const fetchIdx = fn.indexOf("fetch('/api/settings/database/change-type'");
|
|
assert.ok(verifyIdx > 0, "saveDbTypeChange must mint the grace grant via confirmDatabaseInstallBeforeSetup");
|
|
assert.ok(fetchIdx > verifyIdx, "the change-type POST must come after the verification");
|
|
assert.match(fn, /if \(!verified\) return;/, "a cancelled verification must abort the change");
|
|
});
|
|
|
|
test("settings.js: togglePhpmyadmin's disable branch verifies before POSTing disable and restores the toggle on cancel", () => {
|
|
const fnStart = settingsSource.indexOf("async function togglePhpmyadmin(enabled, confirmOrphan)");
|
|
assert.ok(fnStart > 0, "togglePhpmyadmin must exist");
|
|
const fnEnd = settingsSource.indexOf("phpmyadminToggle.addEventListener('change'", fnStart);
|
|
assert.ok(fnEnd > fnStart, "could not bound togglePhpmyadmin body");
|
|
const fn = stripComments(settingsSource.slice(fnStart, fnEnd));
|
|
|
|
const verifyIdx = fn.indexOf("window.confirmDatabaseInstallBeforeSetup('phpmyadmin')");
|
|
const fetchIdx = fn.indexOf("fetch('/api/settings/database/disable'");
|
|
assert.ok(verifyIdx > 0, "the disable branch must mint the grace grant via confirmDatabaseInstallBeforeSetup");
|
|
assert.ok(fetchIdx > verifyIdx, "the disable POST must come after the verification");
|
|
assert.match(fn, /if \(!verified\) \{\s*if \(phpmyadminToggle\) phpmyadminToggle\.checked = true;\s*return;\s*\}/,
|
|
"a cancelled verification must restore the toggle and abort");
|
|
});
|
|
|
|
test("settings.js: disableMongoDB verifies before POSTing mongodb/disable (disablePgAdmin parity)", () => {
|
|
const fnStart = settingsSource.indexOf("async function disableMongoDB()");
|
|
assert.ok(fnStart > 0, "disableMongoDB must exist");
|
|
const fnEnd = settingsSource.indexOf("mongodbToggle.addEventListener('change'", fnStart);
|
|
assert.ok(fnEnd > fnStart, "could not bound disableMongoDB body");
|
|
const fn = stripComments(settingsSource.slice(fnStart, fnEnd));
|
|
|
|
const verifyIdx = fn.indexOf("window.confirmDatabaseInstallBeforeSetup('mongodb')");
|
|
const fetchIdx = fn.indexOf("fetch('/api/settings/database/mongodb/disable'");
|
|
assert.ok(verifyIdx > 0, "disableMongoDB must mint the grace grant via confirmDatabaseInstallBeforeSetup");
|
|
assert.ok(fetchIdx > verifyIdx, "the mongodb/disable POST must come after the verification");
|
|
assert.match(fn, /if \(!verified\) \{\s*if \(mongodbToggle\) mongodbToggle\.checked = true;\s*return;\s*\}/,
|
|
"a cancelled verification must restore the toggle and abort");
|
|
});
|