633 lines
37 KiB
JavaScript
633 lines
37 KiB
JavaScript
// Standalone verification harness for panel database-user privilege scoping
|
|
// (audit finding 2.1) plus the MongoDB operation mutex (audit finding 2.8).
|
|
//
|
|
// Two layers:
|
|
// 1. Unit tests against utils/db-user-privileges.js — including executing
|
|
// the generated mongosh eval scripts against a mock `db` driver, so the
|
|
// grant/revoke SEMANTICS are verified, not just string shapes.
|
|
// 2. Static regression checks against index.js — the panel-issued user
|
|
// creation paths must contain no SUPERUSER / root / *AnyDatabase
|
|
// grants, while the install-time admin keeps its single reserved root
|
|
// role and the MySQL path scopes its grants so the panel's own schema
|
|
// and the system schemas are unreachable by panel-issued accounts
|
|
// (audit H1).
|
|
//
|
|
// For live servers, scripts/migrate-db-user-privileges.js --verify performs
|
|
// the runtime equivalent (db.getUser() / pg_roles flags / SHOW GRANTS).
|
|
//
|
|
// Run: node scripts/verify-db-user-privileges.js
|
|
const assert = require("assert");
|
|
const fs = require("fs");
|
|
const path = require("path");
|
|
|
|
const priv = require("../utils/db-user-privileges");
|
|
|
|
let passed = 0;
|
|
const failures = [];
|
|
function check(name, fn) {
|
|
try {
|
|
fn();
|
|
passed++;
|
|
} catch (err) {
|
|
failures.push({ name, err });
|
|
console.error(`FAIL: ${name}\n ${err.message}`);
|
|
}
|
|
}
|
|
|
|
// ---- 1. per-user database naming ---------------------------------------------
|
|
|
|
check("panelUserDatabaseName derives lowercase user_<name>", () => {
|
|
assert.strictEqual(priv.panelUserDatabaseName("Alice_01"), "user_alice_01");
|
|
assert.strictEqual(priv.panelUserDatabaseName("web-prod"), "user_web-prod");
|
|
});
|
|
|
|
check("panelUserDatabaseName rejects invalid usernames (fail closed)", () => {
|
|
for (const bad of ["", null, undefined, 42, "a b", "a'b", 'a"b', "a;b", "$(id)", "a$b", "x".repeat(65), "café"]) {
|
|
assert.strictEqual(priv.panelUserDatabaseName(bad), null, JSON.stringify(bad));
|
|
}
|
|
});
|
|
|
|
check("panelUserDatabaseName long names stay within 63 bytes and never collide", () => {
|
|
const a = "a".repeat(64); // max panel username length
|
|
const b = "a".repeat(63) + "b";
|
|
const dbA = priv.panelUserDatabaseName(a);
|
|
const dbB = priv.panelUserDatabaseName(b);
|
|
assert.ok(dbA && dbA.length <= 63);
|
|
assert.ok(dbB && dbB.length <= 63);
|
|
assert.notStrictEqual(dbA, dbB, "two distinct long usernames must not share a database");
|
|
assert.strictEqual(dbA, priv.panelUserDatabaseName(a), "naming must be deterministic");
|
|
});
|
|
|
|
check("panelUsernameCaseCollides flags case-variant duplicates, not exact ones (fail closed)", () => {
|
|
assert.strictEqual(priv.panelUsernameCaseCollides("Bob", ["bob", "alice"]), true, "'Bob' vs 'bob' would share one folded per-user database");
|
|
assert.strictEqual(priv.panelUsernameCaseCollides("bob", ["BOB"]), true);
|
|
assert.strictEqual(priv.panelUsernameCaseCollides("bob", ["bob"]), false, "exact duplicates are the caller's ordinary 'already exists' case, not a case collision");
|
|
assert.strictEqual(priv.panelUsernameCaseCollides("bob", ["alice"]), false);
|
|
assert.strictEqual(priv.panelUsernameCaseCollides("bob", null), false, "non-array input fails closed");
|
|
assert.strictEqual(priv.panelUsernameCaseCollides("bob", "not-an-array"), false);
|
|
assert.strictEqual(priv.panelUsernameCaseCollides("b o b", ["bob"]), false, "invalid username fails closed to false");
|
|
assert.strictEqual(priv.panelUsernameCaseCollides(null, ["bob"]), false, "invalid username fails closed to false");
|
|
assert.strictEqual(priv.panelUsernameCaseCollides("Bob", [null, 5, "bob"]), true, "non-string entries are ignored, not fatal");
|
|
});
|
|
|
|
// ---- 2. MongoDB role sets ------------------------------------------------------
|
|
|
|
check("mongoPanelUserRoles grants exactly readWrite+dbAdmin on the user's own db", () => {
|
|
const roles = priv.mongoPanelUserRoles("alice");
|
|
assert.deepStrictEqual(roles, [
|
|
{ role: "readWrite", db: "user_alice" },
|
|
{ role: "dbAdmin", db: "user_alice" },
|
|
]);
|
|
assert.ok(roles.every(r => r.db !== "admin"), "no role may be anchored on the admin database");
|
|
for (const bad of ["", null, "a b", "a'b"]) {
|
|
assert.strictEqual(priv.mongoPanelUserRoles(bad), null);
|
|
}
|
|
});
|
|
|
|
check("mongoRoleIsDangerous flags server-wide roles and admin-db user/dbAdmin", () => {
|
|
assert.ok(priv.mongoRoleIsDangerous({ role: "root", db: "admin" }));
|
|
assert.ok(priv.mongoRoleIsDangerous({ role: "readWriteAnyDatabase", db: "admin" }));
|
|
assert.ok(priv.mongoRoleIsDangerous({ role: "dbAdminAnyDatabase", db: "admin" }));
|
|
assert.ok(priv.mongoRoleIsDangerous({ role: "userAdmin", db: "admin" }));
|
|
assert.ok(priv.mongoRoleIsDangerous({ role: "dbAdmin", db: "admin" }));
|
|
assert.ok(priv.mongoRoleIsDangerous({ role: "__system", db: "admin" }));
|
|
assert.ok(priv.mongoRoleIsDangerous({ role: "restore", db: "admin" }));
|
|
// The scoped grants the panel now issues must NOT be flagged:
|
|
assert.ok(!priv.mongoRoleIsDangerous({ role: "readWrite", db: "user_alice" }));
|
|
assert.ok(!priv.mongoRoleIsDangerous({ role: "dbAdmin", db: "user_alice" }));
|
|
});
|
|
|
|
// Mock driver implementing the subset of the mongo shell API the generated
|
|
// eval scripts use. Lets us execute the scripts for real and inspect what
|
|
// they actually did.
|
|
function makeMockAdminDb(existingRoles) {
|
|
const state = { users: { mockuser: { roles: existingRoles } }, grants: [], revokes: [], created: [] };
|
|
const adminDb = {
|
|
getUser: (name) => (state.users[name] ? { user: name, roles: state.users[name].roles } : null),
|
|
createUser: (spec) => { state.created.push(spec); state.users[spec.user] = { roles: spec.roles }; },
|
|
grantRolesToUser: (name, roles) => { state.grants.push({ name, roles }); },
|
|
revokeRolesFromUser: (name, roles) => { state.revokes.push({ name, roles }); },
|
|
};
|
|
return { state, db: { getSiblingDB: (name) => (name === "admin" ? adminDb : null) } };
|
|
}
|
|
|
|
check("buildMongoCreateUserEval creates the user with scoped roles only", () => {
|
|
const evalScript = priv.buildMongoCreateUserEval("alice", 'p@$$"w\'ord');
|
|
assert.ok(evalScript, "builder must succeed");
|
|
const mock = makeMockAdminDb([]);
|
|
// The script must be valid JS against the shell API surface:
|
|
new Function("db", "print", "printjson", evalScript)(mock.db, () => {}, () => {});
|
|
assert.strictEqual(mock.state.created.length, 1);
|
|
const created = mock.state.created[0];
|
|
assert.strictEqual(created.user, "alice");
|
|
assert.deepStrictEqual(created.roles, priv.mongoPanelUserRoles("alice"));
|
|
assert.ok(!JSON.stringify(created.roles).includes("AnyDatabase"));
|
|
assert.ok(!JSON.stringify(created.roles).includes('"root"'));
|
|
});
|
|
|
|
check("buildMongoCreateUserEval fails closed on invalid input", () => {
|
|
assert.strictEqual(priv.buildMongoCreateUserEval("a b", "password123"), null);
|
|
assert.strictEqual(priv.buildMongoCreateUserEval("alice", ""), null);
|
|
assert.strictEqual(priv.buildMongoCreateUserEval("alice", null), null);
|
|
assert.strictEqual(priv.buildMongoCreateUserEval("'; dropUser('x')//", "password123"), null);
|
|
});
|
|
|
|
check("buildMongoRescopeEval grants scoped roles then revokes exactly the dangerous pairs", () => {
|
|
const evalScript = priv.buildMongoRescopeEval("mockuser");
|
|
assert.ok(evalScript);
|
|
const existing = [
|
|
{ role: "root", db: "admin" },
|
|
{ role: "readWriteAnyDatabase", db: "admin" },
|
|
{ role: "readWrite", db: "user_mockuser" }, // pre-existing scoped grant — must survive
|
|
];
|
|
const mock = makeMockAdminDb(existing);
|
|
let printed = [];
|
|
new Function("db", "print", "printjson", evalScript)(mock.db, (m) => printed.push(m), () => {});
|
|
assert.ok(printed.includes("ADP_RESCOPE_OK"), printed.join("|"));
|
|
// Grant happens, and happens before revoke:
|
|
assert.deepStrictEqual(mock.state.grants, [{ name: "mockuser", roles: priv.mongoPanelUserRoles("mockuser") }]);
|
|
assert.deepStrictEqual(mock.state.revokes, [{
|
|
name: "mockuser",
|
|
roles: [{ role: "root", db: "admin" }, { role: "readWriteAnyDatabase", db: "admin" }],
|
|
}]);
|
|
});
|
|
|
|
check("buildMongoRescopeEval is a no-op revoke when the user already holds only scoped roles", () => {
|
|
const mock = makeMockAdminDb([{ role: "readWrite", db: "user_mockuser" }]);
|
|
new Function("db", "print", "printjson", priv.buildMongoRescopeEval("mockuser"))(mock.db, () => {}, () => {});
|
|
assert.deepStrictEqual(mock.state.revokes, []);
|
|
assert.strictEqual(mock.state.grants.length, 1);
|
|
});
|
|
|
|
check("buildMongoRescopeEval reports missing users without throwing", () => {
|
|
const mock = makeMockAdminDb([]);
|
|
delete mock.state.users.mockuser;
|
|
let printed = [];
|
|
new Function("db", "print", "printjson", priv.buildMongoRescopeEval("mockuser"))(mock.db, (m) => printed.push(m), () => {});
|
|
assert.ok(printed.includes("ADP_USER_MISSING"));
|
|
assert.strictEqual(mock.state.grants.length, 0);
|
|
});
|
|
|
|
// ---- 3. PostgreSQL SQL builders -----------------------------------------------
|
|
|
|
check("pgQuoteIdent accepts plain identifiers and rejects everything else", () => {
|
|
assert.strictEqual(priv.pgQuoteIdent("alice"), '"alice"');
|
|
assert.strictEqual(priv.pgQuoteIdent("user_01-x"), '"user_01-x"');
|
|
for (const bad of ["", null, undefined, 42, 'a"b', "a'b", "a b", "a;b", "--x", "-lead", "x".repeat(64)]) {
|
|
assert.strictEqual(priv.pgQuoteIdent(bad), null, JSON.stringify(bad));
|
|
}
|
|
});
|
|
|
|
check("pgDollarQuoted refuses tag collisions", () => {
|
|
assert.strictEqual(priv.pgDollarQuoted("body", "tag"), "$tag$body$tag$");
|
|
assert.strictEqual(priv.pgDollarQuoted("contains $tag$ inside", "tag"), null);
|
|
assert.strictEqual(priv.pgDollarQuoted("ok", "bad tag!"), null);
|
|
});
|
|
|
|
check("pgLiteral doubles single quotes", () => {
|
|
assert.strictEqual(priv.pgLiteral("it's"), "it''s");
|
|
});
|
|
|
|
function assertNoUnnegatedPrivilege(sql, privilege) {
|
|
// Matches e.g. SUPERUSER / CREATEDB / CREATEROLE but not NOSUPERUSER etc.
|
|
const re = new RegExp("(?<![A-Za-z])" + privilege + "(?![A-Za-z])");
|
|
const m = sql.match(re);
|
|
assert.ok(!m, `un-negated ${privilege} found in: ${sql}`);
|
|
}
|
|
|
|
check("buildPostgresCreateRoleSql: pgAdmin bootstrap is NOSUPERUSER NOCREATEROLE CREATEDB", () => {
|
|
const sql = priv.buildPostgresCreateRoleSql({ username: "pgadmin_boot", password: "pw12345678", createdb: true });
|
|
assert.ok(sql.includes(" NOSUPERUSER "), sql);
|
|
assert.ok(sql.includes(" NOCREATEROLE "), sql);
|
|
assert.ok(sql.includes(" CREATEDB "), sql);
|
|
assert.ok(sql.startsWith("CREATE ROLE"));
|
|
assertNoUnnegatedPrivilege(sql, "SUPERUSER");
|
|
assertNoUnnegatedPrivilege(sql, "CREATEROLE");
|
|
});
|
|
|
|
check("buildPostgresCreateRoleSql: unified panel users get NOCREATEDB", () => {
|
|
const sql = priv.buildPostgresCreateRoleSql({ username: "alice", password: "pw12345678" });
|
|
assert.ok(sql.includes(" NOCREATEDB "), sql);
|
|
assertNoUnnegatedPrivilege(sql, "CREATEDB");
|
|
assertNoUnnegatedPrivilege(sql, "SUPERUSER");
|
|
assertNoUnnegatedPrivilege(sql, "CREATEROLE");
|
|
});
|
|
|
|
check("buildPostgresCreateRoleSql: passwords are dollar-quoted, never string-embedded", () => {
|
|
const evil = "pw'; DROP ROLE alice;--$$";
|
|
const sql = priv.buildPostgresCreateRoleSql({ username: "alice", password: evil });
|
|
assert.ok(/\$adp_[0-9a-f]+\$/.test(sql), "dollar-quote delimiters must be present");
|
|
assert.ok(!sql.includes("'" + evil), "raw password must never appear in a single-quoted literal");
|
|
// The payload text legitimately appears INSIDE the dollar-quoted literal;
|
|
// what must never happen is it escaping outside one:
|
|
const outsideQuotes = sql.replace(/\$adp_[0-9a-f]{12}\$[\s\S]*?\$adp_[0-9a-f]{12}\$/g, "");
|
|
assert.ok(!/DROP ROLE/.test(outsideQuotes), "payload must not break out of the dollar-quoted literal");
|
|
assert.strictEqual(priv.buildPostgresCreateRoleSql({ username: 'a"b', password: "x" }), null);
|
|
assert.strictEqual(priv.buildPostgresCreateRoleSql({ username: "alice", password: "" }), null);
|
|
});
|
|
|
|
check("buildPostgresCreatePanelUserSql: create-only + refusal marker + guarded per-user database", () => {
|
|
const sql = priv.buildPostgresCreatePanelUserSql({ username: "alice", password: "pw12345678" });
|
|
assert.ok(/IF NOT EXISTS \(SELECT FROM pg_catalog\.pg_roles/.test(sql), "existence check");
|
|
assert.ok(/CREATE ROLE "alice" WITH LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE/.test(sql), "scoped create branch");
|
|
// Create-only (hijack fix): an existing role must raise the refusal
|
|
// marker, never be re-passworded or flag-clamped — a previous version ran
|
|
// ALTER ROLE ... PASSWORD in the ELSE branch, silently taking over any
|
|
// pre-existing role (including "postgres", the panel's own channel).
|
|
assert.ok(/RAISE EXCEPTION 'ADP_PG_ROLE_ALREADY_EXISTS: role "alice" already exists/.test(sql), "existing roles are refused via the deterministic marker");
|
|
assert.ok(!/ALTER ROLE/.test(sql), "no ALTER ROLE may appear anywhere in the create batch");
|
|
assert.ok(
|
|
/SELECT 'CREATE DATABASE "user_alice" OWNER "alice"' WHERE NOT EXISTS \(SELECT FROM pg_database WHERE datname = 'user_alice'\)\\gexec/.test(sql),
|
|
"idempotent guarded CREATE DATABASE via \\gexec"
|
|
);
|
|
assertNoUnnegatedPrivilege(sql, "SUPERUSER");
|
|
assertNoUnnegatedPrivilege(sql, "CREATEDB");
|
|
assertNoUnnegatedPrivilege(sql, "CREATEROLE");
|
|
assert.strictEqual(priv.buildPostgresCreatePanelUserSql({ username: "a b", password: "x" }), null);
|
|
// DO block and password literal must use DIFFERENT dollar-quote tags —
|
|
// a shared tag makes the DO-body scan stop at the password literal's
|
|
// opening tag and execute the rest of the password as bare SQL.
|
|
const tags = [...new Set(sql.match(/\$adp_[0-9a-f]+\$/g) || [])];
|
|
assert.strictEqual(tags.length, 2, `expected two distinct dollar-quote tags, got: ${tags.join(" ")}`);
|
|
const doTag = sql.match(/DO (\$adp_[0-9a-f]+\$)/)[1];
|
|
const pwdTag = sql.match(/PASSWORD (\$adp_[0-9a-f]+\$)/)[1];
|
|
assert.notStrictEqual(doTag, pwdTag, "DO tag must differ from password tag");
|
|
});
|
|
|
|
check("reserved system account names are refused for MySQL and PostgreSQL provisioning", () => {
|
|
// MySQL: server superuser, packaging maintenance account (a panel admin
|
|
// channel identity), and the internal mysql*/mariadb* accounts — matched
|
|
// case-insensitively because MySQL matches user names case-insensitively.
|
|
for (const reserved of priv.MYSQL_RESERVED_USERNAMES) {
|
|
assert.ok(priv.mySqlAccountIsReserved(reserved), reserved);
|
|
assert.ok(priv.mySqlAccountIsReserved(reserved.toUpperCase()), `${reserved} upper-case variant must be refused`);
|
|
}
|
|
for (const allowed of ["webapp", "alice", "sysadmin1", "mysql_admin", "mariadb_user", "rooot", "rootuser", "mysqladmin"]) {
|
|
assert.strictEqual(priv.mySqlAccountIsReserved(allowed), false, `${allowed} is not reserved`);
|
|
}
|
|
for (const bad of [null, undefined, 42, "", {}]) {
|
|
assert.strictEqual(priv.mySqlAccountIsReserved(bad), false, `non-string input ${JSON.stringify(bad)} is not a reserved match (invalidity is the validators' job)`);
|
|
}
|
|
// PostgreSQL: the bootstrap superuser (also the panel's peer-auth
|
|
// identity), the public pseudo-role, and the server-reserved pg_ prefix.
|
|
for (const reserved of ["postgres", "POSTGRES", "public", "PUBLIC", "pg_monitor", "PG_READ_ALL_DATA"]) {
|
|
assert.ok(priv.postgresRoleIsReserved(reserved), reserved);
|
|
}
|
|
for (const allowed of ["pgadmin", "alice", "webapp", "pgx", "postgresuser"]) {
|
|
assert.strictEqual(priv.postgresRoleIsReserved(allowed), false, `${allowed} is not a reserved role name`);
|
|
}
|
|
for (const bad of [null, undefined, 42, ""]) {
|
|
assert.strictEqual(priv.postgresRoleIsReserved(bad), false, `non-string input ${JSON.stringify(bad)} is not a reserved match`);
|
|
}
|
|
});
|
|
|
|
check("emitted dollar-quote tags are distinct and never occur inside the password", () => {
|
|
// The security property, independent of tag randomness: whatever tags
|
|
// the builder picks, (1) the DO tag and the password tag differ, (2)
|
|
// neither occurs in the password, and (3) the password round-trips
|
|
// through the dollar-quoted literal byte-for-byte.
|
|
const passwords = ["pw12345678", "pw$adp_aaaaaaaaaaaa$pw", "pw'--$$;DROP", "$adp_", "$$", "x".repeat(300)];
|
|
for (const pw of passwords) {
|
|
const sql = priv.buildPostgresCreatePanelUserSql({ username: "alice", password: pw });
|
|
assert.ok(sql, `builder must succeed for ${JSON.stringify(pw.slice(0, 24))}`);
|
|
const lit = sql.match(/PASSWORD (\$adp_[0-9a-f]+\$)([\s\S]*?)\1;/);
|
|
assert.ok(lit, "password literal must be well-formed and closed by its own tag");
|
|
assert.strictEqual(lit[2], pw, "password must round-trip unchanged");
|
|
const doTag = sql.match(/DO (\$adp_[0-9a-f]+\$)/)[1];
|
|
const pwdTag = lit[1];
|
|
assert.notStrictEqual(doTag, pwdTag, "DO tag must differ from password tag");
|
|
assert.ok(!pw.includes(pwdTag.slice(1, -1)), "password tag must not occur in the password");
|
|
assert.ok(!pw.includes(doTag.slice(1, -1)), "DO tag must not occur in the password");
|
|
}
|
|
});
|
|
|
|
check("buildPostgresCreatePanelUserSql fails closed when tag generation is impossible", () => {
|
|
// Pin randomBytes to a constant so every candidate tag is identical:
|
|
// the two tags can then never differ, and any password containing that
|
|
// constant tag also collides with the literal. Both callers must fail
|
|
// closed instead of emitting broken SQL.
|
|
const crypto = require("crypto");
|
|
const realRandomBytes = crypto.randomBytes;
|
|
crypto.randomBytes = () => Buffer.alloc(6);
|
|
try {
|
|
assert.strictEqual(
|
|
priv.buildPostgresCreatePanelUserSql({ username: "alice", password: "pw$adp_000000000000$pw" }),
|
|
null,
|
|
"password colliding with the constant tag must be rejected"
|
|
);
|
|
assert.strictEqual(
|
|
priv.buildPostgresCreatePanelUserSql({ username: "alice", password: "normal-passw0rd" }),
|
|
null,
|
|
"two distinct tags can never be drawn, so fail closed"
|
|
);
|
|
} finally {
|
|
crypto.randomBytes = realRandomBytes;
|
|
}
|
|
});
|
|
|
|
check("buildPostgresRescopeSql only removes privilege (or sets CREATEDB for pgAdmin)", () => {
|
|
const unified = priv.buildPostgresRescopeSql({ username: "alice" });
|
|
assert.ok(unified.includes("ALTER ROLE \"alice\" WITH NOSUPERUSER NOCREATEDB NOCREATEROLE;"));
|
|
assert.ok(/\\gexec/.test(unified), "unified users get their per-user database");
|
|
const pgadmin = priv.buildPostgresRescopeSql({ username: "pgadmin_boot", createdb: true, withDatabase: false });
|
|
assert.ok(pgadmin.includes("ALTER ROLE \"pgadmin_boot\" WITH NOSUPERUSER CREATEDB NOCREATEROLE;"));
|
|
assert.ok(!/\\gexec/.test(pgadmin), "pgAdmin bootstrap gets no per-user database (matches fresh installs)");
|
|
for (const sql of [unified, pgadmin]) {
|
|
assertNoUnnegatedPrivilege(sql, "SUPERUSER");
|
|
assertNoUnnegatedPrivilege(sql, "CREATEROLE");
|
|
}
|
|
assert.strictEqual(priv.buildPostgresRescopeSql({ username: "a;b" }), null);
|
|
assert.strictEqual(priv.buildPostgresRescopeSql({ username: "alice", withDatabase: true }).includes("CREATE DATABASE"), true);
|
|
});
|
|
|
|
// ---- 3b. MySQL SQL builders (audit H1) -------------------------------------------
|
|
|
|
check("isProtectedMySQLDatabase covers the panel DB case-insensitively and the system schemas", () => {
|
|
assert.strictEqual(priv.MYSQL_SYSTEM_DATABASES.join(","), "mysql,sys,information_schema,performance_schema");
|
|
for (const sys of priv.MYSQL_SYSTEM_DATABASES) {
|
|
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"));
|
|
});
|
|
|
|
check("buildMySqlGlobalGrantSql: exact panel privilege set, then panel/mysql/sys revokes", () => {
|
|
const sql = priv.buildMySqlGlobalGrantSql("alice", "%", "adpanel");
|
|
const lines = sql.split("\n");
|
|
assert.strictEqual(lines[0], "GRANT " + priv.MYSQL_PANEL_USER_PRIVILEGES.join(", ") + " ON *.* TO 'alice'@'%';");
|
|
assert.deepStrictEqual(lines.slice(1), [
|
|
"REVOKE ALL PRIVILEGES ON `adpanel`.* FROM 'alice'@'%';",
|
|
"REVOKE ALL PRIVILEGES ON `mysql`.* FROM 'alice'@'%';",
|
|
"REVOKE ALL PRIVILEGES ON `sys`.* FROM 'alice'@'%';",
|
|
]);
|
|
for (const adminPriv of ["SUPER", "FILE", "PROCESS", "RELOAD", "SHUTDOWN", "GRANT OPTION", "CREATE USER", "REPLICATION", "CREATE ROLE", "DROP ROLE"]) {
|
|
assert.ok(!lines[0].includes(adminPriv), `grant must not include ${adminPriv}`);
|
|
}
|
|
});
|
|
|
|
check("MySQL builders fail closed on invalid identifiers", () => {
|
|
// Shared list: invalid for usernames (64 cap) and database names (63 cap).
|
|
for (const bad of ["", null, undefined, 42, "a b", "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)}`);
|
|
}
|
|
// Hosts: %, localhost, hostnames and IPv6 are legitimate (255 cap); spaces,
|
|
// semicolons, quotes, backslashes and backticks never are.
|
|
for (const badHost of ["", null, undefined, 42, "a b", "a'b", 'a"b', "a`b", "a;b", "a\\b", "x".repeat(256)]) {
|
|
assert.strictEqual(priv.buildMySqlGlobalGrantSql("alice", badHost, "adpanel"), null, `host ${JSON.stringify(badHost)}`);
|
|
}
|
|
assert.ok(priv.buildMySqlGlobalGrantSql("alice", "db1.internal.example", "adpanel"));
|
|
assert.ok(priv.buildMySqlGlobalGrantSql("alice", "::1", "adpanel"));
|
|
for (const badDb of ["", null, undefined, "a b", "a`b", "a;b", "x".repeat(65)]) {
|
|
assert.strictEqual(priv.buildMySqlGlobalGrantSql("alice", "%", badDb), null, `db ${JSON.stringify(badDb)}`);
|
|
assert.strictEqual(priv.buildMySqlPerDatabaseGrantsSql("alice", "%", ["web"], badDb), null, `db ${JSON.stringify(badDb)}`);
|
|
}
|
|
});
|
|
|
|
check("buildMySqlPerDatabaseGrantsSql: backtick-quoted, protected DBs excluded, never 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");
|
|
// Ungrantable names are skipped (user gets less, never more), not fatal:
|
|
const partial = priv.buildMySqlPerDatabaseGrantsSql("alice", "%", ["good_db", "bad db", null, 42, ""], "adpanel");
|
|
assert.strictEqual(partial.split("\n").length, 1);
|
|
assert.ok(partial.includes("`good_db`"));
|
|
assert.strictEqual(priv.buildMySqlPerDatabaseGrantsSql("alice", "%", "not-an-array", "adpanel"), null);
|
|
// An empty enumeration is a valid fail-closed outcome (no grants at all):
|
|
assert.strictEqual(priv.buildMySqlPerDatabaseGrantsSql("alice", "%", [], "adpanel"), "");
|
|
});
|
|
|
|
// ---- 4. static regression checks against index.js ------------------------------
|
|
|
|
const indexSrc = fs.readFileSync(path.join(__dirname, "..", "index.js"), "utf8");
|
|
|
|
// Strip block comments and full-line // comments before asserting: the
|
|
// panel source deliberately NAMES the forbidden privileges in explanatory
|
|
// prose (e.g. "clamps SUPERUSER flags"), and that prose is not a grant.
|
|
// Trailing // comments are not stripped — doing so correctly would require
|
|
// parsing string literals, and over-stripping could hide real code.
|
|
function stripComments(src) {
|
|
return src
|
|
.replace(/\/\*[\s\S]*?\*\//g, "")
|
|
.replace(/^[ \t]*\/\/.*$/gm, "");
|
|
}
|
|
|
|
function extractFunction(name) {
|
|
const start = indexSrc.indexOf(`async function ${name}(`);
|
|
assert.ok(start !== -1, `function ${name} not found in index.js`);
|
|
const next = indexSrc.indexOf("\nasync function ", start + 1);
|
|
return indexSrc.slice(start, next === -1 ? undefined : next);
|
|
}
|
|
|
|
check("index.js createPostgresUser delegates to the scoped builder", () => {
|
|
const body = stripComments(extractFunction("createPostgresUser"));
|
|
assert.ok(body.includes("buildPostgresCreatePanelUserSql"), "must use the shared builder");
|
|
assertNoUnnegatedPrivilege(body, "SUPERUSER");
|
|
assertNoUnnegatedPrivilege(body, "CREATEROLE");
|
|
assertNoUnnegatedPrivilege(body, "CREATEDB");
|
|
});
|
|
|
|
check("index.js createPostgresDbUser (pgAdmin bootstrap) is non-superuser", () => {
|
|
const body = stripComments(extractFunction("createPostgresDbUser"));
|
|
assert.ok(body.includes("buildPostgresCreateRoleSql"), "must use the shared builder");
|
|
assert.ok(/createdb:\s*true/.test(body), "pgAdmin bootstrap keeps CREATEDB");
|
|
assertNoUnnegatedPrivilege(body, "SUPERUSER");
|
|
assertNoUnnegatedPrivilege(body, "CREATEROLE");
|
|
});
|
|
|
|
check("index.js createMongoUser and legacy path issue scoped roles only", () => {
|
|
for (const name of ["createMongoUser", "createMongoUserLegacy"]) {
|
|
const body = stripComments(extractFunction(name));
|
|
assert.ok(body.includes("buildMongoCreateUserEval"), `${name} must use the shared builder`);
|
|
assert.ok(!/role:\s*["']root["']/.test(body), `${name} must not grant root`);
|
|
assert.ok(!/AnyDatabase/.test(body), `${name} must not grant AnyDatabase roles`);
|
|
}
|
|
});
|
|
|
|
check("index.js standalone mongodb create endpoint issues scoped roles only", () => {
|
|
const start = indexSrc.indexOf('app.post("/api/settings/database/mongodb/users"');
|
|
const end = indexSrc.indexOf("app.delete(", start);
|
|
const body = stripComments(indexSrc.slice(start, end));
|
|
assert.ok(start !== -1 && end > start, "endpoint not found");
|
|
assert.ok(body.includes("buildMongoCreateUserEval"), "must use the shared builder");
|
|
assert.ok(!/"readWriteAnyDatabase"|'readWriteAnyDatabase'/.test(body), "must not grant readWriteAnyDatabase");
|
|
});
|
|
|
|
check("index.js standalone mongodb create endpoint enforces case-insensitive username uniqueness", () => {
|
|
const start = indexSrc.indexOf('app.post("/api/settings/database/mongodb/users"');
|
|
const end = indexSrc.indexOf("app.delete(", start);
|
|
const body = stripComments(indexSrc.slice(start, end));
|
|
assert.ok(start !== -1 && end > start, "endpoint not found");
|
|
assert.ok(body.includes("panelUsernameCaseCollides"), "case-variant names must be gated via the shared helper (per-user databases fold case)");
|
|
assert.ok(body.includes("existingNames.includes(cleanUsername)"), "the exact-match 'User already exists' check must remain");
|
|
});
|
|
|
|
check("index.js installMongoDB keeps exactly one reserved root admin (install-time)", () => {
|
|
const start = indexSrc.indexOf("async function installMongoDB(");
|
|
const end = indexSrc.indexOf("\nasync function ", start + 1);
|
|
const body = stripComments(indexSrc.slice(start, end));
|
|
const rootGrants = body.match(/role:\s*'root'/g) || [];
|
|
assert.strictEqual(rootGrants.length, 1, "install flow must create exactly one root account");
|
|
});
|
|
|
|
check("index.js createMySqlUser delegates MySQL scoping to the shared builders (audit H1)", () => {
|
|
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 issue schema-wide grants itself — the grant lives in utils now");
|
|
assert.ok(!/GRANT SELECT/.test(body), "the inline DML/DDL grant literal is gone (MYSQL_PANEL_USER_PRIVILEGES is the single source)");
|
|
// The only admin-grade token allowed inline is the defensive REVOKE that
|
|
// resets accounts created by older, over-granting panel versions.
|
|
assert.ok(/REVOKE ALL PRIVILEGES, GRANT OPTION FROM/.test(body), "account reset REVOKE must strip stale grants");
|
|
assert.strictEqual((body.match(/GRANT OPTION/g) || []).length, 1, "GRANT OPTION may only occur in the account reset REVOKE");
|
|
|
|
// 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"), "partial-revokes engines must use the shared builder");
|
|
assert.ok(grantBody.includes("buildMySqlPerDatabaseGrantsSql"), "legacy engines 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 grants outside utils — the grant lives in utils now");
|
|
assert.ok(!/GRANT SELECT/.test(grantBody), "no inline privilege-list GRANT may remain (MYSQL_PANEL_USER_PRIVILEGES is the single source)");
|
|
assert.ok(grantBody.includes("databases === null"), "enumeration failure must be handled fail-closed, not defaulted to a global grant");
|
|
});
|
|
|
|
check("index.js createMySqlUser is create-only and refuses reserved system accounts (hijack fix)", () => {
|
|
const body = stripComments(extractFunction("createMySqlUser"));
|
|
// CREATE USER IF NOT EXISTS + ALTER USER ... IDENTIFIED BY used to
|
|
// re-password ANY pre-existing untracked account ({"username":"root"})
|
|
// because existence was only checked against panel bookkeeping; DROP USER
|
|
// IF EXISTS (the dead forceRecreate branch) would have deleted it. A
|
|
// plain CREATE USER fails the batch at its first statement instead.
|
|
assert.ok(body.includes("mySqlAccountIsReserved"), "reserved system account names must be refused before any SQL");
|
|
assert.ok(!/CREATE USER IF NOT EXISTS/.test(body), "CREATE USER must not be IF NOT EXISTS");
|
|
assert.ok(!/DROP USER/.test(body), "createMySqlUser must never drop an account");
|
|
assert.ok(!/ALTER USER/.test(body), "createMySqlUser must never ALTER an account");
|
|
assert.ok(body.includes("mySqlAccountIsValid"), "account identifiers must be validated before quoting");
|
|
});
|
|
|
|
check("index.js generic create route probes the live server and gates reserved names (hijack fix)", () => {
|
|
const start = indexSrc.indexOf('app.post("/api/settings/database/users"');
|
|
const end = indexSrc.indexOf('app.post("/api/settings/database/users/:username/password"', start);
|
|
assert.ok(start !== -1 && end > start, "generic create route not found");
|
|
const body = stripComments(indexSrc.slice(start, end));
|
|
assert.ok(body.includes("mySqlAccountIsReserved"), "MySQL reserved names must be gated before the action token");
|
|
assert.ok(body.includes("postgresRoleIsReserved"), "PostgreSQL reserved names must be gated before the action token");
|
|
assert.ok(body.includes("probeMySqlAccountExists"), "the route must probe mysql.user on the live server — bookkeeping alone is not the truth");
|
|
assert.ok(body.includes("existsOnServer === null"), "a failed probe must fail closed (500, nothing created)");
|
|
assert.ok(body.includes("MYSQL_ACCOUNT_ALREADY_EXISTS"), "untracked live accounts must be refused with the 409 code");
|
|
assert.ok(body.includes("ADP_PG_ROLE_ALREADY_EXISTS"), "PostgreSQL refusals must be classified by the builder's marker");
|
|
assert.ok(body.includes("result.accountExists"), "MongoDB refusals must be classified via the accountExists flag");
|
|
});
|
|
|
|
check("index.js setup endpoint refuses reserved names for fresh local MySQL setups (hijack fix)", () => {
|
|
const start = indexSrc.indexOf('app.post("/api/settings/database/setup"');
|
|
const nextPost = indexSrc.indexOf("app.post(", start + 1);
|
|
const body = stripComments(indexSrc.slice(start, nextPost));
|
|
assert.ok(body.includes("mySqlAccountIsReserved"), "setup must refuse reserved system account names");
|
|
assert.ok(body.includes("previousConfig.config?.type === 'mysql'"), "the tracked-admin exemption must be scoped to the same local MySQL deployment");
|
|
assert.ok(body.includes("isLocalDbConfigHost(previousConfig.config?.host)"), "the tracked-admin exemption must not apply to remote configs");
|
|
});
|
|
|
|
check("privileged psql channel aborts batches on error (hijack fix: ON_ERROR_STOP)", () => {
|
|
const privSrc = fs.readFileSync(path.join(__dirname, "..", "privileged", "adpanel-priv"), "utf8");
|
|
const start = privSrc.indexOf("op_psql_postgres() {");
|
|
assert.ok(start !== -1, "op_psql_postgres not found");
|
|
const end = privSrc.indexOf("}", start);
|
|
const body = privSrc.slice(start, end);
|
|
assert.ok(/ON_ERROR_STOP=1/.test(body), "psql must stop at the first failed statement and exit non-zero — without it the panel-user batch continues past the ADP_PG_ROLE_ALREADY_EXISTS raise and plain failures report success (psql exits 0 on SQL errors)");
|
|
});
|
|
|
|
check("index.js ensureMySqlSetupAccount stages without dropping or re-passwording (setup finding 1)", () => {
|
|
const body = stripComments(extractFunction("ensureMySqlSetupAccount"));
|
|
assert.ok(body.includes("CREATE USER IF NOT EXISTS"), "staged provisioning must be create-if-missing");
|
|
assert.ok(!body.includes("DROP USER"), "staged provisioning must never drop an existing account — only rollbackMySqlSetupAccounts may, on staged variants");
|
|
assert.ok(!body.includes("ALTER USER"), "staged provisioning must never change an existing account's password — that happens at commit time only");
|
|
assert.ok(body.includes("_buildMySqlGrantSection"), "staged grants must come from the shared strategy helper");
|
|
});
|
|
|
|
check("index.js setup endpoint stages accounts and fails on phpMyAdmin config write errors (findings 1+2)", () => {
|
|
const start = indexSrc.indexOf('app.post("/api/settings/database/setup"');
|
|
assert.ok(start !== -1, "setup endpoint not found");
|
|
// Slice to the next route registration so the endpoint body alone is checked.
|
|
const nextPost = indexSrc.indexOf("app.post(", start + 1);
|
|
const nextDelete = indexSrc.indexOf("app.delete(", start + 1);
|
|
let end = -1;
|
|
if (nextPost !== -1 && nextDelete !== -1) end = Math.min(nextPost, nextDelete);
|
|
else if (nextPost !== -1) end = nextPost;
|
|
else if (nextDelete !== -1) end = nextDelete;
|
|
assert.ok(end > start, "setup endpoint boundary not found");
|
|
const body = stripComments(indexSrc.slice(start, end));
|
|
assert.ok(body.includes("if (!configurePhpMyAdmin("), "a failed phpMyAdmin config.inc.php write must fail setup, not report success");
|
|
assert.ok(!body.includes("createMySqlUser("), "setup must provision through the staged helper, never the password-clobbering create path");
|
|
});
|
|
|
|
check("index.js probeMySqlAccountHosts matches the host column positionally (review finding: username 'localhost' false positive)", () => {
|
|
const body = stripComments(extractFunction("probeMySqlAccountHosts"));
|
|
// The host must be read from the row's LAST field after the FIRST field
|
|
// matched the probed username. A token scan across the whole row used to
|
|
// treat the username 'localhost' (legal panel name) as a host token,
|
|
// falsely marking the variant pre-existing and exempting the freshly
|
|
// staged @localhost account from every rollback path.
|
|
assert.ok(body.includes("fields[0].toLowerCase() !== username.toLowerCase()"), "the first row field must be matched against the probed username");
|
|
assert.ok(body.includes('fields[fields.length - 1]'), "the host must come from the row's last field");
|
|
assert.ok(!/\(\^\|\\s\)/.test(body), "the whole-row host-token regex must not return");
|
|
});
|
|
|
|
check("index.js generic create endpoint refuses same-name creates against the host-less setup admin (review finding)", () => {
|
|
const start = indexSrc.indexOf('app.post("/api/settings/database/users"');
|
|
const end = indexSrc.indexOf('app.post("/api/settings/database/users/:username/password"', start);
|
|
assert.ok(start !== -1 && end > start, "generic create endpoint not found");
|
|
const body = stripComments(indexSrc.slice(start, end));
|
|
assert.ok(
|
|
body.includes("!Object.prototype.hasOwnProperty.call(u, 'host')"),
|
|
"the host-less (setup-created) entry must be detected"
|
|
);
|
|
assert.ok(body.includes("['%', 'localhost'].includes(cleanHost.toLowerCase())"), "the '%' and 'localhost' variants owned by the setup admin must be guarded");
|
|
});
|
|
|
|
check("index.js pgAdmin recovery branch is serialized on pgadminOperationMutex (review finding)", () => {
|
|
const src = stripComments(indexSrc);
|
|
assert.ok(src.includes("async function ensurePgAdminBackendReady()"), "the pgAdmin backend-readiness/recovery branch must be extracted into a helper");
|
|
const start = src.indexOf('if (service === "pgadmin") {');
|
|
const end = src.indexOf('if (service === "phpmyadmin") {', start);
|
|
assert.ok(start !== -1 && end > start, "pgadmin branch not found");
|
|
const body = src.slice(start, end);
|
|
assert.ok(body.includes("pgadminOperationMutex.tryAcquire()"), "recovery must hold the same mutex as setup and disable");
|
|
assert.ok(body.includes("releasePgAdminRecoveryLock()"), "the recovery lock must be released in a finally");
|
|
});
|
|
|
|
check("2.8: mongodbOperationMutex present; no boolean lock remains", () => {
|
|
const src = stripComments(indexSrc).replace(/releaseMongoOperationLock/g, "");
|
|
// The mutex may be the original inline IIFE or the shared
|
|
// createOperationMutex factory both database locks now come from; what the
|
|
// finding requires is a promise-based FIFO mutex, not a boolean flag.
|
|
assert.ok(
|
|
/const mongodbOperationMutex = (?:createOperationMutex\(|\(\(\) => \{)/.test(src),
|
|
"promise mutex must exist"
|
|
);
|
|
assert.ok(/tryAcquire/.test(src), "mutex must expose tryAcquire");
|
|
assert.ok(!/\bmongodbOperationLock\b\s*=/.test(src), "the old boolean lock must not be assigned anywhere");
|
|
const endpointCount = (src.match(/mongodbOperationMutex\.tryAcquire\(\)/g) || []).length;
|
|
assert.strictEqual(endpointCount, 3, "all three mongo mutation endpoints must acquire the mutex");
|
|
});
|
|
|
|
// ---- summary -------------------------------------------------------------------
|
|
|
|
console.log(`\n${passed} checks passed, ${failures.length} failed`);
|
|
if (failures.length > 0) {
|
|
process.exit(1);
|
|
}
|
|
console.log("db-user-privileges verification: OK");
|