Initial upload to Gitea
This commit is contained in:
1 parent
78193254ad
commit
8478998cae
1485 files changed
+461025
-42348
No files matched your search
@@ -0,0 +1,402 @@
|
||||
"use strict";
|
||||
|
||||
// Tests for audit finding L1: DB credentials on process argv.
|
||||
//
|
||||
// /proc/<pid>/cmdline is world-readable, so any local user could capture the
|
||||
// MySQL root password (mysql --password=... / -p...) or MongoDB passwords
|
||||
// embedded in mongosh --eval scripts, both during install and during routine
|
||||
// panel-driven user management. The remediation:
|
||||
//
|
||||
// - MySQL/MariaDB: credentials travel in the child's MYSQL_PWD environment
|
||||
// variable (/proc/<pid>/environ is 0400 and owned by the process uid, so
|
||||
// it is not readable by other local users) — index.js probe + cached
|
||||
// admin command, privileged/adpanel-priv op_mysql_admin, initialize.sh.
|
||||
// - MongoDB: mongosh has no environment or stdin auth, so scripts that
|
||||
// embed passwords are staged as 0600 files inside 0700 temp directories
|
||||
// (_mongoshRunScriptFile in index.js) and removed when the child exits;
|
||||
// scripts/migrate-db-user-privileges.js stages an auth preamble the same
|
||||
// way and fails closed on connectionStatus.
|
||||
//
|
||||
// index.js boots servers on require, so the helper is verified functionally
|
||||
// by extracting its source into a scratch module (same technique as
|
||||
// audit-l1-l2-l4-l6-hardening.test.js uses for source assertions), while the
|
||||
// bash runner and the migration script are exercised end-to-end with shims
|
||||
// on PATH that record argv/environ without ever persisting the secret.
|
||||
|
||||
const test = require("node:test");
|
||||
const assert = require("node:assert");
|
||||
const fs = require("node:fs");
|
||||
const os = require("node:os");
|
||||
const path = require("node:path");
|
||||
const { spawnSync } = require("node:child_process");
|
||||
|
||||
const ROOT = path.join(__dirname, "..");
|
||||
const INDEX_JS = path.join(ROOT, "index.js");
|
||||
const PRIV_SCRIPT = path.join(ROOT, "privileged", "adpanel-priv");
|
||||
const INIT_SH = path.join(ROOT, "initialize.sh");
|
||||
const MIGRATE_JS = path.join(ROOT, "scripts", "migrate-db-user-privileges.js");
|
||||
const CREATE_USER_JS = path.join(ROOT, "scripts", "create-user.js");
|
||||
|
||||
const indexSource = fs.readFileSync(INDEX_JS, "utf8");
|
||||
const privSource = fs.readFileSync(PRIV_SCRIPT, "utf8");
|
||||
const initSource = fs.readFileSync(INIT_SH, "utf8");
|
||||
const migrateSource = fs.readFileSync(MIGRATE_JS, "utf8");
|
||||
|
||||
// Live shell code (comments included): strip them so assertions cannot be
|
||||
// satisfied/violated by prose.
|
||||
const privCode = privSource.split("\n").filter((l) => !l.trim().startsWith("#")).join("\n");
|
||||
const initCode = initSource.split("\n").filter((l) => !l.trim().startsWith("#")).join("\n");
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Source assertions — the vulnerable argv patterns are gone and the safe
|
||||
// mechanisms are wired in.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
test("L1: index.js no longer places MySQL passwords on argv", () => {
|
||||
assert(!indexSource.includes("`--password=${"), "mysql --password=${...} must not be built anywhere");
|
||||
assert(!/-u',\s*adminUser,\s*'-p'/.test(indexSource), "mongosh -u admin -p <password> must not be used");
|
||||
assert(indexSource.includes("MYSQL_PWD"), "MYSQL_PWD environment mechanism must be present");
|
||||
assert(indexSource.includes("_mysqlEnvWithPassword(envPassword)"), "auth probe must pass the password via env");
|
||||
assert(indexSource.includes("if (adminCmd.envPassword)"), "cached env-password method must reach runMySqlAdmin's spawn");
|
||||
});
|
||||
|
||||
test("L1: index.js no longer passes password-bearing scripts to mongosh --eval", () => {
|
||||
assert(!/--eval',\s*createUserScript/.test(indexSource), "install-time createUser script must not go through --eval");
|
||||
assert(!/--eval',\s*mongoCommands[\s\S]{0,200}(buildMongoCreateUserEval|changeUserPassword)/.test(indexSource));
|
||||
assert(!/["']--eval["'],\s*evalScript/.test(indexSource), "settings-API mongosh runner must not use --eval");
|
||||
// The two delete-user sites were the last --eval spawns; the M2 remediation
|
||||
// moved them onto the staged-script mechanism as well, so NO --eval spawn
|
||||
// remains anywhere in index.js.
|
||||
const remaining = indexSource.match(/spawn\("(?:mongosh|mongo)",\s*\[[^\]]*--eval[^\]]*\]/g) || [];
|
||||
assert.equal(remaining.length, 0, "no spawn may pass a script via --eval (delete-user sites now stage 0600 files)");
|
||||
assert.equal((indexSource.match(/dropUser\(\$\{safeUsername\}\)/g) || []).length, 3,
|
||||
"all delete-user scripts must be username-only dropUser scripts (all staged)");
|
||||
// The safe staging helper exists and the ENOENT legacy fallbacks survive —
|
||||
// create, password update AND delete (M2 added the delete fallback when it
|
||||
// moved onto the staged runner; the fourth site is the mongodb branch of
|
||||
// checkDatabaseConnection degrading on a missing mongosh binary).
|
||||
assert(indexSource.includes("function _mongoshRunScriptFile"));
|
||||
assert(indexSource.includes("function _mysqlEnvWithPassword"));
|
||||
assert.equal((indexSource.match(/res\.errCode === 'ENOENT'/g) || []).length, 4,
|
||||
"mongosh->legacy ENOENT fallback must be preserved for create, password update and delete; the mongodb connection check degrades on a missing mongosh");
|
||||
});
|
||||
|
||||
test("L1: privileged runner never places the MySQL password on argv", () => {
|
||||
assert(!privCode.includes("--password"), "op_mysql_admin must not build --password arguments");
|
||||
assert(privCode.includes('MYSQL_PWD="$MYSQL_PASSWORD" mysql'), "probe must hand the password via MYSQL_PWD");
|
||||
assert(privCode.includes('export MYSQL_PWD="$MYSQL_PASSWORD"'), "exec'd client must receive MYSQL_PWD");
|
||||
});
|
||||
|
||||
test("L1: initialize.sh no longer places DB or panel credentials on argv", () => {
|
||||
assert(!/-p"\$\{?[A-Z]/.test(initCode), "mysql -p\"$password\" style flags must be gone");
|
||||
assert(!/--password(?!-hash)/.test(initCode), "no plaintext --password flags in live install code");
|
||||
assert(!/--current-password/.test(initCode), "no --current-password flags in live install code");
|
||||
assert(!/ADPANEL_USER_(?:CURRENT_PASSWORD|TOTP_SECRET)=|env_cmd\+=\("MYSQL_(?:URL|PASSWORD)=/.test(initCode),
|
||||
"account operations must not put credentials in env(1) arguments");
|
||||
assert(initCode.includes('run_create_user_with_credentials "$HASH" "$CURRENT" "$CREATE_USER_SCRIPT" --update-password'),
|
||||
"password change must carry the current password through the credential pipe");
|
||||
assert(initCode.includes('run_create_user_with_credentials "$admin_hash" "$admin_secret" "$script_path"'),
|
||||
"administrator bootstrap must carry its TOTP seed through the credential pipe");
|
||||
assert(!/--secret "/.test(initCode), "no TOTP secrets on create-user.js argv");
|
||||
assert(!/-a "\$/.test(initCode.replace(/tee -a |cp -a /g, "")), "no redis-cli -a password flags");
|
||||
assert(initCode.includes('MYSQL_PWD="$root_pass"'), "mysql_exec_as_root must use MYSQL_PWD");
|
||||
assert(initCode.includes("REDISCLI_AUTH="), "redis probes must use the REDISCLI_AUTH env var");
|
||||
assert(initCode.includes("ADPANEL_HASH_INPUT="), "bcrypt hashing must read the password from the environment");
|
||||
assert(!/hashSync\(process\.argv/.test(initCode), "no password passed to bcrypt via argv");
|
||||
assert(initCode.includes("process.env.MYSQL_PASSWORD || ''"), "MySQL URL encoding must read the password from the environment");
|
||||
assert(initCode.includes("process.env.REDIS_PASSWORD || ''"), "Redis URL encoding must read the password from the environment");
|
||||
assert(!initCode.includes("process.argv[1] || ''"), "URL encoding must not take passwords from argv");
|
||||
assert(initCode.includes('run_create_user_with_credentials "$pass_hash" "$SECRET" "${cmd[@]}"'),
|
||||
"user creation must carry its TOTP seed through the credential pipe");
|
||||
assert(initCode.includes('ADPANEL_TOTP_SECRET="$SECRET"'), "QR rendering must carry the TOTP secret via env");
|
||||
assert(!/--password "\$PASS1"/.test(initCode), "panel user creation must pass a pre-computed hash, not the password");
|
||||
});
|
||||
|
||||
const createUserSource = fs.readFileSync(CREATE_USER_JS, "utf8");
|
||||
const credentialInputProbe = `${createUserSource.slice(createUserSource.indexOf("function parseArgs("), createUserSource.indexOf("function requireSudo("))}
|
||||
const argv = process.argv.slice(1);
|
||||
const args = parseArgs(argv);
|
||||
const accepted = args.credentialsFromStdin && readStdinCredentials(args);
|
||||
process.stdout.write(JSON.stringify({ accepted, argv, passwordHash: args.passwordHash,
|
||||
credential: args.updatePassword ? args.currentPassword : args.secret }));
|
||||
`;
|
||||
|
||||
test("initializer pipes both credentials without putting either in command arguments", () => {
|
||||
const runner = initSource.slice(initSource.indexOf("run_create_user_with_credentials()"), initSource.indexOf("bootstrap_db_and_create_admin()"));
|
||||
const hash = "test-bcrypt-hash";
|
||||
for (const [mode, credential] of [["--admin", "TESTSEED234"], ["--update-password", " spaces $! \\ % "], ["--update-password", ""]]) {
|
||||
const result = spawnSync("bash", ["-c", `${runner}
|
||||
sudo_shim() { "$@"; }
|
||||
SUDO=sudo_shim
|
||||
run_create_user_with_credentials "$TEST_HASH" "$TEST_CREDENTIAL" -e "$1" -- "$2"
|
||||
`, "credential-input-test", credentialInputProbe, mode], {
|
||||
env: { ...process.env, TEST_HASH: hash, TEST_CREDENTIAL: credential }, encoding: "utf8",
|
||||
});
|
||||
assert.strictEqual(result.status, 0, result.stderr);
|
||||
assert.deepStrictEqual(JSON.parse(result.stdout), {
|
||||
accepted: true, argv: [mode, "--credentials-stdin"], passwordHash: hash, credential: credential || null,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
test("truncated credential input cannot turn a verified change into a forced reset", () => {
|
||||
const result = spawnSync(process.execPath, ["-e", credentialInputProbe, "--", "--update-password", "--credentials-stdin"], {
|
||||
input: "test-bcrypt-hash\0", encoding: "utf8",
|
||||
});
|
||||
assert.strictEqual(result.status, 0, result.stderr);
|
||||
assert.strictEqual(JSON.parse(result.stdout).accepted, false);
|
||||
});
|
||||
|
||||
test("L1: migrate-db-user-privileges.js stages auth instead of mongosh -u/-p", () => {
|
||||
assert(!migrateSource.includes('"-p", opts.mongoAdminPassword'), "mongo admin password must not go on mongosh argv");
|
||||
assert(migrateSource.includes("connectionStatus: 1"), "staged auth preamble must fail closed on connectionStatus");
|
||||
assert(migrateSource.includes("mkdtempSync"), "staged scripts must live in a private temp dir");
|
||||
assert(migrateSource.includes("mode: 0o600"), "staged scripts must be 0600");
|
||||
assert(migrateSource.includes("ADPANEL_MONGO_ADMIN_PASSWORD"), "env-var credential path stays documented/supported");
|
||||
assert(migrateSource.includes("mongoAdminPasswordFromCli"), "CLI-flag password usage must be detected for the warning");
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Functional: _mongoshRunScriptFile extracted from index.js into a scratch
|
||||
// module and driven against a fake shell binary.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function loadMongoshHelper() {
|
||||
const start = indexSource.indexOf("function _mysqlEnvWithPassword");
|
||||
// The helper block ends where the MySQL admin-channel section begins (the
|
||||
// former `_probeMySqlCmd` boundary function was retired with the auth-only
|
||||
// probe it provided).
|
||||
const end = indexSource.indexOf("// --- dedicated MySQL admin channel");
|
||||
assert.ok(start !== -1 && end !== -1 && start < end, "helper block not found in index.js");
|
||||
const helperSrc = indexSource.slice(start, end);
|
||||
const modPath = path.join(os.tmpdir(), `adpanel-l1-helper-${process.pid}-${Date.now()}.js`);
|
||||
fs.writeFileSync(modPath, [
|
||||
"const fs = require('node:fs');",
|
||||
"const os = require('node:os');",
|
||||
"const path = require('node:path');",
|
||||
"const { spawn } = require('node:child_process');",
|
||||
helperSrc,
|
||||
"module.exports = { _mongoshRunScriptFile, _mysqlEnvWithPassword };",
|
||||
].join("\n"), { mode: 0o600 });
|
||||
try {
|
||||
return require(modPath);
|
||||
} finally {
|
||||
fs.rmSync(modPath, { force: true });
|
||||
}
|
||||
}
|
||||
|
||||
test("L1: _mongoshRunScriptFile stages the script off-argv and cleans up", async () => {
|
||||
const { _mongoshRunScriptFile } = loadMongoshHelper();
|
||||
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "adpanel-l1-shell-"));
|
||||
try {
|
||||
const fakeShell = path.join(tmp, "fakeshell.js");
|
||||
fs.writeFileSync(fakeShell, [
|
||||
"#!/usr/bin/env node",
|
||||
"const fs = require('node:fs');",
|
||||
"const scriptPath = process.argv[process.argv.length - 1];",
|
||||
"const content = fs.readFileSync(scriptPath, 'utf8');",
|
||||
"console.log('ARGV=' + JSON.stringify(process.argv.slice(1)));",
|
||||
"console.log('SCRIPT=' + content);",
|
||||
].join("\n"), { mode: 0o755 });
|
||||
|
||||
const SECRET = "s3cr3t-DOES-NOT-BELONG-ON-ARGV";
|
||||
const res = await _mongoshRunScriptFile(fakeShell, ["--quiet"], `db.auth("u", "${SECRET}");`);
|
||||
assert.equal(res.code, 0);
|
||||
assert.ok(res.stdout.includes("SCRIPT=") && res.stdout.includes(SECRET), "staged file must reach the child");
|
||||
const argvLine = res.stdout.split("\n").find((l) => l.startsWith("ARGV="));
|
||||
assert.ok(argvLine, "fake shell must report its argv");
|
||||
const argv = JSON.parse(argvLine.slice(5));
|
||||
assert.ok(argv.includes("--quiet"), "leading args preserved");
|
||||
assert.ok(!argv.some((a) => a.includes(SECRET)), "secret must never appear in argv");
|
||||
// The staged directory is removed once the child exits.
|
||||
const stagedPath = argv[argv.length - 1];
|
||||
assert.ok(/adpanel-mongosh-/.test(path.dirname(stagedPath)));
|
||||
assert.ok(!fs.existsSync(stagedPath), "staged script must be deleted after the child exits");
|
||||
assert.ok(!fs.existsSync(path.dirname(stagedPath)), "staging dir must be deleted after the child exits");
|
||||
} finally {
|
||||
fs.rmSync(tmp, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("L1: _mongoshRunScriptFile preserves timeout and spawn-error semantics", async () => {
|
||||
const { _mongoshRunScriptFile } = loadMongoshHelper();
|
||||
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "adpanel-l1-shell-"));
|
||||
try {
|
||||
const sleeper = path.join(tmp, "sleeper.js");
|
||||
fs.writeFileSync(sleeper, "#!/usr/bin/env node\nsetTimeout(() => {}, 5000);\n", { mode: 0o755 });
|
||||
const timedOut = await _mongoshRunScriptFile(sleeper, [], "1;", { timeoutMs: 300 });
|
||||
assert.equal(timedOut.code, -1);
|
||||
assert.equal(timedOut.stderr, "timeout");
|
||||
|
||||
const missing = await _mongoshRunScriptFile(path.join(tmp, "does-not-exist"), [], "1;");
|
||||
assert.equal(missing.code, 1);
|
||||
assert.equal(missing.errCode, "ENOENT", "spawn errors must expose errCode for the legacy fallback");
|
||||
} finally {
|
||||
fs.rmSync(tmp, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Functional: privileged/adpanel-priv mysql-admin op driven with a shim
|
||||
// `mysql` binary that records argv/environ. Requires root (the runner refuses
|
||||
// to run otherwise), skipped elsewhere.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const isRoot = typeof process.getuid === "function" && process.getuid() === 0;
|
||||
|
||||
test("L1: adpanel-priv mysql-admin keeps the root password off argv", { skip: !isRoot && "requires root" }, () => {
|
||||
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "adpanel-l1-priv-"));
|
||||
try {
|
||||
const log = path.join(tmp, "mysql-calls.jsonl");
|
||||
const shimDir = path.join(tmp, "bin");
|
||||
fs.mkdirSync(shimDir);
|
||||
const SECRET = "TEST-root-password-OFF-ARGV";
|
||||
fs.writeFileSync(path.join(shimDir, "mysql"), [
|
||||
`#!${process.execPath}`,
|
||||
`const fs = require('node:fs');`,
|
||||
`fs.appendFileSync(process.env.ADPANEL_L1_LOG, JSON.stringify({`,
|
||||
` argv: process.argv.slice(1),`,
|
||||
` envHasPwd: process.env.MYSQL_PWD === process.env.ADPANEL_L1_SECRET,`,
|
||||
` argvHasPwd: process.argv.join(' ').includes(process.env.ADPANEL_L1_SECRET),`,
|
||||
`}) + '\\n');`,
|
||||
`// The runner probes admin CAPABILITY (mysql.user grant columns), not just`,
|
||||
`// authentication; a shimmed client must answer the probe affirmatively.`,
|
||||
`if (process.argv.includes('-N') && process.argv.includes('-e')) { console.log('1'); }`,
|
||||
`process.exit(0);`,
|
||||
].join("\n"), { mode: 0o755 });
|
||||
|
||||
// MYSQL_PASSWORD defaults to empty (socket-auth scenario); scenario A
|
||||
// overrides it. extraEnv is spread last so it can override anything —
|
||||
// it must never carry a full env copy that would clobber the shimmed PATH.
|
||||
const runPriv = (extraEnv = {}) => spawnSync("bash", [PRIV_SCRIPT, "mysql-admin"], {
|
||||
input: "SELECT 1;\n",
|
||||
encoding: "utf8",
|
||||
env: {
|
||||
...process.env,
|
||||
MYSQL_PASSWORD: "",
|
||||
PATH: `${shimDir}:${process.env.PATH}`,
|
||||
ADPANEL_L1_LOG: log,
|
||||
ADPANEL_L1_SECRET: SECRET,
|
||||
...extraEnv,
|
||||
},
|
||||
});
|
||||
|
||||
// Method 1: MYSQL_PASSWORD provided -> probe + exec both carry MYSQL_PWD,
|
||||
// and no invocation ever sees the password on argv.
|
||||
let res = runPriv({ MYSQL_PASSWORD: SECRET });
|
||||
assert.equal(res.status, 0, res.stderr);
|
||||
let calls = fs.readFileSync(log, "utf8").trim().split("\n").map((l) => JSON.parse(l));
|
||||
assert.equal(calls.length, 2, "expected probe + exec invocations");
|
||||
for (const c of calls) {
|
||||
assert.ok(!c.argvHasPwd, "password must never appear on the mysql client argv");
|
||||
assert.ok(c.envHasPwd, "password must reach the client via MYSQL_PWD");
|
||||
}
|
||||
// The kernel execs the PATH-resolved binary, so argv[0] is its full path;
|
||||
// the arguments after it are what matters.
|
||||
assert.ok(calls[1].argv[0].endsWith("/mysql"), "exec'd client must be the mysql binary");
|
||||
assert.deepEqual(calls[1].argv.slice(1), ["-u", "root"], "exec'd client keeps its original args");
|
||||
|
||||
// Method 2: no MYSQL_PASSWORD -> socket auth, and MYSQL_PWD must NOT be
|
||||
// exported (it would silently change the meaning of the other methods).
|
||||
fs.rmSync(log, { force: true });
|
||||
res = runPriv();
|
||||
assert.equal(res.status, 0, res.stderr);
|
||||
calls = fs.readFileSync(log, "utf8").trim().split("\n").map((l) => JSON.parse(l));
|
||||
assert.equal(calls.length, 2, "expected probe + exec invocations");
|
||||
for (const c of calls) {
|
||||
assert.ok(!c.argvHasPwd, "password must never appear on the mysql client argv");
|
||||
assert.ok(!c.envHasPwd, "MYSQL_PWD must not leak into the socket-auth method");
|
||||
}
|
||||
} finally {
|
||||
fs.rmSync(tmp, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("L1: create-user.js rejects plaintext credential flags", () => {
|
||||
const src = createUserSource;
|
||||
assert(!/out\.password = argv\[/.test(src), "--password must not be parsed from argv");
|
||||
assert(!/out\.currentPassword = argv\[/.test(src), "--current-password must not be parsed from argv");
|
||||
assert(!/out\.secret = argv\[/.test(src), "--secret must not be parsed from argv");
|
||||
for (const envName of ["ADPANEL_USER_PASSWORD", "ADPANEL_USER_CURRENT_PASSWORD", "ADPANEL_USER_TOTP_SECRET"]) {
|
||||
assert(src.includes(`process.env.${envName}`), `${envName} fallback must exist`);
|
||||
}
|
||||
assert(src.includes("--password-hash"), "legacy prehashed CLI input remains supported");
|
||||
assert(src.includes("/proc/<pid>/cmdline"), "usage must document why flags are rejected");
|
||||
|
||||
// Functional: each plaintext flag fails closed with guidance before any
|
||||
// sudo check or DB access (parseArgs exits 2 first).
|
||||
for (const flag of ["--password", "--secret", "--current-password"]) {
|
||||
const res = spawnSync(process.execPath,
|
||||
[path.join(ROOT, "scripts", "create-user.js"), "--email", "t@example.com", flag, "SHOULD-NOT-BE-ACCEPTED"],
|
||||
{ encoding: "utf8" });
|
||||
assert.equal(res.status, 2, `${flag} must be rejected with exit 2, got ${res.status}: ${res.stderr}`);
|
||||
assert.ok(res.stderr.includes("/proc/<pid>/cmdline"), `${flag} rejection must explain the argv exposure`);
|
||||
assert.ok(!res.stdout.includes("SHOULD-NOT-BE-ACCEPTED"));
|
||||
}
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Functional: scripts/migrate-db-user-privileges.js driven with a shim
|
||||
// `mongosh` that records argv and the staged script, proving the admin
|
||||
// password travels in the 0600 file instead of argv.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
test("L1: migrate-db-user-privileges.js stages mongosh auth off-argv", () => {
|
||||
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "adpanel-l1-migrate-"));
|
||||
try {
|
||||
const configDir = path.join(tmp, "config");
|
||||
fs.mkdirSync(configDir);
|
||||
fs.writeFileSync(path.join(configDir, "mongodb-config.json"), JSON.stringify({
|
||||
enabled: true,
|
||||
port: "27017",
|
||||
users: [{ username: "siteAdmin" }, { username: "bob" }],
|
||||
}));
|
||||
|
||||
const log = path.join(tmp, "mongosh-calls.jsonl");
|
||||
const shimDir = path.join(tmp, "bin");
|
||||
fs.mkdirSync(shimDir);
|
||||
const SECRET = "TEST-mongo-admin-OFF-ARGV";
|
||||
fs.writeFileSync(path.join(shimDir, "mongosh"), [
|
||||
`#!${process.execPath}`,
|
||||
`const fs = require('node:fs');`,
|
||||
`const scriptPath = process.argv[process.argv.length - 1];`,
|
||||
`const script = fs.readFileSync(scriptPath, 'utf8');`,
|
||||
`fs.appendFileSync(process.env.ADPANEL_L1_LOG, JSON.stringify({`,
|
||||
` argv: process.argv.slice(1),`,
|
||||
` script,`,
|
||||
` mode: fs.statSync(scriptPath).mode & 0o777,`,
|
||||
`}) + '\\n');`,
|
||||
`console.log('ADP_RESCOPE_OK');`,
|
||||
`process.exit(0);`,
|
||||
].join("\n"), { mode: 0o755 });
|
||||
|
||||
const res = spawnSync(process.execPath, [MIGRATE_JS, "--apply", "--config-dir", configDir], {
|
||||
encoding: "utf8",
|
||||
env: {
|
||||
...process.env,
|
||||
PATH: `${shimDir}:${process.env.PATH}`,
|
||||
ADPANEL_L1_LOG: log,
|
||||
ADPANEL_L1_SECRET: SECRET,
|
||||
ADPANEL_MONGO_ADMIN_USER: "siteAdmin",
|
||||
ADPANEL_MONGO_ADMIN_PASSWORD: SECRET,
|
||||
},
|
||||
});
|
||||
assert.equal(res.status, 0, `${res.stderr}\n${res.stdout}`);
|
||||
|
||||
const calls = fs.readFileSync(log, "utf8").trim().split("\n").map((l) => JSON.parse(l));
|
||||
assert.equal(calls.length, 1, "exactly one eval for the single unprotected user");
|
||||
const call = calls[0];
|
||||
assert.ok(!call.argv.some((a) => a.includes(SECRET)), "password must never appear on mongosh argv");
|
||||
assert.ok(!call.argv.includes("--eval"), "staged file must replace --eval");
|
||||
assert.ok(call.argv.includes("-u") === false, "no -u flag either");
|
||||
assert.equal(call.mode, 0o600, "staged script must be 0600");
|
||||
assert.ok(call.script.includes("db.auth("), "staged script carries the auth preamble");
|
||||
assert.ok(call.script.includes(JSON.stringify(SECRET)), "staged script carries the password (inside the 0600 file)");
|
||||
assert.ok(call.script.includes("connectionStatus: 1"), "staged auth fails closed on connectionStatus");
|
||||
// The staging directory is removed at process exit.
|
||||
const leftovers = fs.readdirSync(os.tmpdir()).filter((d) => d.startsWith("adpanel-mongosh-"));
|
||||
assert.deepEqual(leftovers, [], "no staging directories may survive the process");
|
||||
} finally {
|
||||
fs.rmSync(tmp, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
Reference in new issue
Block a user