937 lines
60 KiB
JavaScript
937 lines
60 KiB
JavaScript
"use strict";
|
||
|
||
// adpanel:login-staleness-reproof + adpanel:restore-staleness-reverify —
|
||
// source + behavior pins for the password-change × in-flight
|
||
// login/remember-restore revocation-bypass TOCTOU (audit M1).
|
||
//
|
||
// Finding: a credential compare is seconds of wall time (bcrypt on the
|
||
// admission semaphore). T0 the attacker submits the OLD password and the
|
||
// compare proves the snapshot hash; T1 the victim's password change commits
|
||
// — its UPDATE lands and destroyBrowserSessionsForUser /
|
||
// revokeRememberLoginsForUser sweep, but the attacker's session is not yet
|
||
// bound (buildActiveBrowserSessionRecord returns null for a session without
|
||
// sess.user) and the remember id is not yet minted, so the sweep misses it;
|
||
// T2 the compare returns TRUE against the stale snapshot, the post-compare
|
||
// re-read checked only suspension, and the bind minted a session + a fresh
|
||
// 365-day remember registry id fingerprinted from the NEW hash — a live
|
||
// credential that survived the password change. Same shape (narrowed to the
|
||
// CAS-race window) on remember-restore: the row snapshot is read before the
|
||
// rotate CAS and the bind, so a mid-restore change slipped the rotation into
|
||
// the sweep's read→HDEL gap and bound the pre-change row.
|
||
//
|
||
// Fix (this file pins it):
|
||
// 1. POST /login: between the re-read and the bind, a hash-string
|
||
// inequality (latestUser.password !== user.password, where user.password
|
||
// is exactly the hash the compare PROVED) triggers a bounded re-proof of
|
||
// the submitted password against the LIVE hash — same admission
|
||
// semaphore, same 8 s window, same uniform failCredentials settle as the
|
||
// rehash-CAS re-proof (arm:stale-credential). Mismatch → the ONE uniform
|
||
// 400 with the failure recorded on this request's own budgets; re-proof
|
||
// success (a benign parallel rehash of the SAME password, or a change
|
||
// reverted to it) → bind proceeds with the re-read row. The string
|
||
// inequality decides only WHETHER to re-prove, never the verdict.
|
||
// 2. restoreRememberedLogin: after the rotation CAS succeeds and before the
|
||
// bind, re-read the row (8s bounded like the sibling lookups) and
|
||
// re-verify getRememberLoginFingerprint(freshRow) === parsed.fp — the fp
|
||
// ties the credential to the password hash, so a mid-restore change
|
||
// fails the restore closed (clear state + clear cookie + silent false).
|
||
// 3. The captcha-completion path needed no PASSWORD re-proof:
|
||
// completePendingCaptchaLogin already re-resolves the row and
|
||
// re-verifies the fingerprint against the challenge-time snapshot —
|
||
// the pattern both fixes mirror. Conscious amendment
|
||
// (adpanel:login-proof-generation): the completion GAINED the
|
||
// generation record (accountEpoch at mint), the comparable-epoch gate,
|
||
// and the beforeSave fresh-read revalidation covering the binder's
|
||
// regenerate→save window — pinned by
|
||
// tests/captcha-completion-staleness.test.js.
|
||
//
|
||
// The behavioral harnesses use the house vm-extraction technique
|
||
// (tests/login-id-refusal-parity.test.js, tests/remember-restore-and-
|
||
// confirmed-bounds.test.js): the REAL handler-helper block, the REAL
|
||
// post-re-read region and the REAL restore body run verbatim against the
|
||
// REAL throttle store and REAL bcrypt (bcryptjs at cost 4 — cryptographic
|
||
// verdicts, millisecond cost), so the interleaves below are simulations of
|
||
// the timeline, not re-implementations of the guard.
|
||
|
||
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 bcryptjs = require("bcryptjs");
|
||
|
||
const ROOT = path.join(__dirname, "..");
|
||
const INDEX_JS = path.join(ROOT, "index.js");
|
||
const indexSource = fs.readFileSync(INDEX_JS, "utf8");
|
||
|
||
const { createLoginThrottle } = require(path.join(ROOT, "utils", "login-throttle.js"));
|
||
const { MemoryStore, ipKeyGenerator } = require("express-rate-limit");
|
||
const { getDummyHashForCost, BCRYPT_COST_PARITY_FLOOR } = require(path.join(ROOT, "utils", "bcrypt-rounds.js"));
|
||
const { createLoginSessionBinder } = require(path.join(ROOT, "utils", "login-session-bind.js"));
|
||
const { credentialGenerationMismatch } = require(path.join(ROOT, "utils", "session-account-binding.js"));
|
||
|
||
function indexOfOrThrow(needle, from = 0) {
|
||
const idx = indexSource.indexOf(needle, from);
|
||
assert.ok(idx >= 0, `expected source pin not found: ${needle}`);
|
||
return idx;
|
||
}
|
||
|
||
function countOccurrences(needle, haystack = indexSource) {
|
||
let count = 0;
|
||
let pos = 0;
|
||
for (;;) {
|
||
const idx = haystack.indexOf(needle, pos);
|
||
if (idx < 0) return count;
|
||
count += 1;
|
||
pos = idx + needle.length;
|
||
}
|
||
}
|
||
|
||
// Balanced `{ ... }`-terminated block starting at a marker, brace-counting
|
||
// outside strings and comments (same approach as the sibling vm-extraction
|
||
// tests).
|
||
function extractBalancedBlock(source, startMarker) {
|
||
const start = source.indexOf(startMarker);
|
||
assert.ok(start >= 0, `marker not found: ${startMarker}`);
|
||
let i = start + startMarker.length;
|
||
let depth;
|
||
if (startMarker.endsWith("{")) {
|
||
depth = 1;
|
||
} else {
|
||
while (i < source.length && /\s/.test(source[i])) i += 1;
|
||
assert.ok(i < source.length && source[i] === "{", `no opening brace after: ${startMarker}`);
|
||
depth = 1;
|
||
}
|
||
let inString = null;
|
||
while (i < source.length && depth > 0) {
|
||
i += 1;
|
||
const ch = source[i];
|
||
if (inString) {
|
||
if (ch === "\\") { i += 1; continue; }
|
||
if (ch === inString) inString = null;
|
||
continue;
|
||
}
|
||
if (ch === "/" && source[i + 1] === "/") {
|
||
while (i < source.length && source[i] !== "\n") i += 1;
|
||
continue;
|
||
}
|
||
if (ch === "/" && source[i + 1] === "*") {
|
||
i += 2;
|
||
while (i < source.length && !(source[i] === "*" && source[i + 1] === "/")) i += 1;
|
||
i += 1;
|
||
continue;
|
||
}
|
||
if (ch === '"' || ch === "'" || ch === "`") inString = ch;
|
||
else if (ch === "{") depth += 1;
|
||
else if (ch === "}") depth -= 1;
|
||
}
|
||
assert.ok(depth === 0, `unbalanced braces after: ${startMarker}`);
|
||
return source.slice(start, i + 1);
|
||
}
|
||
|
||
const WITH_TIMEOUT_SOURCE = extractBalancedBlock(indexSource, "function withTimeout(promise, ms, label = \"timeout\") {");
|
||
const SAFE_COMPARE_SOURCE = extractBalancedBlock(indexSource, "function safeCompare(a, b) {");
|
||
const HAS_TWO_FACTOR_SOURCE = extractBalancedBlock(indexSource, "function hasTwoFactorEnabled(user) {");
|
||
const RESTORE_SOURCE = extractBalancedBlock(indexSource, "async function restoreRememberedLogin(req, res) {");
|
||
|
||
// The REAL helpers, instantiated in a minimal realm (crypto/Buffer are the
|
||
// only things safeCompare + getRememberLoginFingerprint need).
|
||
const SAFE_COMPARE = vm.runInContext(`(${SAFE_COMPARE_SOURCE})`, vm.createContext({ Buffer, crypto }));
|
||
const { getRememberLoginFingerprint: GET_FP } = require("../utils/remember-login-fingerprint");
|
||
const HAS_TWO_FACTOR = vm.runInContext(`(${HAS_TWO_FACTOR_SOURCE})`, vm.createContext({}));
|
||
const REAL_WITH_TIMEOUT = vm.runInContext(`(${WITH_TIMEOUT_SOURCE})`, vm.createContext({ setTimeout, clearTimeout, Promise }));
|
||
|
||
function loginHandlerBody() {
|
||
const start = indexOfOrThrow('app.post("/login", async (req, res) => {');
|
||
const end = indexSource.indexOf('app.post("/logout"', start);
|
||
assert.ok(end > start, 'app.post("/logout" must follow app.post("/login"');
|
||
return indexSource.slice(start, end);
|
||
}
|
||
|
||
// The handler's failure-helper block (failCredentials → the admission
|
||
// helper), verbatim — defined before the lookup, exactly as in the handler.
|
||
function loginHelpersBlock() {
|
||
const body = loginHandlerBody();
|
||
const start = body.indexOf("const failCredentials = async (debugLabel, resolvedUser) => {");
|
||
const end = body.indexOf("const user = await findUserByEmail(emailStr);");
|
||
assert.ok(start >= 0 && end > start, "the failure-helper block must be extractable");
|
||
return body.slice(start, end);
|
||
}
|
||
|
||
// The handler's post-compare region: from the latestUser re-read through
|
||
// `return sendOk();` — the suspension re-check, the staleness re-proof, the
|
||
// bind and the success tail, verbatim.
|
||
function loginTailRegion() {
|
||
const body = loginHandlerBody();
|
||
const start = body.indexOf("const latestUser = await findUserByEmail(user.email);");
|
||
const sendOkAnchor = "return sendOk();";
|
||
const end = body.indexOf(sendOkAnchor, start);
|
||
assert.ok(start >= 0 && end > start, "the post-compare region must be extractable");
|
||
return body.slice(start, end + sendOkAnchor.length);
|
||
}
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// Real credentials (bcryptjs, cost 4 — millisecond compares, real verdicts)
|
||
// ---------------------------------------------------------------------------
|
||
|
||
const PASSWORD = "correct horse battery staple";
|
||
const NEW_PASSWORD = "rotated-away password";
|
||
const OLD_HASH = bcryptjs.hashSync(PASSWORD, 4);
|
||
const CHANGED_HASH = bcryptjs.hashSync(NEW_PASSWORD, 4);
|
||
const REHASH_HASH = bcryptjs.hashSync(PASSWORD, 4); // same password, DIFFERENT salt
|
||
|
||
assert.notStrictEqual(OLD_HASH, REHASH_HASH, "two hashes of the same password must be unequal strings (the benign-rehash premise)");
|
||
assert.ok(bcryptjs.compareSync(PASSWORD, OLD_HASH) && bcryptjs.compareSync(PASSWORD, REHASH_HASH), "precondition: both same-password hashes verify");
|
||
assert.ok(!bcryptjs.compareSync(PASSWORD, CHANGED_HASH), "precondition: the changed hash refuses the old password");
|
||
|
||
const CANONICAL = "victim@example.test";
|
||
const USER_ID = 4242;
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// Source pins
|
||
// ---------------------------------------------------------------------------
|
||
|
||
test("login source pins: the staleness re-proof sits rehash-CAS → re-read → suspension → staleness → bind, with the shared admission + window + uniform failure", () => {
|
||
const body = loginHandlerBody();
|
||
const casIdx = body.indexOf("if (rehashCasLost) {");
|
||
const reReadIdx = body.indexOf("const latestUser = await findUserByEmail(user.email);");
|
||
const suspensionIdx = body.indexOf("if (latestUser?.suspended)");
|
||
const stalenessIdx = body.indexOf("if (latestUser.password !== user.password) {");
|
||
// Conscious pin update (adpanel:login-proof-generation): the bind call grew
|
||
// a beforeSave hook, so the single-line call form became a multi-line one;
|
||
// the pin's subject (the bind sits last, after the gates) is unchanged.
|
||
const bindIdx = body.indexOf("await loginSessionBinder.bindLoginSession(req, res, {");
|
||
assert.ok(casIdx >= 0 && casIdx < reReadIdx, "the rehash-CAS re-proof must precede the re-read — user.password is the PROVEN hash only after it adopts the live/verified credential");
|
||
assert.ok(reReadIdx >= 0 && reReadIdx < suspensionIdx && suspensionIdx < stalenessIdx && stalenessIdx < bindIdx,
|
||
"ordering is load-bearing: re-read → suspension → staleness re-proof → bind (the bind must be unreachable on an unproven current credential)");
|
||
assert.strictEqual(countOccurrences("if (latestUser.password !== user.password) {", body), 1, "exactly one staleness gate — no parallel copy");
|
||
|
||
const stalenessBlock = extractBalancedBlock(body, "if (latestUser.password !== user.password) {");
|
||
// The re-proof runs INSIDE the same admission discipline and the same 8 s
|
||
// window as the compares it re-checks (the sibling CAS re-proof's posture,
|
||
// pinned verbatim by tests/bcrypt-cost-parity.test.js).
|
||
assert.ok(
|
||
stalenessBlock.includes('withTimeout(loginBcryptAdmission.run(() => bcrypt.compare(passStr, latestUser.password)), 8000, "bcrypt-timeout")'),
|
||
"the re-proof compare runs under the login admission semaphore inside the 8 s window"
|
||
);
|
||
// Both failure arms settle through the ONE uniform path — no second
|
||
// failure shape.
|
||
assert.ok(stalenessBlock.includes('failCredentials("arm:staleness-reproof", user)'), "the mismatch arm is the uniform credential failure");
|
||
assert.ok(stalenessBlock.includes('failCredentials("arm:staleness-reproof-window-breached", user)'), "the window-breach arm is the uniform credential failure (same settle as the sibling compare windows)");
|
||
assert.ok(loginTailRegion().includes("// adpanel:login-staleness-reproof"), "the region carries its adpanel tag (the comment precedes the gate the block extractor starts at)");
|
||
assert.ok(!stalenessBlock.includes("sendError("), "no bespoke response shape inside the block — every failure routes through failCredentials");
|
||
assert.ok(!stalenessBlock.includes("res.setHeader(") && !stalenessBlock.includes("loginDelay()"), "no inline Retry-After / delay — the uniform shape is owned by the shared helpers");
|
||
});
|
||
|
||
test("login source pin: the staleness block's only passStr use is the bcrypt.compare argument — the hash inequality never decides the verdict", () => {
|
||
const body = loginHandlerBody();
|
||
const stalenessBlock = extractBalancedBlock(body, "if (latestUser.password !== user.password) {");
|
||
assert.strictEqual(
|
||
countOccurrences("passStr", stalenessBlock), 1,
|
||
"passStr appears exactly once — inside bcrypt.compare. A raw string comparison (passStr === ... / includes / indexOf) would refuse different-salt hashes of the SAME password and break legitimate concurrent logins; only bcrypt decides."
|
||
);
|
||
assert.ok(stalenessBlock.includes("bcrypt.compare(passStr, latestUser.password)"), "the verdict is a real compare against the re-read row's hash");
|
||
});
|
||
|
||
// adpanel:login-proof-generation — the MFA state the TOTP proof ran against
|
||
// is the SNAPSHOT row's; a 2FA enable / seed rotation / seal break committing
|
||
// before the bind must deny the login (a proof verified before a credential
|
||
// change is never promoted onto the new generation), through the ONE uniform
|
||
// credential-failure path.
|
||
test("login source pins: the MFA-staleness gate sits staleness-re-proof → MFA gate → bind, uniform failure, no disclosure", () => {
|
||
const body = loginHandlerBody();
|
||
const stalenessIdx = body.indexOf("if (latestUser.password !== user.password) {");
|
||
const mfaIdx = body.indexOf("if (hasTwoFactorEnabled(user) !== hasTwoFactorEnabled(latestUser)");
|
||
const provedIdx = body.indexOf("const provedEpoch = latestUser.session_epoch;");
|
||
const bindIdx = body.indexOf("await loginSessionBinder.bindLoginSession(req, res, {");
|
||
assert.ok(stalenessIdx >= 0 && stalenessIdx < mfaIdx && mfaIdx < provedIdx && provedIdx < bindIdx,
|
||
"ordering is load-bearing: staleness re-proof → MFA gate → provedEpoch capture → bind");
|
||
// The gate is a multi-line condition; slice it from its opening to the end
|
||
// of its uniform-failure return.
|
||
const mfaFailIdx = body.indexOf('return failCredentials("arm:stale-mfa", user)', mfaIdx);
|
||
assert.ok(mfaFailIdx > mfaIdx && mfaFailIdx < provedIdx, "the MFA-staleness denial precedes the provedEpoch capture");
|
||
const mfaBlock = body.slice(mfaIdx, mfaFailIdx + 'return failCredentials("arm:stale-mfa", user)'.length);
|
||
assert.ok(mfaBlock.includes("String(latestUser.secret || \"\") !== String(user.secret || \"\")"), "the seed bytes are compared between the snapshot and the re-read row");
|
||
assert.ok(mfaBlock.includes("Boolean(latestUser.totpSealedError) !== Boolean(user.totpSealedError)"), "the seal-break flag transition is compared between the snapshot and the re-read row");
|
||
assert.ok(!mfaBlock.includes("sendError("), "no bespoke response shape inside the gate — every failure routes through failCredentials");
|
||
assert.ok(body.includes("// adpanel:login-proof-generation"), "the region carries its adpanel tag");
|
||
});
|
||
|
||
test("login source pins: the bind call re-proofs on a fresh read inside the binder (beforeSave), and only the labeled staleness error settles as the uniform failure", () => {
|
||
const body = loginHandlerBody();
|
||
const bindIdx = body.indexOf("await loginSessionBinder.bindLoginSession(req, res, {");
|
||
assert.ok(bindIdx >= 0, "the bind call exists");
|
||
const bindCall = extractBalancedBlock(body, "await loginSessionBinder.bindLoginSession(req, res, {");
|
||
assert.ok(/user: latestUser,/.test(bindCall), "the bind binds the re-read row");
|
||
assert.ok(bindCall.includes("beforeSave: async () => {"), "the bind carries the beforeSave revalidation hook");
|
||
assert.ok(bindCall.includes("const revalidated = await findUserByEmail(latestUser.email);"), "the hook re-reads the row fresh (never cached req.currentUser state)");
|
||
assert.ok(bindCall.includes("credentialGenerationMismatch(provedEpoch, revalidated.session_epoch)"), "the proved generation is re-checked against the live row via the ONE shared strict comparison");
|
||
assert.ok(bindCall.includes("bcrypt.compare(passStr, revalidated.password)"), "a moved hash triggers the bounded re-proof of the submitted password against the fresh hash");
|
||
assert.ok(
|
||
bindCall.includes('withTimeout(loginBcryptAdmission.run(() => bcrypt.compare(passStr, revalidated.password)), 8000, "bcrypt-timeout")'),
|
||
"the hook's re-proof runs under the login admission semaphore inside the 8 s window (same discipline as the staleness re-proof)"
|
||
);
|
||
// The labeled-error helper + the converting catch sit around the bind call
|
||
// (helper before, catch after) — pin them on the enclosing statement
|
||
// region, from the labeled helper's definition through the success return.
|
||
const rejectIdx = body.indexOf('const rejectStaleCompletion = () => Object.assign(new Error("login completion rejected a stale credential state"), { code: "arm:stale-completion" });');
|
||
assert.ok(rejectIdx >= 0 && rejectIdx < bindIdx, "the labeled helper is defined before the bind call");
|
||
const bindRegion = body.slice(rejectIdx, body.indexOf("return sendOk();", rejectIdx));
|
||
assert.ok(bindRegion.includes('err?.code === "arm:stale-completion"'), "the catch converts ONLY the labeled staleness error");
|
||
assert.ok(bindRegion.includes('failCredentials("arm:stale-completion", user)'), "the labeled settle is the ONE uniform credential failure");
|
||
assert.ok(bindRegion.includes("throw err;"), "non-labeled errors rethrow to the handler's outer catch unchanged");
|
||
// The epoch is captured uncoerced from the re-read row.
|
||
assert.ok(body.includes("const provedEpoch = latestUser.session_epoch;"), "the proved generation is the re-read row's epoch, no coercion");
|
||
// The shared comparison is consumed from its one home — no inline copy.
|
||
assert.match(indexSource, /const \{[^{}]*\bcredentialGenerationMismatch\b[^{}]*\} = require\("\.\/utils\/session-account-binding"\);/,
|
||
"credentialGenerationMismatch comes from the shared session-account-binding module");
|
||
});
|
||
|
||
test("restore source pins: the re-verify sits rotate-CAS → re-read → re-verify → bind, with the fail-closed clear shape and the bounded lookup", () => {
|
||
const rotateIdx = RESTORE_SOURCE.indexOf("await rotateRememberLoginCookie(req, res, user, parsed);");
|
||
const refuseIdx = RESTORE_SOURCE.indexOf("if (!expiresAt) {", rotateIdx);
|
||
const reReadIdx = RESTORE_SOURCE.indexOf('const freshRestoreRow = await withTimeout(findUserById(parsed.uid), 8000, "remember-restore-staleness-lookup-timeout");');
|
||
// Conscious pin update (adpanel:credential-generation): the bind now
|
||
// sources the FRESH row (both re-verify legs proved the presented token
|
||
// against THAT object), so the bind marker tracks the fresh-row bind
|
||
// line. Same assertion strength: the bind follows the re-read/re-verify.
|
||
const bindIdx = RESTORE_SOURCE.indexOf("req.session.user = freshRestoreRow.email;");
|
||
assert.ok(rotateIdx >= 0 && refuseIdx > rotateIdx, "the rotation CAS gates the restore");
|
||
assert.ok(reReadIdx > refuseIdx && bindIdx > reReadIdx,
|
||
"ordering is load-bearing: CAS success → staleness re-read/re-verify → bind (a mid-restore change must fail before the session binds)");
|
||
assert.strictEqual(countOccurrences("findUserById(parsed.uid)", RESTORE_SOURCE), 2,
|
||
"exactly two lookups: the restore-start read and the staleness re-read — both 8s-bounded at the call site");
|
||
assert.ok(RESTORE_SOURCE.includes("// adpanel:restore-staleness-reverify"), "the re-verify carries its adpanel tag");
|
||
assert.ok(RESTORE_SOURCE.includes("safeCompare(parsed.fp, getRememberLoginFingerprint(freshRestoreRow))"),
|
||
"the re-verify is the fingerprint check against the re-read row (the fp ties the credential to the password hash)");
|
||
// The failure shape is the house fail-closed clear (the rotation-refusal
|
||
// shape): clear state + clear cookie + silent false, BEFORE the bind.
|
||
const verifyWindow = RESTORE_SOURCE.slice(reReadIdx, bindIdx);
|
||
const stateIdx = verifyWindow.indexOf("clearRememberLoginSessionState(req);");
|
||
const cookieIdx = verifyWindow.indexOf("clearRememberLoginCookie(req, res);");
|
||
const falseIdx = verifyWindow.indexOf("return false;");
|
||
assert.ok(stateIdx >= 0 && cookieIdx > stateIdx && falseIdx > cookieIdx, "mismatch → clear state → clear cookie → return false (no bind, no exception needed)");
|
||
assert.ok(verifyWindow.includes("freshRestoreRow.suspended") && verifyWindow.includes("!freshRestoreRow.password"),
|
||
"a row that vanished, lost its credential, or was suspended mid-restore fails the restore too");
|
||
// adpanel:credential-generation — the epoch leg rides the SAME fail-closed
|
||
// condition: the credential writers bump session_epoch in the same
|
||
// statement as the credential, so a proof minted before a credential
|
||
// change (snapshot epoch ≠ re-read row epoch) is denied the bind exactly
|
||
// like a fingerprint mismatch. Comparable-only — the fingerprint leg above
|
||
// stays authoritative on legacy reads (absent/NULL epoch is uncomparable).
|
||
assert.ok(verifyWindow.includes("credentialGenerationMismatch(user.session_epoch, freshRestoreRow.session_epoch)"),
|
||
"the epoch leg (the ONE shared predicate, snapshot vs re-read row) sits inside the re-verify's fail-closed condition");
|
||
});
|
||
|
||
test("captcha-completion pin: the pattern-source path keeps its own re-resolution + fingerprint re-verification, now with the window-covering re-verify", () => {
|
||
// adpanel:login-staleness-reproof — completePendingCaptchaLogin re-resolves
|
||
// the row and re-verifies getRememberLoginFingerprint against the
|
||
// challenge-time snapshot before binding (the pattern the POST /login
|
||
// re-proof mirrors). Conscious pin update (adpanel:login-proof-generation):
|
||
// the completion GAINED a second fingerprint verification — the beforeSave
|
||
// hook's re-verify against a FRESH row, covering the binder's
|
||
// regenerate→save window the pre-bind read cannot see (a change-time sweep
|
||
// misses the unbound regenerated sid and the unminted remember id). The
|
||
// two verifications have distinct roles: pre-bind (challenge-time proof
|
||
// vs the live row) and in-window (after regeneration, before persistence);
|
||
// the anti-fork intent is preserved — no THIRD copy, and the hook is the
|
||
// shared-window guard, not a parallel of the pre-bind check.
|
||
const completionStart = indexOfOrThrow("async function completePendingCaptchaLogin(req, res) {");
|
||
const completionEnd = indexSource.indexOf('app.post("/api/captcha/verify"', completionStart);
|
||
const completionBody = indexSource.slice(completionStart, completionEnd);
|
||
assert.ok(completionBody.includes("const user = await findUserByEmail(pending.email);"), "the completion re-resolves the row at finalize time");
|
||
assert.ok(
|
||
completionBody.includes('safeCompare(String(pending.userFingerprint || ""), expectedUserFingerprint)') &&
|
||
completionBody.includes("const expectedUserFingerprint = getRememberLoginFingerprint(user);"),
|
||
"the completion re-verifies the challenge-time fingerprint against the fresh row — the pattern both fixes mirror"
|
||
);
|
||
assert.ok(
|
||
completionBody.includes('safeCompare(String(pending.userFingerprint || ""), getRememberLoginFingerprint(revalidated))'),
|
||
"the beforeSave hook re-verifies the challenge-time fingerprint against the FRESH row inside the bind window"
|
||
);
|
||
assert.strictEqual(countOccurrences("getRememberLoginFingerprint(", completionBody), 2,
|
||
"exactly TWO fingerprint verifications in the completion path — the pre-bind re-verify and the beforeSave window re-verify, each with a distinct role (no third copy forked in)");
|
||
assert.ok(!completionBody.includes("latestUser.password") && !completionBody.includes("freshRestoreRow"),
|
||
"the completion path carries none of the other paths' staleness machinery (no cross-path copy)");
|
||
});
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// Behavioral harness — POST /login post-compare region
|
||
// ---------------------------------------------------------------------------
|
||
|
||
function makeLoginSandbox({ user, latestUser, srcKey = "staleness-src" }) {
|
||
const captures = [];
|
||
const headers = {};
|
||
const warns = [];
|
||
const securityLogs = [];
|
||
const captchaArms = [];
|
||
const compares = [];
|
||
const refunds = [];
|
||
const binds = [];
|
||
const audits = [];
|
||
const failureAudits = [];
|
||
const sendOks = [];
|
||
const gateClears = [];
|
||
const totpResets = [];
|
||
const clearedCookies = [];
|
||
const tombstones = [];
|
||
const rememberMints = [];
|
||
const rememberRevokes = [];
|
||
const cacheUpserts = [];
|
||
const binderEvents = [];
|
||
|
||
const throttle = createLoginThrottle({ MemoryStore, ipKeyGenerator, env: {}, logger: { warn: () => {} } });
|
||
const realRefund = throttle.refundCredentialAttempt.bind(throttle);
|
||
throttle.refundCredentialAttempt = async (...a) => { refunds.push(a[0]); return realRefund(...a); };
|
||
const realReset = throttle.resetTotpSource.bind(throttle);
|
||
throttle.resetTotpSource = async (...a) => { totpResets.push(a[2]); return realReset(...a); };
|
||
|
||
// The first lookup (the post-compare re-read) returns latestUser; a scenario
|
||
// that commits a mid-window change sets __overrideLookups (inside the
|
||
// barrier) so the LATER lookup — the beforeSave hook's fresh read —
|
||
// consumes those rows instead.
|
||
const overrideLookups = [];
|
||
|
||
// express-session-shaped session record: regenerate replaces the record and
|
||
// repoints the sid; both operations report through the err callback once.
|
||
// The __insideRegenerate / __insideSave slots are the controlled barriers:
|
||
// a scenario installs an async step that runs INSIDE the shared binder's
|
||
// window, before the operation completes — the interleave point the
|
||
// change-time sweeps cannot cover (the sid is unbound, the remember id
|
||
// unminted).
|
||
const req = {
|
||
sessionID: "login-sid-1",
|
||
session: {
|
||
regenerate: (cb) => {
|
||
binderEvents.push("regenerate");
|
||
for (const key of Object.keys(req.session)) {
|
||
if (key !== "regenerate" && key !== "save") delete req.session[key];
|
||
}
|
||
req.sessionID = "login-sid-2";
|
||
Promise.resolve()
|
||
.then(() => (typeof sandbox.__insideRegenerate === "function" ? sandbox.__insideRegenerate() : undefined))
|
||
.then(() => cb(null), (err) => cb(err));
|
||
},
|
||
save: (cb) => {
|
||
binderEvents.push("save");
|
||
Promise.resolve()
|
||
.then(() => (typeof sandbox.__insideSave === "function" ? sandbox.__insideSave() : undefined))
|
||
.then(() => cb(null), (err) => cb(err));
|
||
},
|
||
},
|
||
};
|
||
|
||
// The REAL shared binder over recording deps — the extracted tail region's
|
||
// bind call runs the tombstone→regenerate→bind→serve→save core verbatim,
|
||
// with the mint/hygiene machinery observable through the dep recordings.
|
||
const realBinder = createLoginSessionBinder({
|
||
withTimeout: REAL_WITH_TIMEOUT,
|
||
writeRevokedSidTombstone: async (sid) => { tombstones.push(String(sid)); return true; },
|
||
sessionCarriesProtectedPendingAuthState: (sess) =>
|
||
!!sess && (sess.captchaSolved === true || !!(sess.pendingCaptchaLogin && typeof sess.pendingCaptchaLogin === "object")),
|
||
getSessionDisplayId: (sid) => `sid:${sid}`,
|
||
ensureRememberLoginSessionId: (r) => {
|
||
if (!r.session.rememberLoginId) r.session.rememberLoginId = "rid-login";
|
||
return r.session.rememberLoginId;
|
||
},
|
||
buildBrowserSessionAuditFromRequest: (r, email, rememberLoginId) => ({ email, rememberLoginId }),
|
||
setRememberLoginCookie: () => { rememberMints.push(1); return 7776000000; },
|
||
markRememberLoginSessionFresh: (r, expiresAt) => { r.session.rememberLoginExpiresAt = expiresAt; },
|
||
upsertActiveBrowserSessionCacheEntry: (sessionId) => { cacheUpserts.push(sessionId); },
|
||
clearRememberLoginCookie: () => { clearedCookies.push(1); },
|
||
revokeRememberLoginRegistryEntry: async (rememberLoginId) => { rememberRevokes.push(rememberLoginId); return true; },
|
||
logger: { warn: (...p) => warns.push(p.map(String).join(" ")) },
|
||
});
|
||
|
||
const sandbox = {
|
||
loginCredentialReservation: null,
|
||
emailStr: CANONICAL,
|
||
passStr: PASSWORD,
|
||
throttleIpKey: srcKey,
|
||
req,
|
||
res: { setHeader: (k, v) => { headers[k] = String(v); } },
|
||
user,
|
||
loginThrottle: throttle,
|
||
loginRetryAfterSeconds: (cfg, reason) => 30,
|
||
findUserByEmail: async () => (overrideLookups.length ? overrideLookups.shift() : latestUser),
|
||
loginBcryptAdmission: { run: (fn) => fn() },
|
||
bcrypt: {
|
||
compare: async (pwd, hash) => { compares.push(hash); return bcryptjs.compare(pwd, hash); },
|
||
},
|
||
getDummyHashForCost,
|
||
BCRYPT_COST_PARITY_FLOOR,
|
||
DUMMY_BCRYPT_HASH: "$2a$12$" + "a".repeat(53),
|
||
sendError: (status, message, options = {}) => {
|
||
captures.push({ status, message, options: JSON.parse(JSON.stringify(options)), headers: Object.assign({}, headers) });
|
||
return { status, message };
|
||
},
|
||
sendOk: () => { sendOks.push(1); return { ok: true }; },
|
||
flagLoginCaptchaRequired: () => { captchaArms.push(1); },
|
||
capdbg: () => {},
|
||
securityLog: (msg) => { securityLogs.push(String(msg)); },
|
||
loginDelay: async () => {},
|
||
clearRememberLoginCookie: () => { clearedCookies.push(1); },
|
||
revokeRememberLoginsForUser: async () => {},
|
||
// The REAL factory instance behind a recording wrapper
|
||
// (adpanel:binder-call-contract — the call sites invoke the named method).
|
||
loginSessionBinder: {
|
||
bindLoginSession: async (reqArg, resArg, opts) => {
|
||
binds.push({ user: opts.user, beforeSave: typeof opts?.beforeSave === "function" });
|
||
return realBinder.bindLoginSession(reqArg, resArg, opts);
|
||
},
|
||
},
|
||
clearLoginCaptchaGateForIp: (key) => { gateClears.push(String(key)); },
|
||
// adpanel:failed-login-audit — the failure recorder's call sits inside
|
||
// failCredentials, so a failure scenario now fires it; the failure rows
|
||
// get their OWN sink (the success-row assertions below count __audits,
|
||
// which must stay success-only), mirroring the real recorder's split.
|
||
loginAuditRecorder: {
|
||
recordSuccessfulLoginAudit: (rec) => { audits.push(rec); },
|
||
recordFailedLoginAudit: (rec) => { failureAudits.push(rec); },
|
||
},
|
||
hasTwoFactorEnabled: HAS_TWO_FACTOR,
|
||
credentialGenerationMismatch,
|
||
setTimeout,
|
||
clearTimeout,
|
||
console: { warn: (...p) => warns.push(p.map(String).join(" ")), error: () => {}, log: () => {} },
|
||
__captures: captures,
|
||
__compares: compares,
|
||
__refunds: refunds,
|
||
__binds: binds,
|
||
__audits: audits,
|
||
__failureAudits: failureAudits,
|
||
__sendOks: sendOks,
|
||
__captchaArms: captchaArms,
|
||
__warns: warns,
|
||
__securityLogs: securityLogs,
|
||
__gateClears: gateClears,
|
||
__totpResets: totpResets,
|
||
__clearedCookies: clearedCookies,
|
||
__tombstones: tombstones,
|
||
__rememberMints: rememberMints,
|
||
__rememberRevokes: rememberRevokes,
|
||
__cacheUpserts: cacheUpserts,
|
||
__binderEvents: binderEvents,
|
||
__overrideLookups: overrideLookups,
|
||
};
|
||
return sandbox;
|
||
}
|
||
|
||
// T0 preamble, run before the extracted region: the dual-key reservation is
|
||
// admitted and the T0 compare PROVED passStr against the snapshot hash —
|
||
// the exact handler state at the re-read (the reservation stands, match =
|
||
// true). The extracted region then runs verbatim.
|
||
const LOGIN_PREAMBLE = `
|
||
const __reservation = await loginThrottle.reserveCredentialAttempt(throttleIpKey, emailStr, user);
|
||
if (!__reservation.admitted) throw new Error("scenario precondition: the reservation must admit");
|
||
admitReservation(__reservation, user);
|
||
`;
|
||
|
||
function runLoginHarness(sandbox) {
|
||
const context = vm.createContext(sandbox);
|
||
vm.runInContext(WITH_TIMEOUT_SOURCE, context, { filename: "withTimeout.js" });
|
||
vm.runInContext(loginHelpersBlock(), context, { filename: "login-failure-helpers.js" });
|
||
const scenario = `${LOGIN_PREAMBLE}\n${loginTailRegion()}`;
|
||
return vm.runInContext(`(async () => {\n${scenario}\n})()`, context, { filename: "staleness-scenario.js" });
|
||
}
|
||
|
||
test("interleave: compare proved the OLD hash, the password changed, the bind-time re-proof compares the NEW hash and refuses — uniform 400, failure recorded, no bind, no remember credential", async () => {
|
||
// T0: reservation admitted on the snapshot row; the T0 compare PROVED
|
||
// PASSWORD against OLD_HASH (the snapshot's user.password is exactly the
|
||
// proven hash — the rehash-CAS block above left it unchanged: the row was
|
||
// at parity, no heal ran).
|
||
// T1: the victim's password change commits (CHANGED_HASH is the live row).
|
||
// T2: the handler's post-compare region runs verbatim.
|
||
const user = { id: USER_ID, email: CANONICAL, password: OLD_HASH, suspended: false, session_epoch: 1 };
|
||
const latestUser = { id: USER_ID, email: CANONICAL, password: CHANGED_HASH, suspended: false, session_epoch: 1 };
|
||
const sandbox = makeLoginSandbox({ user, latestUser });
|
||
await runLoginHarness(sandbox);
|
||
|
||
assert.strictEqual(sandbox.__compares.length, 1, "exactly one compare ran in the region — the re-proof");
|
||
assert.strictEqual(sandbox.__compares[0], CHANGED_HASH, "the re-proof compared the submitted password against the LIVE (changed) hash, never the stale snapshot");
|
||
|
||
assert.strictEqual(sandbox.__captures.length, 1, "exactly one response");
|
||
const capture = sandbox.__captures[0];
|
||
assert.strictEqual(capture.status, 400, "the mismatch answers the uniform failure status");
|
||
assert.strictEqual(capture.message, "Invalid credentials", "byte-identical unknown-email body string");
|
||
assert.deepStrictEqual(capture.headers, {}, "no Retry-After on the uniform failure");
|
||
assert.strictEqual(sandbox.__captchaArms.length, 1, "the uniform failure arms the captcha exactly like every other credential failure");
|
||
assert.strictEqual(sandbox.__warns.length, 0, "no ordering-bug diagnostic — the arrival carried its admitted reservation");
|
||
|
||
assert.strictEqual(sandbox.__binds.length, 0, "NO session bind — the revocation bypass is closed");
|
||
assert.strictEqual(sandbox.__sendOks.length, 0, "no success response");
|
||
assert.strictEqual(sandbox.__audits.length, 0, "no durable success row");
|
||
assert.strictEqual(sandbox.__clearedCookies.length, 0, "the uniform failure does not touch cookies (byte-parity with the other credential failures)");
|
||
|
||
assert.strictEqual(sandbox.loginCredentialReservation, null, "the outstanding reservation was finalized");
|
||
assert.strictEqual(sandbox.__refunds.length, 0, "FINALIZED, not refunded — the failure record stands (the fail-closed settle)");
|
||
|
||
// The failure is RECORDED on the attacker's own budgets — bounded like
|
||
// every credential failure. The dual-key reservation bumped source +
|
||
// fold + id; finalize kept them. Fill the source budget from 1: exactly 9
|
||
// more admissions, then the honest source refusal.
|
||
const throttle = sandbox.loginThrottle;
|
||
let admitted = 0;
|
||
let refusal = null;
|
||
for (let i = 0; i < 30; i += 1) {
|
||
const r = await throttle.reserveCredentialAttempt("staleness-src", CANONICAL, user);
|
||
if (!r.admitted) { refusal = r; break; }
|
||
admitted += 1;
|
||
}
|
||
assert.strictEqual(admitted, 9, "source budget: 1 (the staleness failure) + 9 = the 10-per-source max — the failure consumed budget exactly like every failure");
|
||
assert.ok(refusal && refusal.reason === "source", "the next reservation is refused at the source budget");
|
||
assert.strictEqual(await throttle.isIpBlocked("staleness-src"), true, "the source budget is full");
|
||
|
||
// The fold + id budgets carry the same failure: from 10, a fresh source
|
||
// key admits 10 more (to the 20-per-account max), then refuses on the
|
||
// account leg.
|
||
let admittedAccount = 0;
|
||
let accountRefusal = null;
|
||
for (let i = 0; i < 30; i += 1) {
|
||
const r = await throttle.reserveCredentialAttempt(`fill-src-${i}`, CANONICAL, user);
|
||
if (!r.admitted) { accountRefusal = r; break; }
|
||
admittedAccount += 1;
|
||
}
|
||
assert.strictEqual(admittedAccount, 10, "account budget: 1 (the staleness failure) + 9 (source-limited fill) + 10 = the 20-per-account max");
|
||
assert.ok(accountRefusal && accountRefusal.reason === "account", "the next reservation is refused at the account budget");
|
||
assert.strictEqual(await throttle.isAccountBlocked(CANONICAL), true, "the fold budget is full");
|
||
assert.strictEqual(await throttle.isAccountBlockedById(USER_ID), true, "the id budget is full");
|
||
});
|
||
|
||
test("benign parallel rehash: the row was rehashed to a different-salt hash of the SAME password — the re-proof verifies and the bind proceeds with the re-read row", async () => {
|
||
// The constraint the string check must not violate: another login's cost
|
||
// heal (or a change reverted to the same password) leaves a hash that is
|
||
// an UNEQUAL STRING but the SAME credential. The inequality must trigger
|
||
// only a re-proof; bcrypt's verdict admits the login.
|
||
const user = { id: USER_ID, email: CANONICAL, password: OLD_HASH, suspended: false, session_epoch: 1 };
|
||
const latestUser = { id: USER_ID, email: CANONICAL, password: REHASH_HASH, suspended: false, session_epoch: 1 };
|
||
const sandbox = makeLoginSandbox({ user, latestUser });
|
||
await runLoginHarness(sandbox);
|
||
|
||
assert.strictEqual(sandbox.__compares.length, 1, "exactly one re-proof compare ran (the inequality triggered it)");
|
||
assert.strictEqual(sandbox.__compares[0], REHASH_HASH, "the re-proof ran against the re-read row's hash");
|
||
assert.strictEqual(sandbox.__captures.length, 0, "no failure response — the same password verifies against its new hash");
|
||
assert.strictEqual(sandbox.__binds.length, 1, "the bind proceeded");
|
||
assert.strictEqual(sandbox.__binds[0].user, latestUser, "the bind binds the RE-READ row (the current credential), not the stale snapshot");
|
||
assert.strictEqual(sandbox.__sendOks.length, 1, "the success response answers");
|
||
assert.strictEqual(sandbox.__audits.length, 1, "one durable success row");
|
||
assert.strictEqual(sandbox.__audits[0].method, "password", "the password method is recorded");
|
||
assert.strictEqual(sandbox.__audits[0].user, latestUser, "the audit row's subject is the re-read row");
|
||
assert.strictEqual(sandbox.__refunds.length, 1, "the success refunds the outstanding reservation (net zero recorded)");
|
||
assert.deepStrictEqual(sandbox.__totpResets, [latestUser], "the TOTP reset threads the re-read row (the id key clears with the email key)");
|
||
assert.strictEqual(sandbox.__gateClears.length, 1, "the bucketed-IP gate clear stays on the success path");
|
||
});
|
||
|
||
test("no-change path: an unchanged hash runs NO re-proof compare and the success tail is byte-identical to the pre-fix shape", async () => {
|
||
const row = { id: USER_ID, email: CANONICAL, password: OLD_HASH, suspended: false, session_epoch: 1 };
|
||
const sandbox = makeLoginSandbox({ user: row, latestUser: row });
|
||
await runLoginHarness(sandbox);
|
||
|
||
assert.strictEqual(sandbox.__compares.length, 0, "the staleness gate must not spend a compare when the hash is unchanged — the happy path is untouched");
|
||
assert.strictEqual(sandbox.__captures.length, 0, "no failure response");
|
||
assert.strictEqual(sandbox.__binds.length, 1, "the bind proceeded");
|
||
assert.strictEqual(sandbox.__binds[0].user, row, "the bind binds the re-read row");
|
||
assert.strictEqual(sandbox.__sendOks.length, 1, "the success response answers");
|
||
assert.strictEqual(sandbox.__refunds.length, 1, "the reservation refunds on success");
|
||
assert.strictEqual(sandbox.__audits.length, 1, "the audit row matches the pre-fix shape");
|
||
assert.strictEqual(sandbox.__audits[0].method, "password", "the password method is recorded");
|
||
// The success choreography order is unchanged: bind → gate clear → TOTP
|
||
// reset → refund → audit → sendOk (the gate clear precedes the reset; both
|
||
// precede the refund and the audit).
|
||
assert.deepStrictEqual(
|
||
[sandbox.__gateClears.length, sandbox.__totpResets.length, sandbox.__refunds.length, sandbox.__audits.length, sandbox.__sendOks.length],
|
||
[1, 1, 1, 1, 1],
|
||
"every success-tail step fired exactly once"
|
||
);
|
||
});
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// Behavioral harness — remember-restore body
|
||
// ---------------------------------------------------------------------------
|
||
|
||
function buildRestoreHarness({ lookupQueue }) {
|
||
const events = [];
|
||
const calls = { lookups: 0, clearState: 0, clearCookie: 0, markFresh: 0, saves: 0, rotates: 0, regens: 0, tombstones: 0 };
|
||
const session = {
|
||
regenerate: (cb) => { calls.regens += 1; events.push("regenerate"); req.sessionID = "regenerated-sid-2"; cb(null); },
|
||
save: (cb) => { calls.saves += 1; events.push("save"); cb(null); },
|
||
};
|
||
const req = { cookies: { "adpanel.remember": "tok" }, session, sessionID: "restore-sid-1" };
|
||
const queue = lookupQueue.slice();
|
||
const sandbox = {
|
||
console: { log: () => {}, warn: () => {} },
|
||
REMEMBER_LOGIN_COOKIE_NAME: "adpanel.remember",
|
||
readRememberLoginToken: () => null, // set below once PARSED exists
|
||
securityLog: (msg) => events.push(`log:${String(msg)}`),
|
||
loginAuditRecorder: { recordSuccessfulLoginAudit: ({ method }) => events.push(`audit:${String(method)}`) },
|
||
remoteProxyTrustBlocksRememberIssuance: () => false,
|
||
findUserById: async () => {
|
||
calls.lookups += 1;
|
||
return queue.length > 1 ? queue.shift() : queue[0];
|
||
},
|
||
safeCompare: SAFE_COMPARE,
|
||
getRememberLoginFingerprint: GET_FP,
|
||
// adpanel:credential-generation — the restore body's epoch leg (sibling
|
||
// fix) consumes the ONE shared strict comparison; these scenarios' rows
|
||
// keep an unchanged generation, so the fingerprint leg stays the denier.
|
||
credentialGenerationMismatch,
|
||
...require("../utils/remember-login-completion"),
|
||
isSessionSidRevoked: async () => false,
|
||
getRememberLoginLegacyCutoff: () => 0,
|
||
isManagedRememberLoginToken: () => true,
|
||
revokeRememberLoginsForUser: async () => { events.push("revokeUser"); },
|
||
sessionCarriesProtectedPendingAuthState: () => false,
|
||
getSessionDisplayId: (id) => `sid:${id}`,
|
||
writeRevokedSidTombstone: async () => { calls.tombstones += 1; events.push("tombstone"); return true; },
|
||
clearRememberLoginSessionState: () => { calls.clearState += 1; events.push("clearState"); },
|
||
clearRememberLoginCookie: () => { calls.clearCookie += 1; events.push("clearCookie"); },
|
||
rotateRememberLoginCookie: async () => { calls.rotates += 1; events.push("rotate"); return 4102444800000; },
|
||
buildBrowserSessionAuditFromRequest: () => ({ rememberLoginId: "remember-id-restore" }),
|
||
markRememberLoginSessionFresh: () => { calls.markFresh += 1; events.push("markFresh"); },
|
||
withTimeout: WITH_TIMEOUT_SOURCE ? vm.runInContext(`(${WITH_TIMEOUT_SOURCE})`, vm.createContext({ setTimeout, clearTimeout, Promise })) : null,
|
||
req,
|
||
};
|
||
// The presented token's fingerprint was minted from the FIRST row in the
|
||
// queue (the restore-start row) — the REAL fingerprint construction.
|
||
const PARSED = {
|
||
v: 2,
|
||
uid: String(lookupQueue[0].id),
|
||
iat: Date.now() - 60000,
|
||
exp: Date.now() + 365 * 24 * 3600 * 1000,
|
||
fp: GET_FP(lookupQueue[0]),
|
||
jti: "remember-id-restore",
|
||
};
|
||
sandbox.readRememberLoginToken = () => PARSED;
|
||
vm.createContext(sandbox);
|
||
const fn = vm.runInContext(`(${RESTORE_SOURCE})`, sandbox, { filename: "restore-sandbox.js" });
|
||
return { fn, calls, events, req, session, PARSED };
|
||
}
|
||
|
||
test("restore interleave: the hash changes after the rotation CAS succeeds — the re-verify fails the restore closed before the bind", async () => {
|
||
// T0: the row is read (OLD_HASH, fp matches the presented token); the
|
||
// rotate CAS succeeds. T1 (inside the read→bind gap): the password change
|
||
// commits. T2: the re-read sees CHANGED_HASH → the fp no longer matches →
|
||
// fail closed. No session bound to the pre-change row.
|
||
const oldRow = { id: USER_ID, email: CANONICAL, password: OLD_HASH, secret: "s3cret", suspended: false, session_epoch: 3 };
|
||
const changedRow = { id: USER_ID, email: CANONICAL, password: CHANGED_HASH, secret: "s3cret", suspended: false, session_epoch: 3 };
|
||
const { fn, calls, events, req, session } = buildRestoreHarness({ lookupQueue: [oldRow, changedRow] });
|
||
|
||
const ok = await fn(req, {});
|
||
assert.strictEqual(ok, false, "the restore fails closed (silent false — the middleware continues unauthenticated)");
|
||
assert.strictEqual(calls.lookups, 2, "exactly two lookups: the restore-start read and the staleness re-read");
|
||
assert.deepStrictEqual(
|
||
events,
|
||
["log:remember-restore attempt", "regenerate", "rotate", "clearState", "clearCookie"],
|
||
"the CAS rotated, then the re-verify failed: clear state → clear cookie — no bind, no freshness mark, no save, no audit"
|
||
);
|
||
assert.strictEqual(session.user, undefined, "NO session bound to the pre-change row");
|
||
assert.strictEqual(calls.markFresh, 0, "no freshness markers — the restore never authenticated");
|
||
assert.strictEqual(calls.saves, 0, "the bounded save never ran");
|
||
assert.strictEqual(calls.tombstones, 0, "no tombstone needed (the regenerated sid never carried state)");
|
||
});
|
||
|
||
test("restore interleave: the row vanishes or is suspended mid-restore — the same fail-closed clear (no bind)", async () => {
|
||
const oldRow = { id: USER_ID, email: CANONICAL, password: OLD_HASH, secret: "s3cret", suspended: false, session_epoch: 3 };
|
||
const suspendedRow = { id: USER_ID, email: CANONICAL, password: OLD_HASH, secret: "s3cret", suspended: true, session_epoch: 3 };
|
||
|
||
for (const [name, second] of [["vanished", null], ["suspended", suspendedRow]]) {
|
||
const { fn, calls, events, req, session } = buildRestoreHarness({ lookupQueue: [oldRow, second] });
|
||
const ok = await fn(req, {});
|
||
assert.strictEqual(ok, false, `${name}: the restore fails closed`);
|
||
assert.deepStrictEqual(
|
||
events,
|
||
["log:remember-restore attempt", "regenerate", "rotate", "clearState", "clearCookie"],
|
||
`${name}: clear state → clear cookie, no bind, no audit`
|
||
);
|
||
assert.strictEqual(session.user, undefined, `${name}: no session bound`);
|
||
assert.strictEqual(calls.lookups, 2, `${name}: the re-read ran`);
|
||
}
|
||
});
|
||
|
||
test("restore no-change path: an unchanged hash completes byte-identically to the pre-fix success choreography", async () => {
|
||
// The re-verify must be invisible on the happy path: the same row comes
|
||
// back, the fp matches, and the success choreography is exactly the
|
||
// pre-fix list (attempt log → regenerate → rotate → hygiene clear →
|
||
// markFresh → save → audit) with NO extra events.
|
||
const row = { id: USER_ID, email: CANONICAL, password: OLD_HASH, secret: "s3cret", suspended: false, session_epoch: 3 };
|
||
const { fn, calls, events, req, session } = buildRestoreHarness({ lookupQueue: [row, row] });
|
||
|
||
const ok = await fn(req, {});
|
||
assert.strictEqual(ok, true, "the restore completes");
|
||
assert.strictEqual(calls.lookups, 3, "both the pre-bind and post-save re-reads ran on the success path");
|
||
assert.deepStrictEqual(
|
||
events,
|
||
["log:remember-restore attempt", "regenerate", "rotate", "clearState", "markFresh", "save", "audit:remember-restore"],
|
||
"byte-identical success choreography — the re-verify adds no observable step"
|
||
);
|
||
assert.strictEqual(session.user, row.email, "the session is bound");
|
||
assert.strictEqual(session.accountId, USER_ID, "the account binding is unchanged");
|
||
assert.strictEqual(session.accountEpoch, 3, "the epoch binding is unchanged");
|
||
assert.strictEqual(calls.clearCookie, 0, "no cookie hygiene on success");
|
||
});
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// adpanel:login-proof-generation — behavioral harness, the completion window
|
||
// ---------------------------------------------------------------------------
|
||
|
||
// The MFA-state staleness and the completion-window denials. Rows carry the
|
||
// mapUserRow shape (secret is the DECRYPTED seed, totpSealedError the seal
|
||
// flag, session_epoch the credential generation). The TOTP proof of the
|
||
// pre-region timeline ran against the SNAPSHOT row — the scenarios commit
|
||
// their credential changes AFTER that proof, exactly the timeline the fix
|
||
// must deny.
|
||
|
||
test("login-proof-generation: MFA enabled between the snapshot and the re-read — the login is denied through the uniform failure, never bound", async () => {
|
||
// T0: no 2FA on the snapshot row (no TOTP proof ran); the compare proved
|
||
// PASSWORD. T1: 2FA enrollment commits. T2: the re-read carries a seed —
|
||
// binding would mint a session the TOTP step never proved.
|
||
const user = { id: USER_ID, email: CANONICAL, password: OLD_HASH, secret: null, totpSealedError: false, suspended: false, session_epoch: 1 };
|
||
const latestUser = { id: USER_ID, email: CANONICAL, password: OLD_HASH, secret: "JBSWY3DPEHPK3PXP", totpSealedError: false, suspended: false, session_epoch: 1 };
|
||
const sandbox = makeLoginSandbox({ user, latestUser });
|
||
await runLoginHarness(sandbox);
|
||
|
||
assert.strictEqual(sandbox.__compares.length, 0, "no re-proof compare — the hash never moved; the MFA gate is the deny");
|
||
assert.strictEqual(sandbox.__captures.length, 1, "exactly one response");
|
||
assert.strictEqual(sandbox.__captures[0].status, 400, "the uniform failure status");
|
||
assert.strictEqual(sandbox.__captures[0].message, "Invalid credentials", "byte-identical uniform body — no disclosure of which check denied");
|
||
assert.deepStrictEqual(sandbox.__captures[0].headers, {}, "no Retry-After on the uniform failure");
|
||
assert.strictEqual(sandbox.__captchaArms.length, 1, "the uniform failure arms the captcha like every other credential failure");
|
||
assert.strictEqual(sandbox.__binds.length, 0, "NO session bind — an MFA state the proof never covered must not authenticate");
|
||
assert.strictEqual(sandbox.req.session.user, undefined, "no identity bound on the session");
|
||
assert.strictEqual(sandbox.__sendOks.length, 0, "no success response");
|
||
assert.strictEqual(sandbox.__audits.length, 0, "no durable success row");
|
||
assert.strictEqual(sandbox.__failureAudits.length, 1, "the failed-login audit fired (the uniform failure path)");
|
||
assert.strictEqual(sandbox.loginCredentialReservation, null, "the reservation was finalized");
|
||
assert.strictEqual(sandbox.__refunds.length, 0, "FINALIZED, not refunded — the failure stands");
|
||
});
|
||
|
||
test("login-proof-generation: the TOTP seed rotated after the proof — denied through the uniform failure", async () => {
|
||
// The TOTP proof consumed a code against the snapshot seed; a rotation
|
||
// committing before the bind must not ride the proof onto the new seed.
|
||
const user = { id: USER_ID, email: CANONICAL, password: OLD_HASH, secret: "SEEDOLDSEEDOLDSEED", totpSealedError: false, suspended: false, session_epoch: 1 };
|
||
const latestUser = { id: USER_ID, email: CANONICAL, password: OLD_HASH, secret: "SEEDNEWSEEDNEWSEED", totpSealedError: false, suspended: false, session_epoch: 1 };
|
||
const sandbox = makeLoginSandbox({ user, latestUser });
|
||
await runLoginHarness(sandbox);
|
||
|
||
assert.strictEqual(sandbox.__captures.length, 1, "exactly one response");
|
||
assert.strictEqual(sandbox.__captures[0].status, 400, "the uniform failure status");
|
||
assert.strictEqual(sandbox.__captures[0].message, "Invalid credentials", "byte-identical uniform body");
|
||
assert.strictEqual(sandbox.__binds.length, 0, "NO session bind");
|
||
assert.strictEqual(sandbox.__sendOks.length, 0, "no success response");
|
||
assert.strictEqual(sandbox.__refunds.length, 0, "FINALIZED, not refunded");
|
||
});
|
||
|
||
test("login-proof-generation: a totpSealedError transition — denied; the seal break is never read as 'MFA disabled'", async () => {
|
||
// The snapshot row held a working seed; the re-read row's seal is BROKEN
|
||
// (decrypts to null + totpSealedError). hasTwoFactorEnabled stays TRUE on
|
||
// both rows (the seal flag enables) — the byte/flag legs are what deny.
|
||
const user = { id: USER_ID, email: CANONICAL, password: OLD_HASH, secret: "SEEDOLDSEEDOLDSEED", totpSealedError: false, suspended: false, session_epoch: 1 };
|
||
const latestUser = { id: USER_ID, email: CANONICAL, password: OLD_HASH, secret: null, totpSealedError: true, suspended: false, session_epoch: 1 };
|
||
const sandbox = makeLoginSandbox({ user, latestUser });
|
||
await runLoginHarness(sandbox);
|
||
|
||
assert.strictEqual(sandbox.__captures.length, 1, "exactly one response");
|
||
assert.strictEqual(sandbox.__captures[0].status, 400, "the uniform failure status");
|
||
assert.strictEqual(sandbox.__captures[0].message, "Invalid credentials", "byte-identical uniform body");
|
||
assert.strictEqual(sandbox.__binds.length, 0, "NO session bind — a broken seal must not downgrade to a no-2FA login");
|
||
assert.strictEqual(sandbox.__sendOks.length, 0, "no success response");
|
||
});
|
||
|
||
test("login-proof-generation: a benign concurrent rehash landing INSIDE the binder's window (same password, new cost) is still accepted", async () => {
|
||
// The pre-bind gates all passed (snapshot === re-read). T1, inside the
|
||
// binder's regenerate: another login's cost heal rehashes the SAME password
|
||
// (unequal string, same credential — and NOT a credential-generation bump).
|
||
// T2: the beforeSave hook re-reads the rehashed row, the epoch matches, and
|
||
// the bounded re-proof of the submitted password against the fresh hash
|
||
// VERIFIES — the bind proceeds.
|
||
const row = { id: USER_ID, email: CANONICAL, password: OLD_HASH, secret: null, totpSealedError: false, suspended: false, session_epoch: 1 };
|
||
const sandbox = makeLoginSandbox({ user: row, latestUser: row });
|
||
sandbox.__insideRegenerate = () => {
|
||
sandbox.__overrideLookups.push({ id: USER_ID, email: CANONICAL, password: REHASH_HASH, secret: null, totpSealedError: false, suspended: false, session_epoch: 1 });
|
||
};
|
||
await runLoginHarness(sandbox);
|
||
|
||
assert.deepStrictEqual(sandbox.__compares, [REHASH_HASH], "exactly one compare — the hook's re-proof against the fresh rehashed hash");
|
||
assert.strictEqual(sandbox.__captures.length, 0, "no failure response — the same password verifies against its new hash");
|
||
assert.strictEqual(sandbox.__binds.length, 1, "the bind proceeded");
|
||
assert.strictEqual(sandbox.__binds[0].beforeSave, true, "the bind carried the revalidation hook");
|
||
assert.strictEqual(sandbox.req.session.user, CANONICAL, "the session is bound");
|
||
assert.strictEqual(sandbox.__binderEvents.includes("save"), true, "the bounded save ran");
|
||
assert.strictEqual(sandbox.__sendOks.length, 1, "the success response answers");
|
||
assert.strictEqual(sandbox.__audits.length, 1, "one durable success row");
|
||
assert.strictEqual(sandbox.__refunds.length, 1, "the success refunds the reservation");
|
||
assert.strictEqual(sandbox.__rememberRevokes.length, 0, "no credential revoked on success");
|
||
});
|
||
|
||
test("login-proof-generation: a password reset + its session sweep committing inside the binder's regenerate window denies the login at completion — no authenticated session persists", async () => {
|
||
// T0: every pre-bind gate passed (snapshot === re-read, epoch 1). T1,
|
||
// inside the binder's regenerate: the victim's password reset COMMITS —
|
||
// CHANGED_HASH + the generation bump — and its sweep runs, but the sweep
|
||
// cannot see this login (the regenerated sid is unbound, the remember id
|
||
// unminted). T2: the beforeSave hook re-reads the fresh row, sees the new
|
||
// generation, and rejects through the labeled error; the shared binder's
|
||
// catch revokes the just-minted remember credential and tombstones the
|
||
// regenerated sid; the route settles the uniform credential failure.
|
||
const row = { id: USER_ID, email: CANONICAL, password: OLD_HASH, secret: null, totpSealedError: false, suspended: false, session_epoch: 1 };
|
||
const sandbox = makeLoginSandbox({ user: row, latestUser: row });
|
||
const commits = [];
|
||
sandbox.__insideRegenerate = () => {
|
||
commits.push("password-reset+sweep");
|
||
sandbox.__overrideLookups.push({ id: USER_ID, email: CANONICAL, password: CHANGED_HASH, secret: null, totpSealedError: false, suspended: false, session_epoch: 2 });
|
||
};
|
||
await runLoginHarness(sandbox);
|
||
|
||
assert.deepStrictEqual(commits, ["password-reset+sweep"], "the change committed inside the window (before any save)");
|
||
assert.strictEqual(sandbox.__captures.length, 1, "exactly one response");
|
||
assert.strictEqual(sandbox.__captures[0].status, 400, "the uniform failure status");
|
||
assert.strictEqual(sandbox.__captures[0].message, "Invalid credentials", "byte-identical uniform body — no disclosure of the completion rejection");
|
||
assert.strictEqual(sandbox.__sendOks.length, 0, "no success response");
|
||
assert.strictEqual(sandbox.__audits.length, 0, "no durable success row");
|
||
assert.strictEqual(sandbox.__refunds.length, 0, "FINALIZED, not refunded — the failure stands");
|
||
// No authenticated session persists: the bounded save never ran (the
|
||
// hook rejected before it) and the minted credential is revoked.
|
||
assert.strictEqual(sandbox.__binderEvents.includes("regenerate"), true, "the binder reached the regenerate");
|
||
assert.strictEqual(sandbox.__binderEvents.includes("save"), false, "the save never ran — the record never persisted");
|
||
assert.strictEqual(sandbox.__rememberMints.length, 1, "the remember credential was minted before the hook ran (the hygiene has something to revoke)");
|
||
assert.deepStrictEqual(sandbox.__rememberRevokes, ["rid-login"], "the just-minted remember credential was revoked by the binder's catch");
|
||
assert.strictEqual(sandbox.__clearedCookies.length, 1, "the remember cookie was cleared off the failed response");
|
||
assert.deepStrictEqual(sandbox.__tombstones, ["login-sid-2"], "the regenerated sid was tombstoned so a late store write cannot commit the authenticated record");
|
||
});
|
||
|
||
test("login-proof-generation: a hash change inside the window WITHOUT a generation bump (legacy row) denies via the bounded re-proof", async () => {
|
||
// The epoch leg is uncomparable-proof here (same epoch on both reads): the
|
||
// password-hash leg carries the denial — the re-proof of the submitted
|
||
// password against the FRESH hash fails, and no re-proof success is
|
||
// possible because the submitted password is no longer the account's.
|
||
const row = { id: USER_ID, email: CANONICAL, password: OLD_HASH, secret: null, totpSealedError: false, suspended: false, session_epoch: 1 };
|
||
const sandbox = makeLoginSandbox({ user: row, latestUser: row });
|
||
sandbox.__insideRegenerate = () => {
|
||
sandbox.__overrideLookups.push({ id: USER_ID, email: CANONICAL, password: CHANGED_HASH, secret: null, totpSealedError: false, suspended: false, session_epoch: 1 });
|
||
};
|
||
await runLoginHarness(sandbox);
|
||
|
||
assert.deepStrictEqual(sandbox.__compares, [CHANGED_HASH], "the hook's re-proof compared the submitted password against the fresh changed hash");
|
||
assert.strictEqual(sandbox.__captures.length, 1, "exactly one response");
|
||
assert.strictEqual(sandbox.__captures[0].status, 400, "the uniform failure status");
|
||
assert.strictEqual(sandbox.__sendOks.length, 0, "no success response");
|
||
assert.strictEqual(sandbox.__binderEvents.includes("save"), false, "the save never ran");
|
||
assert.deepStrictEqual(sandbox.__rememberRevokes, ["rid-login"], "the minted remember credential was revoked");
|
||
assert.deepStrictEqual(sandbox.__tombstones, ["login-sid-2"], "the regenerated sid was tombstoned");
|
||
});
|
||
|
||
test("login-proof-generation: legacy rows without a comparable epoch still complete on the password/fingerprint authority", async () => {
|
||
// An epoch-less row (legacy DB) is UNCOMPARABLE, never epoch 0: the gate
|
||
// must not deny an honest login whose hash and MFA state are unchanged.
|
||
const row = { id: USER_ID, email: CANONICAL, password: OLD_HASH, secret: null, totpSealedError: false, suspended: false, session_epoch: undefined };
|
||
const sandbox = makeLoginSandbox({ user: row, latestUser: row });
|
||
await runLoginHarness(sandbox);
|
||
|
||
assert.strictEqual(sandbox.__compares.length, 0, "no re-proof — the hash is unchanged");
|
||
assert.strictEqual(sandbox.__captures.length, 0, "no failure response");
|
||
assert.strictEqual(sandbox.__binds.length, 1, "the bind proceeded");
|
||
assert.strictEqual(sandbox.__sendOks.length, 1, "the success response answers");
|
||
assert.strictEqual(sandbox.__refunds.length, 1, "the success refunds the reservation");
|
||
assert.strictEqual(sandbox.req.session.user, CANONICAL, "the session is bound");
|
||
});
|