Files
Kelx/tests/db-mysql-scoping.test.js
2026-11-30 16:32:37 +00:00

375 lines
21 KiB
JavaScript

"use strict";
// Tests for audit finding H1: panel-issued MySQL users held DML/DDL
// privilege schema-wide (ON *.*), which included the panel's own database —
// mysql-schema.sql stores users.password hashes, 2FA secrets,
// recovery_codes and node tokens there — so every panel-created user could
// read, rewrite or drop the panel's accounts. The comment that used to
// claim isolation via phpMyAdmin "hide_db + AllowDeny rules" was also
// wrong: configurePhpMyAdmin only ever writes hide_db (a cosmetic UI
// filter) and no AllowDeny rules exist anywhere.
//
// Remediation contract locked here:
// - The grant lives in utils/db-user-privileges.js (pure, fail-closed
// builders): with @@partial_revokes=ON (MySQL >= 8) a global DML/DDL
// grant plus REVOKE ALL on the panel database, mysql and sys; on
// MariaDB / MySQL 5.7 / partial_revokes OFF, per-database grants over
// every existing non-protected database only.
// - index.js createMySqlUser picks the strategy via _detectMySqlFlavor
// (SELECT VERSION() + @@global.partial_revokes through the admin
// channel) and enumerates databases via SHOW DATABASES. Detection or
// enumeration failure grants over whatever was enumerated (possibly
// nothing) — never a fallback to a schema-wide grant.
// - runMySqlAdmin resolves include the client's stdout on every channel;
// the probes depend on it.
//
// index.js boots servers on require, so the index-side contract is asserted
// at source level (same technique as tests/argv-secret-exposure.test.js)
// while the builders are exercised directly.
const test = require("node:test");
const assert = require("node:assert");
const fs = require("node:fs");
const path = require("node:path");
const vm = require("node:vm");
const ROOT = path.join(__dirname, "..");
const priv = require(path.join(ROOT, "utils", "db-user-privileges"));
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 scripts/verify-db-user-privileges.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 ADMIN_PRIVILEGES = [
"SUPER", "FILE", "PROCESS", "RELOAD", "SHUTDOWN", "GRANT OPTION",
"CREATE USER", "REPLICATION", "CREATE ROLE", "DROP ROLE",
];
test("H1: MySQL builders fail closed on invalid input", () => {
for (const bad of ["", null, undefined, 42, "a b", "a'b", "a`b", "a;b", "a\\b", "$(id)", "x".repeat(65)]) {
assert.strictEqual(priv.buildMySqlGlobalGrantSql(bad, "%", "adpanel"), null, `user ${JSON.stringify(bad)}`);
assert.strictEqual(priv.buildMySqlPerDatabaseGrantsSql(bad, "%", ["web"], "adpanel"), null, `user ${JSON.stringify(bad)}`);
assert.strictEqual(priv.buildMySqlGlobalGrantSql("alice", "%", bad), null, `db ${JSON.stringify(bad)}`);
}
for (const badHost of ["", "a b", "a;b", "a'b", "a`b", "x".repeat(256)]) {
assert.strictEqual(priv.buildMySqlGlobalGrantSql("alice", badHost, "adpanel"), null, `host ${JSON.stringify(badHost)}`);
}
assert.strictEqual(priv.buildMySqlPerDatabaseGrantsSql("alice", "%", "not-an-array", "adpanel"), null);
});
test("H1: protected set covers the panel DB case-insensitively and the four system schemas", () => {
for (const sys of ["mysql", "sys", "information_schema", "performance_schema"]) {
assert.ok(priv.isProtectedMySQLDatabase(sys, "adpanel"), sys);
assert.ok(priv.isProtectedMySQLDatabase(sys.toUpperCase(), "adpanel"), sys);
}
assert.ok(priv.isProtectedMySQLDatabase("adpanel", "adpanel"));
assert.ok(priv.isProtectedMySQLDatabase("ADPANEL", "adpanel"));
assert.ok(priv.isProtectedMySQLDatabase("adpanel", "ADPanel"));
assert.ok(!priv.isProtectedMySQLDatabase("customer_app", "adpanel"));
});
test("H1: per-database SQL backtick-quotes identifiers, excludes protected DBs, never grants schema-wide", () => {
const privs = priv.MYSQL_PANEL_USER_PRIVILEGES.join(", ");
const sql = priv.buildMySqlPerDatabaseGrantsSql(
"alice", "localhost",
["web1", "adpanel", "ADPANEL", "mysql", "sys", "information_schema", "performance_schema", "web1", "blog-2"],
"adpanel"
);
assert.deepStrictEqual(sql.split("\n"), [
`GRANT ${privs} ON \`web1\`.* TO 'alice'@'localhost';`,
`GRANT ${privs} ON \`blog-2\`.* TO 'alice'@'localhost';`,
]);
assert.ok(!/ON\s+\*\.\*/.test(sql), "per-database strategy must never grant schema-wide");
// An empty enumeration is the fail-closed outcome, not an error.
assert.strictEqual(priv.buildMySqlPerDatabaseGrantsSql("alice", "%", [], "adpanel"), "");
});
test("H1: global-grant SQL grants the exact panel privilege list and fences panel/phpmyadmin/mysql/sys per privilege", () => {
const privs = priv.MYSQL_PANEL_USER_PRIVILEGES.join(", ");
const sql = priv.buildMySqlGlobalGrantSql("alice", "%", "adpanel");
const lines = sql.split("\n");
// The global grant, then per-privilege REVOKEs over each fenced schema.
// A blanket `REVOKE ALL PRIVILEGES ON db.*` fails with ER_NONEXISTING_GRANT
// (1141) under partial_revokes=ON for privileges the fresh account does not
// hold, aborting the batch AFTER the global grant ran — an unfenced account
// was left live; per-privilege revokes restrict exactly what it holds.
assert.strictEqual(lines[0], `GRANT ${privs} ON *.* TO 'alice'@'%';`);
const fenced = ["adpanel", "mysql", "sys", "phpmyadmin"];
const expected = [];
for (const schema of fenced) {
for (const p of priv.MYSQL_PANEL_USER_PRIVILEGES) {
expected.push(`REVOKE ${p} ON \`${schema}\`.* FROM 'alice'@'%';`);
}
}
assert.deepStrictEqual(lines.slice(1), expected);
for (const adminPriv of ADMIN_PRIVILEGES) {
assert.ok(!privs.includes(adminPriv), `panel privilege list must not include ${adminPriv}`);
}
});
test("H1: index.js createMySqlUser no longer issues schema-wide grants itself", () => {
const body = stripComments(extractFunction("createMySqlUser"));
assert.ok(body.includes("_buildMySqlGrantSection"), "grant-strategy selection must live in the shared helper createMySqlUser delegates to");
assert.ok(!/ON\s+\*\.\*/.test(body), "createMySqlUser must not emit a schema-wide grant — the grant lives in utils");
assert.ok(!/GRANT SELECT/.test(body), "no inline privilege-list GRANT may remain");
// The helper createMySqlUser delegates to carries the actual scoping
// contract, so it is pinned with the same rigor:
const grantBody = stripComments(extractFunction("_buildMySqlGrantSection"));
assert.ok(grantBody.includes("buildMySqlGlobalGrantSql"), "must use the shared builder for MySQL >= 8 with partial revokes");
assert.ok(grantBody.includes("buildMySqlPerDatabaseGrantsSql"), "must use the shared per-database builder");
assert.ok(grantBody.includes("_detectMySqlFlavor"), "grant strategy must be picked by server flavor");
assert.ok(grantBody.includes("listMySqlDatabases"), "per-database strategy must enumerate existing databases");
assert.ok(!/ON\s+\*\.\*/.test(grantBody), "no schema-wide grant outside utils — the grant lives in utils");
assert.ok(!/GRANT SELECT/.test(grantBody), "no inline privilege-list GRANT may remain");
assert.ok(grantBody.includes("databases === null"), "enumeration failure must be handled fail-closed");
});
test("H1: runMySqlAdmin resolves include the client's stdout on every channel", () => {
const body = stripComments(extractFunction("runMySqlAdmin"));
assert.strictEqual((body.match(/resolve\(\{ ok: true, stdout \}\)/g) || []).length, 3,
"privileged runner, direct client and skip-grant fallback must all return stdout");
});
test("H1 (hijack fix): createMySqlUser is create-only; the create route probes the live server", () => {
const body = stripComments(extractFunction("createMySqlUser"));
assert.ok(body.includes("mySqlAccountIsReserved"), "reserved system account names must be refused inside the provisioning function");
assert.ok(!/CREATE USER IF NOT EXISTS/.test(body), "CREATE USER must not be IF NOT EXISTS — create-or-reset silently hijacks pre-existing accounts");
assert.ok(!/DROP USER/.test(body), "createMySqlUser must never drop");
assert.ok(!/ALTER USER/.test(body), "createMySqlUser must never ALTER — a pre-existing account's password is never this function's business");
// The generic create route must gate reserved names per engine and probe
// the LIVE server (bookkeeping alone is what let {"username":"root"}
// hijack the superuser), refusing untracked accounts with a 409.
const routeStart = indexSource.indexOf('app.post("/api/settings/database/users"');
const routeEnd = indexSource.indexOf('app.post("/api/settings/database/users/:username/password"', routeStart);
assert.ok(routeStart !== -1 && routeEnd > routeStart, "generic create route not found");
const routeBody = stripComments(indexSource.slice(routeStart, routeEnd));
assert.ok(routeBody.includes("mySqlAccountIsReserved"), "the route must gate MySQL reserved names before the action token");
assert.ok(routeBody.includes("postgresRoleIsReserved"), "the route must gate PostgreSQL reserved names before the action token");
assert.ok(routeBody.includes("probeMySqlAccountExists"), "the route must probe the live server before provisioning");
assert.ok(routeBody.includes("MYSQL_ACCOUNT_ALREADY_EXISTS"), "untracked live accounts must be refused with the 409 code");
assert.ok(routeBody.includes("existsOnServer === null"), "a failed pre-existence probe must fail closed");
});
// ---------------------------------------------------------------------------
// Functional: the provisioning block (flavor detection, database enumeration,
// grant composition) is sliced out of index.js into a vm sandbox and driven
// against a stubbed runMySqlAdmin, so the STRATEGY selection is verified, not
// just the source shape (same technique as tests/webhook-config-write-lock.test.js).
// ---------------------------------------------------------------------------
const INDEX_JS = path.join(ROOT, "index.js");
function endIndexOfFunction(source, startMarker) {
const start = source.indexOf(startMarker);
assert.ok(start >= 0, `marker ${startMarker} not found`);
const bodyStart = source.indexOf("{", start);
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 i + 1;
}
}
assert.fail(`unbalanced braces after marker ${startMarker}`);
}
function buildMySqlUserModule(runMySqlAdminStub) {
const source = fs.readFileSync(INDEX_JS, "utf8");
const start = source.indexOf("// Least-privilege builders for panel-issued MySQL accounts");
assert.ok(start !== -1, "MySQL user-provisioning block not found in index.js");
const end = endIndexOfFunction(source, "async function createMySqlUser");
const slice = source.slice(start, end);
const sandbox = {
module: { exports: {} },
// index.js declares the flavor cache next to the admin-command cache and
// clears both via _resetMySqlAdminCache; the harness re-declares the
// cache variable the sliced functions close over, and a source assertion
// below pins index.js's own declaration + invalidation. env is scrubbed
// so the panel database name defaults deterministically to "adpanel".
require: (mod) => {
assert.strictEqual(mod, "./utils/db-user-privileges");
return priv;
},
process: { env: {} },
console,
runMySqlAdmin: runMySqlAdminStub,
// Faithful mirror of index.js's stripLogControlChars
// (adpanel:log-email-control-chars): the provisioning block's console
// lines strip the interpolated account username.
stripLogControlChars: (value) => String(value || "").replace(/[\x00-\x1f\x7f]/g, ""),
};
vm.createContext(sandbox);
vm.runInContext(
"let _cachedMySqlFlavor = null;\n" +
slice +
"\nmodule.exports = { createMySqlUser, _detectMySqlFlavor, listMySqlDatabases };",
sandbox
);
return sandbox.module.exports;
}
function stubRunMySqlAdmin({ version, partialRevokes, databases, failAll = false }) {
const calls = [];
const stub = (sql) => {
calls.push(sql);
if (failAll) return { ok: false, error: "stub channel failure" };
if (sql.includes("SELECT VERSION()")) return { ok: true, stdout: `VERSION()\n${version}` };
if (sql.includes("SELECT @@global.partial_revokes")) {
return { ok: true, stdout: `@@global.partial_revokes\n${partialRevokes}` };
}
if (sql.includes("SHOW DATABASES")) return { ok: true, stdout: `Database\n${databases.join("\n")}` };
return { ok: true, stdout: "" };
};
stub.calls = calls;
return stub;
}
test("H1 (functional): MariaDB flavor grants per database, excluding protected DBs", async () => {
const stub = stubRunMySqlAdmin({
version: "10.11.6-MariaDB-1:10.11.6+maria~ubu2204",
databases: ["information_schema", "mysql", "performance_schema", "sys", "adpanel", "web1", "blog2"],
});
const mod = buildMySqlUserModule(stub);
const result = await mod.createMySqlUser("alice", "secret-password", "%");
assert.ok(result.ok, "creation must succeed on the happy path");
const finalSql = stub.calls[stub.calls.length - 1];
// Create-only account provisioning (hijack fix): no DROP USER, no
// IF NOT EXISTS, no ALTER USER — a pre-existing account must fail the
// batch at its first statement instead of being re-passworded/demoted.
assert.ok(!finalSql.includes("DROP USER"), "creation must never drop anything");
assert.ok(!/CREATE USER IF NOT EXISTS/.test(finalSql), "CREATE USER must not be IF NOT EXISTS (create-or-reset is the hijack)");
assert.ok(finalSql.includes("CREATE USER 'alice'@'%' IDENTIFIED BY"), "plain CREATE USER opens the batch");
assert.ok(!/ALTER USER/.test(finalSql), "no ALTER USER may appear — the password is set by the CREATE alone");
assert.ok(finalSql.includes("REVOKE ALL PRIVILEGES, GRANT OPTION FROM 'alice'@'%'"), "account reset strips stale grants on the fresh account");
assert.ok(finalSql.includes("ON `web1`.* TO 'alice'@'%'"), "existing non-protected DBs are granted");
assert.ok(finalSql.includes("ON `blog2`.* TO 'alice'@'%'"));
assert.ok(!/ON\s+\*\.\*/.test(finalSql), "MariaDB must never receive a schema-wide grant");
// No trailing FLUSH PRIVILEGES: account-management statements reload the
// grant tables themselves, so the admin channel never needs RELOAD (the
// dedicated panel admin account must not hold it).
assert.ok(!finalSql.includes("FLUSH PRIVILEGES"), "account batches must not end with FLUSH PRIVILEGES (no RELOAD on the admin channel)");
assert.strictEqual(stub.calls.filter((c) => c.includes("SELECT @@global.partial_revokes")).length, 0,
"MariaDB must not be probed for partial_revokes");
});
test("H1 (functional): MySQL 8 with partial_revokes=ON grants globally then revokes panel/mysql/sys", async () => {
const stub = stubRunMySqlAdmin({
version: "8.0.36-0ubuntu0.22.04.1",
partialRevokes: "1",
databases: [], // must never be needed
});
const mod = buildMySqlUserModule(stub);
await mod.createMySqlUser("alice", "secret-password", "localhost");
const finalSql = stub.calls[stub.calls.length - 1];
assert.ok(/GRANT SELECT, [^;]+ ON \*\.\* TO 'alice'@'localhost';/.test(finalSql), "global DML/DDL grant is issued");
// Per-privilege fencing: a blanket `REVOKE ALL PRIVILEGES ON db.*` fails
// with ER_NONEXISTING_GRANT (1141) under partial_revokes=ON for privileges
// the fresh account does not hold, stranding the account unfenced.
assert.ok(finalSql.includes("REVOKE SELECT ON `adpanel`.* FROM 'alice'@'localhost';") &&
finalSql.includes("REVOKE TRIGGER ON `adpanel`.* FROM 'alice'@'localhost';"), "panel DB fenced off per privilege");
assert.ok(finalSql.includes("REVOKE SELECT ON `mysql`.* FROM 'alice'@'localhost';") &&
finalSql.includes("REVOKE SELECT ON `sys`.* FROM 'alice'@'localhost';"), "mysql/sys fenced off");
assert.ok(finalSql.includes("REVOKE SELECT ON `phpmyadmin`.* FROM 'alice'@'localhost';"), "phpmyadmin control schema fenced off");
assert.strictEqual(stub.calls.filter((c) => c.includes("SHOW DATABASES")).length, 0,
"partial-revokes strategy needs no database enumeration");
});
test("H1 (functional): MySQL 8 with partial_revokes=OFF falls back to per-database grants", async () => {
const stub = stubRunMySqlAdmin({
version: "8.0.36-0ubuntu0.22.04.1",
partialRevokes: "0",
databases: ["adpanel", "web1"],
});
const mod = buildMySqlUserModule(stub);
await mod.createMySqlUser("alice", "secret-password", "%");
const finalSql = stub.calls[stub.calls.length - 1];
assert.ok(finalSql.includes("ON `web1`.* TO 'alice'@'%'"));
assert.ok(!/ON\s+\*\.\*/.test(finalSql), "partial_revokes OFF must never see a schema-wide grant");
});
test("H1 (functional): detection and enumeration failures fail closed to zero grants", async () => {
// Probes fail while the write channel still works — this isolates the
// property under test: unusable probes must yield fail-closed SQL, never
// a schema-wide grant.
const probeBroken = (sql) =>
sql.includes("SELECT ") ? { ok: false, error: "stub probe failure" } : { ok: true, stdout: "" };
const calls = [];
const stub = (sql) => { calls.push(sql); return probeBroken(sql); };
const mod = buildMySqlUserModule(stub);
const result = await mod.createMySqlUser("alice", "secret-password", "%");
assert.ok(result.ok, "account creation proceeds (fail closed, not aborted)");
const noFlavorSql = calls[calls.length - 1];
assert.ok(!/ON\s+\*\.\*/.test(noFlavorSql), "a failed probe must not produce a schema-wide grant");
assert.ok(noFlavorSql.includes("CREATE USER 'alice'@'%'"));
// Probes broken AND enumeration empty: account exists, zero grants.
const dead = stubRunMySqlAdmin({ version: "8.0.36", partialRevokes: "1", databases: [], failAll: true });
const modDead = buildMySqlUserModule(dead);
await modDead.createMySqlUser("alice", "secret-password", "%");
const deadSql = dead.calls[dead.calls.length - 1];
assert.ok(deadSql.includes("CREATE USER 'alice'@'%'"), "account is still created");
// The only grant-shaped token allowed is the GRANT OPTION inside the reset
// REVOKE; no data or DDL GRANT may be issued at all.
const withoutReset = deadSql.replace(/REVOKE ALL PRIVILEGES, GRANT OPTION FROM '[^']*'@'[^']*';/g, "");
assert.ok(!/GRANT /.test(withoutReset), "with nothing enumerated, no GRANT may be issued at all");
assert.ok(!deadSql.includes("FLUSH PRIVILEGES"), "account batches must not end with FLUSH PRIVILEGES (no RELOAD on the admin channel)");
});
test("H1 (functional): the flavor cache prevents re-probing on the second call", async () => {
const stub = stubRunMySqlAdmin({
version: "10.11.6-MariaDB",
databases: ["web1"],
});
const mod = buildMySqlUserModule(stub);
await mod.createMySqlUser("alice", "secret-password", "%");
const probesAfterFirst = stub.calls.filter((c) => c.includes("SELECT VERSION()")).length;
assert.strictEqual(probesAfterFirst, 1);
await mod.createMySqlUser("bob", "secret-password", "%");
assert.strictEqual(stub.calls.filter((c) => c.includes("SELECT VERSION()")).length, 1,
"flavor detection must be cached across user creations");
});
test("H1 (hijack fix): reserved system account names are refused before any SQL runs", async () => {
for (const name of ["root", "ROOT", "debian-sys-maint", "Debian-Sys-Maint", "mysql.sys", "mariadb.sys", "mysql", "mariadb"]) {
const stub = stubRunMySqlAdmin({ version: "10.11.6-MariaDB", databases: ["web1"] });
const mod = buildMySqlUserModule(stub);
const result = await mod.createMySqlUser(name, "secret-password", "%");
// deepEqual, not deepStrictEqual: results cross the vm context boundary,
// so their Object.prototype differs from this realm's.
assert.deepEqual(result, { ok: false, error: `'${name}' is a reserved MySQL system account name` }, JSON.stringify(name));
assert.strictEqual(stub.calls.length, 0, `no SQL may run for reserved name ${JSON.stringify(name)}`);
}
// Non-reserved names are unaffected by the gate.
const stub = stubRunMySqlAdmin({ version: "10.11.6-MariaDB", databases: ["web1"] });
const mod = buildMySqlUserModule(stub);
assert.ok((await mod.createMySqlUser("webapp", "secret-password", "%")).ok);
assert.ok((await mod.createMySqlUser("sysadmin1", "secret-password", "localhost")).ok,
"a name CONTAINING a reserved token is not itself reserved");
assert.ok((await mod.createMySqlUser("mysql_admin", "secret-password", "%")).ok);
});
test("H1: index.js keeps the flavor cache beside the admin-command cache", () => {
assert.ok(indexSource.includes("let _cachedMySqlFlavor = null;"), "flavor cache must be declared at module scope");
assert.ok(/function _resetMySqlAdminCache\(\) \{[\s\S]*?_cachedMySqlAdminCmd = null;[\s\S]*?_cachedMySqlFlavor = null;/.test(indexSource),
"the reset helper must clear both caches together");
const src = stripComments(indexSource)
.replace(/function _resetMySqlAdminCache\(\) \{[\s\S]*?\n\}/, "")
.replace(/let _cachedMySqlAdminCmd = null;/, "");
assert.ok(!/_cachedMySqlAdminCmd = null;/.test(src),
"no site may clear the admin-command cache without clearing the flavor cache");
});