Initial upload to Gitea

This commit is contained in:
antonn committed 2026-11-30 16:32:37 +00:00
1 parent 78193254ad
commit 8478998cae
1485 files changed
+461025 -42348

No files matched your search

+871
View File
@@ -0,0 +1,871 @@
#!/usr/bin/env node
// Migration for audit finding 2.1 (and H1 for MySQL) on EXISTING
// installations: panel-created database users issued by older panel versions
// hold privilege far beyond their own data — PostgreSQL SUPERUSER/CREATEROLE,
// MongoDB root/*AnyDatabase, and MySQL DML/DDL ON *.* which includes the
// panel's own schema (users.password hashes, 2FA secrets, recovery codes,
// node tokens). This script re-issues them the scoped grants the panel
// issues today:
//
// PostgreSQL (unified phpMyAdmin users):
// ALTER ROLE ... NOSUPERUSER NOCREATEDB NOCREATEROLE
// + CREATE DATABASE user_<name> OWNER <name> (only if missing)
// PostgreSQL (pgAdmin bootstrap login):
// ALTER ROLE ... NOSUPERUSER CREATEDB NOCREATEROLE
// MongoDB (all panel users except the install-time admin):
// grant readWrite+dbAdmin on user_<name>, revoke root/*AnyDatabase
// MySQL (audit H1; accounts are discovered on the server, so this needs
// the mysql/mariadb client and admin access — not just panel config
// files):
// REVOKE ALL PRIVILEGES, GRANT OPTION, then either
// - MySQL >= 8 with @@partial_revokes=ON: global DML/DDL grant +
// REVOKE ALL on the panel schema, mysql and sys, or
// - MariaDB / MySQL 5.7 / partial_revokes OFF: per-database DML/DDL
// grants over every existing database except the panel schema and
// the system schemas.
// Only panel-recorded accounts — plus accounts demonstrably holding
// schema-wide, protected-schema or admin grants — are rescoped; other
// server accounts are never touched, so a manually created narrow app
// account can never be widened by this script.
//
// Modes:
// (default) dry run — print every SQL statement / eval script,
// change nothing. Review before applying.
// --apply execute the migration.
// --verify read-only live check: query each panel user's ACTUAL
// privileges (pg_roles / db.getUser() / SHOW GRANTS) and
// exit non-zero if any still holds admin privilege.
// This is the runtime companion to
// scripts/verify-db-user-privileges.js.
//
// Options:
// --config-dir DIR panel directory containing the -config.json
// files (default: repo root)
// --protect-user NAME never touch this DB user (repeatable); always
// includes the install-time MongoDB admin
// (users[0] of mongodb-config.json), the
// authenticated --mongo-admin-user, the
// reserved roles postgres/admin/root/pg_*, and
// the install-time MySQL accounts (root,
// debian-sys-maint, mysql.sys, mysql.session,
// mysql.infoschema, mariadb.sys)
// --mongo-admin-user U MongoDB admin credentials for authenticated
// --mongo-admin-password P operation. Prefer the env vars
// ADPANEL_MONGO_ADMIN_USER /
// ADPANEL_MONGO_ADMIN_PASSWORD — passing the
// password as a CLI flag puts it on this
// process's argv, which any local user can read
// through /proc/<pid>/cmdline (the flag is only
// kept for compatibility and triggers a
// warning). Either way the password never
// reaches the mongo shell's argv: authentication
// runs from a 0600 script staged in a 0700 temp
// directory. Without credentials the script
// uses the panel's own maintenance window:
// temporarily disable authorization in
// /etc/mongod.conf, restart, migrate, restore.
// That mode requires root.
//
// Exit codes: 0 success, 1 one or more users failed / failed verification,
// 2 usage or environment error.
//
// Run on the panel server: node scripts/migrate-db-user-privileges.js
"use strict";
const fs = require("fs");
const os = require("os");
const path = require("path");
const { spawnSync } = require("child_process");
const priv = require("../utils/db-user-privileges");
const DRY_RUN_BANNER =
"DRY RUN — printing planned statements only. Re-run with --apply to execute.";
function failUsage(message) {
console.error(`error: ${message}`);
process.exit(2);
}
function parseArgs(argv) {
const opts = {
apply: false,
verify: false,
configDir: path.join(__dirname, ".."),
protectUsers: [],
mongoAdminUser: process.env.ADPANEL_MONGO_ADMIN_USER || null,
mongoAdminPassword: process.env.ADPANEL_MONGO_ADMIN_PASSWORD || null,
};
for (let i = 0; i < argv.length; i++) {
const a = argv[i];
if (a === "--apply") opts.apply = true;
else if (a === "--verify") opts.verify = true;
else if (a === "--config-dir") opts.configDir = argv[++i];
else if (a === "--protect-user") opts.protectUsers.push(argv[++i]);
else if (a === "--mongo-admin-user") opts.mongoAdminUser = argv[++i];
else if (a === "--mongo-admin-password") {
opts.mongoAdminPassword = argv[++i];
opts.mongoAdminPasswordFromCli = true;
}
else if (a === "--help" || a === "-h") {
console.log("See the header comment of this file for usage.");
process.exit(0);
} else {
failUsage(`unknown argument: ${a}`);
}
}
if (opts.apply && opts.verify) failUsage("--apply and --verify are mutually exclusive");
for (const dep of [opts.configDir]) {
if (typeof dep !== "string" || !dep) failUsage("missing value for a flag");
}
return opts;
}
function readJson(file) {
try {
return JSON.parse(fs.readFileSync(file, "utf8"));
} catch {
return null;
}
}
function isRoot() {
return typeof process.getuid === "function" && process.getuid() === 0;
}
function run(cmd, args, { timeoutMs = 60000, input = null, env = null } = {}) {
const r = spawnSync(cmd, args, {
input,
timeout: timeoutMs,
encoding: "utf8",
maxBuffer: 16 * 1024 * 1024,
...(env ? { env } : {}),
});
return {
code: r.status,
stdout: (r.stdout || "").trim(),
stderr: (r.stderr || "").trim(),
error: r.error ? r.error.message : null,
};
}
// ---- target enumeration -------------------------------------------------------
function collectTargets(configDir) {
const unified = readJson(path.join(configDir, "database-config.json"));
const mongoCfg = readJson(path.join(configDir, "mongodb-config.json"));
const pgadminCfg = readJson(path.join(configDir, "pgadmin-config.json"));
const targets = {
// unified phpMyAdmin-managed users, split by engine actually in use
pgUnified: [],
mongoUnified: [],
mysqlUnified: [],
// standalone MongoDB management: users[0] is the install-time admin
mongoAdmin: null,
mongoStandalone: [],
// pgAdmin bootstrap roles
pgAdmin: [],
mongoPort: String((mongoCfg && mongoCfg.port) || "27017"),
mysqlType: false,
};
if (unified && unified.enabled && Array.isArray(unified.users)) {
const type = (unified.config && unified.config.type) || "mysql";
for (const u of unified.users) {
if (!u || !u.username) continue;
if (type === "postgresql") targets.pgUnified.push(u.username);
else if (type === "mongodb") {
targets.mongoUnified.push(u.username);
if (unified.config && unified.config.port) targets.mongoPort = String(unified.config.port);
} else if (type === "mysql") {
targets.mysqlUnified.push({ username: u.username, host: u.host || "%" });
targets.mysqlType = true;
}
}
}
if (mongoCfg && mongoCfg.enabled && Array.isArray(mongoCfg.users)) {
const names = mongoCfg.users.map((u) => u && u.username).filter(Boolean);
if (names.length > 0) targets.mongoAdmin = names[0];
targets.mongoStandalone = names.slice(1);
if (mongoCfg.port) targets.mongoPort = String(mongoCfg.port);
}
if (pgadminCfg && pgadminCfg.enabled && Array.isArray(pgadminCfg.users)) {
for (const u of pgadminCfg.users) {
if (u && u.pgUser) targets.pgAdmin.push(u.pgUser);
}
}
return targets;
}
function buildProtectedSet(targets, opts) {
const protectedNames = new Set(opts.protectUsers);
if (targets.mongoAdmin) protectedNames.add(targets.mongoAdmin);
if (opts.mongoAdminUser) protectedNames.add(opts.mongoAdminUser);
// Reserved server roles, whatever their origin.
for (const reserved of ["postgres", "admin", "root", "pg_signal_backend", "pg_read_all_data", "pg_write_all_data"]) {
protectedNames.add(reserved);
}
return protectedNames;
}
// ---- PostgreSQL ----------------------------------------------------------------
// Resolve a psql invocation running as the PostgreSQL superuser:
// root -> runuser, otherwise sudo, otherwise direct (peer auth as postgres).
function makePsqlRunner() {
const psqlArgs = ["-v", "ON_ERROR_STOP=1", "-A", "-t", "-F", "|", "-d", "postgres"];
const candidates = [];
if (isRoot()) candidates.push({ cmd: "runuser", pre: ["-u", "postgres", "--"] });
candidates.push({ cmd: "sudo", pre: ["-u", "postgres", "--"] });
candidates.push({ cmd: "psql", pre: [] });
for (const c of candidates) {
const probe = run(c.cmd, [...c.pre, "psql", ...psqlArgs, "-c", "SELECT 1"], { timeoutMs: 15000 });
if (probe.code === 0) {
return {
describe: `${c.cmd} ${c.pre.join(" ")} psql`.trim(),
// Statements go over stdin, never -c: psql expands meta-commands
// (\gexec) only in stdin/interactive mode, and -c would send the
// whole script as a single SQL statement.
sql: (statement) => run(c.cmd, [...c.pre, "psql", ...psqlArgs], { input: statement }),
};
}
}
return null;
}
function migratePostgresGroup(psql, label, users, createdb, withDatabase) {
let failures = 0;
for (const username of users) {
const sql = priv.buildPostgresRescopeSql({ username, createdb, withDatabase: withDatabase !== false });
if (!sql) {
console.error(` [${label}] SKIP ${username}: invalid identifier (fail closed)`);
failures++;
continue;
}
if (!psql) {
console.log(` [${label}] ${username} would run:\n${sql.replace(/^/gm, " ")}`);
continue;
}
const res = psql.sql(sql);
if (res.code === 0) {
console.log(` [${label}] ${username}: rescoped (NOSUPERUSER ${createdb ? "CREATEDB " : "NOCREATEDB "}NOCREATEROLE${withDatabase === false ? "" : " + per-user database"})`);
} else {
console.error(` [${label}] ${username}: FAILED — ${res.stderr || res.error || `exit ${res.code}`}`);
failures++;
}
}
return failures;
}
function verifyPostgres(psql, groups) {
const expectations = [
{ users: groups.pgUnified, rolsuper: false, rolcreatedb: false, rolcreaterole: false, label: "unified" },
{ users: groups.pgAdmin, rolsuper: false, rolcreatedb: true, rolcreaterole: false, label: "pgAdmin bootstrap" },
];
let bad = 0;
for (const group of expectations) {
for (const username of group.users) {
const res = psql.sql(
`SELECT rolname, rolsuper, rolcreatedb, rolcreaterole FROM pg_roles WHERE rolname = '${String(username).replace(/'/g, "''")}';`
);
if (res.code !== 0) {
console.error(` [pg/${group.label}] ${username}: query failed — ${res.stderr || res.error}`);
bad++;
continue;
}
const line = res.stdout.split(/\r?\n/).find((l) => l.trim());
if (!line) {
console.error(` [pg/${group.label}] ${username}: role not found`);
bad++;
continue;
}
const [, rolsuper, rolcreatedb, rolcreaterole] = line.split("|").map((s) => s.trim());
const ok = rolsuper === "f"
&& rolcreatedb === (group.rolcreatedb ? "t" : "f")
&& rolcreaterole === "f";
if (ok) {
console.log(` [pg/${group.label}] ${username}: OK (rolsuper=${rolsuper} rolcreatedb=${rolcreatedb} rolcreaterole=${rolcreaterole})`);
} else {
console.error(` [pg/${group.label}] ${username}: STILL OVER-PRIVILEGED (rolsuper=${rolsuper} rolcreatedb=${rolcreatedb} rolcreaterole=${rolcreaterole})`);
bad++;
}
}
}
return bad;
}
// ---- MongoDB -------------------------------------------------------------------
function buildMongoshRunner(opts, port) {
// mongosh/mongo have no environment-variable or stdin auth, and -u/-p
// would publish the admin password on argv, which any local user can read
// through /proc/<pid>/cmdline. When credentials are used, authentication
// is prepended to each eval and staged as a 0600 file inside a 0700 temp
// directory removed at process exit. The connectionStatus check makes the
// preamble fail closed: an unauthenticated connection can never pass.
let authPreamble = null;
let stageDir = null;
let stagePath = null;
if (opts.mongoAdminUser) {
authPreamble =
"db = db.getSiblingDB('admin');\n" +
`try { db.auth(${JSON.stringify(opts.mongoAdminUser)}, ${JSON.stringify(opts.mongoAdminPassword || "")}); } ` +
"catch (e) { print('MONGO_AUTH_FAILED: ' + e.message); quit(1); }\n" +
"if ((((db.runCommand({ connectionStatus: 1 }) || {}).authInfo || {}).authenticatedUsers || []).length < 1) { print('MONGO_AUTH_FAILED'); quit(1); }\n";
}
const stageScript = (script) => {
if (!stageDir) {
stageDir = fs.mkdtempSync(path.join(os.tmpdir(), "adpanel-mongosh-"));
fs.chmodSync(stageDir, 0o700);
stagePath = path.join(stageDir, "cmd.js");
process.on("exit", () => { try { fs.rmSync(stageDir, { recursive: true, force: true }); } catch { } });
}
fs.writeFileSync(stagePath, (authPreamble || "") + script + "\n", { mode: 0o600 });
return stagePath;
};
// Prefer mongosh; fall back to the legacy mongo shell, which supports
// the same eval surface (the panel keeps a legacy path for the same
// reason).
const shells = [
{ cmd: "mongosh", extraArgs: ["--host", "127.0.0.1", "--port", String(port)] },
{ cmd: "mongo", extraArgs: ["--host", "127.0.0.1", "--port", String(port)] },
];
const evalScript = (script) => {
let lastMissing = "no mongo shell found";
const scriptPath = stageScript(script);
for (const shell of shells) {
const res = run(shell.cmd, [...shell.extraArgs, "admin", "--quiet", scriptPath], { timeoutMs: 30000 });
if (res.error && res.error.includes("ENOENT")) {
lastMissing = `${shell.cmd} not found`;
continue;
}
return res;
}
return { code: 1, stdout: "", stderr: lastMissing };
};
return { eval: evalScript, authenticated: Boolean(opts.mongoAdminUser) };
}
// The panel's own maintenance pattern, mirrored from index.js: temporarily
// disable authorization (pinning bindIp to loopback for the window), run,
// then restore the original configuration — including on failure.
function withMongoAuthDisabled(port, fn) {
const confPath = "/etc/mongod.conf";
let originalBindIp = null;
let hadAuth = false;
let conf;
try {
conf = fs.readFileSync(confPath, "utf8");
} catch (err) {
throw new Error(`cannot read ${confPath} (${err.message}); pass --mongo-admin-user/--mongo-admin-password instead`);
}
hadAuth = conf.includes("authorization: enabled");
if (hadAuth) {
if (!isRoot()) {
throw new Error("disabling MongoDB authorization requires root; run as root or pass --mongo-admin-user/--mongo-admin-password");
}
const bindMatch = conf.match(/bindIp:\s*([\d.,]+)/);
originalBindIp = bindMatch ? bindMatch[1] : "127.0.0.1";
let modified = conf.replace(/bindIp:\s*[\d.,]+/g, "bindIp: 127.0.0.1");
modified = modified.replace(/security:\s*\n\s*authorization:\s*enabled\s*/g, "");
fs.writeFileSync(confPath, modified, { mode: 0o644 });
const restart = run("systemctl", ["restart", "mongod"], { timeoutMs: 45000 });
if (restart.code !== 0) {
// Best effort restore before bailing out.
fs.writeFileSync(confPath, conf, { mode: 0o644 });
run("systemctl", ["restart", "mongod"], { timeoutMs: 45000 });
throw new Error("failed to restart mongod for the maintenance window");
}
const sleep = run("sleep", ["2"]);
void sleep;
}
try {
return fn();
} finally {
if (hadAuth) {
try {
let cur = fs.readFileSync(confPath, "utf8");
if (originalBindIp) cur = cur.replace(/bindIp:\s*[\d.,]+/g, `bindIp: ${originalBindIp}`);
if (!cur.includes("authorization: enabled")) cur += "\nsecurity:\n authorization: enabled\n";
fs.writeFileSync(confPath, cur, { mode: 0o644 });
const restore = run("systemctl", ["restart", "mongod"], { timeoutMs: 45000 });
if (restore.code !== 0) {
console.error(`FATAL: could not restart mongod with authorization restored: ${restore.stderr || restore.error}`);
process.exit(1);
}
console.log(" [mongo] authorization re-enabled, original bindIp restored");
} catch (err) {
console.error(`FATAL: could not restore ${confPath}: ${err.message}`);
console.error(" MongoDB may be running WITHOUT authorization — fix /etc/mongod.conf immediately.");
process.exit(1);
}
}
}
}
function migrateMongoUsers(mongosh, users) {
let failures = 0;
for (const username of users) {
const script = priv.buildMongoRescopeEval(username);
if (!script) {
console.error(` [mongo] SKIP ${username}: invalid username (fail closed)`);
failures++;
continue;
}
if (!mongosh) {
console.log(` [mongo] ${username} would run:\n ${script}`);
continue;
}
const res = mongosh.eval(script);
if (res.code === 0 && res.stdout.includes("ADP_RESCOPE_OK")) {
const rolesLine = res.stdout.split(/\r?\n/).slice(1).join(" ");
console.log(` [mongo] ${username}: rescoped to ${rolesLine || "scoped roles"}`);
} else if (res.code === 0 && res.stdout.includes("ADP_USER_MISSING")) {
console.warn(` [mongo] ${username}: not present on the server (stale panel entry) — nothing to do`);
} else {
console.error(` [mongo] ${username}: FAILED — ${res.stderr || res.stdout || res.error || `exit ${res.code}`}`);
failures++;
}
}
return failures;
}
function verifyMongoUsers(mongosh, users) {
let bad = 0;
for (const username of users) {
const res = mongosh.eval(
`var u=${JSON.stringify(username)};var i=db.getSiblingDB('admin').getUser(u,{showPrivileges:false});` +
`print(i?JSON.stringify(i.roles||[]):'ADP_USER_MISSING');`
);
if (res.code !== 0) {
console.error(` [mongo] ${username}: query failed — ${res.stderr || res.error}`);
bad++;
continue;
}
if (res.stdout.includes("ADP_USER_MISSING")) {
console.warn(` [mongo] ${username}: not present (stale panel entry)`);
continue;
}
let roles;
try {
roles = JSON.parse(res.stdout.split(/\r?\n/).find((l) => l.trim().startsWith("[")) || "null");
} catch {
roles = null;
}
if (!Array.isArray(roles)) {
console.error(` [mongo] ${username}: could not parse roles — ${res.stdout}`);
bad++;
continue;
}
const dangerous = roles.filter((r) => priv.mongoRoleIsDangerous(r));
if (dangerous.length === 0) {
console.log(` [mongo] ${username}: OK (${roles.map((r) => `${r.role}@${r.db}`).join(", ") || "no roles"})`);
} else {
console.error(` [mongo] ${username}: STILL OVER-PRIVILEGED (${dangerous.map((r) => r.role).join(", ")})`);
bad++;
}
}
return bad;
}
// ---- MySQL -----------------------------------------------------------------------
const MYSQL_ADMIN_PRIVILEGES = ["SUPER", "GRANT OPTION", "FILE", "PROCESS", "RELOAD", "SHUTDOWN", "CREATE USER", "REPLICATION CLIENT", "REPLICATION SLAVE", "CREATE ROLE", "DROP ROLE"];
// Install-time / OS-maintained MySQL accounts that are never rescoped.
const MYSQL_PROTECTED_USERS = [
"root",
"debian-sys-maint",
"mysql.sys",
"mysql.session",
"mysql.infoschema",
"mariadb.sys",
];
function makeMysqlRunner() {
// Channel order mirrors the panel: a MYSQL_PASSWORD from the environment
// is offered first as MYSQL_PWD (environ is 0400 and owned by the process
// uid; argv would be world-readable through /proc/<pid>/cmdline, so the
// password never travels as --password), then socket auth, sudo, and
// -u root. The mariadb client is tried as a fallback for installs where
// the mysql symlink is absent.
const clients = ["mysql", "mariadb"];
const envPwd = (process.env.MYSQL_PASSWORD || "").trim();
const candidates = [];
for (const c of clients) {
if (envPwd) candidates.push({ cmd: c, pre: ["-u", "root"], via: `${c} -u root (MYSQL_PWD)`, env: { ...process.env, MYSQL_PWD: envPwd } });
if (isRoot()) candidates.push({ cmd: c, pre: [], via: `${c} (socket auth)` });
candidates.push({ cmd: "sudo", pre: [c], via: `sudo ${c}` });
candidates.push({ cmd: c, pre: ["-u", "root"], via: `${c} -u root` });
}
for (const c of candidates) {
const probe = run(c.cmd, [...c.pre, "--connect-timeout=3", "-B", "-N", "-e", "SELECT 1"], { timeoutMs: 15000, env: c.env });
if (probe.code === 0) {
return {
describe: c.via,
// Multi-statement SQL goes over stdin in batch mode (-B keeps probe
// output parseable); stdin, like the panel's own channel, keeps
// every statement out of argv.
sql: (statements) => run(c.cmd, [...c.pre, "-B"], { input: statements, timeoutMs: 60000, env: c.env }),
};
}
}
return null;
}
function mysqlPanelDbName() {
return String(process.env.MYSQL_DATABASE || process.env.MYSQL_DB || "adpanel").trim();
}
// Batch-mode rows from a single-column probe: a header line names the
// column, the following line carries the value. Rows are located by shape,
// so wrapper output around the client's rows cannot shift positions.
function mysqlProbeRows(stdout) {
return String(stdout || "").split(/\r?\n/).map((l) => l.trim()).filter((l) => l);
}
// Same classification the panel's _detectMySqlFlavor performs, so migration
// and runtime provisioning always pick the same grant strategy.
function detectMySqlGrantStrategy(mysql) {
const vres = mysql.sql("SELECT VERSION();");
if (vres.code !== 0) return { error: vres.stderr || vres.error || `exit ${vres.code}` };
const version = mysqlProbeRows(vres.stdout).find((l) => /^\d+(\.\d+)+/.test(l));
if (!version) return { error: "could not parse SELECT VERSION() output" };
if (/mariadb/i.test(version)) return { flavor: "mariadb" };
const major = parseInt(version.split(".")[0], 10);
if (!Number.isFinite(major)) return { error: `unparseable version string: ${version}` };
if (major < 8) return { flavor: "mysql-legacy" };
// MySQL >= 8: an unreadable @@global.partial_revokes counts as OFF — the
// per-database strategy is the more restrictive direction.
const prres = mysql.sql("SELECT @@global.partial_revokes;");
const rows = prres.code === 0 ? mysqlProbeRows(prres.stdout) : [];
const idx = rows.findIndex((l) => l === "@@global.partial_revokes");
return { flavor: idx >= 0 && rows[idx + 1] === "1" ? "mysql-partial-revokes" : "mysql-legacy" };
}
function enumerateMySqlDatabases(mysql, panelDb) {
const res = mysql.sql("SHOW DATABASES;");
if (res.code !== 0) return null;
return mysqlProbeRows(res.stdout)
.filter((l) => !/^Database$/i.test(l))
.filter((name) => !priv.isProtectedMySQLDatabase(name, panelDb));
}
// Panel-created accounts are discovered on the server (mysql.user) rather
// than trusted from panel config files, which may be stale or deleted.
// Anything outside the panel's identifier rules, and every install-time or
// OS-maintained account, is reported and left untouched.
//
// Scope discipline: an account the panel did not record is only included when
// it demonstrably carries the audited over-privilege (schema-wide, protected-
// schema or admin grants). Rescoping grants the panel DML/DDL set over every
// non-protected database, so blindly including manually created app accounts
// could WIDEN a narrow account's grants. Panel-recorded accounts are always
// included — the panel is entitled to rescope its own issue.
function discoverMySqlAccounts(mysql, opts, panelRecorded, panelDb) {
const res = mysql.sql("SELECT user, host FROM mysql.user;");
if (res.code !== 0) return { error: res.stderr || res.error || `exit ${res.code}` };
const panelUsernames = new Set((panelRecorded || []).map((a) => String((a && a.username) || "").toLowerCase()));
const accounts = [];
for (const line of mysqlProbeRows(res.stdout)) {
if (/^user\thost$/i.test(line)) continue; // batch-mode header
const tab = line.indexOf("\t");
const username = tab === -1 ? line : line.slice(0, tab);
const host = tab === -1 ? "%" : line.slice(tab + 1);
if (!username) continue;
const label = `${username}@${host}`;
if (
[...MYSQL_PROTECTED_USERS, ...opts.protectUsers]
.some((p) => String(p).toLowerCase() === username.toLowerCase())
) {
console.log(` protecting ${label} (install-time / system / --protect-user)`);
continue;
}
if (!priv.mySqlAccountIsValid(username, host)) {
console.log(` protecting ${label} (outside the panel's identifier rules — not touched)`);
continue;
}
if (!panelUsernames.has(username.toLowerCase())) {
const grantsRes = mysql.sql(`SHOW GRANTS FOR '${username}'@'${host}';`);
const over = grantsRes.code === 0
? mysqlProbeRows(grantsRes.stdout).filter((l) => mysqlGrantLineIsOverprivileged(l, panelDb))
: [];
if (over.length === 0) {
console.log(` skipping ${label} (not panel-recorded, no schema-wide or protected-schema grants — untouched)`);
continue;
}
console.log(` including ${label} (not panel-recorded but over-privileged: ${over[0].slice(0, 120)})`);
accounts.push({ username, host, source: "over-privileged" });
continue;
}
accounts.push({ username, host, source: "panel" });
}
return { accounts };
}
function buildMySqlAccountResetSql(username, host) {
// Identifiers already passed priv.mySqlAccountIsValid, so plain quoting is
// injection-safe. Stripping everything first makes the scoped grants below
// the account's complete final state, even for accounts over-granted by
// older panel versions or by hand.
return `REVOKE ALL PRIVILEGES, GRANT OPTION FROM '${username}'@'${host}';`;
}
function migrateMySqlUsers(mysql, accounts, panelDb, opts) {
let failures = 0;
const strategy = detectMySqlGrantStrategy(mysql);
if (strategy.error) {
console.error(` [mysql] flavor detection FAILED (${strategy.error}) — accounts left untouched`);
return accounts.length;
}
// With partial revokes the global grant is restricted afterwards; without
// it, the grants must be enumerated per database. A failed enumeration
// leaves every account untouched rather than half-migrated.
const databases = strategy.flavor === "mysql-partial-revokes"
? null
: enumerateMySqlDatabases(mysql, panelDb);
if (strategy.flavor !== "mysql-partial-revokes" && databases === null) {
console.error(" [mysql] database enumeration FAILED — accounts left untouched");
return accounts.length;
}
console.log(
` [mysql] strategy: ${strategy.flavor} ` +
(strategy.flavor === "mysql-partial-revokes"
? "(global grant + panel/mysql/sys revokes)"
: `(per-database grants over ${databases.length} database(s))`)
);
for (const { username, host } of accounts) {
const grantSql = strategy.flavor === "mysql-partial-revokes"
? priv.buildMySqlGlobalGrantSql(username, host, panelDb)
: priv.buildMySqlPerDatabaseGrantsSql(username, host, databases, panelDb);
if (!grantSql) {
console.error(` [mysql] SKIP ${username}@${host}: grant builder rejected identifiers (fail closed)`);
failures++;
continue;
}
const sql = buildMySqlAccountResetSql(username, host) + "\n" + grantSql + "\nFLUSH PRIVILEGES;";
if (!opts.apply) {
console.log(` [mysql] ${username}@${host} would run:\n${sql.replace(/^/gm, " ")}`);
continue;
}
const res = mysql.sql(sql);
if (res.code === 0) {
console.log(` [mysql] ${username}@${host}: rescoped`);
} else {
console.error(` [mysql] ${username}@${host}: FAILED — ${res.stderr || res.error || `exit ${res.code}`}`);
failures++;
}
}
return failures;
}
// Over-privileged = any non-USAGE grant ON *.*, any privilege at all on a
// protected schema (the panel database or the system schemas), or any of the
// admin-only privileges anywhere in the grant list.
function mysqlGrantLineIsOverprivileged(line, panelDb) {
const upper = line.toUpperCase();
for (const p of MYSQL_ADMIN_PRIVILEGES) {
if (upper.includes(p.toUpperCase())) return true;
}
if (/\bON\s+\*\.\*/.test(upper) && !/^GRANT USAGE ON \*\.\*/.test(upper)) return true;
const protectedNames = ["mysql", "sys", "performance_schema", String(panelDb || "").toLowerCase()]
.filter(Boolean)
.map((n) => n.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
return new RegExp("\\bON\\s+`?(?:" + protectedNames.join("|") + ")`?\\.\\*", "i").test(line);
}
function verifyMysqlUsers(mysql, accounts, panelDb) {
let bad = 0;
for (const { username, host, source } of accounts) {
const res = mysql.sql(`SHOW GRANTS FOR '${username}'@'${host}';`);
if (res.code !== 0) {
const errText = res.stderr || res.error || `exit ${res.code}`;
if (/1141/.test(errText)) {
console.warn(` [mysql] ${username}@${host}: not present on the server (stale panel entry)`);
continue;
}
console.error(` [mysql] ${username}@${host}: SHOW GRANTS failed — ${errText}`);
bad++;
continue;
}
const offending = mysqlProbeRows(res.stdout).filter((l) => mysqlGrantLineIsOverprivileged(l, panelDb));
if (offending.length === 0) {
console.log(` [mysql] ${username}@${host}: OK (no schema-wide or protected-schema grants)`);
} else if (source === "over-privileged") {
// Not a panel account — reported so the admin knows the server still
// carries the audited over-privilege, but not counted as a migration
// failure: --apply was never licensed to rewrite that account's role.
console.warn(` [mysql] ${username}@${host}: WARNING — not panel-recorded but holds schema-wide/admin grants (not counted): ${offending[0].slice(0, 140)}`);
} else {
console.error(` [mysql] ${username}@${host}: STILL OVER-PRIVILEGED (${offending.length} grant line(s); e.g. ${offending[0].slice(0, 140)})`);
bad++;
}
}
return bad;
}
// ---- main -----------------------------------------------------------------------
const opts = parseArgs(process.argv.slice(2));
if (opts.mongoAdminPasswordFromCli) {
console.error("warning: --mongo-admin-password placed the admin password on this process's argv (world-readable via /proc/<pid>/cmdline); prefer the ADPANEL_MONGO_ADMIN_PASSWORD environment variable");
}
const targets = collectTargets(opts.configDir);
const protectedNames = buildProtectedSet(targets, opts);
const filterUsers = (users) => users.filter((u) => {
if (protectedNames.has(u)) {
console.log(` protecting ${u} (reserved / install-time admin / --protect-user)`);
return false;
}
if (/^pg_/i.test(u)) {
console.log(` protecting ${u} (pg_* system role)`);
return false;
}
return true;
});
console.log(`Panel DB user migration (finding 2.1) — mode: ${opts.verify ? "VERIFY (read-only)" : opts.apply ? "APPLY" : "DRY RUN"}`);
console.log(`Config dir: ${opts.configDir}\n`);
const pgUnified = filterUsers(targets.pgUnified);
const pgAdmin = filterUsers(targets.pgAdmin);
const mongoUsers = filterUsers([...new Set([...targets.mongoUnified, ...targets.mongoStandalone])]);
if (targets.mongoAdmin) console.log(`MongoDB install-time admin (kept, never rescoped): ${targets.mongoAdmin}\n`);
if (opts.verify) {
let bad = 0;
if (pgUnified.length || pgAdmin.length) {
const psql = makePsqlRunner();
if (!psql) {
console.error("PostgreSQL: no usable psql access (tried runuser/sudo/peer). Run on the server as root.");
bad += pgUnified.length + pgAdmin.length;
} else {
console.log(`PostgreSQL via: ${psql.describe}`);
bad += verifyPostgres(psql, { pgUnified, pgAdmin });
}
}
if (mongoUsers.length) {
const mongosh = buildMongoshRunner(opts, targets.mongoPort);
if (mongosh.authenticated) {
bad += verifyMongoUsers(mongosh, mongoUsers);
} else {
// --verify is read-only: never use the authorization-disabled
// maintenance window here. Probe unauthenticated access (only
// possible when authorization is off) and require credentials
// otherwise.
const probe = mongosh.eval("db.getSiblingDB('admin').getUsers()");
if (probe.code === 0) {
console.warn(" [mongo] WARNING: server answered WITHOUT authentication (authorization disabled?) — re-enable before production use");
bad += verifyMongoUsers(mongosh, mongoUsers);
} else {
console.error(" [mongo] cannot verify without admin credentials — pass --mongo-admin-user/--mongo-admin-password (read-only mode will not disable authorization)");
bad += mongoUsers.length;
}
}
}
if (targets.mysqlType) {
const mysql = makeMysqlRunner();
if (!mysql) {
console.error("MySQL: no usable mysql/mariadb client access (tried MYSQL_PWD/socket/sudo) — cannot verify");
bad += 1;
} else {
console.log(`MySQL via: ${mysql.describe}`);
const discovery = discoverMySqlAccounts(mysql, opts, targets.mysqlUnified, mysqlPanelDbName());
if (discovery.error) {
console.error(`MySQL: account discovery failed — ${discovery.error}`);
bad += 1;
} else {
bad += verifyMysqlUsers(mysql, discovery.accounts, mysqlPanelDbName());
}
}
}
if (bad > 0) {
console.error(`\nverification FAILED for ${bad} user(s)`);
process.exit(1);
}
console.log("\nverification OK: no panel user holds server-wide admin privilege");
process.exit(0);
}
let failures = 0;
let anyWork = false;
if (pgUnified.length || pgAdmin.length) {
anyWork = true;
const psql = opts.apply ? makePsqlRunner() : null;
if (opts.apply && !psql) {
console.error("PostgreSQL: no usable psql access (tried runuser/sudo/peer). Run on the server as root.");
failures += pgUnified.length + pgAdmin.length;
} else {
if (psql) console.log(`PostgreSQL via: ${psql.describe}`);
if (pgUnified.length) {
console.log("\n== PostgreSQL unified panel users (NOSUPERUSER NOCREATEDB NOCREATEROLE + per-user database) ==");
failures += migratePostgresGroup(psql, "pg/unified", pgUnified, false);
}
if (pgAdmin.length) {
console.log("\n== PostgreSQL pgAdmin bootstrap logins (NOSUPERUSER CREATEDB NOCREATEROLE) ==");
// No per-user database: matches the fresh-install bootstrap path,
// which creates none (CREATEDB covers pgAdmin's needs).
failures += migratePostgresGroup(psql, "pg/pgadmin", pgAdmin, true, false);
}
}
}
if (mongoUsers.length) {
anyWork = true;
const mongosh = opts.apply ? buildMongoshRunner(opts, targets.mongoPort) : null;
console.log("\n== MongoDB panel users (grant readWrite+dbAdmin on user_<name>, revoke root/*AnyDatabase) ==");
if (opts.apply && !mongosh.authenticated) {
failures += withMongoAuthDisabled(targets.mongoPort, () => migrateMongoUsers(mongosh, mongoUsers));
} else {
failures += migrateMongoUsers(mongosh, mongoUsers);
}
}
if (targets.mysqlType) {
anyWork = true;
console.log("\n== MySQL panel accounts (re-scope grants; panel schema and system schemas fenced off) ==");
const mysql = makeMysqlRunner();
if (!mysql) {
// Account discovery is server-side (mysql.user), so even the dry run
// needs client access; without it nothing can be enumerated or printed.
console.error("MySQL: no usable mysql/mariadb client access (tried MYSQL_PWD/socket/sudo).");
failures += 1;
} else {
console.log(`MySQL via: ${mysql.describe}`);
const discovery = discoverMySqlAccounts(mysql, opts, targets.mysqlUnified, mysqlPanelDbName());
if (discovery.error) {
console.error(`MySQL: account discovery failed — ${discovery.error}`);
failures += 1;
} else if (discovery.accounts.length === 0) {
console.log(" no rescopable MySQL accounts found");
} else {
failures += migrateMySqlUsers(mysql, discovery.accounts, mysqlPanelDbName(), opts);
}
}
}
if (!anyWork) {
console.log("No enabled database configurations with panel users found — nothing to do.");
}
if (!opts.apply) {
console.log(`\n${DRY_RUN_BANNER}`);
}
if (failures > 0) {
console.error(`\n${failures} user(s) FAILED`);
process.exit(1);
}
if (opts.apply) {
console.log("\nmigration complete");
}
process.exit(0);