Files
Kelx/tests/password-policy-parity.test.js
T
2026-11-30 16:32:37 +00:00

179 lines
9.5 KiB
JavaScript

"use strict";
// Tests for audit finding M2: password changes must enforce the same policy as
// account creation.
//
// Account creation validates the password with getProvisionedPasswordError
// (length, 72-byte bcrypt cap, control characters, common-password blocklist,
// email-local-part check, repeated/sequential rejection). Three password
// change paths skipped that validator and only checked length >= 8, so
// e.g. an admin reset (or a self-service change) could set "password123" on
// an account that creation would have rejected, and a >72-byte password was
// silently truncated by bcrypt before hashing:
//
// - POST /api/settings/accounts/:email/change-password (admin reset, M2)
// - POST /api/settings/change-password (self-service, settings)
// - POST /api/account/password/change (self-service, account modal)
//
// All three now call the same shared validator before hashing. index.js boots
// servers on require, so the shared validator is behavior-tested by extracting
// its live source from index.js, and route-level behavior is locked with
// source assertions (same technique as the other audit-*.test.js files).
const test = require("node:test");
const assert = require("node:assert");
const fs = require("node:fs");
const path = require("node:path");
const ROOT = path.join(__dirname, "..");
const INDEX_JS = path.join(ROOT, "index.js");
const SETTINGS_EJS = path.join(ROOT, "views", "settings.ejs");
const indexSource = fs.readFileSync(INDEX_JS, "utf8");
const settingsEjsSource = fs.readFileSync(SETTINGS_EJS, "utf8");
function sliceBetween(source, startMarker, endMarker) {
const start = source.indexOf(startMarker);
assert.ok(start >= 0, `start marker not found: ${startMarker}`);
const end = source.indexOf(endMarker, start + startMarker.length);
assert.ok(end > start, `end marker not found after start: ${endMarker}`);
return source.slice(start, end);
}
// ---------------------------------------------------------------------------
// The shared validator, evaluated from its live source in index.js
// ---------------------------------------------------------------------------
const validatorSource = sliceBetween(
indexSource,
"function getProvisionedPasswordError",
"function normalizeTotpCode"
);
const getProvisionedPasswordError = new Function(
`${validatorSource}\nreturn getProvisionedPasswordError;`
)();
test("shared validator: common passwords and symbol-mangled variants are rejected", () => {
assert.strictEqual(getProvisionedPasswordError("password123", "user@example.com"), "Use a stronger password");
assert.strictEqual(getProvisionedPasswordError("Password123!", "user@example.com"), "Use a stronger password");
assert.strictEqual(getProvisionedPasswordError("AdPanel123!", "user@example.com"), "Use a stronger password");
assert.strictEqual(getProvisionedPasswordError("changeme", "user@example.com"), "Use a stronger password");
});
test("shared validator: 72-byte bcrypt cap is enforced, not left to silent truncation", () => {
assert.strictEqual(
getProvisionedPasswordError("a".repeat(73), "user@example.com"),
"Password must be 72 bytes or less"
);
// 72 one-byte characters is exactly at the limit and must still be accepted
// (varied content, so the repeated/sequential checks stay out of the way).
const atTheLimit = "xK9#mQv2".repeat(9).slice(0, 72);
assert.strictEqual(Buffer.byteLength(atTheLimit, "utf8"), 72);
assert.strictEqual(getProvisionedPasswordError(atTheLimit, "user@example.com"), "");
});
test("shared validator: email local part, repeated and sequential passwords are rejected", () => {
assert.strictEqual(
getProvisionedPasswordError("mypassname123", "name@example.com"),
"Password cannot contain the email name"
);
assert.strictEqual(getProvisionedPasswordError("a".repeat(12), "user@example.com"), "Use a stronger password");
assert.strictEqual(getProvisionedPasswordError("abcdefgh", "user@example.com"), "Use a stronger password");
});
test("shared validator: non-string input and control characters are rejected", () => {
assert.strictEqual(getProvisionedPasswordError(undefined, "user@example.com"), "Password required");
assert.strictEqual(getProvisionedPasswordError(12345678, "user@example.com"), "Password required");
assert.match(getProvisionedPasswordError("okay\u0007pass", "user@example.com"), /invalid characters/);
});
test("shared validator: 8+ char passwords without a known weakness are accepted", () => {
assert.strictEqual(getProvisionedPasswordError("xK9#mQv2", "user@example.com"), "");
// All-lowercase 8+ is intentionally accepted (documented in the validator).
assert.strictEqual(getProvisionedPasswordError("purple-donkey-42", "user@example.com"), "");
});
// ---------------------------------------------------------------------------
// Route parity: every panel-account password mutation path uses the validator
// ---------------------------------------------------------------------------
const ADMIN_RESET_START = 'app.post("/api/settings/accounts/:email/change-password"';
const SELF_SETTINGS_START = 'app.post("/api/settings/change-password"';
const SELF_ACCOUNT_START = 'app.post("/api/account/password/change"';
const adminResetRoute = sliceBetween(indexSource, ADMIN_RESET_START, 'app.get("/api/servers/:name/files/list"');
const selfSettingsRoute = sliceBetween(indexSource, SELF_SETTINGS_START, 'app.get("/api/settings/servers"');
const selfAccountRoute = sliceBetween(indexSource, SELF_ACCOUNT_START, 'app.post("/api/account/email/verify"');
test("admin reset (M2) runs the creation-time password policy against the target account", () => {
const policyAt = adminResetRoute.indexOf(
"getProvisionedPasswordError(newPassword, targetUser.email || targetEmailLower)"
);
assert.ok(policyAt >= 0, "admin reset must call the shared validator with the target's email");
// The validator needs the loaded target row, and the hash must only happen
// after the policy accepted the password.
const lookupAt = adminResetRoute.indexOf("const targetUser = await findUserByEmail(targetEmail)");
const hashAt = adminResetRoute.indexOf("bcrypt.hash(newPassword, BCRYPT_ROUNDS)");
assert.ok(lookupAt >= 0 && hashAt >= 0, "route anchors present");
assert.ok(lookupAt < policyAt && policyAt < hashAt,
"order must be target lookup -> policy validation -> bcrypt.hash");
// The old weak length-only check must be gone from this route.
assert.ok(!adminResetRoute.includes("newPassword.length < 8"),
"the weak length-only check must not survive in the admin reset route");
});
test("self-service password changes run the same policy (no downgrade path)", () => {
assert.ok(selfSettingsRoute.includes("getProvisionedPasswordError(newPassword, email)"),
"settings change-password must call the shared validator with the session email");
assert.ok(selfAccountRoute.includes("getProvisionedPasswordError(newPassword, user.email || req.session.user)"),
"account modal change-password must call the shared validator");
assert.ok(!selfSettingsRoute.includes("newPassword.length < 8"));
assert.ok(!selfAccountRoute.includes("newPassword.length < 8"));
// Validation must precede the current-password compare and the hash in both
// self-service routes so a rejected password never reaches bcrypt.
for (const [name, route] of [["settings", selfSettingsRoute], ["account modal", selfAccountRoute]]) {
const policyAt = route.indexOf("getProvisionedPasswordError(newPassword");
const hashAt = route.indexOf("bcrypt.hash(newPassword, BCRYPT_ROUNDS)");
assert.ok(policyAt >= 0 && hashAt >= 0 && policyAt < hashAt,
`${name}: policy validation must precede bcrypt.hash`);
}
});
test("exactly one validator definition exists and account creation still uses it", () => {
assert.strictEqual(
indexSource.split("function getProvisionedPasswordError").length - 1,
1,
"the validator must not be forked into divergent copies"
);
const createRoute = sliceBetween(indexSource, 'app.post("/api/admin/user/create"', 'app.post("/api/admin/branding/update"');
assert.ok(createRoute.includes("getProvisionedPasswordError(password, emailLower)"),
"account creation must keep using the shared validator");
});
// ---------------------------------------------------------------------------
// UI parity: the change-password modals advertise the enforced policy
// ---------------------------------------------------------------------------
test("change-password modals advertise 8-72 characters with a client-side cap", () => {
for (const inputId of ["modalNew", "adminNewPassword"]) {
const inputAt = settingsEjsSource.indexOf(`id="${inputId}"`);
assert.ok(inputAt >= 0, `${inputId} input exists`);
const inputHtml = settingsEjsSource.slice(inputAt, settingsEjsSource.indexOf(">", inputAt) + 1);
assert.ok(inputHtml.includes('placeholder="8-72 characters"'),
`${inputId} must advertise the 8-72 policy`);
assert.ok(inputHtml.includes('maxlength="72"'),
`${inputId} must carry the same 72-char cap as the create-account modal`);
}
assert.ok(!settingsEjsSource.slice(
settingsEjsSource.indexOf('id="modalNew"'),
settingsEjsSource.indexOf('id="adminChangePasswordCredentialLabel"')
).includes("Minimum 8 characters"),
"neither account password-change modal may still advertise the weaker old policy");
// The pgAdmin/MongoDB service-credential forms keep "Minimum 8 characters"
// on purpose: those flows enforce a different server-side policy (the real
// credential is handed to the database engine and is not subject to the
// panel-login 72-byte bcrypt cap).
});