1021 lines
53 KiB
JavaScript
1021 lines
53 KiB
JavaScript
"use strict";
|
|
|
|
// adpanel:session-inventory-error-propagation + adpanel:credential-generation +
|
|
// adpanel:credential-session-rebind — regression tests for the credential-reset
|
|
// eviction-surfacing finding.
|
|
//
|
|
// Findings pinned here:
|
|
// 1. (Truthful warnings) Every credential-change response renders
|
|
// sessionInvalidationWarnings through the ONE shared renderer
|
|
// (utils/session-invalidation-warnings.js): the destroyer's additive
|
|
// `scanIncomplete: true` flag must reach the client as a truthful warning
|
|
// even when the degraded scan happened to produce no error strings. The
|
|
// old per-route copies passed `sessionInvalidation.errors` verbatim and
|
|
// silently dropped the flag — an unverified sign-out sweep looked like a
|
|
// clean success.
|
|
// 2. (Invalidation is guaranteed regardless) The epoch bump RIDES the
|
|
// credential's own compare-and-swap, which commits BEFORE any eviction
|
|
// machinery runs. Even when destroyBrowserSessionsForUser REJECTS
|
|
// outright, the row's generation has already moved: every pre-change
|
|
// session (HTTP record, socket handshake binding, remember restore)
|
|
// fails the ONE shared binding predicate on its next use. Asserted with
|
|
// the REAL sessionAccountBindingMismatch and the REAL socket liveness
|
|
// checker — never a mock.
|
|
// 3. (Owner rebind) On a completing change the caller's regenerated session
|
|
// is bound to exactly the generation the CAS committed (it passes the
|
|
// REAL binding predicate against the post-change row) and the remember
|
|
// cookie is re-issued with forceFreshId.
|
|
// 4. (Suspension surfaces, contract unchanged) The suspension route is NOT a
|
|
// credential change (no epoch bump — a missed session is blocked by the
|
|
// suspended state at auth time, not by a binding mismatch), so it gets
|
|
// the suspension-specific note and its standing fail-loudly contract
|
|
// (500 + sessionEvictionFailed) now also keys on scanIncomplete — which
|
|
// cannot change any current outcome, because a degraded scan always
|
|
// produces scan error strings today.
|
|
//
|
|
// Behavior harness: the house vm-extraction technique (the real route
|
|
// statements run against fake db/session/res objects with a REAL rebinder,
|
|
// the REAL epoch generator, the REAL binding predicate and the REAL socket
|
|
// liveness checker injected).
|
|
|
|
const test = require("node:test");
|
|
const assert = require("node:assert");
|
|
const fs = require("node:fs");
|
|
const path = require("node:path");
|
|
const vm = require("node:vm");
|
|
const crypto = require("node:crypto");
|
|
|
|
const ROOT = path.join(__dirname, "..");
|
|
const INDEX_JS = path.join(ROOT, "index.js");
|
|
const SETTINGS_JS = path.join(ROOT, "public", "js", "settings.js");
|
|
const ADMIN_RESET_JS = path.join(ROOT, "services", "admin-2fa-reset.js");
|
|
|
|
const indexSource = fs.readFileSync(INDEX_JS, "utf8");
|
|
const settingsSource = fs.readFileSync(SETTINGS_JS, "utf8");
|
|
const adminResetSource = fs.readFileSync(ADMIN_RESET_JS, "utf8");
|
|
|
|
// Real utils under test.
|
|
const { createCredentialSessionRebinder } = require("../utils/credential-session-rebind.js");
|
|
const { createCredentialCommitService, CREDENTIAL_COMMIT_SQL } = require("../services/account-credentials");
|
|
const { newSessionEpochDifferentFrom } = require("../utils/session-epoch.js");
|
|
const { sessionAccountBindingMismatch } = require("../utils/session-account-binding.js");
|
|
const { createSocketSessionLivenessChecker, SOCKET_SESSION_LIVENESS_VERDICTS } = require("../utils/socket-session-liveness.js");
|
|
|
|
// The shared warnings renderer (the module under test). Loaded defensively so
|
|
// the pre-fix run reports the missing module as a failing assertion instead of
|
|
// aborting the whole file.
|
|
let renderSessionInvalidationWarnings = null;
|
|
let CREDENTIAL_SCAN_INCOMPLETE_NOTE = null;
|
|
let SUSPENSION_SCAN_INCOMPLETE_NOTE = null;
|
|
try {
|
|
const renderer = require("../utils/session-invalidation-warnings.js");
|
|
renderSessionInvalidationWarnings = renderer.renderSessionInvalidationWarnings;
|
|
CREDENTIAL_SCAN_INCOMPLETE_NOTE = renderer.CREDENTIAL_SCAN_INCOMPLETE_NOTE;
|
|
SUSPENSION_SCAN_INCOMPLETE_NOTE = renderer.SUSPENSION_SCAN_INCOMPLETE_NOTE;
|
|
} catch (_) { /* the unit tests below fail with a precise message */ }
|
|
|
|
function countOccurrences(haystack, needle) {
|
|
return haystack.split(needle).length - 1;
|
|
}
|
|
|
|
// Paren-balanced extraction of a full `app.post(...);` statement (skips
|
|
// strings and comments so adpanel: comments cannot desync the tracker) — the
|
|
// same technique as tests/credential-change-atomic-guard.test.js.
|
|
function extractRouteStatement(source, marker) {
|
|
const start = source.indexOf(marker);
|
|
assert.ok(start >= 0, `route marker not found: ${marker}`);
|
|
let i = start;
|
|
let depth = 0;
|
|
let started = false;
|
|
let inString = null;
|
|
while (i < source.length) {
|
|
const ch = source[i];
|
|
if (inString) {
|
|
if (ch === "\\") { i += 2; continue; }
|
|
if (ch === inString) inString = null;
|
|
i += 1;
|
|
continue;
|
|
}
|
|
if (ch === "/" && source[i + 1] === "/") {
|
|
const j = source.indexOf("\n", i);
|
|
i = j < 0 ? source.length : j;
|
|
continue;
|
|
}
|
|
if (ch === "/" && source[i + 1] === "*") {
|
|
const j = source.indexOf("*/", i + 2);
|
|
i = j < 0 ? source.length : j + 2;
|
|
continue;
|
|
}
|
|
if (ch === '"' || ch === "'" || ch === "`") { inString = ch; i += 1; continue; }
|
|
if (ch === "(") { depth += 1; started = true; }
|
|
else if (ch === ")") { depth -= 1; }
|
|
if (started && depth === 0) {
|
|
let end = i + 1;
|
|
while (end < source.length && source[end] === ";") end += 1;
|
|
return source.slice(start, end);
|
|
}
|
|
i += 1;
|
|
}
|
|
assert.fail(`unbalanced route statement: ${marker}`);
|
|
}
|
|
|
|
const ROUTE_PASSWORD = 'app.post("/api/account/password/change"';
|
|
const ROUTE_SETTINGS_PASSWORD = 'app.post("/api/settings/change-password"';
|
|
const ROUTE_EMAIL = 'app.post("/api/account/email/change"';
|
|
const ROUTE_CONFIRM = 'app.post("/api/account/2fa/confirm"';
|
|
const ROUTE_ADMIN_CHANGE_PASSWORD = 'app.post("/api/settings/accounts/:email/change-password"';
|
|
const ROUTE_SUSPENSION = 'app.post("/api/settings/accounts/:email/suspension"';
|
|
|
|
const statements = {
|
|
password: extractRouteStatement(indexSource, ROUTE_PASSWORD),
|
|
settings: extractRouteStatement(indexSource, ROUTE_SETTINGS_PASSWORD),
|
|
email: extractRouteStatement(indexSource, ROUTE_EMAIL),
|
|
confirm: extractRouteStatement(indexSource, ROUTE_CONFIRM),
|
|
adminChangePassword: extractRouteStatement(indexSource, ROUTE_ADMIN_CHANGE_PASSWORD),
|
|
suspension: extractRouteStatement(indexSource, ROUTE_SUSPENSION),
|
|
};
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Unit — the ONE shared warnings renderer
|
|
// ---------------------------------------------------------------------------
|
|
|
|
test("renderer module exists and exports the one home of the warning notes", () => {
|
|
assert.ok(typeof renderSessionInvalidationWarnings === "function", "utils/session-invalidation-warnings.js must export renderSessionInvalidationWarnings (the ONE home of the rendered warnings)");
|
|
assert.ok(typeof CREDENTIAL_SCAN_INCOMPLETE_NOTE === "string" && CREDENTIAL_SCAN_INCOMPLETE_NOTE.length > 0, "the credential-change scan-incomplete note must exist");
|
|
assert.ok(typeof SUSPENSION_SCAN_INCOMPLETE_NOTE === "string" && SUSPENSION_SCAN_INCOMPLETE_NOTE.length > 0, "the suspension scan-incomplete note must exist");
|
|
});
|
|
|
|
test("renderer: clean eviction renders no warnings", () => {
|
|
assert.deepEqual(renderSessionInvalidationWarnings({ destroyed: 2, errors: [], scanIncomplete: false }), []);
|
|
assert.deepEqual(renderSessionInvalidationWarnings({ destroyed: 2, errors: [] }), [], "a result without the scanIncomplete field renders no note");
|
|
});
|
|
|
|
test("renderer: error strings pass through unchanged", () => {
|
|
const out = renderSessionInvalidationWarnings({ errors: ["sid-a:revoked-sid tombstone not durable", "remember-revoke:redis down"], scanIncomplete: false });
|
|
assert.deepEqual(out, ["sid-a:revoked-sid tombstone not durable", "remember-revoke:redis down"]);
|
|
});
|
|
|
|
test("renderer: scanIncomplete is surfaced even with NO error strings (the dropped-field regression)", () => {
|
|
const out = renderSessionInvalidationWarnings({ destroyed: 2, errors: [], scanIncomplete: true });
|
|
assert.equal(out.length, 1, "the degraded scan must produce exactly the truthful note");
|
|
assert.equal(out[0], CREDENTIAL_SCAN_INCOMPLETE_NOTE);
|
|
});
|
|
|
|
test("renderer: the note is APPENDED after the error strings, never replaces them", () => {
|
|
const out = renderSessionInvalidationWarnings({ errors: ["sid-b:destroy failed"], scanIncomplete: true });
|
|
assert.deepEqual(out, ["sid-b:destroy failed", CREDENTIAL_SCAN_INCOMPLETE_NOTE]);
|
|
});
|
|
|
|
test("renderer: never throws on malformed results (warnings are additive context, never a new failure mode)", () => {
|
|
assert.deepEqual(renderSessionInvalidationWarnings(undefined), []);
|
|
assert.deepEqual(renderSessionInvalidationWarnings(null), []);
|
|
assert.deepEqual(renderSessionInvalidationWarnings({}), []);
|
|
assert.deepEqual(renderSessionInvalidationWarnings({ errors: "not-an-array", scanIncomplete: true }), [CREDENTIAL_SCAN_INCOMPLETE_NOTE]);
|
|
});
|
|
|
|
test("renderer: suspension keeps its operation-specific note instead of claiming a credential change", () => {
|
|
const out = renderSessionInvalidationWarnings({ errors: [], scanIncomplete: true }, { scanIncompleteNote: SUSPENSION_SCAN_INCOMPLETE_NOTE });
|
|
assert.deepEqual(out, [SUSPENSION_SCAN_INCOMPLETE_NOTE]);
|
|
assert.notEqual(SUSPENSION_SCAN_INCOMPLETE_NOTE, CREDENTIAL_SCAN_INCOMPLETE_NOTE, "the two notes must stay distinct");
|
|
});
|
|
|
|
test("renderer: the notes are truthful about their invalidation mechanisms", () => {
|
|
// Credential changes bump the epoch in-statement (adpanel:credential-generation):
|
|
// a missed session fails the binding check because the GENERATION changed.
|
|
assert.ok(/credential generation changed/.test(CREDENTIAL_SCAN_INCOMPLETE_NOTE), "the credential note must cite the generation change");
|
|
assert.ok(!/suspended/.test(CREDENTIAL_SCAN_INCOMPLETE_NOTE), "the credential note must not cite suspension");
|
|
// Suspension keeps its own note even though the service now revokes the
|
|
// session generation as defense in depth against later unsuspension.
|
|
assert.ok(/suspended/.test(SUSPENSION_SCAN_INCOMPLETE_NOTE), "the suspension note must cite the suspended state");
|
|
assert.ok(!/credential generation changed/.test(SUSPENSION_SCAN_INCOMPLETE_NOTE), "the suspension note must not claim a password or 2FA change");
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Source pins — every eviction-surfacing response renders through the ONE
|
|
// renderer; the note strings have no per-route copies
|
|
// ---------------------------------------------------------------------------
|
|
|
|
test("source: the five credential routes + the suspension route render sessionInvalidationWarnings through the shared renderer", () => {
|
|
for (const [name, stmt] of Object.entries(statements)) {
|
|
assert.ok(stmt.includes("renderSessionInvalidationWarnings(sessionInvalidation"), `${name}: the response must render the warnings through the shared renderer`);
|
|
assert.ok(!stmt.includes("sessionInvalidationWarnings: sessionInvalidation.errors"), `${name}: the raw errors pass-through (which dropped scanIncomplete) must be gone from this route`);
|
|
}
|
|
});
|
|
|
|
test("source: the renderer module is the only home of the note strings; wiring is one-way and single", () => {
|
|
assert.equal(countOccurrences(indexSource, CREDENTIAL_SCAN_INCOMPLETE_NOTE), 0, "index.js must not inline the credential note");
|
|
assert.equal(countOccurrences(indexSource, SUSPENSION_SCAN_INCOMPLETE_NOTE), 0, "index.js must not inline the suspension note");
|
|
assert.equal(countOccurrences(adminResetSource, CREDENTIAL_SCAN_INCOMPLETE_NOTE), 0, "admin-2fa-reset.js must not inline the note");
|
|
assert.equal(countOccurrences(indexSource, 'require("./utils/session-invalidation-warnings")'), 1, "exactly one renderer require in index.js");
|
|
assert.equal(countOccurrences(adminResetSource, 'require("../utils/session-invalidation-warnings")'), 1, "exactly one renderer require in the service module");
|
|
assert.ok(!adminResetSource.includes('require("../index")'), "the service module must never require index.js");
|
|
});
|
|
|
|
test("source: the suspension route keys its standing fail-loudly contract on scanIncomplete too (contract otherwise unchanged)", () => {
|
|
assert.ok(statements.suspension.includes("sessionInvalidation.errors.length > 0 || sessionInvalidation.scanIncomplete === true"), "the sessionEvictionFailed predicate must treat a degraded scan as incomplete eviction");
|
|
assert.ok(statements.suspension.includes("renderSessionInvalidationWarnings(sessionInvalidation, { scanIncompleteNote: SUSPENSION_SCAN_INCOMPLETE_NOTE })"), "the suspension bodies use the suspension-specific note");
|
|
assert.ok(statements.suspension.includes("scanIncomplete: false"), "the unsuspend-path result literal carries the same shape");
|
|
const actionSource = fs.readFileSync(path.join(ROOT, "services", "account-actions.js"), "utf8");
|
|
assert.ok(actionSource.includes("UPDATE users SET suspended = ?, suspended_at = ?, suspended_by = ?, session_epoch = ? WHERE id = ? AND admin = 0"), "suspension and the session generation must commit atomically");
|
|
assert.ok(actionSource.includes("suspended ? newSessionEpochDifferentFrom(Number(live.session_epoch || 0)) : live.session_epoch"), "suspension revokes the locked live generation and unsuspension preserves it");
|
|
assert.ok(statements.suspension.includes("setAccountSuspension(db, currentUser, targetUser"), "the route delegates its loaded target to the shared setter");
|
|
assert.ok(!statements.suspension.includes("session_epoch"), "the shared service owns session generation changes, not the route");
|
|
});
|
|
|
|
test("source: the admin 2FA reset service renders the warnings through the shared renderer and revokes both MFA credentials", () => {
|
|
assert.ok(adminResetSource.includes("renderSessionInvalidationWarnings(sessionInvalidation)"), "the service response must render through the shared renderer");
|
|
assert.ok(!adminResetSource.includes("sessionInvalidationWarnings: sessionInvalidation.errors"), "the raw errors pass-through must be gone");
|
|
// adpanel:admin-reset-target-pinning — the write's exact shape is still
|
|
// pinned byte-for-byte; the keying moved from the email to the LOADED row's
|
|
// immutable id (an email-keyed write could silently land on a replacement
|
|
// row recreated with the same email between the lookup and the write), and
|
|
// the in-statement epoch bump is unchanged.
|
|
const commitSource = fs.readFileSync(path.join(ROOT, "services", "account-credentials.js"), "utf8");
|
|
assert.equal(countOccurrences(commitSource, "UPDATE users SET secret = NULL, recovery_codes = NULL, session_epoch = ? WHERE id = ?"), 1, "the shared id-keyed write clears both MFA credentials with the epoch");
|
|
assert.ok(adminResetSource.includes("resetAccountTwoFactor(db, targetUser, actingAdmin)"), "the reset service delegates the actor-guarded write");
|
|
});
|
|
|
|
test("source: the settings.js handlers surface the warnings additively on their existing feedback elements", () => {
|
|
assert.equal(countOccurrences(settingsSource, "Array.isArray(data.sessionInvalidationWarnings) && data.sessionInvalidationWarnings.length"), 3, "exactly the three handlers consume the warnings");
|
|
assert.equal(countOccurrences(settingsSource, "data.sessionInvalidationWarnings.join(' ')"), 3, "each handler appends the joined warning text");
|
|
// Positional proof: one occurrence inside each of the three handlers, in file order.
|
|
const selfServiceStart = settingsSource.indexOf("modalSave.addEventListener('click'");
|
|
const adminPwStart = settingsSource.indexOf("async function saveAdminChangePassword");
|
|
const qrResetStart = settingsSource.indexOf("async function confirmQRReset");
|
|
const guard = "Array.isArray(data.sessionInvalidationWarnings) && data.sessionInvalidationWarnings.length";
|
|
const first = settingsSource.indexOf(guard);
|
|
const second = settingsSource.indexOf(guard, first + 1);
|
|
const third = settingsSource.indexOf(guard, second + 1);
|
|
assert.ok(first > selfServiceStart && first < adminPwStart, "the self-service change-password handler surfaces the warnings");
|
|
assert.ok(second > adminPwStart && second < qrResetStart, "saveAdminChangePassword surfaces the warnings");
|
|
assert.ok(third > qrResetStart, "confirmQRReset surfaces the warnings");
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Behavior harness — the REAL route statements over fake db/session/res with
|
|
// the REAL rebinder, epoch generator, binding predicate and liveness checker
|
|
// ---------------------------------------------------------------------------
|
|
|
|
function makeRes() {
|
|
const res = { statusCode: 0, body: null, headersSent: false, cookies: [], cleared: [] };
|
|
res.status = (code) => { res.statusCode = code; res.headersSent = true; return res; };
|
|
res.json = (body) => { res.body = body; return res; };
|
|
res.cookie = (name, value, opts) => res.cookies.push({ name, value, opts });
|
|
res.clearCookie = (name, opts) => res.cleared.push({ name, opts });
|
|
res.set = () => res;
|
|
return res;
|
|
}
|
|
|
|
function makeSession({ user = "user@example.test" } = {}) {
|
|
return {
|
|
user,
|
|
accountId: 7,
|
|
accountEpoch: 3,
|
|
pending2faAccountEpoch: 3,
|
|
rememberLoginId: "stale-remember-id",
|
|
regenerate(cb) {
|
|
this.__oldSid = this.__sid || "old-sid";
|
|
this.__sid = `regenerated-${Math.random().toString(16).slice(2, 8)}`;
|
|
for (const key of Object.keys(this)) {
|
|
if (!["regenerate", "save", "__sid"].includes(key)) delete this[key];
|
|
}
|
|
this.user = user; // express-session keeps the raw record object; identity is re-bound by the rebinder
|
|
cb(null);
|
|
},
|
|
save(cb) { cb(null); },
|
|
};
|
|
}
|
|
|
|
function makeReq({ body, session, params } = {}) {
|
|
return {
|
|
body,
|
|
params: params || {},
|
|
headers: { "user-agent": "test-agent" },
|
|
get: (k) => (k.toLowerCase() === "user-agent" ? "test-agent" : undefined),
|
|
is: () => "application/json",
|
|
sessionID: "old-sid",
|
|
session: session || makeSession(),
|
|
};
|
|
}
|
|
|
|
// Eviction result shapes mirroring destroyBrowserSessionsForUser's contract.
|
|
const CLEAN_DESTROY = { destroyed: 2, skipped: 0, rememberLoginsRevoked: 1, errors: [], scanIncomplete: false };
|
|
const DEGRADED_DESTROY = { destroyed: 2, skipped: 0, rememberLoginsRevoked: 1, errors: [], scanIncomplete: true };
|
|
function failingDestroy() {
|
|
return async () => { throw new Error("store down"); };
|
|
}
|
|
|
|
function makeSimpleDb({ passwordAffectedRows = 1, emailAffectedRows = 1 } = {}) {
|
|
const queries = [];
|
|
return {
|
|
queries,
|
|
async query(sql, params) {
|
|
queries.push({ sql, params });
|
|
if (sql === CREDENTIAL_COMMIT_SQL.password) {
|
|
return { affectedRows: passwordAffectedRows };
|
|
}
|
|
if (sql === CREDENTIAL_COMMIT_SQL.email) {
|
|
return { affectedRows: emailAffectedRows };
|
|
}
|
|
throw new Error(`unexpected db.query in test: ${sql}`);
|
|
},
|
|
};
|
|
}
|
|
|
|
// Stateful fake db for the 2FA confirm route (the NULL-safe <=> CAS + the
|
|
// pre-flight raw-secret read), same shape as tests/credential-change-atomic-guard.test.js.
|
|
function makeConfirmDb({ initialSecret } = {}) {
|
|
const state = { secret: initialSecret, recovery_codes: "[]", secretUpdates: 0, epoch: 3 };
|
|
const queries = [];
|
|
return {
|
|
state,
|
|
queries,
|
|
async query(sql, params) {
|
|
queries.push({ sql, params });
|
|
if (sql === "SELECT id, secret FROM users WHERE id = ? LIMIT 1") {
|
|
return [{ id: params[0], secret: state.secret }];
|
|
}
|
|
if (sql === CREDENTIAL_COMMIT_SQL.twoFactor) {
|
|
const pin = params.at(-2);
|
|
const matches = (pin == null ? state.secret == null : state.secret === pin) && state.epoch === params.at(-1);
|
|
if (matches) {
|
|
state.secret = params[0];
|
|
state.recovery_codes = params[1];
|
|
state.epoch = params[2];
|
|
state.secretUpdates += 1;
|
|
return { affectedRows: 1 };
|
|
}
|
|
return { affectedRows: 0 };
|
|
}
|
|
throw new Error(`unexpected db.query in test: ${sql}`);
|
|
},
|
|
};
|
|
}
|
|
|
|
function makeCryptoStub() {
|
|
let n = 0;
|
|
return {
|
|
encryptTotpSecret: (plain) => `sealed:${plain}:#${++n}`,
|
|
decryptTotpSecret: (stored) => {
|
|
if (stored == null) return null;
|
|
const m = /^sealed:(.*):#\d+$/.exec(String(stored));
|
|
return m ? m[1] : String(stored);
|
|
},
|
|
};
|
|
}
|
|
|
|
// Builds a vm context carrying the REAL route statement and a REAL rebinder
|
|
// instance (same proven shape as tests/credential-change-atomic-guard.test.js,
|
|
// with the destroyer parameterized so the degradation modes are injectable).
|
|
function makeHarness({ user, db, recoveryVerified = null, twoFactorEnabled = false, claimRecoveryOk = true, claimTotpResult = { won: false }, verifyDelta = { delta: 0 }, destroyImpl = null } = {}) {
|
|
const calls = [];
|
|
const rebinderDeps = {
|
|
withTimeout: (p) => p,
|
|
destroyBrowserSessionsForUser: async (u) => {
|
|
calls.push(["destroy", u && u.email, u && u.id]);
|
|
if (destroyImpl) return destroyImpl(u);
|
|
return { ...CLEAN_DESTROY };
|
|
},
|
|
writeRevokedSidTombstone: async (sid) => { calls.push(["tombstone", sid]); return true; },
|
|
getSessionDisplayId: (sid) => `display(${sid})`,
|
|
ensureRememberLoginSessionId: (req) => {
|
|
calls.push(["ensureRememberId"]);
|
|
if (!req.session.rememberLoginId) req.session.rememberLoginId = "ensured-1";
|
|
return req.session.rememberLoginId;
|
|
},
|
|
buildBrowserSessionAuditFromRequest: (req, email, rememberLoginId) => {
|
|
calls.push(["audit", email, rememberLoginId]);
|
|
return { email, rememberLoginId, userAgent: req.headers["user-agent"] };
|
|
},
|
|
setRememberLoginCookie: (req, res, u, options) => {
|
|
calls.push(["mint", u && u.email, u && u.password, u && u.secret, u && u.session_epoch, options]);
|
|
req.session.rememberLoginId = "minted-1";
|
|
return 4102444800000;
|
|
},
|
|
markRememberLoginSessionFresh: (req, exp) => calls.push(["fresh", exp]),
|
|
upsertActiveBrowserSessionCacheEntry: (sid) => calls.push(["upsert", sid]),
|
|
clearRememberLoginCookie: () => calls.push(["clearCookie"]),
|
|
revokeRememberLoginRegistryEntry: async (id) => { calls.push(["revoke", id]); return true; },
|
|
logger: { warn: () => {} },
|
|
};
|
|
|
|
let sealCounter = 0;
|
|
const sandbox = {
|
|
app: { post: (...args) => calls.push(["route", ...args]) },
|
|
accountCredentialRateLimiter: {},
|
|
accountTotpRateLimiter: {},
|
|
recoveryRateLimiter: {},
|
|
isAuthenticated: async () => true,
|
|
findUserByEmail: async () => user,
|
|
getValidRecoveryVerification: () => recoveryVerified,
|
|
getProvisionedPasswordError: () => null,
|
|
bcrypt: { compare: async () => true, hash: async () => "hashed-new-password", hashSync: () => "hashed-code" },
|
|
BCRYPT_ROUNDS: 4,
|
|
withTimeout: (p) => Promise.resolve(p),
|
|
hasTwoFactorEnabled: () => twoFactorEnabled,
|
|
verifyTotpForUser: async () => ({ ok: true, skipped: false }),
|
|
verifyPasswordForUser: async () => true,
|
|
claimRecoveryCode: async () => {
|
|
calls.push(["claimRecoveryCode"]);
|
|
return claimRecoveryOk ? { ok: true, remaining: 5 } : { ok: false };
|
|
},
|
|
db,
|
|
credentialCommitService: createCredentialCommitService({ db }),
|
|
stripLogControlChars: (s) => String(s == null ? "" : s),
|
|
getRequestIp: () => "127.0.0.1",
|
|
disconnectSocketsForUser: (email, reason, options) => {
|
|
calls.push(["disconnect", email, reason, options]);
|
|
return 1;
|
|
},
|
|
// The renderer exactly as index.js requires it (the route statements call
|
|
// it on the response path — a missing module would fail loudly here).
|
|
renderSessionInvalidationWarnings,
|
|
credentialSessionRebinder: (() => {
|
|
const real = createCredentialSessionRebinder(rebinderDeps);
|
|
return {
|
|
rebindOwnerSession: async (req, res, payload) => {
|
|
calls.push(["rebindPayload", payload && payload.user && payload.user.session_epoch, payload && payload.destroyAs && payload.destroyAs.session_epoch]);
|
|
return real.rebindOwnerSession(req, res, payload);
|
|
},
|
|
};
|
|
})(),
|
|
newSessionEpochDifferentFrom,
|
|
console: { log: () => {}, error: () => {}, warn: () => {} },
|
|
speakeasy: {
|
|
totp: { verifyDelta: () => verifyDelta },
|
|
generateSecret: ({ length }) => ({ base32: `GEN${length}SECRETBASE32X`, otpauth_url: "otpauth://totp/stub" }),
|
|
otpauthURL: ({ label }) => `otpauth://totp/stub?label=${encodeURIComponent(label)}`,
|
|
},
|
|
qrcodeStub: { toDataURL: async () => "data:image/png;base64,stub" },
|
|
require: (name) => {
|
|
if (name === "qrcode") return sandbox.qrcodeStub;
|
|
throw new Error(`unexpected require in test: ${name}`);
|
|
},
|
|
process: { env: {} },
|
|
totpSecretCrypto: makeCryptoStub(),
|
|
markTotpCodeUsed: (key, code) => calls.push(["markTotpCodeUsed", key, code]),
|
|
totpAccountKey: (u) => `id:${u && u.id}`,
|
|
claimTotpStep: async (id, step) => {
|
|
calls.push(["claimTotpStep", id, step]);
|
|
return claimTotpResult;
|
|
},
|
|
currentTotpStep: () => 12345,
|
|
crypto,
|
|
JSON,
|
|
Promise,
|
|
Date,
|
|
Symbol,
|
|
Object,
|
|
String,
|
|
Number,
|
|
Math,
|
|
RegExp,
|
|
Error,
|
|
setTimeout,
|
|
};
|
|
|
|
return {
|
|
calls,
|
|
load(statementKey) {
|
|
const captured = [];
|
|
const ctx = vm.createContext({ ...sandbox, app: { post: (...args) => captured.push(args) } });
|
|
vm.runInContext(statements[statementKey], ctx, { filename: `index.js[${statementKey}]` });
|
|
assert.equal(captured.length, 1, "exactly one route registration per statement");
|
|
const handler = captured[0][2];
|
|
assert.equal(typeof handler, "function");
|
|
return handler;
|
|
},
|
|
};
|
|
}
|
|
|
|
const BASE_USER = { id: 42, email: "user@example.test", password: "$2a$12$oldhash", secret: null, session_epoch: 3, admin: 0, suspended: 0 };
|
|
|
|
function confirmHarness(db, overrides = {}) {
|
|
return makeHarness({
|
|
user: { ...BASE_USER, secret: "OLDS3CRETBASE32XQ" },
|
|
db,
|
|
twoFactorEnabled: true,
|
|
...overrides,
|
|
});
|
|
}
|
|
|
|
// Harness for the two admin routes that evict WITHOUT rebinding the caller
|
|
// (the admin per-account change-password and the suspension route): real route
|
|
// statements, fake deps, the real renderer injected (as index.js wires it).
|
|
function makeAdminRouteHarness({ statementKey, db, targetUser, adminUser, destroyImpl = null, stepUpResult = null } = {}) {
|
|
const calls = [];
|
|
const transactionDb = require("./helpers/account-transaction").attachAccountTransaction(db, { actor: adminUser, target: targetUser });
|
|
const sandbox = {
|
|
...require("../services/account-actions"),
|
|
app: { post: (...args) => calls.push(["route", ...args]) },
|
|
sessionRevoke2faRateLimiter: {},
|
|
isAdmin: async () => true,
|
|
requireActionTokenOr403: async () => { calls.push(["token"]); return true; },
|
|
findUserByEmail: async (email) => {
|
|
const lower = String(email || "").toLowerCase();
|
|
if (adminUser && String(adminUser.email).toLowerCase() === lower) return adminUser;
|
|
if (targetUser && String(targetUser.email).toLowerCase() === lower) return targetUser;
|
|
return null;
|
|
},
|
|
getProvisionedPasswordError: () => null,
|
|
requireDestructiveActionStepUp: async () => { calls.push(["stepUp"]); return stepUpResult || { ok: true, graceExpiresAt: 0 }; },
|
|
withTimeout: (p) => Promise.resolve(p),
|
|
bcrypt: { compare: async () => true, hash: async () => "hashed-new-password" },
|
|
BCRYPT_ROUNDS: 4,
|
|
newSessionEpochDifferentFrom,
|
|
db: transactionDb,
|
|
resetAccountPassword: require("../services/account-credentials").resetAccountPassword,
|
|
destroyBrowserSessionsForUser: async (u, options) => {
|
|
calls.push(["destroy", u && u.email]);
|
|
if (destroyImpl) return destroyImpl(u, options);
|
|
return { ...CLEAN_DESTROY };
|
|
},
|
|
disconnectSocketsForUser: (email, reason) => { calls.push(["disconnect", email, reason]); return 2; },
|
|
cancelSchedulesCreatedBy: async () => { calls.push(["cancelSchedules"]); return {}; },
|
|
cancelQueuedAiAgentJobsForUser: async () => { calls.push(["cancelJobs"]); return {}; },
|
|
stripLogControlChars: (s) => String(s == null ? "" : s),
|
|
getRequestIp: () => "127.0.0.1",
|
|
getVerifiedSessionRevokeGraceState: async () => ({ expiresAt: 0 }),
|
|
getDestructiveActionSecurityAsync: async () => ({ stepUp: "password" }),
|
|
// The renderer + suspension note exactly as index.js requires them. Before
|
|
// the fix the route statements do not reference them; after the fix a
|
|
// missing module would fail loudly here instead of rendering undefined.
|
|
renderSessionInvalidationWarnings,
|
|
SUSPENSION_SCAN_INCOMPLETE_NOTE,
|
|
STALE_TARGET_409_MESSAGE: require("../services/admin-2fa-reset").STALE_TARGET_409_MESSAGE,
|
|
console: { log: () => {}, error: () => {}, warn: () => {} },
|
|
JSON,
|
|
Promise,
|
|
Date,
|
|
Symbol,
|
|
Object,
|
|
String,
|
|
Number,
|
|
Math,
|
|
RegExp,
|
|
Error,
|
|
setTimeout,
|
|
};
|
|
|
|
const captured = [];
|
|
const ctx = vm.createContext({ ...sandbox, app: { post: (...args) => captured.push(args) } });
|
|
vm.runInContext(statements[statementKey], ctx, { filename: `index.js[${statementKey}]` });
|
|
assert.equal(captured.length, 1, "exactly one route registration per statement");
|
|
const handler = captured[0][2];
|
|
assert.equal(typeof handler, "function");
|
|
|
|
return {
|
|
calls,
|
|
handler: (req, res, next) => {
|
|
req.body = { expectedTargetId: targetUser.id, ...req.body };
|
|
return handler(req, res, next);
|
|
},
|
|
makeNext: () => { const nextCalls = []; const next = (e) => nextCalls.push(e); next.calls = nextCalls; return next; },
|
|
};
|
|
}
|
|
|
|
const ADMIN_USER = { id: 7, email: "admin@example.test", admin: 1, password: "$2a$12$adminhash", session_epoch: 5, suspended: 0 };
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Behavior (b) — the response's warnings reflect eviction incompleteness
|
|
// ---------------------------------------------------------------------------
|
|
|
|
test("password change: a degraded inventory scan still answers ok:true, keeps every field, and surfaces the truthful scan-incomplete warning", async () => {
|
|
const db = makeSimpleDb({ passwordAffectedRows: 1 });
|
|
const { load } = makeHarness({ user: BASE_USER, db, destroyImpl: async () => ({ ...DEGRADED_DESTROY }) });
|
|
const h = load("password");
|
|
const res = makeRes();
|
|
|
|
await h(makeReq({ body: { currentPassword: "pw", newPassword: "Newpassword1!", twoFactorCode: "" } }), res);
|
|
|
|
assert.equal(res.statusCode, 0, "200 via res.json");
|
|
assert.equal(res.body.ok, true, "the credential change itself succeeded — ok stays true");
|
|
assert.equal(res.body.sessionsDestroyed, 2, "existing fields are kept");
|
|
assert.equal(res.body.socketsDisconnected, 1);
|
|
assert.equal(res.body.rememberLoginsRevoked, 1);
|
|
assert.ok(Array.isArray(res.body.sessionInvalidationWarnings), "warnings stay an array");
|
|
assert.deepEqual(res.body.sessionInvalidationWarnings, [CREDENTIAL_SCAN_INCOMPLETE_NOTE], "the degraded scan must surface the truthful note (pre-fix this was silently dropped to [])");
|
|
});
|
|
|
|
test("settings change-password: same truthful warning on a degraded scan, message field intact", async () => {
|
|
const db = makeSimpleDb({ passwordAffectedRows: 1 });
|
|
const { load } = makeHarness({ user: { ...BASE_USER, admin: 1 }, db, destroyImpl: async () => ({ ...DEGRADED_DESTROY }) });
|
|
const h = load("settings");
|
|
const res = makeRes();
|
|
|
|
await h(makeReq({ body: { current: "pw", newPassword: "Newpassword1!", confirm: "Newpassword1!" } }), res);
|
|
|
|
assert.equal(res.body.ok, true);
|
|
assert.equal(res.body.message, "password changed successfully");
|
|
assert.deepEqual(res.body.sessionInvalidationWarnings, [CREDENTIAL_SCAN_INCOMPLETE_NOTE]);
|
|
});
|
|
|
|
test("email change: degraded scan surfaces the warning; the old-email sweep and new-email rebind are unchanged", async () => {
|
|
const db = makeSimpleDb({ emailAffectedRows: 1 });
|
|
const { calls, load } = makeHarness({ user: BASE_USER, db, destroyImpl: async () => ({ ...DEGRADED_DESTROY }) });
|
|
const h = load("email");
|
|
const res = makeRes();
|
|
|
|
await h(makeReq({ body: { currentPassword: "pw", newEmail: "new@example.test" } }), res);
|
|
|
|
assert.equal(res.body.ok, true);
|
|
assert.deepEqual(res.body.sessionInvalidationWarnings, [CREDENTIAL_SCAN_INCOMPLETE_NOTE]);
|
|
assert.ok(calls.some((c) => c[0] === "destroy" && c[1] === "user@example.test"), "the sweep still matches the OLD email identity");
|
|
assert.ok(calls.some((c) => c[0] === "mint" && c[1] === "new@example.test" && c[5] && c[5].forceFreshId === true), "the remember re-issue still binds the NEW email");
|
|
});
|
|
|
|
test("2FA confirm: degraded scan surfaces the warning; the recovery-code envelope is intact", async () => {
|
|
const db = makeConfirmDb({ initialSecret: "sealed:OLDS3CRETBASE32XQ:#7" });
|
|
const { load } = confirmHarness(db, { destroyImpl: async () => ({ ...DEGRADED_DESTROY }) });
|
|
const h = load("confirm");
|
|
const res = makeRes();
|
|
|
|
await h(makeReq({
|
|
body: { newCode: "123456", newSecret: "NEWS3CRETBASE32XQ" },
|
|
session: Object.assign(makeSession(), { pending2faSecret: "NEWS3CRETBASE32XQ", pending2faFrom: "standard" }),
|
|
}), res);
|
|
|
|
assert.equal(res.body && res.body.ok, true);
|
|
assert.ok(Array.isArray(res.body.recoveryCodes) && res.body.recoveryCodes.length === 7, "the recovery-code envelope is unchanged");
|
|
assert.equal(res.body.sessionsDestroyed, 2);
|
|
assert.deepEqual(res.body.sessionInvalidationWarnings, [CREDENTIAL_SCAN_INCOMPLETE_NOTE], "the 2FA confirm must surface the degraded scan too");
|
|
});
|
|
|
|
test("admin per-account change-password: a vanished row returns 409 before any eviction", async () => {
|
|
const harness = makeAdminRouteHarness({ statementKey: "adminChangePassword", db: makeAdminResetDb(0), targetUser: BASE_USER, adminUser: ADMIN_USER });
|
|
const res = makeRes();
|
|
const next = harness.makeNext();
|
|
await harness.handler(makeReq({ params: { email: BASE_USER.email }, body: { newPassword: "Newpassword1!", confirm: "Newpassword1!" }, session: { user: ADMIN_USER.email } }), res, next);
|
|
assert.equal(next.calls.length, 0);
|
|
assert.equal(res.statusCode, 409);
|
|
assert.equal(res.body.ok, undefined);
|
|
assert.equal(harness.calls.filter((call) => ["destroy", "disconnect"].includes(call[0])).length, 0);
|
|
});
|
|
|
|
test("admin per-account change-password: degraded scan surfaces the truthful warning; the reset itself stands", async () => {
|
|
const db = makeAdminResetDb();
|
|
const harness = makeAdminRouteHarness({
|
|
statementKey: "adminChangePassword",
|
|
db,
|
|
targetUser: BASE_USER,
|
|
adminUser: ADMIN_USER,
|
|
destroyImpl: async () => ({ ...DEGRADED_DESTROY }),
|
|
});
|
|
const res = makeRes();
|
|
const next = harness.makeNext();
|
|
|
|
await harness.handler(makeReq({ params: { email: "user@example.test" }, body: { newPassword: "Newpassword1!", confirm: "Newpassword1!" }, session: { user: ADMIN_USER.email } }), res, next);
|
|
|
|
assert.equal(next.calls.length, 0, "no error passthrough");
|
|
assert.equal(res.statusCode, 0, "200 via res.json");
|
|
assert.equal(res.body.ok, true, "the admin reset itself succeeded — ok stays true (its documented contract)");
|
|
assert.equal(res.body.sessionsDestroyed, 2);
|
|
assert.equal(res.body.rememberLoginsRevoked, 1);
|
|
assert.deepEqual(res.body.sessionInvalidationWarnings, [CREDENTIAL_SCAN_INCOMPLETE_NOTE], "the epoch rides the reset's UPDATE, so the note's invalidation promise is TRUE here");
|
|
const casQuery = db.queries.find((q) => q.sql === "UPDATE users SET password = ?, session_epoch = ? WHERE id = ?");
|
|
assert.ok(casQuery, "the id-keyed reset write ran");
|
|
assert.ok(Number.isInteger(casQuery.params[1]) && casQuery.params[1] !== BASE_USER.session_epoch, "the reset commits a fresh generation in-statement");
|
|
});
|
|
|
|
test("admin 2FA reset (real service module): degraded scan surfaces the truthful warning; clean scan stays warnings-free", async () => {
|
|
const TARGET = { id: 42, email: "target@example.test", admin: 0, secret: "sealed:TOTPSEED", session_epoch: 3 };
|
|
const ADMIN = { id: 7, email: "admin@example.test", admin: 1, suspended: 0, session_epoch: 9 };
|
|
function makeDeps(destroyImpl) {
|
|
return {
|
|
isAdmin: async () => true,
|
|
requireActionTokenOr403: async () => true,
|
|
findUserByEmail: async (email) => (email === ADMIN.email ? ADMIN : email === TARGET.email ? TARGET : null),
|
|
requireDestructiveActionStepUp: async () => ({ ok: true }),
|
|
db: require("./helpers/account-transaction").attachAccountTransaction({ async query() { return { affectedRows: 1 }; } }, { actor: ADMIN, target: TARGET }),
|
|
destroyBrowserSessionsForUser: async (u) => {
|
|
if (destroyImpl) return destroyImpl(u);
|
|
return { ...CLEAN_DESTROY };
|
|
},
|
|
disconnectSocketsForUser: () => 3,
|
|
recordActivity: () => {},
|
|
getRequestIp: () => "127.0.0.1",
|
|
normalizeAdminTargetEmail: (raw) => (typeof raw === "string" && raw.includes("@") ? raw.trim() : null),
|
|
stripLogControlChars: (s) => String(s == null ? "" : s),
|
|
logger: { log: () => {}, error: () => {}, warn: () => {} },
|
|
};
|
|
}
|
|
const { createAdminTwoFactorResetService } = require("../services/admin-2fa-reset.js");
|
|
|
|
const degradedRes = makeRes();
|
|
const degradedService = createAdminTwoFactorResetService(makeDeps(async () => ({ ...DEGRADED_DESTROY })));
|
|
await degradedService.handleAdmin2faReset(
|
|
makeReq({ body: { email: "target@example.test", expectedTargetId: TARGET.id }, session: { user: ADMIN.email } }),
|
|
degradedRes,
|
|
{ action: "POST /api/admin/user/reset-2fa", proofLabel: "Admin 2FA reset", logSuffix: "" }
|
|
);
|
|
assert.equal(degradedRes.body.ok, true, "the reset stands");
|
|
assert.equal(degradedRes.body.cleared, true);
|
|
assert.deepEqual(degradedRes.body.sessionInvalidationWarnings, [CREDENTIAL_SCAN_INCOMPLETE_NOTE], "the admin 2FA reset must surface the degraded scan (pre-fix: silently dropped)");
|
|
assert.ok(Number.isInteger(degradedRes.body.sessionsDestroyed), "existing response fields are kept");
|
|
|
|
const cleanRes = makeRes();
|
|
const cleanService = createAdminTwoFactorResetService(makeDeps(null));
|
|
await cleanService.handleAdmin2faReset(
|
|
makeReq({ body: { email: "target@example.test", expectedTargetId: TARGET.id }, session: { user: ADMIN.email } }),
|
|
cleanRes,
|
|
{ action: "POST /api/admin/user/reset-2fa", proofLabel: "Admin 2FA reset", logSuffix: "" }
|
|
);
|
|
assert.deepEqual(cleanRes.body.sessionInvalidationWarnings, [], "a complete eviction renders no warnings (the pinned clean-path shape is unchanged)");
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Behavior (a) — the invalidation chain survives an eviction that FAILS
|
|
// outright: the epoch rides the credential's own UPDATE, which commits before
|
|
// any eviction machinery, so every pre-change session fails the REAL binding
|
|
// predicate on its next use
|
|
// ---------------------------------------------------------------------------
|
|
|
|
test("password change: destroyBrowserSessionsForUser rejecting answers 500 (never ok:true) but the CAS already committed the new generation — old sessions fail the REAL binding predicate", async () => {
|
|
const db = makeSimpleDb({ passwordAffectedRows: 1 });
|
|
const { load } = makeHarness({ user: BASE_USER, db, destroyImpl: failingDestroy() });
|
|
const h = load("password");
|
|
const req = makeReq({ body: { currentPassword: "pw", newPassword: "Newpassword1!", twoFactorCode: "" } });
|
|
const res = makeRes();
|
|
|
|
await h(req, res);
|
|
|
|
assert.equal(res.statusCode, 500, "an eviction failure must not report success");
|
|
assert.equal(res.body.ok, undefined, "no success fields ride a failed eviction");
|
|
assert.equal(res.body.error, "Failed to update password");
|
|
|
|
// The credential's own CAS ran BEFORE the rebind, so the generation moved.
|
|
const casQuery = db.queries.find((q) => q.sql === CREDENTIAL_COMMIT_SQL.password);
|
|
assert.ok(casQuery, "the credential CAS ran");
|
|
const committedEpoch = casQuery.params[1];
|
|
assert.ok(Number.isInteger(committedEpoch) && committedEpoch !== BASE_USER.session_epoch, "a fresh generation was committed in-statement");
|
|
|
|
// The REAL shared predicate (not a mock): a session bound pre-change — the
|
|
// stale record a missed sweep would leave behind, and the caller's own
|
|
// unrebound session — mismatches the post-change row.
|
|
const postChangeRow = { ...BASE_USER, password: "hashed-new-password", session_epoch: committedEpoch };
|
|
assert.equal(
|
|
sessionAccountBindingMismatch({ accountId: BASE_USER.id, accountEpoch: BASE_USER.session_epoch }, postChangeRow),
|
|
true,
|
|
"a pre-change session record fails the binding check on its next request"
|
|
);
|
|
assert.equal(
|
|
sessionAccountBindingMismatch(req.session, postChangeRow),
|
|
true,
|
|
"the caller's own (never re-bound, because the rebind failed) session is torn down too — a failed change never leaves the caller on a live old-generation session"
|
|
);
|
|
});
|
|
|
|
test("2FA confirm: destroy rejecting answers the 500 but the CAS committed the new generation and old socket-session records fail the REAL binding predicate", async () => {
|
|
const db = makeConfirmDb({ initialSecret: "sealed:OLDS3CRETBASE32XQ:#7" });
|
|
const { load } = confirmHarness(db, { destroyImpl: failingDestroy() });
|
|
const h = load("confirm");
|
|
const res = makeRes();
|
|
|
|
await h(makeReq({
|
|
body: { newCode: "123456", newSecret: "NEWS3CRETBASE32XQ" },
|
|
session: Object.assign(makeSession(), { pending2faSecret: "NEWS3CRETBASE32XQ", pending2faFrom: "standard" }),
|
|
}), res);
|
|
|
|
assert.equal(res.statusCode, 500);
|
|
assert.equal(res.body.ok, undefined);
|
|
assert.equal(res.body.error, "Failed to update 2FA");
|
|
assert.equal(db.state.secretUpdates, 1, "the winning CAS committed the new secret + generation before any eviction ran");
|
|
const postChangeRow = { ...BASE_USER, secret: "NEWS3CRETBASE32XQ", session_epoch: db.state.epoch };
|
|
assert.equal(
|
|
sessionAccountBindingMismatch({ accountId: BASE_USER.id, accountEpoch: BASE_USER.session_epoch }, postChangeRow),
|
|
true,
|
|
"the pre-change binding mismatches the committed generation"
|
|
);
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Behavior (c) — owner rebind on a completing change: the caller is re-bound
|
|
// to exactly the committed generation and passes the REAL binding predicate
|
|
// ---------------------------------------------------------------------------
|
|
|
|
test("password change: the owner's regenerated session binds the committed generation (passes the REAL binding predicate) and the remember cookie is re-issued forceFreshId", async () => {
|
|
const db = makeSimpleDb({ passwordAffectedRows: 1 });
|
|
const { calls, load } = makeHarness({ user: BASE_USER, db, destroyImpl: async () => ({ ...DEGRADED_DESTROY }) });
|
|
const h = load("password");
|
|
const req = makeReq({ body: { currentPassword: "pw", newPassword: "Newpassword1!", twoFactorCode: "" } });
|
|
const res = makeRes();
|
|
|
|
await h(req, res);
|
|
|
|
assert.equal(res.body.ok, true);
|
|
const committedEpoch = db.queries.find((q) => q.sql === CREDENTIAL_COMMIT_SQL.password).params[1];
|
|
const payloadCall = calls.find((c) => c[0] === "rebindPayload");
|
|
assert.ok(payloadCall, "the route rebinds through the shared rebinder");
|
|
assert.equal(payloadCall[1], committedEpoch, "the rebind payload carries exactly the committed generation");
|
|
assert.equal(req.session.accountEpoch, committedEpoch, "the owner's regenerated session binds the committed generation");
|
|
assert.equal(req.session.accountId, BASE_USER.id, "the owner's account id is re-bound");
|
|
|
|
const postChangeRow = { ...BASE_USER, password: "hashed-new-password", session_epoch: committedEpoch };
|
|
assert.equal(sessionAccountBindingMismatch(req.session, postChangeRow), false, "the re-bound owner passes the REAL binding predicate against the post-change row (not torn down as stale)");
|
|
|
|
const mint = calls.find((c) => c[0] === "mint");
|
|
assert.ok(mint, "the remember cookie was re-issued");
|
|
assert.equal(mint[1], BASE_USER.email, "the mint targets the owner");
|
|
assert.equal(mint[2], "hashed-new-password", "the mint material is the NEW password");
|
|
assert.equal(mint[3], null, "a password change leaves the row's (null) 2FA secret unchanged in the mint material");
|
|
assert.equal(mint[4], committedEpoch, "the mint material carries the committed generation");
|
|
assert.ok(mint[5] && mint[5].forceFreshId === true, "the re-issue follows the user-wide remember revoke, so forceFreshId is mandatory (adpanel:remember-fresh-reissue)");
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Behavior (d) — HTTP and socket binding agree: the SAME committed generation
|
|
// tears down both surfaces (REAL predicate + REAL liveness checker)
|
|
// ---------------------------------------------------------------------------
|
|
|
|
test("HTTP and socket binding agree: the generation the credential CAS commits tears a stale socket down ('account-binding-stale') and keeps the re-bound one alive", async () => {
|
|
const db = makeSimpleDb({ passwordAffectedRows: 1 });
|
|
const { load } = makeHarness({ user: BASE_USER, db, destroyImpl: async () => ({ ...DEGRADED_DESTROY }) });
|
|
const h = load("password");
|
|
const res = makeRes();
|
|
await h(makeReq({ body: { currentPassword: "pw", newPassword: "Newpassword1!", twoFactorCode: "" } }), res);
|
|
assert.equal(res.body.ok, true);
|
|
|
|
const committedEpoch = db.queries.find((q) => q.sql === CREDENTIAL_COMMIT_SQL.password).params[1];
|
|
const postChangeRow = { ...BASE_USER, password: "hashed-new-password", session_epoch: committedEpoch };
|
|
|
|
// HTTP leg: the REAL predicate tears the pre-change binding down and keeps the re-bound one.
|
|
assert.equal(sessionAccountBindingMismatch({ accountId: BASE_USER.id, accountEpoch: BASE_USER.session_epoch }, postChangeRow), true, "HTTP: pre-change binding is stale");
|
|
assert.equal(sessionAccountBindingMismatch({ accountId: BASE_USER.id, accountEpoch: committedEpoch }, postChangeRow), false, "HTTP: the re-bound binding matches");
|
|
|
|
// Socket leg: the REAL liveness checker feeds the record each socket kept
|
|
// from its handshake plus the re-read row, and reaches the SAME verdicts.
|
|
const records = new Map([
|
|
["stale-socket-sid", { accountId: BASE_USER.id, accountEpoch: BASE_USER.session_epoch }],
|
|
["fresh-socket-sid", { accountId: BASE_USER.id, accountEpoch: committedEpoch }],
|
|
]);
|
|
const checker = createSocketSessionLivenessChecker({
|
|
getSessionRecord: async (sid) => records.get(sid) || null,
|
|
isSessionSidRevoked: async () => false,
|
|
});
|
|
const stale = await checker("stale-socket-sid", { user: postChangeRow });
|
|
assert.equal(stale.verdict, SOCKET_SESSION_LIVENESS_VERDICTS.DEAD, "a socket bound to the pre-change generation is torn down");
|
|
assert.equal(stale.reason, "account-binding-stale", "the teardown reason is the shared binding mismatch");
|
|
const fresh = await checker("fresh-socket-sid", { user: postChangeRow });
|
|
assert.equal(fresh.verdict, SOCKET_SESSION_LIVENESS_VERDICTS.ALIVE, "a socket re-bound to the committed generation stays");
|
|
|
|
// The eviction's tombstone leg agrees too: a destroyed (tombstoned) sid is
|
|
// dead for sockets exactly as it is for HTTP. The record here matches the
|
|
// row's binding (the binding leg runs first and would mask this verdict
|
|
// otherwise) — the sid is revoked, so it is dead regardless.
|
|
const tombstoneChecker = createSocketSessionLivenessChecker({
|
|
getSessionRecord: async () => ({ accountId: BASE_USER.id, accountEpoch: committedEpoch }),
|
|
isSessionSidRevoked: async () => true,
|
|
});
|
|
const tombstoned = await tombstoneChecker("destroyed-socket-sid", { user: postChangeRow });
|
|
assert.equal(tombstoned.verdict, SOCKET_SESSION_LIVENESS_VERDICTS.DEAD, "a tombstoned socket sid is dead even with a stale record in place");
|
|
assert.equal(tombstoned.reason, "sid-revoked");
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Behavior — the suspension route: surfacing only, contract otherwise
|
|
// unchanged (suspension is NOT a credential change)
|
|
// ---------------------------------------------------------------------------
|
|
|
|
const SUSPENSION_TARGET = { id: 42, email: "user@example.test", admin: 0, suspended: 0, session_epoch: 3, password: "$2a$12$oldhash" };
|
|
|
|
// Fake db for the admin per-account change-password route: recognizes its
|
|
// id-keyed (deliberately non-CAS, documented last-writer-wins) reset UPDATE.
|
|
function makeAdminResetDb(affectedRows = 1) {
|
|
const queries = [];
|
|
return {
|
|
queries,
|
|
async query(sql, params) {
|
|
queries.push({ sql, params });
|
|
if (sql === "UPDATE users SET password = ?, session_epoch = ? WHERE id = ?") {
|
|
return { affectedRows };
|
|
}
|
|
throw new Error(`unexpected db.query in test: ${sql}`);
|
|
},
|
|
};
|
|
}
|
|
|
|
function makeSuspensionDb() {
|
|
const queries = [];
|
|
const db = {
|
|
queries,
|
|
async query(sql, params) {
|
|
queries.push({ sql, params });
|
|
if (sql === "UPDATE users SET suspended = ?, suspended_at = ?, suspended_by = ?, session_epoch = ? WHERE id = ? AND admin = 0") {
|
|
return { affectedRows: 1 };
|
|
}
|
|
throw new Error(`unexpected db.query in test: ${sql}`);
|
|
},
|
|
};
|
|
db.pool = { getConnection: async () => ({
|
|
beginTransaction: async () => {}, commit: async () => {}, rollback: async () => {}, release() {},
|
|
execute: async (sql, params) => {
|
|
if (sql.startsWith("SELECT id, admin")) return [[{ ...ADMIN_USER }]];
|
|
if (sql.startsWith("SELECT id, email")) return [[{ ...SUSPENSION_TARGET }]];
|
|
return [await db.query(sql, params)];
|
|
}
|
|
}) };
|
|
return db;
|
|
}
|
|
|
|
test("suspension: a degraded inventory scan fails LOUDLY (standing 500 contract) instead of ok:true with an unverified sweep — with the suspension-specific note", async () => {
|
|
const db = makeSuspensionDb();
|
|
const harness = makeAdminRouteHarness({
|
|
statementKey: "suspension",
|
|
db,
|
|
targetUser: SUSPENSION_TARGET,
|
|
adminUser: ADMIN_USER,
|
|
destroyImpl: async () => ({ ...DEGRADED_DESTROY }),
|
|
});
|
|
const res = makeRes();
|
|
const next = harness.makeNext();
|
|
|
|
await harness.handler(makeReq({
|
|
params: { email: "user@example.test" },
|
|
body: { suspended: true },
|
|
session: { user: ADMIN_USER.email },
|
|
}), res, next);
|
|
|
|
assert.equal(next.calls.length, 0);
|
|
assert.equal(res.statusCode, 500, "an unverified eviction must not report a clean suspension");
|
|
assert.equal(res.body.ok, false);
|
|
assert.equal(res.body.sessionEvictionFailed, true, "scanIncomplete must key the standing fail-loudly contract");
|
|
assert.equal(res.body.suspended, true, "the suspension itself stands (auth-time checks block the account)");
|
|
assert.deepEqual(db.queries.map((query) => query.sql), ["UPDATE users SET suspended = ?, suspended_at = ?, suspended_by = ?, session_epoch = ? WHERE id = ? AND admin = 0"], "suspension and epoch invalidation committed together before eviction");
|
|
assert.notEqual(db.queries[0].params[3], SUSPENSION_TARGET.session_epoch, "an incomplete sweep cannot leave the pre-suspension generation current");
|
|
assert.deepEqual(res.body.sessionInvalidationWarnings, [SUSPENSION_SCAN_INCOMPLETE_NOTE], "the surfaced note remains suspension-specific");
|
|
});
|
|
|
|
test("suspension: per-session eviction errors keep the existing 500 contract, warnings pass through unchanged", async () => {
|
|
const db = makeSuspensionDb();
|
|
const harness = makeAdminRouteHarness({
|
|
statementKey: "suspension",
|
|
db,
|
|
targetUser: SUSPENSION_TARGET,
|
|
adminUser: ADMIN_USER,
|
|
destroyImpl: async () => ({ destroyed: 1, skipped: 0, rememberLoginsRevoked: 0, errors: ["display(sid-9):destroy failed"], scanIncomplete: false }),
|
|
});
|
|
const res = makeRes();
|
|
const next = harness.makeNext();
|
|
|
|
await harness.handler(makeReq({
|
|
params: { email: "user@example.test" },
|
|
body: { suspended: true },
|
|
session: { user: ADMIN_USER.email },
|
|
}), res, next);
|
|
|
|
assert.equal(res.statusCode, 500, "the existing errors-keyed 500 contract is unchanged");
|
|
assert.equal(res.body.ok, false);
|
|
assert.equal(res.body.sessionEvictionFailed, true);
|
|
assert.deepEqual(res.body.sessionInvalidationWarnings, ["display(sid-9):destroy failed"], "the error strings pass through verbatim (the note rides scanIncomplete, which is false here)");
|
|
});
|
|
|
|
test("suspension: a complete eviction keeps the clean ok:true response with no warnings", async () => {
|
|
const db = makeSuspensionDb();
|
|
const harness = makeAdminRouteHarness({
|
|
statementKey: "suspension",
|
|
db,
|
|
targetUser: SUSPENSION_TARGET,
|
|
adminUser: ADMIN_USER,
|
|
destroyImpl: async () => ({ ...CLEAN_DESTROY }),
|
|
});
|
|
const res = makeRes();
|
|
const next = harness.makeNext();
|
|
|
|
await harness.handler(makeReq({
|
|
params: { email: "user@example.test" },
|
|
body: { suspended: true },
|
|
session: { user: ADMIN_USER.email },
|
|
}), res, next);
|
|
|
|
assert.equal(res.statusCode, 0);
|
|
assert.equal(res.body.ok, true);
|
|
assert.equal(res.body.sessionEvictionFailed, false);
|
|
assert.deepEqual(res.body.sessionInvalidationWarnings, []);
|
|
assert.equal(res.body.suspended, true);
|
|
});
|
|
|
|
test("suspension: unsuspend performs no eviction and stays warnings-free", async () => {
|
|
const db = makeSuspensionDb();
|
|
const harness = makeAdminRouteHarness({
|
|
statementKey: "suspension",
|
|
db,
|
|
targetUser: SUSPENSION_TARGET,
|
|
adminUser: ADMIN_USER,
|
|
destroyImpl: async () => { throw new Error("no eviction on unsuspend"); },
|
|
});
|
|
const res = makeRes();
|
|
const next = harness.makeNext();
|
|
|
|
await harness.handler(makeReq({
|
|
params: { email: "user@example.test" },
|
|
body: { suspended: false },
|
|
session: { user: ADMIN_USER.email },
|
|
}), res, next);
|
|
|
|
assert.equal(res.statusCode, 0);
|
|
assert.equal(res.body.ok, true);
|
|
assert.equal(res.body.suspended, false);
|
|
assert.deepEqual(res.body.sessionInvalidationWarnings, []);
|
|
assert.equal(harness.calls.some((c) => c[0] === "destroy"), false, "unsuspend does not evict");
|
|
});
|