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,319 @@
|
||||
"use strict";
|
||||
|
||||
// Tests for audit finding M1: predictable pgAdmin recovery credentials.
|
||||
//
|
||||
// The ensureDbToolBackendReady('pgadmin') recovery path used to reset the
|
||||
// pgAdmin admin password with a credential derived from MYSQL_PASSWORD (the
|
||||
// panel's own MySQL secret) or sha256(SESSION_SECRET || admin-email) — the
|
||||
// latter a deterministic backdoor into a tool that can reach PostgreSQL with
|
||||
// stored server passwords. It also silently replaced the admin's chosen
|
||||
// password with a value nobody could later retrieve (lockout).
|
||||
//
|
||||
// The remediation pins:
|
||||
// - no derived fallbacks: only an explicit PGADMIN_SETUP_PASSWORD is
|
||||
// honored, otherwise every recovery generates a fresh crypto.randomBytes
|
||||
// secret (base64url: 24 chars, pgAdmin password-policy safe, no
|
||||
// shell/env-hostile characters);
|
||||
// - the credential is sealed at rest with the EXISTING AES-256-GCM
|
||||
// webhook-secret envelope helpers (no duplicated crypto, no plaintext,
|
||||
// no base64-as-encryption) under bootstrapAuth in pgadmin-config.json,
|
||||
// written BEFORE the privileged reset runs, and dropped again if the
|
||||
// reset job fails; recovery refuses to run when sealing is impossible
|
||||
// (SESSION_SECRET unset) — it never falls back to plaintext;
|
||||
// - the one-time handoff (recoveredCredentials) is returned only when the
|
||||
// recovery actually ran, on the admin + action-token gated no-store
|
||||
// access-token response, and is never logged;
|
||||
// - the startup warmup logs only THAT a recovery occurred;
|
||||
// - POST /api/settings/database/pgadmin/credentials is the supported
|
||||
// retrieval path: isAdmin + requireActionTokenOr403, no-store, 404 when
|
||||
// nothing sealed is stored, and it only ever serves sealed envelopes.
|
||||
// - POST /api/settings/database/access-token requires the credential
|
||||
// step-up for pgadmin (its readiness branch resets the live admin
|
||||
// password and hands back the plaintext on probe failure), audit logs
|
||||
// the handoff, and never mints a grace grant for merely opening a tool.
|
||||
//
|
||||
// index.js boots servers on require, so (same technique as
|
||||
// tests/argv-secret-exposure.test.js) the recovery block is verified by
|
||||
// source assertions and the crypto helpers are extracted into a scratch
|
||||
// module for functional round-trip checks.
|
||||
|
||||
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 nodeCrypto = require("node:crypto");
|
||||
|
||||
const ROOT = path.join(__dirname, "..");
|
||||
const INDEX_JS = path.join(ROOT, "index.js");
|
||||
const indexSource = fs.readFileSync(INDEX_JS, "utf8");
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Source slices
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function slice(startMarker, endMarker) {
|
||||
const start = indexSource.indexOf(startMarker);
|
||||
assert.ok(start !== -1, `marker not found: ${startMarker}`);
|
||||
const end = indexSource.indexOf(endMarker, start);
|
||||
assert.ok(end !== -1, `end marker not found: ${endMarker}`);
|
||||
return indexSource.slice(start, end);
|
||||
}
|
||||
|
||||
// The pgAdmin recovery body (probe → sealed reset → one-time handoff) lives
|
||||
// in ensurePgAdminBackendReady; ensureDbToolBackendReady is the generic
|
||||
// wrapper that delegates to it under the pgadmin operation mutex — slice the
|
||||
// function that actually owns the recovery.
|
||||
const readyFn = slice("async function ensurePgAdminBackendReady", "async function ensureDbToolBackendReady");
|
||||
const pgadminBranch = slice("async function ensureDbToolBackendReady", 'if (service === "phpmyadmin")');
|
||||
const pgadminRecovery = slice("let pgProbeText = await probePgAdmin();", 'if (service === "phpmyadmin")');
|
||||
const accessTokenRoute = slice('app.post("/api/settings/database/access-token"', 'app.get("/db-open/:service"');
|
||||
const settingsGetRoute = slice('app.get("/api/settings/database", async', 'app.post("/api/settings/database/verify-install"');
|
||||
const credentialsRoute = slice('app.post("/api/settings/database/pgadmin/credentials"', 'app.get("/api/settings/database/mongodb/status"');
|
||||
const startupWarmup = slice("// Warm/recover DB tool backends on startup", "SHOW COLUMNS FROM users LIKE 'agent_access'");
|
||||
|
||||
// Comments document the constraints (and deliberately name the removed
|
||||
// fallbacks); negative assertions must hold for live code, not prose.
|
||||
function codeOf(source) {
|
||||
return source.split("\n").filter((l) => !l.trim().startsWith("//")).join("\n");
|
||||
}
|
||||
const pgadminBranchCode = codeOf(pgadminBranch);
|
||||
const pgadminRecoveryCode = codeOf(pgadminRecovery);
|
||||
const accessTokenRouteCode = codeOf(accessTokenRoute);
|
||||
const credentialsRouteCode = codeOf(credentialsRoute);
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// M1.1 — no derived fallback credentials in the recovery path
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
test("M1: pgAdmin recovery no longer derives the reset password", () => {
|
||||
assert(!pgadminBranchCode.includes("MYSQL_PASSWORD"), "MYSQL_PASSWORD must not be a recovery fallback in the pgAdmin readiness branch");
|
||||
assert(!pgadminRecoveryCode.includes("createHash"), "no sha256/createHash derivation over SESSION_SECRET or the admin email");
|
||||
assert(!pgadminRecoveryCode.includes("AdPanel-"), "the old derived-password prefix must be gone");
|
||||
assert(pgadminRecoveryCode.includes("process.env.PGADMIN_SETUP_PASSWORD ? String(process.env.PGADMIN_SETUP_PASSWORD) : null"),
|
||||
"an explicitly-set operator password must still be honored");
|
||||
assert(pgadminRecoveryCode.includes("crypto.randomBytes(18).toString('base64url')"),
|
||||
"otherwise the reset password must be freshly generated random bytes");
|
||||
});
|
||||
|
||||
test("M1: the generated password satisfies the pgAdmin policy without shell-hostile characters", () => {
|
||||
for (let i = 0; i < 50; i++) {
|
||||
const pw = nodeCrypto.randomBytes(18).toString("base64url");
|
||||
assert.equal(pw.length, 24, "18 random bytes must expand to 24 base64url chars");
|
||||
assert.match(pw, /^[A-Za-z0-9_-]+$/, "base64url alphabet contains no shell/env-hostile characters");
|
||||
}
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// M1.2 — the reset credential is sealed at rest before the reset runs
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
test("M1: recovery seals the credential with the existing envelope helper and stores it as bootstrapAuth", () => {
|
||||
assert(pgadminRecoveryCode.includes("encryptWebhookSecret(recoveryPassword)"),
|
||||
"the reset password must only be persisted through the shared AES-256-GCM envelope helper");
|
||||
assert(pgadminRecoveryCode.includes("encryptWebhookSecret(recoveryEmail)"),
|
||||
"the paired login email is sealed too");
|
||||
assert(pgadminRecoveryCode.includes("cfg.bootstrapAuth"), "sealed credential lives under bootstrapAuth in the pgAdmin config");
|
||||
assert(!pgadminRecoveryCode.includes("writeFileSync"),
|
||||
"persistence must go through savePgAdminConfig so the 0600 file mode is preserved");
|
||||
// Crash-safety ordering: the seal is written BEFORE the privileged reset,
|
||||
// so a crash mid-recovery cannot strand an admin behind a stored password.
|
||||
assert.ok(
|
||||
pgadminRecoveryCode.indexOf("persistSealedResetCredential") < pgadminRecoveryCode.indexOf('"job", "pgadmin-setup-recover"'),
|
||||
"sealing must precede the pgadmin-setup-recover invocation"
|
||||
);
|
||||
// And a failed reset must not leave a credential that is not in effect.
|
||||
assert(pgadminRecoveryCode.includes("delete cfg.bootstrapAuth"), "a failed reset drops the pre-sealed credential");
|
||||
});
|
||||
|
||||
test("M1: recovery fails closed instead of storing plaintext when sealing is impossible", () => {
|
||||
assert(pgadminRecoveryCode.includes("!process.env.SESSION_SECRET"),
|
||||
"recovery must refuse to run without SESSION_SECRET (envelope helper cannot seal)");
|
||||
assert(pgadminRecoveryCode.includes("recovery refused"), "the refusal must carry a clear error");
|
||||
// No plaintext/base64 fallback storage anywhere in the block.
|
||||
assert(!pgadminRecoveryCode.includes("savePgAdminConfig({"), "never rewrites the config from a hand-built plaintext object");
|
||||
assert(!pgadminRecoveryCode.includes(".toString('base64')"), "base64 is not encryption — only the envelope helper seals");
|
||||
});
|
||||
|
||||
test("M1: the recovery trigger logic is unchanged", () => {
|
||||
assert(pgadminRecoveryCode.includes("if (!pgProbeText.includes('pgadmin'))"), "recovery still runs only when the content probe fails");
|
||||
assert(pgadminRecoveryCode.includes('"job", "pgadmin-setup-recover"'), "the privileged job invocation is unchanged");
|
||||
assert(pgadminRecoveryCode.includes("PGADMIN_SETUP_PASSWORD: recoveryPassword"), "the password still travels via env (sudoers env_keep)");
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// M1.3 — one-time handoff: recoveredCredentials only when recovery ran
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
test("M1: recoveredCredentials is returned only when this call performed a recovery", () => {
|
||||
assert(readyFn.includes("let recoveredCredentials = null;"), "the field starts unset");
|
||||
assert(/return recoveredCredentials \? \{ ok: true, recoveredCredentials \} : \{ ok: true \};/.test(readyFn),
|
||||
"the plain ok path must not embed the field");
|
||||
assert(/recoveredCredentials \? \{ recoveredCredentials \}/.test(readyFn),
|
||||
"the content-probe failure path embeds it only when a recovery ran");
|
||||
});
|
||||
|
||||
test("M1: the access-token route surfaces the handoff on gated, no-store responses only", () => {
|
||||
assert(accessTokenRouteCode.includes('res.set("Cache-Control", "no-store");'), "route must stay no-store");
|
||||
assert(accessTokenRouteCode.includes('requireActionTokenOr403(req, res, "POST /api/settings/database/access-token")'),
|
||||
"route must stay action-token gated");
|
||||
assert(accessTokenRouteCode.includes("...(readiness.recoveredCredentials ? { recoveredCredentials: readiness.recoveredCredentials } : {})"),
|
||||
"success payload includes the field only when the recovery ran");
|
||||
assert(accessTokenRouteCode.includes("if (readiness.recoveredCredentials)"),
|
||||
"the 503 branch surfaces the handoff only when the recovery ran");
|
||||
});
|
||||
|
||||
test("M1: the reset credential is never logged", () => {
|
||||
const consoleLines = indexSource.split("\n").filter((l) => /console\./.test(l));
|
||||
for (const needle of ["recoveredCredentials", "recoveryPassword", "bootstrapAuth"]) {
|
||||
assert(consoleLines.every((l) => !l.includes(needle)), `${needle} must never appear in any console.* call`);
|
||||
}
|
||||
});
|
||||
|
||||
test("M1: startup warmup logs only that a recovery occurred", () => {
|
||||
assert(startupWarmup.includes("pgReady.recoveredCredentials"), "warmup must detect a recovery");
|
||||
assert(!startupWarmup.includes("recoveredCredentials.password"), "no credential value may reach the warmup logs");
|
||||
assert(startupWarmup.includes("retrieve them from Settings"), "warmup must point the admin at the retrieval path");
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// M1.4 — supported retrieval endpoint
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
test("M1: the retrieval endpoint is admin + action-token gated and no-store", () => {
|
||||
assert(credentialsRouteCode.includes('if (!(await isAdmin(req))) return res.status(403).json({ error: "not authorized" });'),
|
||||
"isAdmin gate");
|
||||
assert(credentialsRouteCode.includes('requireActionTokenOr403(req, res, "POST /api/settings/database/pgadmin/credentials")'),
|
||||
"action-token gate bound to the exact route action");
|
||||
assert(credentialsRouteCode.includes('res.set("Cache-Control", "no-store");'), "no-store on a credential-bearing response");
|
||||
assert(credentialsRouteCode.includes("404"), "404 when nothing sealed is stored");
|
||||
});
|
||||
|
||||
test("M1: the retrieval endpoint only serves sealed envelopes via the shared decrypt helper", () => {
|
||||
assert(credentialsRouteCode.includes("isEncryptedWebhookSecretValue"),
|
||||
"hand-edited plaintext values are treated as absent, never exposed");
|
||||
assert(credentialsRouteCode.includes("decryptWebhookSecret(stored.password)") && credentialsRouteCode.includes("decryptWebhookSecret(stored.email)"),
|
||||
"decryption goes through the shared envelope helper");
|
||||
assert(credentialsRouteCode.includes("could not be decrypted"), "unsealable envelopes fail closed");
|
||||
});
|
||||
|
||||
test("M1: the retrieval endpoint enforces the credential step-up before any disclosure", () => {
|
||||
// The response carries the live pgAdmin admin password, so the route needs
|
||||
// the same step-up as the other live-secret reveals (node config.yml /
|
||||
// one-time command): fresh password or 2FA verification, or a live grace
|
||||
// grant. Without it a hijacked admin session is one GET /api/settings/
|
||||
// database (which mints the one-time token) plus one POST away from the
|
||||
// plaintext credential.
|
||||
const tokenIdx = credentialsRouteCode.indexOf('requireActionTokenOr403(req, res, "POST /api/settings/database/pgadmin/credentials")');
|
||||
const currentUserIdx = credentialsRouteCode.indexOf("const currentUser = await findUserByEmail(req.session.user)");
|
||||
const stepUpIdx = credentialsRouteCode.indexOf('requireDestructiveActionStepUp(req, res, currentUser, "pgAdmin4 saved credentials reveal"');
|
||||
const storedIdx = credentialsRouteCode.indexOf("loadPgAdminConfig()?.bootstrapAuth");
|
||||
|
||||
assert.ok(tokenIdx !== -1, "action-token gate present");
|
||||
assert.ok(currentUserIdx > tokenIdx, "the verified user record must load after the token gate");
|
||||
assert.ok(stepUpIdx > currentUserIdx, "the credential step-up must come after the user record load");
|
||||
assert.ok(storedIdx > stepUpIdx, "the sealed store must not be touched before the step-up gate — even the existence of a credential is not disclosed unverified");
|
||||
assert.match(credentialsRouteCode, /persistGrant: false/,
|
||||
"a read-only reveal must not mint a grace grant that could later authorize destructive actions");
|
||||
assert.match(credentialsRouteCode, /database_pgadmin_credentials_reveal/, "the reveal must be audit logged");
|
||||
});
|
||||
|
||||
test("M1: the settings GET mints the matching pgadminCredentials action token", () => {
|
||||
assert(settingsGetRoute.includes('pgadminCredentials: issueActionToken(req, "POST /api/settings/database/pgadmin/credentials"'),
|
||||
"GET /api/settings/database must issue the token for the retrieval route");
|
||||
assert(/pgadminCredentials:.*oneTime: true/.test(settingsGetRoute), "the credential token is one-time");
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// M1.5 — access-token route: the recovery handoff requires credential step-up
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
test("M1: the access-token route bounds step-up credential guessing with the shared limiter", () => {
|
||||
assert(accessTokenRouteCode.includes('app.post("/api/settings/database/access-token", sessionRevoke2faRateLimiter, async (req, res) => {'),
|
||||
"the route must mount sessionRevoke2faRateLimiter (its skip only counts credential-bearing requests, so normal opens and phpMyAdmin traffic are unthrottled)");
|
||||
});
|
||||
|
||||
test("M1: the access-token route requires the credential step-up for pgadmin before any readiness work", () => {
|
||||
// The pgadmin readiness branch resets the live admin password and hands
|
||||
// the new plaintext back on the 503 AND the success path, so this route is
|
||||
// otherwise the "one GET /api/settings/database + one POST" path the
|
||||
// pgadmin/credentials route comment warns about.
|
||||
const tokenIdx = accessTokenRouteCode.indexOf('requireActionTokenOr403(req, res, "POST /api/settings/database/access-token")');
|
||||
const currentUserIdx = accessTokenRouteCode.indexOf("const currentUser = await findUserByEmail(req.session.user)");
|
||||
const gateIdx = accessTokenRouteCode.indexOf('if (service === "pgadmin") {');
|
||||
const stepUpIdx = accessTokenRouteCode.indexOf('requireDestructiveActionStepUp(req, res, currentUser, "pgAdmin4 backend access & credential recovery"');
|
||||
const readyIdx = accessTokenRouteCode.indexOf("ensureDbToolBackendReady(");
|
||||
|
||||
assert.ok(tokenIdx !== -1, "action-token gate present");
|
||||
assert.ok(currentUserIdx > tokenIdx, "the verified user record must load after the token gate");
|
||||
assert.ok(gateIdx !== -1, "the step-up must be scoped to the pgadmin branch");
|
||||
assert.ok(stepUpIdx > gateIdx, "the step-up must sit inside the pgadmin guard - phpMyAdmin reveals no secret and keeps its prompt-free flow");
|
||||
assert.ok(stepUpIdx > currentUserIdx, "the step-up must come after the user record load");
|
||||
assert.ok(readyIdx > stepUpIdx, "the step-up must precede the readiness call - a hijacked session can neither trigger the privileged recovery nor receive the credential");
|
||||
assert(accessTokenRouteCode.includes("persistGrant: false"),
|
||||
"opening a tool must never mint a grace grant that could later authorize destructive actions (it may still reuse a grant that is already live)");
|
||||
});
|
||||
|
||||
test("M1: the recovery handoff is audit logged on BOTH credential-bearing responses", () => {
|
||||
const readyIdx = accessTokenRouteCode.indexOf("ensureDbToolBackendReady(");
|
||||
const auditIdx = accessTokenRouteCode.indexOf('recordActivity("_system", "database_pgadmin_recovery_handoff"');
|
||||
assert.ok(auditIdx !== -1, "the recovery handoff must be audit logged");
|
||||
assert.ok(auditIdx > readyIdx, "the audit must follow the readiness/recovery work");
|
||||
assert(accessTokenRouteCode.includes("if (readiness.recoveredCredentials) {"),
|
||||
"the audit fires only when a recovery actually handed back a credential");
|
||||
// The 503 (backend still unhealthy) hands back the same plaintext as the
|
||||
// success payload, so it must be audited too, before that response returns.
|
||||
// (The payload now sits two spaces deeper: the route body is wrapped in the
|
||||
// Express-4 pre-flight guard sweep's whole-body try/catch.)
|
||||
const handoff503Idx = accessTokenRouteCode.indexOf('res.status(503).json({\n error: readiness.error || "Database tool backend is not ready",\n recoveredCredentials');
|
||||
assert.ok(handoff503Idx !== -1, "the 503 handoff response shape must remain");
|
||||
assert.ok(auditIdx < handoff503Idx, "the 503 handoff must be audited before its response is returned");
|
||||
assert.equal(accessTokenRouteCode.split('recordActivity("_system", "database_pgadmin_recovery_handoff"').length, 3,
|
||||
"the handoff is audited exactly twice: once in the 503 branch, once on the success path");
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Functional — the envelope helpers used for the seal are extracted from
|
||||
// index.js into a scratch module (index.js boots servers on require).
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function loadWebhookSecretCrypto() {
|
||||
const start = indexSource.indexOf("const WEBHOOK_SECRET_ENC_PREFIX");
|
||||
const end = indexSource.indexOf("const DISCORD_WEBHOOK_REGEX");
|
||||
assert.ok(start !== -1 && end !== -1 && start < end, "webhook-secret crypto block not found in index.js");
|
||||
const helperSrc = indexSource.slice(start, end);
|
||||
const modPath = path.join(os.tmpdir(), `adpanel-m1-crypto-${process.pid}-${Date.now()}.js`);
|
||||
fs.writeFileSync(modPath, [
|
||||
"const crypto = require('node:crypto');",
|
||||
helperSrc,
|
||||
"module.exports = { encryptWebhookSecret, decryptWebhookSecret, isEncryptedWebhookSecretValue };",
|
||||
].join("\n"), { mode: 0o600 });
|
||||
try {
|
||||
return require(modPath);
|
||||
} finally {
|
||||
fs.rmSync(modPath, { force: true });
|
||||
}
|
||||
}
|
||||
|
||||
test("M1: sealing refuses to run without SESSION_SECRET (fail closed, no plaintext fallback)", () => {
|
||||
delete process.env.SESSION_SECRET;
|
||||
const { encryptWebhookSecret } = loadWebhookSecretCrypto();
|
||||
assert.throws(() => encryptWebhookSecret("x"), /SESSION_SECRET is not set/,
|
||||
"the helper throws instead of returning a plaintext-storable value");
|
||||
});
|
||||
|
||||
test("M1: the seal round-trips, never embeds plaintext, and fails closed on tamper", () => {
|
||||
process.env.SESSION_SECRET = "m1-test-session-secret-" + nodeCrypto.randomBytes(16).toString("hex");
|
||||
const { encryptWebhookSecret, decryptWebhookSecret, isEncryptedWebhookSecretValue } = loadWebhookSecretCrypto();
|
||||
|
||||
const SECRET = "S3cret-pgAdmin-reset-password";
|
||||
const sealed = encryptWebhookSecret(SECRET);
|
||||
assert(isEncryptedWebhookSecretValue(sealed), "stored value must be an enc:v1 envelope");
|
||||
assert(!sealed.includes(SECRET), "the envelope must not embed the plaintext");
|
||||
assert.equal(decryptWebhookSecret(sealed), SECRET, "the admin-facing retrieval decrypts to the exact credential");
|
||||
|
||||
// GCM verification: a tampered envelope must yield null (unrecoverable),
|
||||
// which the retrieval endpoint maps to a 404.
|
||||
const tampered = sealed.slice(0, -4) + "AAAA";
|
||||
assert.equal(decryptWebhookSecret(tampered), null, "tampered ciphertext must not decrypt");
|
||||
});
|
||||
Reference in new issue
Block a user