1989 lines
113 KiB
JavaScript
1989 lines
113 KiB
JavaScript
"use strict";
|
|
|
|
// adpanel:adversarial-auth-race-matrix — the regression matrix for the five
|
|
// auth fixes of the staleness/revocation campaign, as runnable interleavings:
|
|
//
|
|
// 1. DIRECT-LOGIN CREDENTIAL RACE (adpanel:login-staleness-reproof +
|
|
// adpanel:login-proof-generation)
|
|
// 2. CAPTCHA-COMPLETION CREDENTIAL RACE (adpanel:login-proof-generation)
|
|
// 3. MFA RACES + benign-rehash controls (adpanel:login-proof-generation)
|
|
// 4. RESTORE RACES (adpanel:restore-staleness-reverify +
|
|
// adpanel:credential-generation +
|
|
// adpanel:restore-failure-deauthorization)
|
|
// 5. RECOVERY RACE (adpanel:recovery-regen-two-step)
|
|
// 6. ADMIN ALIAS PARTIAL-FAILURE (adpanel:admin-2fa-reset-preflight +
|
|
// adpanel:credential-generation)
|
|
// 7. CONTROLS — the harness is not rigged (success paths + the owner rebind)
|
|
//
|
|
// Every race test asserts BOTH the wire outcome AND the hygiene artifacts
|
|
// (revoked remember credentials, tombstoned sids, cleared pending state, the
|
|
// written SQL) — a response shape alone proves nothing about revocation.
|
|
//
|
|
// Harness: the house vm-extraction technique (tests/login-staleness-reproof
|
|
// .test.js is the model; helpers are deliberately per-file — nothing here is
|
|
// imported from a sibling test). The REAL handler/restore/completion bodies,
|
|
// the REAL middleware regions, the REAL shared binder (utils/login-session
|
|
// -bind.js), the REAL shared predicates (utils/session-account-binding.js),
|
|
// the REAL epoch generator (utils/session-epoch.js) and REAL bcryptjs at cost
|
|
// 4 run verbatim; interleavings are placed by controlled promise barriers
|
|
// (explicit hooks awaited at exact points) — never timing sleeps. The
|
|
// concurrent credential writer is the pinned CAS shape from
|
|
// tests/credential-change-atomic-guard.test.js (in-statement epoch bump), and
|
|
// its post-commit sweep's view of the in-flight login is RECORDED, not
|
|
// simulated away — the sweep-miss evidence is asserted, not assumed. No test
|
|
// requires index.js.
|
|
|
|
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 { MemoryStore, ipKeyGenerator } = require("express-rate-limit");
|
|
|
|
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 { 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 { createCredentialSessionRebinder } = require(path.join(ROOT, "utils", "credential-session-rebind.js"));
|
|
const { createAdminTwoFactorResetService } = require(path.join(ROOT, "services", "admin-2fa-reset.js"));
|
|
const { createCredentialCommitService } = require("../services/account-credentials");
|
|
// adpanel:session-account-binding / adpanel:credential-generation — the ONE
|
|
// shared predicates and the ONE epoch generator, injected REAL wherever the
|
|
// guard itself is under test. Never stubbed to constants, never copied.
|
|
const { sessionAccountBindingMismatch, credentialGenerationMismatch } = require(path.join(ROOT, "utils", "session-account-binding.js"));
|
|
const { newSessionEpochDifferentFrom, SESSION_EPOCH_MIN, SESSION_EPOCH_MAX } = require(path.join(ROOT, "utils", "session-epoch.js"));
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Extraction helpers (per-file copies of the house extractors)
|
|
// ---------------------------------------------------------------------------
|
|
|
|
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.
|
|
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);
|
|
}
|
|
|
|
// Marker→marker region extraction (for spans that several functions share).
|
|
function extractRegion(source, startMarker, endMarker) {
|
|
const start = source.indexOf(startMarker);
|
|
assert.ok(start >= 0, `region start marker not found: ${startMarker}`);
|
|
const end = source.indexOf(endMarker, start + startMarker.length);
|
|
assert.ok(end > start, `region end marker not found after start: ${endMarker}`);
|
|
return source.slice(start, end);
|
|
}
|
|
|
|
// Paren-balanced extraction of a full `app.post(...);` statement (skips
|
|
// strings and comments so adpanel: comments cannot desync the tracker).
|
|
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}`);
|
|
}
|
|
|
|
// The handler of a `app.use(async (req, res, next) => { ... });` registration,
|
|
// located by anchoring on a UNIQUE statement inside it (there are several
|
|
// app.use middlewares in index.js).
|
|
function extractMiddlewareByAnchor(anchor) {
|
|
const anchorIdx = indexOfOrThrow(anchor);
|
|
const mwMarker = "app.use(async (req, res, next) => {";
|
|
const start = indexSource.lastIndexOf(mwMarker, anchorIdx);
|
|
assert.ok(start >= 0 && start < anchorIdx, `no app.use middleware precedes the anchor: ${anchor}`);
|
|
return extractBalancedBlock(indexSource.slice(start), mwMarker) + ");";
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Extracted REAL sources (each marker is verified by the extractor above)
|
|
// ---------------------------------------------------------------------------
|
|
|
|
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 REQ_FP_SOURCE = extractBalancedBlock(indexSource, "function getPendingCaptchaLoginRequestFingerprint(req) {");
|
|
const CLEAR_PENDING_SOURCE = extractBalancedBlock(indexSource, "function clearPendingCaptchaLogin(req) {");
|
|
const GET_PENDING_SOURCE = extractBalancedBlock(indexSource, "function getPendingCaptchaLogin(req) {");
|
|
const PROTECTED_STATE_SOURCE = extractBalancedBlock(indexSource, "function sessionCarriesProtectedPendingAuthState(session) {");
|
|
const BEGIN_PENDING_SOURCE = extractBalancedBlock(indexSource, "function beginPendingCaptchaLogin(req, user, options = {}) {");
|
|
const COMPLETION_SOURCE = extractBalancedBlock(indexSource, "async function completePendingCaptchaLogin(req, res) {");
|
|
const RESTORE_SOURCE = extractBalancedBlock(indexSource, "async function restoreRememberedLogin(req, res) {");
|
|
const TEARDOWN_FAILED_SOURCE = extractBalancedBlock(indexSource, "async function teardownFailedRememberRestore(req, res) {");
|
|
const TEARDOWN_STALE_SOURCE = extractBalancedBlock(indexSource, "async function teardownStaleAccountSession(req, res, { respond }) {");
|
|
const GET_LOGGED_IN_USER_SOURCE = extractBalancedBlock(indexSource, "async function getLoggedInUser(req) {");
|
|
const IS_AUTHENTICATED_SOURCE = extractBalancedBlock(indexSource, "async function isAuthenticated(req) {");
|
|
const IS_ADMIN_SOURCE = extractBalancedBlock(indexSource, "async function isAdmin(req) {");
|
|
const SHA256_SOURCE = extractBalancedBlock(indexSource, "function sha256Hex(buffer) {");
|
|
const NORMALIZE_TARGET_SOURCE = extractBalancedBlock(indexSource, "function normalizeAdminTargetEmail(raw) {");
|
|
const AUTH_SOURCE = `${GET_LOGGED_IN_USER_SOURCE}\n${IS_AUTHENTICATED_SOURCE}\n${IS_ADMIN_SOURCE}`;
|
|
|
|
// The account-binding middleware — anchored on the ONE shared predicate's use
|
|
// inside it (adpanel:session-account-binding).
|
|
const BINDING_MW_SOURCE = extractMiddlewareByAnchor("if (sessionAccountBindingMismatch(req.session, user)) {");
|
|
assert.ok(BINDING_MW_SOURCE.includes("sessionAccountBindingMismatch(req.session, user)"),
|
|
"the extracted binding middleware must contain the shared-predicate check");
|
|
assert.ok(BINDING_MW_SOURCE.includes("teardownStaleAccountSession(req, res, { respond: true })"),
|
|
"the extracted binding middleware must deny through the stale-account teardown");
|
|
|
|
// The remember middleware — anchored on the restore call site (unique).
|
|
const REMEMBER_MW_SOURCE = extractMiddlewareByAnchor("await restoreRememberedLogin(req, res);");
|
|
assert.ok(REMEMBER_MW_SOURCE.includes("await teardownFailedRememberRestore(req, res);"),
|
|
"the extracted remember middleware must delegate its catch to the teardown helper");
|
|
|
|
// POST /login: the failure-helper block and the post-compare region, verbatim.
|
|
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);
|
|
}
|
|
|
|
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);
|
|
}
|
|
|
|
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);
|
|
}
|
|
|
|
// Two-step recovery regeneration: helpers + both route statements.
|
|
const REGEN_READ_FN = extractRegion(
|
|
indexSource,
|
|
"async function readStoredRecoveryCodes(",
|
|
"function getValidRecoveryRegenAuth"
|
|
);
|
|
const REGEN_GUARD_FN = extractRegion(
|
|
indexSource,
|
|
"function getValidRecoveryRegenAuth(",
|
|
'app.post("/api/account/2fa/regenerate-recovery-codes/verify-password"'
|
|
);
|
|
const REGEN_VERIFY_GRANT_FN = extractRegion(
|
|
indexSource,
|
|
"function getValidRecoveryVerification(",
|
|
"async function claimRecoveryCode("
|
|
);
|
|
const REGEN_CLAIM_FN = extractRegion(
|
|
indexSource,
|
|
"async function claimRecoveryCode(",
|
|
'app.post("/api/account/recovery/verify"'
|
|
);
|
|
const REGEN_STEP1_STATEMENT = extractRouteStatement(
|
|
indexSource,
|
|
'app.post("/api/account/2fa/regenerate-recovery-codes/verify-password", accountCredentialRateLimiter'
|
|
);
|
|
const REGEN_STEP2_STATEMENT = extractRouteStatement(
|
|
indexSource,
|
|
'app.post("/api/account/2fa/regenerate-recovery-codes", accountTotpRateLimiter'
|
|
);
|
|
|
|
// Admin 2FA reset: the REAL thin arrow adapters (both aliases).
|
|
const ADMIN_ROUTE_RESET = extractRouteStatement(
|
|
indexSource,
|
|
'app.post("/api/admin/user/reset-2fa", sessionRevoke2faRateLimiter'
|
|
);
|
|
const ADMIN_ROUTE_CONFIRM = extractRouteStatement(
|
|
indexSource,
|
|
'app.post("/api/admin/user/confirm-2fa-reset", sessionRevoke2faRateLimiter'
|
|
);
|
|
|
|
// The REAL self-contained helpers, instantiated once in minimal realms.
|
|
const REAL_WITH_TIMEOUT = vm.runInContext(`(${WITH_TIMEOUT_SOURCE})`, vm.createContext({ setTimeout, clearTimeout, Promise }));
|
|
const REAL_SAFE_COMPARE = vm.runInContext(`(${SAFE_COMPARE_SOURCE})`, vm.createContext({ Buffer, crypto }));
|
|
const { getRememberLoginFingerprint: REAL_GET_FP } = require("../utils/remember-login-fingerprint");
|
|
const REAL_HAS_TWO_FACTOR = vm.runInContext(`(${HAS_TWO_FACTOR_SOURCE})`, vm.createContext({}));
|
|
const REAL_SHA256 = vm.runInContext(`(${SHA256_SOURCE})`, vm.createContext({ crypto }));
|
|
const REAL_NORMALIZE_TARGET = vm.runInContext(`(${NORMALIZE_TARGET_SOURCE})`, vm.createContext({}));
|
|
const REAL_CLEAR_PENDING = vm.runInContext(`(${CLEAR_PENDING_SOURCE})`, vm.createContext({}));
|
|
const REAL_PROTECTED_STATE = vm.runInContext(`(${PROTECTED_STATE_SOURCE})`, vm.createContext({}));
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// 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
|
|
const REHASH_HASH_2 = bcryptjs.hashSync(PASSWORD, 4); // same password, a THIRD salt
|
|
|
|
assert.notStrictEqual(OLD_HASH, REHASH_HASH, "two hashes of the same password must be unequal strings (the benign-rehash premise)");
|
|
assert.notStrictEqual(REHASH_HASH, REHASH_HASH_2, "each rehash salt must differ");
|
|
assert.ok(bcryptjs.compareSync(PASSWORD, OLD_HASH) && bcryptjs.compareSync(PASSWORD, REHASH_HASH) && bcryptjs.compareSync(PASSWORD, REHASH_HASH_2),
|
|
"precondition: all same-password hashes verify against PASSWORD");
|
|
assert.ok(!bcryptjs.compareSync(PASSWORD, CHANGED_HASH), "precondition: the changed hash refuses the old password");
|
|
|
|
const CANONICAL = "victim@example.test";
|
|
const USER_ID = 4242;
|
|
const EPOCH_A = 1;
|
|
|
|
function row(overrides = {}) {
|
|
return Object.assign(
|
|
{ id: USER_ID, email: CANONICAL, password: OLD_HASH, secret: null, totpSealedError: false, suspended: false, session_epoch: EPOCH_A },
|
|
overrides
|
|
);
|
|
}
|
|
|
|
// The pinned SQL shapes this file's concurrent writer commits (the CAS shape
|
|
// pinned by tests/credential-change-atomic-guard.test.js).
|
|
const PASSWORD_RESET_CAS_SQL = require("../services/account-credentials").CREDENTIAL_COMMIT_SQL.password;
|
|
const LOGIN_REHASH_CAS_SQL = "UPDATE users SET password = ? WHERE id = ? AND password = ?";
|
|
// adpanel:admin-reset-target-pinning — the admin 2FA clear keys on 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); the epoch bump stays IN THE SAME statement.
|
|
const ADMIN_2FA_CLEAR_SQL = "UPDATE users SET secret = NULL, recovery_codes = NULL, session_epoch = ? WHERE id = ?";
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Barrier utilities — controlled promise barriers, never timing sleeps
|
|
// ---------------------------------------------------------------------------
|
|
|
|
function deferred() {
|
|
let resolve;
|
|
let reject;
|
|
const promise = new Promise((res, rej) => { resolve = res; reject = rej; });
|
|
return { promise, resolve, reject };
|
|
}
|
|
|
|
// JSON-safe snapshot of an express-session-shaped record (functions and
|
|
// symbol keys drop — exactly what a store write would serialize).
|
|
function snapshotSession(session) {
|
|
return JSON.parse(JSON.stringify(session || {}));
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// The concurrent credential writer — the pinned in-statement CAS + bump + the
|
|
// writer's post-commit revocation sweep. The sweep's view of the in-flight
|
|
// login is RECORDED at commit time via onSweep: what the sweep would see is
|
|
// exactly the miss evidence the race tests assert.
|
|
// ---------------------------------------------------------------------------
|
|
|
|
function createSimulatedCredentialWriter({ row: dbRow, onSweep, timeline }) {
|
|
const queries = [];
|
|
const sweeps = [];
|
|
async function commitCredentialChange({ newHash, sweepLabel = "post-change-sweep" } = {}) {
|
|
const provenHash = String(dbRow.password); // the writer's own pre-flight snapshot
|
|
const provedEpoch = dbRow.session_epoch;
|
|
const bumpedEpoch = newSessionEpochDifferentFrom(Number(dbRow.session_epoch || 0));
|
|
const params = [newHash, bumpedEpoch, dbRow.id, provenHash, provedEpoch];
|
|
queries.push({ sql: PASSWORD_RESET_CAS_SQL, params, epoch: bumpedEpoch, provenHash });
|
|
if (dbRow.password !== provenHash || dbRow.session_epoch !== provedEpoch) return { affectedRows: 0, committed: false, newEpoch: bumpedEpoch, provenHash };
|
|
dbRow.password = newHash;
|
|
dbRow.session_epoch = bumpedEpoch;
|
|
const observation = typeof onSweep === "function" ? onSweep() : null;
|
|
sweeps.push({ label: sweepLabel, observation });
|
|
timeline.push("sweep");
|
|
return { affectedRows: 1, committed: true, newEpoch: bumpedEpoch, provenHash, hash: newHash, observation };
|
|
}
|
|
// The benign cost-heal writer: the login rehash CAS is EPOCH-FREE (pinned by
|
|
// tests/credential-change-atomic-guard.test.js — a rehash never bumps), and
|
|
// it runs no revocation sweep (the credential did not change).
|
|
async function commitEpochFreeRehash({ newHash } = {}) {
|
|
const provenHash = String(dbRow.password);
|
|
const params = [newHash, dbRow.id, provenHash];
|
|
queries.push({ sql: LOGIN_REHASH_CAS_SQL, params, epoch: null, provenHash });
|
|
if (dbRow.password !== provenHash) return { affectedRows: 0, committed: false };
|
|
dbRow.password = newHash;
|
|
return { affectedRows: 1, committed: true };
|
|
}
|
|
return { commitCredentialChange, commitEpochFreeRehash, queries, sweeps };
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Harness 1/3/7a — POST /login post-compare region over the REAL binder
|
|
// ---------------------------------------------------------------------------
|
|
|
|
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 makeLoginRaceHarness({ user, latestUser }) {
|
|
const captures = [];
|
|
const headers = {};
|
|
const warns = [];
|
|
const securityLogs = [];
|
|
const captchaArms = [];
|
|
const compares = [];
|
|
const totpVerifications = [];
|
|
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 persistedRecords = [];
|
|
const timeline = [];
|
|
let admissions = 0;
|
|
|
|
// Controlled barrier points. Each hook is an async function awaited at the
|
|
// exact interleaving point; the concurrent writer commits INSIDE the hook,
|
|
// so the ordering is structural, not timing-dependent.
|
|
const hooks = { admission: null, regenerate: null, save: null };
|
|
const hookAt = { admission: 1 };
|
|
|
|
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); };
|
|
|
|
const overrideLookups = [];
|
|
|
|
const req = {
|
|
sessionID: "login-sid-1",
|
|
session: {
|
|
regenerate: (cb) => {
|
|
timeline.push("regenerate");
|
|
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(() => (hooks.regenerate ? hooks.regenerate() : undefined))
|
|
.then(() => cb(null), (err) => cb(err));
|
|
},
|
|
save: (cb) => {
|
|
timeline.push("save");
|
|
binderEvents.push("save");
|
|
Promise.resolve()
|
|
.then(() => (hooks.save ? hooks.save() : undefined))
|
|
.then(() => {
|
|
persistedRecords.push({ sid: String(req.sessionID), record: snapshotSession(req.session) });
|
|
timeline.push("save-commit");
|
|
cb(null);
|
|
}, (err) => cb(err));
|
|
},
|
|
},
|
|
};
|
|
|
|
const realBinder = createLoginSessionBinder({
|
|
withTimeout: REAL_WITH_TIMEOUT,
|
|
writeRevokedSidTombstone: async (sid) => { tombstones.push(String(sid)); timeline.push(`tombstone:${sid}`); return true; },
|
|
sessionCarriesProtectedPendingAuthState: REAL_PROTECTED_STATE,
|
|
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); timeline.push("remember-mint"); return 7776000000; },
|
|
markRememberLoginSessionFresh: (r, expiresAt) => { r.session.rememberLoginExpiresAt = expiresAt; },
|
|
upsertActiveBrowserSessionCacheEntry: (sessionId) => { cacheUpserts.push(sessionId); },
|
|
clearRememberLoginCookie: () => { clearedCookies.push(1); timeline.push("cookie-clear"); },
|
|
revokeRememberLoginRegistryEntry: async (rememberLoginId) => { rememberRevokes.push(rememberLoginId); timeline.push(`revoke:${rememberLoginId}`); return true; },
|
|
logger: { warn: (...p) => warns.push(p.map(String).join(" ")) },
|
|
});
|
|
|
|
const sandbox = {
|
|
loginCredentialReservation: null,
|
|
emailStr: CANONICAL,
|
|
passStr: PASSWORD,
|
|
throttleIpKey: "race-src",
|
|
req,
|
|
res: { setHeader: (k, v) => { headers[k] = String(v); } },
|
|
user,
|
|
loginThrottle: throttle,
|
|
loginRetryAfterSeconds: () => 30,
|
|
findUserByEmail: async () => (overrideLookups.length ? overrideLookups.shift() : latestUser),
|
|
loginBcryptAdmission: {
|
|
run: async (fn) => {
|
|
admissions += 1;
|
|
if (admissions === hookAt.admission && typeof hooks.admission === "function") {
|
|
await hooks.admission();
|
|
}
|
|
return 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 () => { timeline.push("revokeUser"); },
|
|
verifyTotpForUser: async (...a) => { totpVerifications.push(a); return { ok: true }; },
|
|
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)); },
|
|
loginAuditRecorder: {
|
|
recordSuccessfulLoginAudit: (rec) => { audits.push(rec); },
|
|
recordFailedLoginAudit: (rec) => { failureAudits.push(rec); },
|
|
},
|
|
hasTwoFactorEnabled: REAL_HAS_TWO_FACTOR,
|
|
credentialGenerationMismatch,
|
|
setTimeout,
|
|
clearTimeout,
|
|
console: { warn: (...p) => warns.push(p.map(String).join(" ")), error: () => {}, log: () => {} },
|
|
__captures: captures,
|
|
__compares: compares,
|
|
__totpVerifications: totpVerifications,
|
|
__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,
|
|
__persistedRecords: persistedRecords,
|
|
__timeline: timeline,
|
|
__overrideLookups: overrideLookups,
|
|
};
|
|
return { sandbox, req, hooks, hookAt, timeline, persistedRecords, overrideLookups, throttle };
|
|
}
|
|
|
|
function runLoginRaceHarness({ sandbox, user, latestUser }) {
|
|
const context = vm.createContext(sandbox);
|
|
vm.runInContext(WITH_TIMEOUT_SOURCE, context, { filename: "race-withTimeout.js" });
|
|
vm.runInContext(loginHelpersBlock(), context, { filename: "race-login-helpers.js" });
|
|
const scenario = `${LOGIN_PREAMBLE}\n${loginTailRegion()}`;
|
|
return vm.runInContext(`(async () => {\n${scenario}\n})()`, context, { filename: "race-login-tail.js" });
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Harness 2/7b — captcha completion over the REAL begin + completion + binder
|
|
// ---------------------------------------------------------------------------
|
|
|
|
function makeCompletionRaceHarness({ challengeRow, liveQueue, twoFactorVerified = false }) {
|
|
const events = [];
|
|
const warns = [];
|
|
const tombstones = [];
|
|
const rememberMints = [];
|
|
const rememberRevokes = [];
|
|
const cookieClears = [];
|
|
const cacheUpserts = [];
|
|
const binderEvents = [];
|
|
const lookups = [];
|
|
const persistedRecords = [];
|
|
const timeline = [];
|
|
const overrideLookups = [];
|
|
const hooks = { regenerate: null, save: null };
|
|
|
|
const realBinder = createLoginSessionBinder({
|
|
withTimeout: REAL_WITH_TIMEOUT,
|
|
writeRevokedSidTombstone: async (sid) => { tombstones.push(String(sid)); timeline.push(`tombstone:${sid}`); return true; },
|
|
sessionCarriesProtectedPendingAuthState: REAL_PROTECTED_STATE,
|
|
getSessionDisplayId: (sid) => `sid:${sid}`,
|
|
ensureRememberLoginSessionId: (r) => {
|
|
if (!r.session.rememberLoginId) r.session.rememberLoginId = "rid-captcha";
|
|
return r.session.rememberLoginId;
|
|
},
|
|
buildBrowserSessionAuditFromRequest: (r, email, rememberLoginId) => ({ email, rememberLoginId }),
|
|
setRememberLoginCookie: () => { rememberMints.push(1); timeline.push("remember-mint"); return 7776000000; },
|
|
markRememberLoginSessionFresh: (r, expiresAt) => { r.session.rememberLoginExpiresAt = expiresAt; },
|
|
upsertActiveBrowserSessionCacheEntry: (sessionId) => { cacheUpserts.push(sessionId); },
|
|
clearRememberLoginCookie: () => { cookieClears.push(1); events.push("clearCookie"); timeline.push("cookie-clear"); },
|
|
revokeRememberLoginRegistryEntry: async (rememberLoginId) => { rememberRevokes.push(rememberLoginId); timeline.push(`revoke:${rememberLoginId}`); return true; },
|
|
logger: { warn: (...p) => warns.push(p.map(String).join(" ")) },
|
|
});
|
|
|
|
const sandbox = {
|
|
PENDING_CAPTCHA_LOGIN_TTL_MS: 300000,
|
|
crypto,
|
|
Buffer,
|
|
console: { warn: (...p) => warns.push(p.map(String).join(" ")), error: () => {}, log: () => {} },
|
|
setTimeout,
|
|
clearTimeout,
|
|
capdbg: () => {},
|
|
isMaintenanceActive: () => false,
|
|
credentialGenerationMismatch,
|
|
hasTwoFactorEnabled: REAL_HAS_TWO_FACTOR,
|
|
safeCompare: REAL_SAFE_COMPARE,
|
|
getRememberLoginFingerprint: REAL_GET_FP,
|
|
clearPendingCaptchaLogin: REAL_CLEAR_PENDING,
|
|
sessionCarriesProtectedPendingAuthState: REAL_PROTECTED_STATE,
|
|
getRequestIp: () => "203.0.113.7",
|
|
findUserByEmail: async () => {
|
|
lookups.push(1);
|
|
return overrideLookups.length ? overrideLookups.shift() : liveQueue[0];
|
|
},
|
|
revokeRememberLoginsForUser: async () => { events.push("revokeUser"); timeline.push("revokeUser"); },
|
|
clearRememberLoginCookie: () => { events.push("clearCookie"); cookieClears.push(1); },
|
|
verifyTotpForUser: async (...a) => { events.push("totpVerify"); return { ok: true }; },
|
|
loginThrottle: {
|
|
ipKey: (ip) => `ip(${ip})`,
|
|
resetTotpSource: async () => { events.push("totpReset"); timeline.push("totpReset"); },
|
|
},
|
|
clearLoginCaptchaGateForIp: (key) => { events.push(`gateClear:${key}`); timeline.push("gateClear"); },
|
|
loginAuditRecorder: {
|
|
recordSuccessfulLoginAudit: (rec) => { events.push(`audit:${String(rec.method)}`); timeline.push("audit"); },
|
|
recordFailedLoginAudit: () => { events.push("audit:failed"); },
|
|
},
|
|
loginSessionBinder: {
|
|
bindLoginSession: async (reqArg, resArg, opts) => {
|
|
binderEvents.push("bindCall");
|
|
return realBinder.bindLoginSession(reqArg, resArg, opts);
|
|
},
|
|
},
|
|
req: {
|
|
sessionID: "captcha-sid-1",
|
|
get: (header) => (String(header || "").toLowerCase() === "user-agent" ? "race-agent/1.0" : undefined),
|
|
session: { captchaRequired: true, captchaSolved: true },
|
|
},
|
|
res: {},
|
|
__challengeRow: challengeRow,
|
|
__twoFactorVerified: twoFactorVerified,
|
|
__events: events,
|
|
__warns: warns,
|
|
__tombstones: tombstones,
|
|
__rememberMints: rememberMints,
|
|
__rememberRevokes: rememberRevokes,
|
|
__cookieClears: cookieClears,
|
|
__cacheUpserts: cacheUpserts,
|
|
__binderEvents: binderEvents,
|
|
__lookups: lookups,
|
|
__overrideLookups: overrideLookups,
|
|
__persistedRecords: persistedRecords,
|
|
__timeline: timeline,
|
|
};
|
|
|
|
const reqSession = sandbox.req.session;
|
|
reqSession.regenerate = (cb) => {
|
|
timeline.push("regenerate");
|
|
binderEvents.push("regenerate");
|
|
for (const key of Object.keys(reqSession)) {
|
|
if (key !== "regenerate" && key !== "save") delete reqSession[key];
|
|
}
|
|
sandbox.req.sessionID = "captcha-sid-2";
|
|
Promise.resolve()
|
|
.then(() => (hooks.regenerate ? hooks.regenerate() : undefined))
|
|
.then(() => cb(null), (err) => cb(err));
|
|
};
|
|
reqSession.save = (cb) => {
|
|
timeline.push("save");
|
|
binderEvents.push("save");
|
|
Promise.resolve()
|
|
.then(() => (hooks.save ? hooks.save() : undefined))
|
|
.then(() => {
|
|
persistedRecords.push({ sid: String(sandbox.req.sessionID), record: snapshotSession(reqSession) });
|
|
timeline.push("save-commit");
|
|
cb(null);
|
|
}, (err) => cb(err));
|
|
};
|
|
|
|
return { sandbox, hooks, events, tombstones, rememberMints, rememberRevokes, cookieClears, binderEvents, persistedRecords, timeline, overrideLookups };
|
|
}
|
|
|
|
function runCompletionRace(h) {
|
|
const context = vm.createContext(h.sandbox);
|
|
vm.runInContext(REQ_FP_SOURCE, context, { filename: "race-req-fp.js" });
|
|
vm.runInContext(GET_PENDING_SOURCE, context, { filename: "race-get-pending.js" });
|
|
vm.runInContext(BEGIN_PENDING_SOURCE, context, { filename: "race-begin-pending.js" });
|
|
vm.runInContext(COMPLETION_SOURCE, context, { filename: "race-completion.js" });
|
|
const minted = vm.runInContext(
|
|
"beginPendingCaptchaLogin(req, __challengeRow, { twoFactorVerified: __twoFactorVerified })",
|
|
context,
|
|
{ filename: "race-begin-call.js" }
|
|
);
|
|
assert.strictEqual(minted, true, "scenario precondition: the pending record must mint");
|
|
// The store round-trip: express-session serializes to JSON on save, so the
|
|
// completion reads back exactly these bytes.
|
|
h.sandbox.req.session.pendingCaptchaLogin = JSON.parse(JSON.stringify(h.sandbox.req.session.pendingCaptchaLogin));
|
|
// The verify route's own solve step (POST /api/captcha/verify).
|
|
h.sandbox.req.session.captchaSolved = true;
|
|
h.sandbox.req.session.captchaRequired = false;
|
|
return vm.runInContext("completePendingCaptchaLogin(req, res)", context, { filename: "race-completion-call.js" });
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Harness 4/7c — remember restore + the REAL remember middleware + REAL
|
|
// failure teardown + REAL auth primitives
|
|
// ---------------------------------------------------------------------------
|
|
|
|
function makeRestoreRaceHarness({ lookupQueue, saveOutcome = "ok", revokeImpl = null }) {
|
|
const events = [];
|
|
const warnings = [];
|
|
const calls = { clearState: 0, clearCookie: 0, markFresh: 0, rotates: 0, regens: 0, lookups: 0, tombstones: 0, next: 0 };
|
|
const nextArgs = [];
|
|
const tombstoneSids = [];
|
|
const revokedIds = [];
|
|
const revokedHints = [];
|
|
const auditMethods = [];
|
|
const persistedRecords = [];
|
|
const timeline = [];
|
|
const hooks = { save: null };
|
|
|
|
const req = { cookies: { "adpanel.remember": "tok" }, sessionID: "pre-restore-sid-1" };
|
|
const queue = lookupQueue.slice();
|
|
const PARSED = {
|
|
v: 2,
|
|
uid: String(lookupQueue[0].id),
|
|
iat: Date.now() - 60000,
|
|
exp: Date.now() + 365 * 24 * 3600 * 1000,
|
|
fp: REAL_GET_FP(lookupQueue[0]),
|
|
jti: "remember-id-restore",
|
|
};
|
|
|
|
const session = {
|
|
regenerate: (cb) => {
|
|
calls.regens += 1;
|
|
events.push("regenerate");
|
|
timeline.push("regenerate");
|
|
req.sessionID = "regenerated-sid-2";
|
|
cb(null);
|
|
},
|
|
save: (cb) => {
|
|
events.push("save");
|
|
timeline.push("save");
|
|
Promise.resolve()
|
|
.then(() => (hooks.save ? hooks.save() : undefined))
|
|
.then(() => {
|
|
if (saveOutcome === "ok") {
|
|
persistedRecords.push({ sid: String(req.sessionID), record: snapshotSession(req.session) });
|
|
timeline.push("save-commit");
|
|
cb(null);
|
|
} else {
|
|
cb(new Error("synthetic store failure"));
|
|
}
|
|
}, (err) => cb(err));
|
|
},
|
|
destroy: (cb) => {
|
|
events.push("destroy");
|
|
timeline.push("destroy");
|
|
delete req.session;
|
|
cb(null);
|
|
},
|
|
};
|
|
req.session = session;
|
|
|
|
const sandbox = {
|
|
console: { log: () => {}, warn: (...a) => warnings.push(a.map(String).join(" ")), error: () => {} },
|
|
REMEMBER_LOGIN_COOKIE_NAME: "adpanel.remember",
|
|
readRememberLoginToken: () => PARSED,
|
|
securityLog: (msg) => events.push(`log:${String(msg)}`),
|
|
loginAuditRecorder: { recordSuccessfulLoginAudit: ({ method }) => { auditMethods.push(String(method)); events.push(`audit:${String(method)}`); timeline.push("audit"); } },
|
|
remoteProxyTrustBlocksRememberIssuance: () => false,
|
|
findUserById: async () => {
|
|
calls.lookups += 1;
|
|
return queue.length > 1 ? queue.shift() : queue[0];
|
|
},
|
|
findUserByEmail: async () => lookupQueue[0],
|
|
safeCompare: REAL_SAFE_COMPARE,
|
|
getRememberLoginFingerprint: REAL_GET_FP,
|
|
credentialGenerationMismatch,
|
|
...require("../utils/remember-login-completion"),
|
|
isSessionSidRevoked: async () => false,
|
|
getRememberLoginLegacyCutoff: () => 0,
|
|
isManagedRememberLoginToken: () => true,
|
|
revokeRememberLoginsForUser: async () => { events.push("revokeUser"); },
|
|
sessionCarriesProtectedPendingAuthState: REAL_PROTECTED_STATE,
|
|
getSessionDisplayId: (id) => `sid:${id}`,
|
|
writeRevokedSidTombstone: async (sid) => { calls.tombstones += 1; tombstoneSids.push(String(sid)); events.push(`tombstone:${sid}`); timeline.push(`tombstone:${sid}`); return true; },
|
|
clearRememberLoginSessionState: (r) => {
|
|
if (!r?.session) return;
|
|
delete r.session.rememberLoginCheckedAt;
|
|
delete r.session.rememberLoginExpiresAt;
|
|
calls.clearState += 1;
|
|
events.push("clearState");
|
|
},
|
|
clearRememberLoginCookie: () => { calls.clearCookie += 1; events.push("clearCookie"); timeline.push("cookie-clear"); },
|
|
rotateRememberLoginCookie: async (r) => {
|
|
calls.rotates += 1;
|
|
events.push("rotate");
|
|
timeline.push("rotate");
|
|
if (r?.session) r.session.rememberLoginId = "rotated-remember-id-3";
|
|
return 4102444800000;
|
|
},
|
|
buildBrowserSessionAuditFromRequest: (r, email, rememberLoginId) => ({ email, rememberLoginId }),
|
|
markRememberLoginSessionFresh: (r, expiresAt) => {
|
|
if (!r?.session) return;
|
|
r.session.rememberLoginCheckedAt = Date.now();
|
|
r.session.rememberLoginExpiresAt = Number(expiresAt) || 0;
|
|
calls.markFresh += 1;
|
|
events.push("markFresh");
|
|
},
|
|
clearPendingCaptchaLogin: (r) => { if (r?.session) delete r.session.pendingCaptchaLogin; },
|
|
removeActiveBrowserSessionCacheEntry: (sid) => { events.push(`cacheRemove:${sid}`); timeline.push(`cacheRemove:${sid}`); },
|
|
invalidateActiveBrowserSessionCache: () => { events.push("cacheInvalidate"); timeline.push("cacheInvalidate"); },
|
|
ensureRememberLoginStoreReady: async () => {},
|
|
ensureRememberLoginRegistryFresh: async () => {},
|
|
ensureRememberLoginCookie: async () => {},
|
|
revokeRememberLoginLineage: async (id, hints) => {
|
|
revokedIds.push(String(id));
|
|
revokedHints.push({ ...(hints || {}) });
|
|
events.push(`revoke:${id}`);
|
|
timeline.push(`revoke:${id}`);
|
|
if (revokeImpl) {
|
|
const outcome = await revokeImpl(id, hints);
|
|
return outcome === undefined ? true : outcome;
|
|
}
|
|
return true;
|
|
},
|
|
withTimeout: REAL_WITH_TIMEOUT,
|
|
req,
|
|
app: { use: (fn) => { sandbox.__capturedMw = fn; } },
|
|
__hooks: hooks,
|
|
};
|
|
|
|
vm.createContext(sandbox);
|
|
vm.runInContext(RESTORE_SOURCE, sandbox, { filename: "race-restore.js" });
|
|
assert.strictEqual(typeof sandbox.restoreRememberedLogin, "function", "the extracted restore body must define the realm global");
|
|
vm.runInContext(TEARDOWN_FAILED_SOURCE, sandbox, { filename: "race-teardown-failed.js" });
|
|
vm.runInContext(AUTH_SOURCE, sandbox, { filename: "race-auth.js" });
|
|
vm.runInContext(REMEMBER_MW_SOURCE, sandbox, { filename: "race-remember-mw.js" });
|
|
assert.strictEqual(typeof sandbox.__capturedMw, "function", "the remember middleware must be captured");
|
|
const next = (...a) => { calls.next += 1; nextArgs.push(a); events.push("next"); timeline.push("next"); };
|
|
let protectedSettingsHandler;
|
|
sandbox.app.get = (...args) => { protectedSettingsHandler = args.at(-1); };
|
|
sandbox.security = { rate_limiting: true, limit: 60, window_seconds: 60, trusted_subnets: [] };
|
|
sandbox.readEnvFile = () => ({});
|
|
sandbox.getDestructiveActionSecurityAsync = async () => ({});
|
|
sandbox.issueActionToken = () => "protected-action-token";
|
|
vm.runInContext(extractRouteStatement(indexSource, 'app.get("/api/settings/security"'), sandbox);
|
|
return {
|
|
mw: sandbox.__capturedMw,
|
|
restore: sandbox.restoreRememberedLogin,
|
|
isAuthenticated: sandbox.isAuthenticated,
|
|
isAdmin: sandbox.isAdmin,
|
|
calls,
|
|
events,
|
|
warnings,
|
|
nextArgs,
|
|
next,
|
|
tombstoneSids,
|
|
revokedIds,
|
|
revokedHints,
|
|
auditMethods,
|
|
persistedRecords,
|
|
timeline,
|
|
hooks,
|
|
req,
|
|
PARSED,
|
|
protectedSettingsHandler,
|
|
sandbox,
|
|
};
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Harness 1b/6 — the per-request account-binding middleware over the REAL
|
|
// shared predicate + the REAL stale-account teardown + REAL auth primitives
|
|
// ---------------------------------------------------------------------------
|
|
|
|
function buildBindingMiddlewareHarness({ rowProvider }) {
|
|
const events = [];
|
|
const warnings = [];
|
|
const tombstones = [];
|
|
const revokedIds = [];
|
|
const revokedHints = [];
|
|
const rememberCookieClears = [];
|
|
const sandbox = {
|
|
console: { log: () => {}, warn: (...a) => warnings.push(a.map(String).join(" ")), error: () => {} },
|
|
sessionAccountBindingMismatch,
|
|
findUserByEmail: async () => rowProvider(),
|
|
revokeRememberLoginLineage: async (id, hints) => {
|
|
revokedIds.push(String(id));
|
|
revokedHints.push({ ...(hints || {}) });
|
|
events.push(`revoke:${id}`);
|
|
return true;
|
|
},
|
|
revokeRememberLoginsForUser: async () => { events.push("revokeUser"); },
|
|
writeRevokedSidTombstone: async (sid) => { tombstones.push(String(sid)); events.push(`tombstone:${sid}`); return true; },
|
|
getSessionDisplayId: (sid) => `sid:${sid}`,
|
|
removeActiveBrowserSessionCacheEntry: (sid) => { events.push(`cacheRemove:${sid}`); },
|
|
invalidateActiveBrowserSessionCache: () => { events.push("cacheInvalidate"); },
|
|
cookieSecureForRequest: () => false,
|
|
clearRememberLoginCookie: () => { rememberCookieClears.push(1); events.push("cookie:remember"); },
|
|
stripLogControlChars: (s) => String(s == null ? "" : s),
|
|
getRequestIp: () => "198.51.100.9",
|
|
app: { use: (fn) => { sandbox.__capturedMw = fn; } },
|
|
};
|
|
vm.createContext(sandbox);
|
|
vm.runInContext(AUTH_SOURCE, sandbox, { filename: "binding-auth.js" });
|
|
vm.runInContext(TEARDOWN_STALE_SOURCE, sandbox, { filename: "binding-teardown-stale.js" });
|
|
vm.runInContext(BINDING_MW_SOURCE, sandbox, { filename: "binding-mw.js" });
|
|
return {
|
|
mw: sandbox.__capturedMw,
|
|
isAuthenticated: sandbox.isAuthenticated,
|
|
isAdmin: sandbox.isAdmin,
|
|
events,
|
|
warnings,
|
|
tombstones,
|
|
revokedIds,
|
|
revokedHints,
|
|
rememberCookieClears,
|
|
};
|
|
}
|
|
|
|
// A protected request carrying a (possibly stale) persisted session record,
|
|
// with express-session-shaped destroy semantics.
|
|
function makeProtectedRequest({ record, sid, path }) {
|
|
const destroyedSids = [];
|
|
const req = {
|
|
session: { ...snapshotSession(record) },
|
|
sessionID: sid,
|
|
path,
|
|
headers: {},
|
|
};
|
|
req.session.destroy = (cb) => {
|
|
destroyedSids.push(String(req.sessionID));
|
|
delete req.session;
|
|
cb(null);
|
|
};
|
|
return { req, destroyedSids };
|
|
}
|
|
|
|
function makeRecordingRes() {
|
|
const res = { statusCode: 0, body: null, redirectTarget: null, cookieClears: [] };
|
|
res.status = (code) => { res.statusCode = code; return res; };
|
|
res.json = (body) => { res.body = body; return res; };
|
|
res.redirect = (...a) => { res.redirectTarget = a[a.length - 1]; return res; };
|
|
res.clearCookie = (name) => { res.cookieClears.push(String(name)); return res; };
|
|
res.setHeader = () => res;
|
|
return res;
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Harness 5 — the two-step recovery regeneration routes over the REAL
|
|
// helpers and the REAL sha256Hex
|
|
// ---------------------------------------------------------------------------
|
|
|
|
const REGEN_USER_ID = 42;
|
|
const REGEN_EMAIL = "owner@example.test";
|
|
|
|
function makeRegenRaceHarness({ rowProvider, storedJson = "[]" }) {
|
|
const calls = [];
|
|
const queries = [];
|
|
const totpVerifications = [];
|
|
const user = rowProvider();
|
|
const sandbox = {
|
|
app: { post: (...args) => calls.push(args) },
|
|
accountCredentialRateLimiter: {},
|
|
accountTotpRateLimiter: {},
|
|
findUserByEmail: async () => rowProvider(),
|
|
hasTwoFactorEnabled: REAL_HAS_TWO_FACTOR,
|
|
verifyPasswordForUser: async (u, pw) => bcryptjs.compare(String(pw), String(u?.password || "")),
|
|
sha256Hex: REAL_SHA256,
|
|
normalizeTotpCode: (raw) => {
|
|
const code = String(raw || "").replace(/\s+/g, "");
|
|
return /^\d{6}$/.test(code) ? code : "";
|
|
},
|
|
verifyTotpForUser: async (u, code) => { totpVerifications.push([u && u.id, code]); return { ok: true }; },
|
|
bcrypt: { hash: async () => "hashed-code", compare: async (pw, hash) => bcryptjs.compare(pw, hash) },
|
|
BCRYPT_ROUNDS: 4,
|
|
db: {
|
|
async query(sql, params) {
|
|
queries.push({ sql, params });
|
|
if (sql === "SELECT recovery_codes FROM users WHERE id = ? LIMIT 1") return [{ recovery_codes: storedJson }];
|
|
throw new Error(`unexpected db.query in regen race harness: ${sql}`);
|
|
},
|
|
},
|
|
RECOVERY_REGEN_AUTH_EXPIRY_MS: 5 * 60 * 1000,
|
|
RECOVERY_VERIFIED_EXPIRY_MS: 5 * 60 * 1000,
|
|
stripLogControlChars: (s) => String(s == null ? "" : s),
|
|
getRequestIp: () => "127.0.0.1",
|
|
recordActivity: (...args) => calls.push(["recordActivity", ...args]),
|
|
console: { log: () => {}, error: () => {}, warn: () => {} },
|
|
crypto,
|
|
Date, JSON, Promise, Object, String, Number, Math, Array, RegExp, Error,
|
|
};
|
|
|
|
sandbox.credentialCommitService = createCredentialCommitService({ db: sandbox.db });
|
|
const ctx = vm.createContext(sandbox);
|
|
vm.runInContext(REGEN_VERIFY_GRANT_FN, ctx, { filename: "regen-verify-grant.js" });
|
|
vm.runInContext(REGEN_CLAIM_FN, ctx, { filename: "regen-claim.js" });
|
|
vm.runInContext(REGEN_READ_FN, ctx, { filename: "regen-read.js" });
|
|
vm.runInContext(REGEN_GUARD_FN, ctx, { filename: "regen-guard.js" });
|
|
vm.runInContext(REGEN_STEP1_STATEMENT, ctx, { filename: "regen-step1.js" });
|
|
vm.runInContext(REGEN_STEP2_STATEMENT, ctx, { filename: "regen-step2.js" });
|
|
assert.strictEqual(calls.length, 2, "exactly two route registrations per harness");
|
|
const step1 = calls.find((args) => String(args[0]).includes("verify-password"))[2];
|
|
const step2 = calls.find((args) => args[0] === "/api/account/2fa/regenerate-recovery-codes")[2];
|
|
return { step1, step2, queries, totpVerifications, calls };
|
|
}
|
|
|
|
function makeRegenRes() {
|
|
const res = { statusCode: 0, body: null, headersSent: false };
|
|
res.status = (code) => { res.statusCode = code; res.headersSent = true; return res; };
|
|
res.json = (body) => { if (!res.statusCode) res.statusCode = 200; res.body = body; return res; };
|
|
return res;
|
|
}
|
|
|
|
function makeRegenReq({ body = {}, session = {} } = {}) {
|
|
return {
|
|
body,
|
|
session,
|
|
headers: {},
|
|
is: (type) => (type === "application/json" ? "application/json" : false),
|
|
};
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Harness 6 — the REAL admin 2FA-reset service behind the REAL thin adapters
|
|
// ---------------------------------------------------------------------------
|
|
|
|
const ADMIN_ACTING = { id: 7, email: "admin@example.test", admin: 1, suspended: 0, session_epoch: 9 };
|
|
|
|
function buildAdminAliasHarness({ targetRow, destroyImpl }) {
|
|
const calls = { queries: [], evictions: [], tokenActions: [], stepUps: [], activity: [], logs: [], disconnects: [] };
|
|
const deps = {
|
|
isAdmin: async () => true,
|
|
requireActionTokenOr403: async (req, res, action) => { calls.tokenActions.push(action); return true; },
|
|
findUserByEmail: async (email) => {
|
|
const rowNow = targetRow();
|
|
if (email === ADMIN_ACTING.email) return ADMIN_ACTING;
|
|
if (email === rowNow.email) return rowNow;
|
|
return null;
|
|
},
|
|
requireDestructiveActionStepUp: async (req, res, actingAdmin, subject, options) => {
|
|
calls.stepUps.push({ actingAdmin, subject, options });
|
|
return { ok: true };
|
|
},
|
|
db: {
|
|
async query(sql, params) {
|
|
calls.queries.push({ sql, params });
|
|
if (sql === ADMIN_2FA_CLEAR_SQL) {
|
|
const rowNow = targetRow();
|
|
// Id-keyed guard: only the LOADED row's id matches (a stale write
|
|
// against a replaced/deleted row would answer affectedRows 0).
|
|
if (Number(rowNow.id) !== Number(params[1])) return { affectedRows: 0 };
|
|
rowNow.secret = null;
|
|
rowNow.recovery_codes = null;
|
|
rowNow.session_epoch = params[0];
|
|
return { affectedRows: 1 };
|
|
}
|
|
throw new Error(`unexpected admin db.query: ${sql}`);
|
|
},
|
|
},
|
|
destroyBrowserSessionsForUser: destroyImpl,
|
|
disconnectSocketsForUser: (email, reason) => { calls.disconnects.push([email, reason]); return 3; },
|
|
recordActivity: (...args) => { calls.activity.push(args); },
|
|
getRequestIp: () => "127.0.0.1",
|
|
normalizeAdminTargetEmail: REAL_NORMALIZE_TARGET,
|
|
stripLogControlChars: (s) => String(s == null ? "" : s),
|
|
logger: {
|
|
log: (...args) => calls.logs.push(["log", ...args]),
|
|
error: (...args) => calls.logs.push(["error", ...args]),
|
|
warn: (...args) => calls.logs.push(["warn", ...args]),
|
|
},
|
|
};
|
|
deps.db = require("./helpers/account-transaction").attachAccountTransaction(deps.db, { actor: ADMIN_ACTING, target: targetRow() });
|
|
const service = createAdminTwoFactorResetService(deps);
|
|
const harnesses = {};
|
|
for (const [key, statement] of [["reset", ADMIN_ROUTE_RESET], ["confirm", ADMIN_ROUTE_CONFIRM]]) {
|
|
const captured = [];
|
|
const ctx = vm.createContext({
|
|
app: { post: (...args) => captured.push(args) },
|
|
sessionRevoke2faRateLimiter: { name: "sessionRevoke2faRateLimiter" },
|
|
handleAdmin2faReset: service.handleAdmin2faReset,
|
|
});
|
|
vm.runInContext(statement, ctx, { filename: `admin-adapter-${key}.js` });
|
|
assert.strictEqual(captured.length, 1, `exactly one registration for ${key}`);
|
|
harnesses[key] = captured[0][2];
|
|
}
|
|
return { handlers: harnesses, calls };
|
|
}
|
|
|
|
// Runs the arrow adapter the way Express 4 does and reports what Express 4
|
|
// would see: a settled handler (correct) or a rejected promise (the bug).
|
|
async function runAdapter(handler, req, res) {
|
|
let rejection = null;
|
|
try {
|
|
await handler(req, res);
|
|
} catch (err) {
|
|
rejection = err;
|
|
}
|
|
return { rejection };
|
|
}
|
|
|
|
function makeAdminReq() {
|
|
return {
|
|
body: { email: CANONICAL, expectedTargetId: USER_ID },
|
|
headers: { "user-agent": "test-agent" },
|
|
sessionID: "admin-sid",
|
|
session: { user: ADMIN_ACTING.email },
|
|
};
|
|
}
|
|
|
|
// Asserts the full hygiene of the simulated credential change's written SQL:
|
|
// the in-statement CAS with a fresh generation, won against the proven hash.
|
|
function assertCommittedResetCas(writer, { expectedProvenHash, previousEpoch, expectedNewHash, expectedId = USER_ID }) {
|
|
assert.strictEqual(writer.queries.length, 1, "exactly one credential write committed");
|
|
const q = writer.queries[0];
|
|
assert.strictEqual(q.sql, PASSWORD_RESET_CAS_SQL, "the concurrent writer is the pinned in-statement CAS (credential + generation in ONE statement)");
|
|
assert.strictEqual(q.params[3], expectedProvenHash, "the CAS pins the hash the writer's own pre-flight proved");
|
|
assert.strictEqual(q.params[0], expectedNewHash, "the CAS writes the new credential hash");
|
|
assert.strictEqual(q.params[2], expectedId, "the CAS is id-keyed");
|
|
assert.strictEqual(credentialGenerationMismatch(previousEpoch, q.params[1]), true, "the in-statement epoch is a NEW generation, different from the row's previous one");
|
|
assert.ok(Number.isInteger(q.params[1]) && q.params[1] >= SESSION_EPOCH_MIN && q.params[1] <= SESSION_EPOCH_MAX, "the epoch param is a CSPRNG generation in the established range");
|
|
}
|
|
|
|
// ===========================================================================
|
|
// GROUP 1 — DIRECT-LOGIN CREDENTIAL RACE
|
|
// ===========================================================================
|
|
|
|
test("1a direct-login credential race: reset commits while the staleness re-proof holds its admission slot — denied at completion (arm:stale-completion), sweep missed the unbound sid, minted remember credential revoked", async () => {
|
|
// T0: the attacker submitted the OLD password and the compare PROVED it
|
|
// against the snapshot (the preamble's admitted reservation stands).
|
|
// Between the compare and the re-read, a benign parallel rehash committed
|
|
// (REHASH_HASH, epoch unchanged — a rehash never bumps), so the re-read's
|
|
// hash differs from the proven snapshot hash and the staleness re-proof
|
|
// runs. T1: while that re-proof holds its admission-semaphore slot (the
|
|
// barrier), the victim's password reset commits — the pinned in-statement
|
|
// CAS + generation bump — and the writer's post-reset sweep runs, but the
|
|
// sweep sees an UNBOUND session and NO minted remember id (the bind has not
|
|
// started). T2: the re-proof resumes against the re-read row (same
|
|
// password, different salt) and VERIFIES — the string inequality decided
|
|
// only whether to re-prove. The bind starts; the beforeSave fresh read
|
|
// lands AFTER the reset commit and sees the new generation → the labeled
|
|
// arm:stale-completion denial; the shared binder's catch revokes the
|
|
// just-minted remember credential and tombstones the regenerated sid; the
|
|
// route settles the ONE uniform credential failure.
|
|
const snapshot = row({ password: OLD_HASH, session_epoch: EPOCH_A });
|
|
const latest = row({ password: REHASH_HASH, session_epoch: EPOCH_A });
|
|
const dbRow = row({ password: REHASH_HASH, session_epoch: EPOCH_A }); // the row after the benign rehash
|
|
|
|
const h = makeLoginRaceHarness({ user: snapshot, latestUser: latest });
|
|
const writer = createSimulatedCredentialWriter({
|
|
row: dbRow,
|
|
timeline: h.timeline,
|
|
onSweep: () => ({
|
|
sid: String(h.req.sessionID || ""),
|
|
boundUser: h.req.session?.user ?? null,
|
|
rememberId: h.req.session?.rememberLoginId ?? null,
|
|
rememberMintedYet: h.sandbox.__rememberMints.length,
|
|
authenticatedRecordInStore: h.persistedRecords.some((p) => p.sid === String(h.req.sessionID)),
|
|
}),
|
|
});
|
|
let committed = null;
|
|
h.hooks.admission = async () => {
|
|
committed = await writer.commitCredentialChange({ newHash: CHANGED_HASH });
|
|
// The reset is live on the row from here on: the beforeSave fresh read
|
|
// (the LATER lookup) consumes the post-reset row.
|
|
h.overrideLookups.push({ id: USER_ID, email: CANONICAL, password: CHANGED_HASH, secret: null, totpSealedError: false, suspended: false, session_epoch: committed.newEpoch });
|
|
};
|
|
|
|
await runLoginRaceHarness({ sandbox: h.sandbox, user: snapshot, latestUser: latest });
|
|
|
|
// The interleaving landed as designed: the sweep ran inside the paused
|
|
// re-proof, before the bind minted anything.
|
|
assert.ok(committed && committed.committed, "the concurrent reset committed (CAS won)");
|
|
assertCommittedResetCas(writer, { expectedProvenHash: REHASH_HASH, previousEpoch: EPOCH_A, expectedNewHash: CHANGED_HASH });
|
|
const sweepObservation = writer.sweeps[0].observation;
|
|
assert.strictEqual(sweepObservation.boundUser, null, "at sweep time the session carried NO bound identity — the sweep cannot see this login");
|
|
assert.strictEqual(sweepObservation.rememberId, null, "at sweep time NO remember id was minted — the sweep cannot revoke it");
|
|
assert.strictEqual(sweepObservation.rememberMintedYet, 0, "the remember mint happens strictly after the sweep");
|
|
assert.strictEqual(sweepObservation.authenticatedRecordInStore, false, "no authenticated record was in the store at sweep time");
|
|
assert.ok(h.timeline.indexOf("sweep") < h.timeline.indexOf("remember-mint"), "ordering is load-bearing: sweep → (bind) → remember mint — the change-time sweep misses the unbound sid and the unminted credential");
|
|
|
|
// Wire outcome: the ONE uniform credential failure, settled at completion.
|
|
assert.strictEqual(h.sandbox.__captures.length, 1, "exactly one response");
|
|
assert.strictEqual(h.sandbox.__captures[0].status, 400, "the uniform failure status");
|
|
assert.strictEqual(h.sandbox.__captures[0].message, "Invalid credentials", "byte-identical unknown-email body string");
|
|
assert.deepStrictEqual(h.sandbox.__captures[0].headers, {}, "no Retry-After on the uniform failure");
|
|
assert.strictEqual(h.sandbox.__failureAudits.length, 1, "the failed-login audit fired");
|
|
assert.strictEqual(h.sandbox.__failureAudits[0].reason, "arm:stale-completion", "the labeled completion denial settles as the uniform failure");
|
|
assert.strictEqual(h.sandbox.__captchaArms.length, 1, "the uniform failure arms the captcha like every other credential failure");
|
|
assert.strictEqual(h.sandbox.__sendOks.length, 0, "no success response");
|
|
assert.strictEqual(h.sandbox.__audits.length, 0, "no durable success row");
|
|
assert.strictEqual(h.sandbox.__refunds.length, 0, "FINALIZED, not refunded — the failure record stands");
|
|
assert.strictEqual(h.sandbox.loginCredentialReservation, null, "the outstanding reservation was finalized");
|
|
|
|
// Hygiene: the re-proof verified (same password), the bind STARTED, and the
|
|
// completion denial revoked every artifact the binder had minted.
|
|
assert.deepStrictEqual(h.sandbox.__compares, [REHASH_HASH], "exactly one compare — the paused staleness re-proof against the re-read row's hash (the benign rehash premise)");
|
|
assert.deepStrictEqual(h.sandbox.__totpVerifications, [], "no TOTP verification consumed anywhere in the region");
|
|
assert.strictEqual(h.sandbox.__binds.length, 1, "the bind call ran (the denial is at completion, not pre-bind)");
|
|
assert.deepStrictEqual(h.timeline.filter((e) => e === "regenerate"), ["regenerate"], "the binder reached the regenerate");
|
|
assert.strictEqual(h.timeline.includes("save"), false, "the bounded save never ran — no authenticated record persisted");
|
|
assert.deepStrictEqual(h.persistedRecords, [], "the store never received an authenticated record");
|
|
assert.deepStrictEqual(h.sandbox.__rememberMints.length, 1, "the remember credential was minted before the hook ran (the hygiene has something to revoke)");
|
|
assert.deepStrictEqual(h.sandbox.__rememberRevokes, ["rid-login"], "the just-minted remember credential was revoked by the binder's catch");
|
|
assert.strictEqual(h.sandbox.__clearedCookies.length, 1, "the remember cookie was cleared off the failed response");
|
|
assert.deepStrictEqual(h.sandbox.__tombstones, ["login-sid-2"], "the regenerated sid was tombstoned so a late store write cannot commit the authenticated record");
|
|
// The binder DID bind the identity onto the live object before the hook
|
|
// rejected (the house completion-denial shape): the residue dies with the
|
|
// request because the save never ran and the sid is tombstoned — the store
|
|
// surface is what the hygiene protects, and it received nothing.
|
|
assert.strictEqual(h.sandbox.req.session.user, CANONICAL, "the live object's residue is bound-but-unsaved (the denial is at completion, not pre-bind)");
|
|
});
|
|
|
|
test("1b direct-login credential race, sub-window: the beforeSave re-read lands BEFORE the reset commits and the save lands AFTER — the stale-epoch record persists past the sweep AND the account-binding middleware denies it on the next protected request (401 teardown)", async () => {
|
|
// The pre-bind gates all passed (snapshot === re-read, epoch 1). The
|
|
// binder's beforeSave fresh read ran and saw the still-current row; the
|
|
// reset committed INSIDE the save barrier — after the fresh read, before
|
|
// the save resolved. The save proceeded: a session record bound to the
|
|
// STALE epoch now exists in the store, and the sweep (which ran mid-save,
|
|
// against a record not yet in the store) missed it. This is the window the
|
|
// pre-bind re-read cannot cover — the defense-in-depth claim is the
|
|
// per-request account-binding middleware (the REAL
|
|
// sessionAccountBindingMismatch + the REAL teardownStaleAccountSession):
|
|
// the stale record must be DENIED on its next protected request.
|
|
const shared = row({ password: OLD_HASH, session_epoch: EPOCH_A });
|
|
const dbRow = row({ password: OLD_HASH, session_epoch: EPOCH_A });
|
|
|
|
const h = makeLoginRaceHarness({ user: shared, latestUser: shared });
|
|
const writer = createSimulatedCredentialWriter({
|
|
row: dbRow,
|
|
timeline: h.timeline,
|
|
onSweep: () => ({
|
|
sid: String(h.req.sessionID || ""),
|
|
boundUser: h.req.session?.user ?? null,
|
|
rememberId: h.req.session?.rememberLoginId ?? null,
|
|
rememberMintedYet: h.sandbox.__rememberMints.length,
|
|
authenticatedRecordInStore: h.persistedRecords.some((p) => p.sid === String(h.req.sessionID)),
|
|
}),
|
|
});
|
|
let committed = null;
|
|
h.hooks.save = async () => {
|
|
committed = await writer.commitCredentialChange({ newHash: CHANGED_HASH });
|
|
};
|
|
|
|
await runLoginRaceHarness({ sandbox: h.sandbox, user: shared, latestUser: shared });
|
|
|
|
// The login SUCCEEDED — the sub-window hole at the login layer is real.
|
|
assert.ok(committed && committed.committed, "the concurrent reset committed inside the save barrier");
|
|
assertCommittedResetCas(writer, { expectedProvenHash: OLD_HASH, previousEpoch: EPOCH_A, expectedNewHash: CHANGED_HASH });
|
|
assert.strictEqual(h.sandbox.__sendOks.length, 1, "the success response answered (the sub-window: every pre-bind gate passed)");
|
|
assert.strictEqual(h.sandbox.__audits.length, 1, "one durable success row");
|
|
assert.strictEqual(h.sandbox.__refunds.length, 1, "the success refunded the reservation");
|
|
assert.deepStrictEqual(h.sandbox.__compares, [], "no re-proof compares — the hash never moved before the gates");
|
|
|
|
const sweepObservation = writer.sweeps[0].observation;
|
|
assert.strictEqual(sweepObservation.boundUser, CANONICAL, "at sweep time the session WAS bound (post-regenerate)");
|
|
assert.strictEqual(sweepObservation.authenticatedRecordInStore, false, "but the record was NOT yet in the store — the sweep's destroy had nothing to kill");
|
|
assert.ok(h.timeline.indexOf("sweep") < h.timeline.indexOf("save-commit"), "ordering: sweep → save-commit — the store write lands AFTER the sweep, resurrecting the stale record");
|
|
|
|
// The stale record EXISTS: bound to the pre-reset epoch while the row has
|
|
// moved to the new generation.
|
|
assert.strictEqual(h.persistedRecords.length, 1, "the save committed exactly one record");
|
|
const staleRecord = h.persistedRecords[0].record;
|
|
assert.strictEqual(staleRecord.user, CANONICAL, "the persisted record carries the identity");
|
|
assert.strictEqual(staleRecord.accountEpoch, EPOCH_A, "the persisted record carries the STALE epoch (bound before the reset committed)");
|
|
assert.strictEqual(staleRecord.rememberLoginId, "rid-login", "the persisted record carries the minted remember credential");
|
|
assert.strictEqual(credentialGenerationMismatch(staleRecord.accountEpoch, dbRow.session_epoch), true, "precondition: the persisted record's epoch no longer matches the live row's generation");
|
|
|
|
// THE DEFENSE-IN-DEPTH CLAIM, PROVEN: the per-request account-binding
|
|
// middleware (REAL predicate + REAL teardown) denies the stale record on
|
|
// its next protected request.
|
|
const b = buildBindingMiddlewareHarness({ rowProvider: () => dbRow });
|
|
const { req: req2, destroyedSids } = makeProtectedRequest({ record: staleRecord, sid: h.persistedRecords[0].sid, path: "/api/panel/state" });
|
|
const res2 = makeRecordingRes();
|
|
let nextCalls = 0;
|
|
const next2 = () => { nextCalls += 1; };
|
|
await b.mw(req2, res2, next2);
|
|
|
|
assert.strictEqual(res2.statusCode, 401, "the stale record is denied with the revoked-sid-gate status");
|
|
assert.deepStrictEqual(JSON.parse(JSON.stringify(res2.body)), { error: "not authenticated" }, "the teardown's respond:true body for /api/ paths (JSON round-trip: the body was minted in the vm realm)");
|
|
assert.strictEqual(nextCalls, 0, "the middleware answered itself — no downstream handler ran");
|
|
assert.deepStrictEqual(b.tombstones, [h.persistedRecords[0].sid], "the stale session's sid was tombstoned (teardownStaleAccountSession ordering)");
|
|
assert.deepStrictEqual(b.revokedIds, ["rid-login"], "the stale record's remember credential was lineage-revoked");
|
|
assert.strictEqual(b.revokedHints.length, 1, "the lineage revoke fired once");
|
|
assert.deepStrictEqual(destroyedSids, [h.persistedRecords[0].sid], "the stale session record was destroyed");
|
|
assert.deepStrictEqual(res2.cookieClears, ["adpanel.sid"], "the session cookie was cleared");
|
|
assert.strictEqual(b.rememberCookieClears.length, 1, "the remember cookie was cleared");
|
|
assert.strictEqual(req2.currentUser, null, "the currentUser fast path is nulled by the teardown");
|
|
assert.strictEqual(req2.session, undefined, "the stale record is gone from the request");
|
|
assert.strictEqual(await b.isAuthenticated(req2), false, "downstream authorization is denied for the stale record");
|
|
});
|
|
|
|
// ===========================================================================
|
|
// GROUP 2 — CAPTCHA-COMPLETION CREDENTIAL RACE
|
|
// ===========================================================================
|
|
|
|
test("2 captcha-completion credential race: reset commits inside the binder's regenerate window (after the fingerprint check) — 401 login-expired, pending cleared, minted remember revoked, both sids tombstoned, no authenticated record saved", async () => {
|
|
// T0: the challenge-time proof minted the pending record (epoch 5); every
|
|
// pre-bind completion check passed (row re-resolved, fingerprint verified,
|
|
// 2FA-consistent, generation comparable and equal). T1: INSIDE the binder's
|
|
// regenerate — the completion window the pre-bind read cannot see — the
|
|
// password reset commits (in-statement CAS + bump) and its sweep runs; the
|
|
// sweep sees the regenerated sid UNBOUND and NO minted remember id. T2:
|
|
// the beforeSave fresh read sees the new generation and rejects through
|
|
// the labeled error; the route settles the existing login-expired
|
|
// envelope; the binder's catch has already revoked the minted credential
|
|
// and tombstoned both sids.
|
|
const challengeRow = row({ session_epoch: 5 });
|
|
const dbRow = row({ session_epoch: 5 });
|
|
|
|
const h = makeCompletionRaceHarness({ challengeRow, liveQueue: [row({ session_epoch: 5 })] });
|
|
const writer = createSimulatedCredentialWriter({
|
|
row: dbRow,
|
|
timeline: h.timeline,
|
|
onSweep: () => ({
|
|
sid: String(h.sandbox.req.sessionID || ""),
|
|
boundUser: h.sandbox.req.session?.user ?? null,
|
|
rememberId: h.sandbox.req.session?.rememberLoginId ?? null,
|
|
rememberMintedYet: h.sandbox.__rememberMints.length,
|
|
authenticatedRecordInStore: h.persistedRecords.some((p) => p.sid === String(h.sandbox.req.sessionID)),
|
|
}),
|
|
});
|
|
let committed = null;
|
|
h.hooks.regenerate = async () => {
|
|
committed = await writer.commitCredentialChange({ newHash: CHANGED_HASH });
|
|
h.overrideLookups.push({ id: USER_ID, email: CANONICAL, password: CHANGED_HASH, secret: null, totpSealedError: false, suspended: false, session_epoch: committed.newEpoch });
|
|
};
|
|
|
|
const result = await runCompletionRace(h);
|
|
|
|
assert.ok(committed && committed.committed, "the concurrent reset committed inside the regenerate window");
|
|
assertCommittedResetCas(writer, { expectedProvenHash: OLD_HASH, previousEpoch: 5, expectedNewHash: CHANGED_HASH });
|
|
const sweepObservation = writer.sweeps[0].observation;
|
|
assert.strictEqual(sweepObservation.boundUser, null, "at sweep time the regenerated session carried NO bound identity");
|
|
assert.strictEqual(sweepObservation.rememberId, null, "at sweep time NO remember id was minted");
|
|
assert.ok(h.timeline.indexOf("sweep") < h.timeline.indexOf("remember-mint"), "ordering: sweep → remember mint — the sweep missed the unminted credential");
|
|
|
|
// Wire outcome: the existing login-expired envelope, unchanged.
|
|
assert.strictEqual(result.ok, false, "the completion is denied");
|
|
assert.strictEqual(result.status, 401, "the existing login-expired status");
|
|
assert.strictEqual(result.error, "login-expired", "the existing login-expired envelope");
|
|
|
|
// Hygiene.
|
|
assert.strictEqual(h.sandbox.req.session.pendingCaptchaLogin, undefined, "the pending record is cleared (regenerated away; afterIdentityBinding also cleared it)");
|
|
assert.strictEqual(h.sandbox.req.session.captchaSolved, undefined, "the solved-captcha flag went with the regeneration");
|
|
assert.ok(h.binderEvents.includes("regenerate"), "the binder reached the regenerate");
|
|
assert.ok(!h.binderEvents.includes("save"), "the bounded save never ran — no authenticated record persisted");
|
|
assert.deepStrictEqual(h.persistedRecords, [], "the store never received an authenticated record");
|
|
assert.strictEqual(h.sandbox.__rememberMints.length, 1, "the remember credential was minted before the hook ran");
|
|
assert.deepStrictEqual(h.sandbox.__rememberRevokes, ["rid-captcha"], "the just-minted remember credential was revoked by the binder's catch");
|
|
assert.strictEqual(h.sandbox.__cookieClears.length, 1, "the remember cookie was cleared off the failed response");
|
|
assert.deepStrictEqual(h.sandbox.__tombstones, ["captcha-sid-1", "captcha-sid-2"], "the pending-state pre-regeneration sid AND the regenerated sid were tombstoned");
|
|
assert.strictEqual(h.events.includes("audit:captcha-completion"), false, "no durable success row");
|
|
assert.strictEqual(h.events.includes("totpReset"), false, "the TOTP budget reset never ran (the login did not complete)");
|
|
assert.strictEqual(h.events.some((e) => String(e).startsWith("gateClear:")), false, "the gate clear never ran");
|
|
});
|
|
|
|
// ===========================================================================
|
|
// GROUP 3 — MFA RACES (+ the benign rehash controls)
|
|
// ===========================================================================
|
|
|
|
test("3a MFA enabled between the login's initial lookup and the re-read — arm:stale-mfa denies with zero TOTP verifications consumed for the new secret", async () => {
|
|
// The snapshot row (proved by the compare) has NO 2FA; the re-read row
|
|
// carries a freshly enrolled seed (the enrollment's in-statement CAS bumped
|
|
// the generation too). The MFA gate denies before the provedEpoch capture:
|
|
// a proof minted while MFA was off must never bind a session on an
|
|
// MFA-enabled row — and the TOTP verification machinery is never reached
|
|
// for the new secret.
|
|
const snapshot = row({ secret: null, session_epoch: EPOCH_A });
|
|
const latest = row({ secret: "JBSWY3DPEHPK3PXP", session_epoch: 2 });
|
|
|
|
const h = makeLoginRaceHarness({ user: snapshot, latestUser: latest });
|
|
await runLoginRaceHarness({ sandbox: h.sandbox, user: snapshot, latestUser: latest });
|
|
|
|
assert.strictEqual(h.sandbox.__captures.length, 1, "exactly one response");
|
|
assert.strictEqual(h.sandbox.__captures[0].status, 400, "the uniform failure status");
|
|
assert.strictEqual(h.sandbox.__captures[0].message, "Invalid credentials", "byte-identical uniform body — no disclosure of which leg denied");
|
|
assert.strictEqual(h.sandbox.__failureAudits[0].reason, "arm:stale-mfa", "the MFA-staleness denial settles as the uniform failure");
|
|
assert.deepStrictEqual(h.sandbox.__totpVerifications, [], "zero TOTP verifications consumed for the new secret — the proof never reaches the new factor");
|
|
assert.deepStrictEqual(h.sandbox.__compares, [], "no re-proof compare — the hash never moved; the MFA gate is the denier");
|
|
assert.strictEqual(h.sandbox.__binds.length, 0, "NO session bind");
|
|
assert.deepStrictEqual(h.sandbox.__binderEvents, [], "the binder was never reached");
|
|
assert.strictEqual(h.sandbox.req.session.user, undefined, "no identity bound");
|
|
assert.strictEqual(h.sandbox.__sendOks.length, 0, "no success response");
|
|
assert.strictEqual(h.sandbox.__audits.length, 0, "no durable success row");
|
|
assert.strictEqual(h.sandbox.__refunds.length, 0, "FINALIZED, not refunded — the failure stands");
|
|
assert.strictEqual(h.sandbox.loginCredentialReservation, null, "the reservation was finalized");
|
|
assert.deepStrictEqual(h.sandbox.__tombstones, [], "nothing minted, nothing tombstoned");
|
|
});
|
|
|
|
test("3b TOTP seed rotated after the old-factor TOTP proof (both rows enabled, seed bytes differ) — the seed-bytes leg denies through the uniform failure", async () => {
|
|
// The TOTP proof consumed its code against the SNAPSHOT seed; a rotation
|
|
// committing before the bind must not ride the proof onto the new seed.
|
|
// Both rows are 2FA-enabled, so the boolean leg passes and the SEED BYTES
|
|
// leg is the denier (the rotation's in-statement CAS bumped the generation
|
|
// too — either leg denies; the uniform failure discloses neither).
|
|
const snapshot = row({ secret: "SEEDOLDSEEDOLDSEED", session_epoch: EPOCH_A });
|
|
const latest = row({ secret: "SEEDNEWSEEDNEWSEED", session_epoch: 2 });
|
|
|
|
const h = makeLoginRaceHarness({ user: snapshot, latestUser: latest });
|
|
await runLoginRaceHarness({ sandbox: h.sandbox, user: snapshot, latestUser: latest });
|
|
|
|
assert.strictEqual(h.sandbox.__captures.length, 1, "exactly one response");
|
|
assert.strictEqual(h.sandbox.__captures[0].status, 400, "the uniform failure status");
|
|
assert.strictEqual(h.sandbox.__captures[0].message, "Invalid credentials", "byte-identical uniform body");
|
|
assert.strictEqual(h.sandbox.__failureAudits[0].reason, "arm:stale-mfa", "the seed-rotation denial settles as the uniform failure");
|
|
assert.deepStrictEqual(h.sandbox.__totpVerifications, [], "no verification consumed against the rotated seed");
|
|
assert.strictEqual(h.sandbox.__binds.length, 0, "NO session bind");
|
|
assert.strictEqual(h.sandbox.__sendOks.length, 0, "no success response");
|
|
assert.strictEqual(h.sandbox.__refunds.length, 0, "FINALIZED, not refunded");
|
|
assert.strictEqual(h.sandbox.req.session.user, undefined, "no identity bound");
|
|
});
|
|
|
|
test("3c MFA changed inside the binder window — the beforeSave seed leg denies with the full save-failure hygiene (no save, remember revoked, sid tombstoned)", async () => {
|
|
// Every pre-bind gate passed (snapshot === re-read, seed SEED-A, epoch 1).
|
|
// T1: INSIDE the binder's regenerate, the seed rotates to SEED-B (a change
|
|
// whose generation leg is left uncomparable here — legacy posture — so the
|
|
// SEED-BYTES leg is the isolated denier). T2: the beforeSave fresh read
|
|
// sees the new seed and rejects; the binder's catch revokes + tombstones.
|
|
const shared = row({ secret: "SEED-A-SEED-A", session_epoch: EPOCH_A });
|
|
|
|
const h = makeLoginRaceHarness({ user: shared, latestUser: shared });
|
|
h.hooks.regenerate = async () => {
|
|
h.overrideLookups.push({ id: USER_ID, email: CANONICAL, password: OLD_HASH, secret: "SEED-B-SEED-B", totpSealedError: false, suspended: false, session_epoch: EPOCH_A });
|
|
};
|
|
|
|
await runLoginRaceHarness({ sandbox: h.sandbox, user: shared, latestUser: shared });
|
|
|
|
assert.strictEqual(h.sandbox.__captures.length, 1, "exactly one response");
|
|
assert.strictEqual(h.sandbox.__captures[0].status, 400, "the uniform failure status");
|
|
assert.strictEqual(h.sandbox.__captures[0].message, "Invalid credentials", "byte-identical uniform body");
|
|
assert.strictEqual(h.sandbox.__failureAudits[0].reason, "arm:stale-completion", "the in-window MFA change denies at completion via the labeled error");
|
|
assert.deepStrictEqual(h.sandbox.__compares, [], "no re-proof compare — the hash never moved; the seed leg is the denier");
|
|
assert.deepStrictEqual(h.timeline.filter((e) => e === "regenerate"), ["regenerate"], "the binder reached the regenerate");
|
|
assert.strictEqual(h.timeline.includes("save"), false, "the bounded save never ran");
|
|
assert.deepStrictEqual(h.persistedRecords, [], "no authenticated record persisted");
|
|
assert.deepStrictEqual(h.sandbox.__rememberRevokes, ["rid-login"], "the minted remember credential was revoked");
|
|
assert.strictEqual(h.sandbox.__clearedCookies.length, 1, "the remember cookie was cleared");
|
|
assert.deepStrictEqual(h.sandbox.__tombstones, ["login-sid-2"], "the regenerated sid was tombstoned");
|
|
assert.strictEqual(h.sandbox.__sendOks.length, 0, "no success response");
|
|
assert.strictEqual(h.sandbox.__audits.length, 0, "no durable success row");
|
|
});
|
|
|
|
test("3-control benign bcrypt rehash inside the paused staleness re-proof window — the same password is still admitted end-to-end (re-proof + beforeSave re-proof both verify)", async () => {
|
|
// The adversarial twins above must not have been built by rigging the
|
|
// windows shut: a benign cost-heal rehash of the SAME password committing
|
|
// inside the paused re-proof (and then again before the beforeSave read)
|
|
// verifies through BOTH re-proofs and the login completes — the string
|
|
// inequality decides only WHETHER to re-prove, never the verdict, and the
|
|
// epoch-free rehash never trips the generation leg.
|
|
const snapshot = row({ password: OLD_HASH, session_epoch: EPOCH_A });
|
|
const latest = row({ password: REHASH_HASH, session_epoch: EPOCH_A });
|
|
const dbRow = row({ password: REHASH_HASH, session_epoch: EPOCH_A });
|
|
|
|
const h = makeLoginRaceHarness({ user: snapshot, latestUser: latest });
|
|
const writer = createSimulatedCredentialWriter({ row: dbRow, timeline: h.timeline });
|
|
h.hooks.admission = async () => {
|
|
// Another login's cost heal rehashes the SAME password (new salt, epoch
|
|
// stays — a rehash is epoch-free by the atomic-guard pin).
|
|
const heal = await writer.commitEpochFreeRehash({ newHash: REHASH_HASH_2 });
|
|
assert.ok(heal.committed, "the benign rehash committed");
|
|
h.overrideLookups.push({ id: USER_ID, email: CANONICAL, password: REHASH_HASH_2, secret: null, totpSealedError: false, suspended: false, session_epoch: EPOCH_A });
|
|
};
|
|
|
|
await runLoginRaceHarness({ sandbox: h.sandbox, user: snapshot, latestUser: latest });
|
|
|
|
assert.deepStrictEqual(h.sandbox.__compares, [REHASH_HASH, REHASH_HASH_2], "exactly two compares: the paused re-proof (against the re-read row) and the beforeSave re-proof (against the fresh rehashed row) — both the SAME password");
|
|
assert.strictEqual(h.sandbox.__captures.length, 0, "no failure response — a rehash of the same password never denies");
|
|
assert.strictEqual(h.sandbox.__sendOks.length, 1, "the success response answers");
|
|
assert.strictEqual(h.sandbox.__audits.length, 1, "one durable success row");
|
|
assert.strictEqual(h.sandbox.__refunds.length, 1, "the success refunds the reservation");
|
|
assert.deepStrictEqual(h.sandbox.__tombstones, [], "a bare pre-auth login sid takes the normal untombstoned path");
|
|
assert.deepStrictEqual(h.sandbox.__rememberRevokes, [], "no credential revoked on success");
|
|
assert.strictEqual(h.persistedRecords.length, 1, "the authenticated record persisted");
|
|
assert.strictEqual(h.persistedRecords[0].record.accountEpoch, EPOCH_A, "the epoch-free rehash never moved the generation");
|
|
assert.deepStrictEqual(writer.queries.map((q) => q.sql), [LOGIN_REHASH_CAS_SQL], "the benign writer is the epoch-free rehash CAS");
|
|
assert.ok(writer.queries.every((q) => !q.sql.includes("session_epoch")), "the rehash write carries NO epoch bump (a rehash is not a credential change)");
|
|
});
|
|
|
|
test("3-control benign bcrypt rehash inside the binder regenerate window — the same password is still admitted (the completion and restore windows deny a moved hash fail-closed by design: no re-proof exists there)", async () => {
|
|
const shared = row({ password: OLD_HASH, session_epoch: EPOCH_A });
|
|
|
|
const h = makeLoginRaceHarness({ user: shared, latestUser: shared });
|
|
h.hooks.regenerate = async () => {
|
|
h.overrideLookups.push({ id: USER_ID, email: CANONICAL, password: REHASH_HASH, secret: null, totpSealedError: false, suspended: false, session_epoch: EPOCH_A });
|
|
};
|
|
|
|
await runLoginRaceHarness({ sandbox: h.sandbox, user: shared, latestUser: shared });
|
|
|
|
assert.deepStrictEqual(h.sandbox.__compares, [REHASH_HASH], "exactly one compare — the beforeSave hook's bounded re-proof against the fresh rehashed hash");
|
|
assert.strictEqual(h.sandbox.__captures.length, 0, "no failure response");
|
|
assert.strictEqual(h.sandbox.__sendOks.length, 1, "the success response answers");
|
|
assert.strictEqual(h.sandbox.__audits.length, 1, "one durable success row");
|
|
assert.strictEqual(h.sandbox.__refunds.length, 1, "the success refunds the reservation");
|
|
assert.deepStrictEqual(h.sandbox.__tombstones, [], "no tombstone on success");
|
|
assert.deepStrictEqual(h.sandbox.__rememberRevokes, [], "no credential revoked on success");
|
|
assert.strictEqual(h.sandbox.req.session.user, CANONICAL, "the session is bound");
|
|
assert.strictEqual(h.timeline.includes("save-commit"), true, "the bounded save ran");
|
|
});
|
|
|
|
// ===========================================================================
|
|
// GROUP 4 — RESTORE RACES
|
|
// ===========================================================================
|
|
|
|
test("restore completion: a credential reset during save cannot authorize the same protected admin request", async () => {
|
|
const snapshotRow = row({ admin: true, session_epoch: 3 });
|
|
const freshRow = row({ admin: true, session_epoch: 3 });
|
|
const dbRow = row({ admin: true, session_epoch: 3 });
|
|
const harness = makeRestoreRaceHarness({ lookupQueue: [snapshotRow, freshRow, dbRow] });
|
|
harness.req.path = "/api/settings/security";
|
|
const writer = createSimulatedCredentialWriter({
|
|
row: dbRow, timeline: harness.timeline,
|
|
onSweep: () => ({
|
|
authenticatedRecordInStore: harness.persistedRecords.some((entry) => entry.sid === harness.req.sessionID),
|
|
}),
|
|
});
|
|
harness.hooks.save = async () => { await writer.commitCredentialChange({ newHash: CHANGED_HASH }); };
|
|
await harness.mw(harness.req, {}, harness.next);
|
|
assert.equal(writer.sweeps[0].observation.authenticatedRecordInStore, false);
|
|
assertCommittedResetCas(writer, { expectedProvenHash: OLD_HASH, previousEpoch: 3, expectedNewHash: CHANGED_HASH });
|
|
const settingsResponse = makeRecordingRes();
|
|
settingsResponse.set = () => settingsResponse;
|
|
await harness.protectedSettingsHandler(harness.req, settingsResponse);
|
|
assert.equal(settingsResponse.statusCode, 403, "the real settings route must refuse the stale restored request");
|
|
assert.equal(settingsResponse.body.actionTokens, undefined);
|
|
|
|
const binding = buildBindingMiddlewareHarness({ rowProvider: () => ({ ...dbRow }) });
|
|
const response = makeRecordingRes();
|
|
let protectedHandlerAdmitted = false;
|
|
let protectedMutations = 0;
|
|
await binding.mw(harness.req, response, () => { protectedHandlerAdmitted = true; });
|
|
if (protectedHandlerAdmitted && await binding.isAdmin(harness.req)) protectedMutations += 1;
|
|
assert.equal(protectedMutations, 0, "a restore based on the pre-reset credential must not authorize an admin mutation");
|
|
assert.equal(await harness.isAuthenticated(harness.req), false);
|
|
assert.equal(harness.auditMethods.length, 0, "stale completion must not record a successful restore");
|
|
});
|
|
|
|
test("restore completion: post-save account changes and revocation clear current-request authority", async () => {
|
|
for (const mode of ["mfa", "suspended", "replacement", "revoked", "lookup-error"]) {
|
|
const before = row({ admin: true, session_epoch: 3 });
|
|
const fresh = { ...before };
|
|
const harness = makeRestoreRaceHarness({ lookupQueue: [before, { ...before }, fresh] });
|
|
let revoked = false;
|
|
harness.sandbox.isSessionSidRevoked = async () => revoked;
|
|
if (mode === "lookup-error") {
|
|
let lookupCount = 0;
|
|
harness.sandbox.findUserById = async () => {
|
|
if (++lookupCount === 3) throw new Error("synthetic completion lookup failure");
|
|
return before;
|
|
};
|
|
}
|
|
harness.hooks.save = async () => {
|
|
if (mode === "mfa") fresh.secret = "rotated-seed";
|
|
if (mode === "suspended") fresh.suspended = true;
|
|
if (mode === "replacement") fresh.id = USER_ID + 1;
|
|
if (mode === "revoked") revoked = true;
|
|
};
|
|
await harness.mw(harness.req, {}, harness.next);
|
|
assert.equal(await harness.isAuthenticated(harness.req), false, mode);
|
|
assert.equal(await harness.isAdmin(harness.req), false, mode);
|
|
assert.equal(harness.req.currentUser, null, mode);
|
|
assert.deepEqual(harness.revokedIds, ["rotated-remember-id-3"], mode);
|
|
assert.deepEqual(harness.tombstoneSids, ["regenerated-sid-2"], mode);
|
|
assert.equal(harness.auditMethods.length, 0, mode);
|
|
assert.equal(harness.calls.next, 1, mode);
|
|
}
|
|
});
|
|
|
|
test("4a restore race: a credential change and revert invalidate both the saved-login fingerprint and epoch, with no identity bind", async () => {
|
|
const snapshotRow = row({ password: OLD_HASH, session_epoch: 3 });
|
|
const dbRow = row({ password: OLD_HASH, session_epoch: 3 });
|
|
const writer = createSimulatedCredentialWriter({ row: dbRow, timeline: [] });
|
|
const change = await writer.commitCredentialChange({ newHash: CHANGED_HASH });
|
|
const revert = await writer.commitCredentialChange({ newHash: OLD_HASH });
|
|
assert.ok(change.committed && revert.committed, "precondition: the change and its revert both committed");
|
|
const freshRow = { ...dbRow }; // what the staleness re-read returns (OLD_HASH bytes, a fresh post-revert generation)
|
|
|
|
assert.notStrictEqual(REAL_GET_FP(snapshotRow), REAL_GET_FP(freshRow), "reverting credential bytes cannot restore the old saved-login fingerprint");
|
|
assert.strictEqual(credentialGenerationMismatch(3, freshRow.session_epoch), true, "precondition: the generation moved (3 → revert's fresh generation)");
|
|
|
|
const h = makeRestoreRaceHarness({ lookupQueue: [snapshotRow, freshRow] });
|
|
await h.mw(h.req, {}, h.next);
|
|
|
|
assert.strictEqual(h.calls.lookups, 2, "exactly two lookups: the restore-start read and the staleness re-read");
|
|
assert.deepStrictEqual(
|
|
h.events,
|
|
["log:remember-restore attempt", "regenerate", "rotate", "clearState", "clearCookie", "next"],
|
|
"the CAS rotated, then the changed generation failed the restore closed: clear state → clear cookie — no bind, no freshness mark, no save, no audit"
|
|
);
|
|
assert.strictEqual(h.req.session?.user, undefined, "NO identity bound to the pre-change generation");
|
|
assert.strictEqual(h.req.session?.accountEpoch, undefined, "no epoch binding either");
|
|
assert.strictEqual(h.calls.markFresh, 0, "no freshness markers — the restore never authenticated");
|
|
assert.strictEqual(h.auditMethods.length, 0, "no durable audit row");
|
|
assert.deepStrictEqual(h.tombstoneSids, [], "a bare pre-auth sid takes the normal untombstoned path");
|
|
assert.strictEqual(h.persistedRecords.length, 0, "the bounded save never ran");
|
|
assert.strictEqual(await h.isAuthenticated(h.req), false, "the request continues unauthenticated");
|
|
assert.strictEqual(h.calls.next, 1, "the middleware continued exactly once");
|
|
});
|
|
|
|
test("4b restore race: the bounded save fails while a concurrent password reset commits — the teardown's captured targeting still revokes the rotated lineage and the request deauthorizes", async () => {
|
|
// Every restore leg passed and the identity bound; the bounded save is in
|
|
// flight when the password reset commits (in-statement CAS + bump + sweep
|
|
// — the sweep sees the regenerated sid bound but the store record NOT yet
|
|
// written). The save then FAILS. The middleware's catch delegates to the
|
|
// ONE failure teardown: the targeting (rotated remember id, email, account
|
|
// id, sid) was captured BEFORE any clearing, so the lineage revoke aims at
|
|
// exactly the credential that crossed the wire — regardless of the
|
|
// concurrent row mutation — and the request continues ANONYMOUS.
|
|
const snapshotRow = row({ password: OLD_HASH, session_epoch: 3 });
|
|
const freshRow = row({ password: OLD_HASH, session_epoch: 3 });
|
|
const dbRow = row({ password: OLD_HASH, session_epoch: 3 });
|
|
|
|
const h = makeRestoreRaceHarness({ lookupQueue: [snapshotRow, freshRow], saveOutcome: "error" });
|
|
const writer = createSimulatedCredentialWriter({
|
|
row: dbRow,
|
|
timeline: h.timeline,
|
|
onSweep: () => ({
|
|
sid: String(h.req.sessionID || ""),
|
|
boundUser: h.req.session?.user ?? null,
|
|
rememberId: h.req.session?.rememberLoginId ?? null,
|
|
authenticatedRecordInStore: h.persistedRecords.some((p) => p.sid === String(h.req.sessionID)),
|
|
}),
|
|
});
|
|
let committed = null;
|
|
h.hooks.save = async () => {
|
|
committed = await writer.commitCredentialChange({ newHash: CHANGED_HASH });
|
|
};
|
|
|
|
await h.mw(h.req, {}, h.next);
|
|
|
|
assert.ok(committed && committed.committed, "the concurrent reset committed during the failing save");
|
|
assertCommittedResetCas(writer, { expectedProvenHash: OLD_HASH, previousEpoch: 3, expectedNewHash: CHANGED_HASH });
|
|
const sweepObservation = writer.sweeps[0].observation;
|
|
assert.strictEqual(sweepObservation.boundUser, CANONICAL, "at sweep time the restore had bound the identity");
|
|
assert.strictEqual(sweepObservation.rememberId, "rotated-remember-id-3", "at sweep time the rotated credential was referenced");
|
|
assert.strictEqual(sweepObservation.authenticatedRecordInStore, false, "but the store record did not exist yet (the save was still in flight) — the sweep's destroy had nothing to kill");
|
|
|
|
// The teardown's CAPTURED targeting — unaffected by the concurrent row
|
|
// mutation — revoked the right lineage.
|
|
assert.deepStrictEqual(h.revokedIds, ["rotated-remember-id-3"], "the revoked id is exactly the CAPTURED rotated registry id");
|
|
assert.strictEqual(h.revokedHints.length, 1, "exactly one lineage revoke fired");
|
|
assert.strictEqual(h.revokedHints[0].emailHint, CANONICAL, "the lineage revoke carries the CAPTURED email hint");
|
|
assert.strictEqual(h.revokedHints[0].uidHint, String(USER_ID), "the lineage revoke carries the CAPTURED account-id hint");
|
|
assert.strictEqual(h.revokedHints[0].lineageHint, "", "no lineage stamp on this harness session — the helper degrades per its contract");
|
|
assert.deepStrictEqual(h.tombstoneSids, ["regenerated-sid-2"], "the REGENERATED sid was tombstoned, never the pre-restore sid");
|
|
assert.deepStrictEqual(
|
|
h.events,
|
|
["log:remember-restore attempt", "regenerate", "rotate", "clearState", "markFresh", "save", "clearState", "clearCookie", "revoke:rotated-remember-id-3", "tombstone:regenerated-sid-2", "destroy", "cacheRemove:regenerated-sid-2", "cacheInvalidate", "next"],
|
|
"restore's bind choreography, the failing save, then the teardown: clear state → clear cookie → revoke(rotated) → tombstone → destroy → cache → next"
|
|
);
|
|
assert.deepStrictEqual(h.auditMethods, [], "a failed restore records NO durable audit row");
|
|
assert.deepStrictEqual(h.persistedRecords, [], "the failed save persisted nothing");
|
|
|
|
// Downstream deauthorization of the CURRENT request.
|
|
assert.strictEqual(h.req.session, undefined, "the failed restore leaves no live session object");
|
|
assert.strictEqual(h.req.currentUser, null, "the currentUser fast path is nulled");
|
|
assert.strictEqual(await h.isAuthenticated(h.req), false, "downstream authorization is denied after the failed restore");
|
|
assert.strictEqual(await h.isAdmin(h.req), false, "the admin gate denies too");
|
|
assert.ok(h.warnings.some((w) => w.includes("Persistent login restore failed") && w.includes("synthetic store failure")), "the original error surfaced in the catch's warn");
|
|
});
|
|
|
|
test("4c restore race, cleanup-failure variant: the lineage revoke REJECTS — the sid tombstone still runs and the request still deauthorizes (no escape, no wedge)", async () => {
|
|
const snapshotRow = row({ password: OLD_HASH, session_epoch: 3 });
|
|
const freshRow = row({ password: OLD_HASH, session_epoch: 3 });
|
|
|
|
const h = makeRestoreRaceHarness({
|
|
lookupQueue: [snapshotRow, freshRow],
|
|
saveOutcome: "error",
|
|
revokeImpl: async () => { h.events.push("revoke-error"); throw new Error("synthetic lineage revoke failure"); },
|
|
});
|
|
|
|
await h.mw(h.req, {}, h.next);
|
|
|
|
assert.deepStrictEqual(h.tombstoneSids, ["regenerated-sid-2"], "the tombstone still ran after the revoke rejected");
|
|
assert.deepStrictEqual(h.revokedIds, ["rotated-remember-id-3"], "the revoke was still ATTEMPTED with the captured rotated id");
|
|
assert.deepStrictEqual(
|
|
h.events.slice(-7),
|
|
["revoke:rotated-remember-id-3", "revoke-error", "tombstone:regenerated-sid-2", "destroy", "cacheRemove:regenerated-sid-2", "cacheInvalidate", "next"],
|
|
"the guarded revoke rejected, the teardown continued through tombstone → destroy → cache → next"
|
|
);
|
|
assert.deepStrictEqual(h.auditMethods, [], "no durable audit row");
|
|
assert.strictEqual(h.req.session, undefined, "no live session object after the teardown");
|
|
assert.strictEqual(h.req.currentUser, null, "the authority clear precedes the awaited cleanup and survives its failure");
|
|
assert.strictEqual(await h.isAuthenticated(h.req), false, "downstream authorization stays denied after the cleanup failure");
|
|
assert.strictEqual(h.calls.next, 1, "the catch still continues unauthenticated exactly once");
|
|
assert.deepStrictEqual(h.nextArgs, [[]], "next() takes no error argument (fail closed, not a 500)");
|
|
assert.ok(h.warnings.some((w) => w.includes("Failed-restore registry revoke errored")), "the guarded revoke's warn fired");
|
|
});
|
|
|
|
// ===========================================================================
|
|
// GROUP 5 — RECOVERY RACE (valid stamp + concurrent password change before
|
|
// step 2)
|
|
// ===========================================================================
|
|
|
|
test("5 recovery race: a valid step-1 password stamp, then a concurrent password change before step 2 — the real sha256Hex fingerprint re-check answers password-stale and burns the stamp (control: without the change the stamp survives to the 2fa-required refusal)", async () => {
|
|
// CONTROL ARM: step 1 proves the current password and stamps the session
|
|
// with the REAL sha256Hex fingerprint of the stored hash; step 2 on an
|
|
// unchanged row passes the stamp gate AND the fingerprint re-check and
|
|
// reaches the second-factor refusal (403 2fa-required) with the stamp
|
|
// intact — the interplay works when nothing moved.
|
|
{
|
|
const dbRow = row({ id: REGEN_USER_ID, email: REGEN_EMAIL, secret: "sealed-owner-seed", session_epoch: 3 });
|
|
const harness = makeRegenRaceHarness({ rowProvider: () => dbRow });
|
|
const session = { user: REGEN_EMAIL };
|
|
const res1 = makeRegenRes();
|
|
await harness.step1(makeRegenReq({ body: { currentPassword: PASSWORD }, session }), res1);
|
|
assert.strictEqual(res1.statusCode, 200, "control: step 1 succeeds on the correct password");
|
|
assert.deepStrictEqual(JSON.parse(JSON.stringify(res1.body)), { ok: true, requires: "totp" }, "control: the answer requires a TOTP unconditionally (JSON round-trip: vm-realm body)");
|
|
assert.ok(session.recoveryRegenAuth, "control: the step-1 stamp is written");
|
|
assert.strictEqual(session.recoveryRegenAuth.passwordFingerprint, REAL_SHA256(String(OLD_HASH)), "control: the stamp binds the REAL sha256Hex fingerprint of the stored hash");
|
|
|
|
const res2 = makeRegenRes();
|
|
await harness.step2(makeRegenReq({ body: {}, session }), res2);
|
|
assert.strictEqual(res2.statusCode, 403, "control: without a second factor the completion refuses");
|
|
assert.deepStrictEqual(JSON.parse(JSON.stringify(res2.body)), { error: "A valid 6-digit code is required", code: "2fa-required" }, "control: the flat 2fa-required answer (JSON round-trip: vm-realm body)");
|
|
assert.ok("recoveryRegenAuth" in session, "control: the stamp SURVIVES the refusal (a retry with a correct TOTP stays possible — the fingerprint matched)");
|
|
assert.deepStrictEqual(harness.totpVerifications, [], "control: no TOTP verification consumed by the refusal");
|
|
assert.strictEqual(harness.queries.filter((q) => q.sql.startsWith("UPDATE")).length, 0, "control: no minting or other UPDATE ran");
|
|
}
|
|
|
|
// RACE ARM: the same valid stamp, but a concurrent password change (the
|
|
// pinned in-statement CAS + bump) commits before step 2. The step-2 route
|
|
// re-derives the fingerprint from the FRESH row: the stamp describes a
|
|
// credential that no longer exists → 403 password-stale, the stamp is
|
|
// DELETED (fail closed, one attempt), no TOTP verification is consumed,
|
|
// and no minting write runs.
|
|
{
|
|
const dbRow = row({ id: REGEN_USER_ID, email: REGEN_EMAIL, secret: "sealed-owner-seed", session_epoch: 3 });
|
|
const writer = createSimulatedCredentialWriter({ row: dbRow, timeline: [] });
|
|
const harness = makeRegenRaceHarness({ rowProvider: () => dbRow });
|
|
|
|
const session = { user: REGEN_EMAIL };
|
|
const res1 = makeRegenRes();
|
|
await harness.step1(makeRegenReq({ body: { currentPassword: PASSWORD }, session }), res1);
|
|
assert.strictEqual(res1.statusCode, 200, "race: step 1 succeeds on the (then-current) password");
|
|
assert.strictEqual(session.recoveryRegenAuth.passwordFingerprint, REAL_SHA256(String(OLD_HASH)), "race: the stamp fingerprinted the hash as it was at step 1");
|
|
|
|
// The concurrent change commits between the steps: a full password reset
|
|
// by another session (its own pre-flight proved OLD_HASH; its CAS + bump
|
|
// + sweep ran). findUserByEmail now serves the FRESH row.
|
|
const committed = await writer.commitCredentialChange({ newHash: CHANGED_HASH });
|
|
assert.ok(committed.committed, "race: the concurrent password change committed");
|
|
assertCommittedResetCas(writer, { expectedProvenHash: OLD_HASH, previousEpoch: 3, expectedNewHash: CHANGED_HASH, expectedId: REGEN_USER_ID });
|
|
|
|
const res2 = makeRegenRes();
|
|
await harness.step2(makeRegenReq({ body: { twoFactorCode: "123456" }, session }), res2);
|
|
assert.strictEqual(res2.statusCode, 403, "race: the stale stamp cannot authorize minting");
|
|
assert.deepStrictEqual(JSON.parse(JSON.stringify(res2.body)), { error: "Your password was changed since verification. Enter your current password again.", code: "password-stale" }, "race: the flat password-stale answer with the real wire string (JSON round-trip: vm-realm body)");
|
|
assert.ok(!("recoveryRegenAuth" in session), "race: the stale stamp is DELETED (fail closed, one attempt)");
|
|
assert.deepStrictEqual(harness.totpVerifications, [], "race: no TOTP verification consumed — the TOTP code the caller spent proves nothing about the new credential");
|
|
const updates = harness.queries.filter((q) => q.sql.startsWith("UPDATE"));
|
|
assert.deepStrictEqual(updates, [], "race: no UPDATE ran in step 2 — the stale stamp denies before any write");
|
|
assert.strictEqual(credentialGenerationMismatch(3, dbRow.session_epoch), true, "race: the row now lives on the concurrent change's new generation");
|
|
}
|
|
});
|
|
|
|
// ===========================================================================
|
|
// GROUP 6 — ADMIN ALIAS PARTIAL-FAILURE
|
|
// ===========================================================================
|
|
|
|
test("6 admin alias partial failure: the in-statement-epoch UPDATE commits, then destroyBrowserSessionsForUser REJECTS — both adapters still answer (500, no hang, no unhandled rejection, no disconnect, no audit), and the committed epoch kills the target's stale-bound sessions on their next request", async () => {
|
|
// The sweep rejection must not hang the request (Express 4 ignores handler
|
|
// rejections) nor pretend success; and because the generation bump rode
|
|
// the SAME statement as the secret clear, the target's sessions die on
|
|
// their next request EVEN THOUGH the eviction sweep rejected.
|
|
for (const [aliasKey, route] of [["reset", "/api/admin/user/reset-2fa"], ["confirm", "/api/admin/user/confirm-2fa-reset"]]) {
|
|
const dbRow = row({ secret: "sealed:TOTPSEED", session_epoch: 3 });
|
|
let destroyCalls = 0;
|
|
const h = buildAdminAliasHarness({
|
|
targetRow: () => dbRow,
|
|
destroyImpl: async () => { destroyCalls += 1; throw new Error("session store down"); },
|
|
});
|
|
const res = makeRecordingRes();
|
|
const { rejection } = await runAdapter(h.handlers[aliasKey], makeAdminReq(), res);
|
|
|
|
assert.strictEqual(rejection, null, `${route}: the rejection must NOT escape the adapter (Express 4 would hang the request)`);
|
|
assert.strictEqual(res.statusCode, 500, `${route}: the request must be answered despite the sweep rejection`);
|
|
assert.deepStrictEqual(JSON.parse(JSON.stringify(res.body)), { error: "internal error" }, `${route}: the guard's flat 500 body`);
|
|
assert.strictEqual(destroyCalls, 1, `${route}: the sweep was attempted exactly once (and rejected)`);
|
|
assert.deepStrictEqual(h.calls.disconnects, [], `${route}: no socket disconnect after a failed sweep (the pipeline stopped at the rejection)`);
|
|
assert.deepStrictEqual(h.calls.activity, [], `${route}: no audit entry for a reset whose remediation failed`);
|
|
|
|
// The destructive write COMMITTED before the sweep rejected: exactly one
|
|
// query, the in-statement clear + generation bump.
|
|
assert.strictEqual(h.calls.queries.length, 1, `${route}: exactly the one destructive write`);
|
|
const q = h.calls.queries[0];
|
|
assert.strictEqual(q.sql, ADMIN_2FA_CLEAR_SQL, `${route}: the write is the in-statement secret clear + epoch bump (adpanel:credential-generation)`);
|
|
assert.strictEqual(q.params[1], USER_ID, `${route}: the write stays keyed by the loaded target's immutable id (adpanel:admin-reset-target-pinning)`);
|
|
assert.ok(Number.isInteger(q.params[0]) && q.params[0] >= SESSION_EPOCH_MIN && q.params[0] <= SESSION_EPOCH_MAX, `${route}: the epoch param is a CSPRNG generation in the established range`);
|
|
assert.strictEqual(credentialGenerationMismatch(3, q.params[0]), true, `${route}: the committed generation is NEW, different from the row's previous one`);
|
|
assert.strictEqual(dbRow.secret, null, `${route}: the fake db applied the secret clear`);
|
|
assert.strictEqual(dbRow.session_epoch, q.params[0], `${route}: the fake db applied the committed generation`);
|
|
|
|
// THE CLAIM, PROVEN: despite the sweep rejection, the target's pre-reset
|
|
// sessions (bound to the OLD generation) die on their next protected
|
|
// request through the per-request account-binding middleware.
|
|
const staleSessionRecord = {
|
|
user: CANONICAL,
|
|
accountId: USER_ID,
|
|
accountEpoch: 3,
|
|
rememberLoginId: "target-rid",
|
|
browserSessionAudit: { email: CANONICAL, rememberLoginId: "target-rid" },
|
|
};
|
|
const b = buildBindingMiddlewareHarness({ rowProvider: () => dbRow });
|
|
const { req: req2, destroyedSids } = makeProtectedRequest({ record: staleSessionRecord, sid: "target-sid", path: "/api/panel/state" });
|
|
const res2 = makeRecordingRes();
|
|
let nextCalls = 0;
|
|
await b.mw(req2, res2, () => { nextCalls += 1; });
|
|
assert.strictEqual(res2.statusCode, 401, `${route}: the target's stale-bound session is denied on its next request`);
|
|
assert.deepStrictEqual(JSON.parse(JSON.stringify(res2.body)), { error: "not authenticated" }, `${route}: the teardown's respond:true body (JSON round-trip: vm-realm body)`);
|
|
assert.strictEqual(nextCalls, 0, `${route}: no downstream handler ran for the stale session`);
|
|
assert.deepStrictEqual(b.tombstones, ["target-sid"], `${route}: the target's stale sid was tombstoned`);
|
|
assert.deepStrictEqual(b.revokedIds, ["target-rid"], `${route}: the target's remember credential was lineage-revoked`);
|
|
assert.deepStrictEqual(destroyedSids, ["target-sid"], `${route}: the stale session record was destroyed`);
|
|
assert.strictEqual(await b.isAuthenticated(req2), false, `${route}: downstream authorization is denied for the target's stale session`);
|
|
assert.ok(h.calls.logs.some((l) => l[0] === "error" && String(l[1]).startsWith("[admin-2fa-reset] pre-flight failed:")), `${route}: the guard logged its own bracketed marker`);
|
|
}
|
|
});
|
|
|
|
// ===========================================================================
|
|
// GROUP 7 — CONTROLS (proving the harness is not rigged)
|
|
// ===========================================================================
|
|
|
|
test("7-control ordinary login success end-to-end: bind + remember mint + save with the row's epoch", async () => {
|
|
const shared = row({ password: OLD_HASH, session_epoch: EPOCH_A });
|
|
const h = makeLoginRaceHarness({ user: shared, latestUser: shared });
|
|
await runLoginRaceHarness({ sandbox: h.sandbox, user: shared, latestUser: shared });
|
|
|
|
assert.strictEqual(h.sandbox.__captures.length, 0, "no failure response");
|
|
assert.strictEqual(h.sandbox.__binds.length, 1, "the bind proceeded");
|
|
assert.strictEqual(h.sandbox.__binds[0].user, shared, "the bind binds the re-read row");
|
|
assert.strictEqual(h.sandbox.__binds[0].beforeSave, true, "the bind carried the beforeSave revalidation hook");
|
|
assert.strictEqual(h.sandbox.__sendOks.length, 1, "the success response answers");
|
|
assert.strictEqual(h.sandbox.__audits.length, 1, "one durable success row");
|
|
assert.strictEqual(h.sandbox.__audits[0].method, "password", "the password method is recorded");
|
|
assert.strictEqual(h.sandbox.__audits[0].user, shared, "the audit row's subject is the re-read row");
|
|
assert.strictEqual(h.sandbox.__refunds.length, 1, "the success refunds the reservation");
|
|
assert.deepStrictEqual(h.sandbox.__tombstones, [], "a bare pre-auth sid takes the normal untombstoned path");
|
|
assert.deepStrictEqual(h.sandbox.__rememberRevokes, [], "no credential revoked on success");
|
|
assert.strictEqual(h.sandbox.__rememberMints.length, 1, "exactly one remember mint");
|
|
assert.strictEqual(h.sandbox.req.session.user, CANONICAL, "the session identity is bound");
|
|
assert.strictEqual(h.sandbox.req.session.accountId, USER_ID, "the account binding is written");
|
|
assert.strictEqual(h.sandbox.req.session.accountEpoch, EPOCH_A, "the epoch binding matches the row's generation");
|
|
assert.strictEqual(h.persistedRecords.length, 1, "the authenticated record persisted");
|
|
assert.strictEqual(h.persistedRecords[0].record.accountEpoch, EPOCH_A, "the persisted record carries the row's generation");
|
|
assert.deepStrictEqual(
|
|
[h.sandbox.__gateClears.length, h.sandbox.__totpResets.length, h.sandbox.__refunds.length, h.sandbox.__audits.length, h.sandbox.__sendOks.length],
|
|
[1, 1, 1, 1, 1],
|
|
"every success-tail step fired exactly once (gate clear → TOTP reset → refund → audit → sendOk)"
|
|
);
|
|
});
|
|
|
|
test("7-control captcha completion success: the pending record completes, binds and persists", async () => {
|
|
const challengeRow = row({ session_epoch: 5 });
|
|
const h = makeCompletionRaceHarness({ challengeRow, liveQueue: [row({ session_epoch: 5 })] });
|
|
|
|
const result = await runCompletionRace(h);
|
|
|
|
assert.strictEqual(result.ok, true, "the benign completion succeeds");
|
|
assert.strictEqual(result.redirect, "/", "the success redirect is unchanged");
|
|
assert.strictEqual(h.sandbox.__lookups.length, 2, "two row reads: the pre-bind re-resolution AND the beforeSave hook's fresh re-read");
|
|
assert.strictEqual(h.sandbox.req.session.user, CANONICAL, "the session is bound");
|
|
assert.strictEqual(h.sandbox.req.session.accountEpoch, 5, "the session carries the account epoch binding");
|
|
assert.strictEqual(h.sandbox.req.session.pendingCaptchaLogin, undefined, "the pending record is cleared");
|
|
assert.deepStrictEqual(h.events, ["totpReset", "gateClear:ip(203.0.113.7)", "audit:captcha-completion"], "the success choreography: TOTP reset (beforeSave) → gate clear → durable audit row");
|
|
assert.ok(h.binderEvents.includes("regenerate") && h.binderEvents.includes("save"), "the shared core ran through the save");
|
|
assert.deepStrictEqual(h.sandbox.__rememberRevokes, [], "no credential revoked on success");
|
|
assert.deepStrictEqual(h.sandbox.__tombstones, ["captcha-sid-1"], "only the pending-state pre-regeneration sid was tombstoned (the preauth-pending rule); the save succeeded so the regenerated sid stays live");
|
|
assert.strictEqual(h.persistedRecords.length, 1, "the authenticated record persisted");
|
|
assert.strictEqual(h.persistedRecords[0].record.accountEpoch, 5, "the persisted record carries the row's generation");
|
|
assert.strictEqual(h.persistedRecords[0].record.rememberLoginId, "rid-captcha", "the persisted record carries the minted remember credential");
|
|
});
|
|
|
|
test("7-control remember restore success: rotate, re-verify, bind, save — the re-verify adds no observable step", async () => {
|
|
const shared = row({ password: OLD_HASH, secret: "s3cret", session_epoch: 3 });
|
|
const h = makeRestoreRaceHarness({ lookupQueue: [shared, shared] });
|
|
await h.mw(h.req, {}, () => { h.calls.next += 1; h.events.push("next"); });
|
|
|
|
assert.deepStrictEqual(
|
|
h.events,
|
|
["log:remember-restore attempt", "regenerate", "rotate", "clearState", "markFresh", "save", "audit:remember-restore", "next"],
|
|
"byte-identical success choreography — the staleness re-verify adds no observable step"
|
|
);
|
|
assert.strictEqual(h.calls.lookups, 3, "both the pre-bind and post-save re-reads ran on the success path");
|
|
assert.strictEqual(h.req.session.user, shared.email, "the session is bound to the FRESH row's identity");
|
|
assert.strictEqual(h.req.session.accountId, USER_ID, "the account binding is written");
|
|
assert.strictEqual(h.req.session.accountEpoch, 3, "the epoch binding matches the row's generation");
|
|
assert.strictEqual(h.req.currentUser?.id, shared.id, "req.currentUser is bound on success");
|
|
assert.strictEqual(h.calls.clearCookie, 0, "no cookie hygiene on success");
|
|
assert.deepStrictEqual(h.tombstoneSids, [], "no tombstone on success");
|
|
assert.deepStrictEqual(h.revokedIds, [], "no revocation on success");
|
|
assert.deepStrictEqual(h.auditMethods, ["remember-restore"], "the durable audit row with method remember-restore");
|
|
assert.strictEqual(h.persistedRecords.length, 1, "the authenticated record persisted");
|
|
assert.strictEqual(h.persistedRecords[0].record.accountEpoch, 3, "the persisted record carries the row's generation");
|
|
assert.strictEqual(await h.isAuthenticated(h.req), true, "downstream authorizes the restored session");
|
|
});
|
|
|
|
test("7-control owner rebind after a password change binds the NEW epoch (the credential-session rebinder)", async () => {
|
|
// The counterpart of the races: when the OWNER's own credential change
|
|
// wins its CAS, the rebind must carry the generation THAT change committed
|
|
// — or the binding middleware would tear the owner down as stale on the
|
|
// next request (the mirror of scenarios 1b/6).
|
|
const oldEpoch = 3;
|
|
const newEpoch = newSessionEpochDifferentFrom(oldEpoch);
|
|
assert.strictEqual(credentialGenerationMismatch(oldEpoch, newEpoch), true, "precondition: the committed generation is new");
|
|
|
|
const destroyedAs = [];
|
|
const tombstones = [];
|
|
const rememberRevokes = [];
|
|
const mintCalls = [];
|
|
const persistedRecords = [];
|
|
const binderEvents = [];
|
|
const realRebinder = createCredentialSessionRebinder({
|
|
withTimeout: REAL_WITH_TIMEOUT,
|
|
destroyBrowserSessionsForUser: async (u) => { destroyedAs.push(u); return { destroyed: 2, rememberLoginsRevoked: 1, errors: [] }; },
|
|
writeRevokedSidTombstone: async (sid) => { tombstones.push(String(sid)); return true; },
|
|
getSessionDisplayId: (sid) => `sid:${sid}`,
|
|
ensureRememberLoginSessionId: (r) => {
|
|
if (!r.session.rememberLoginId) r.session.rememberLoginId = "rid-rebind";
|
|
return r.session.rememberLoginId;
|
|
},
|
|
buildBrowserSessionAuditFromRequest: (r, email, rememberLoginId) => ({ email, rememberLoginId }),
|
|
setRememberLoginCookie: (r, resArg, user, opts) => { mintCalls.push({ ...(opts || {}) }); r.session.rememberLoginId = "rid-rebind-fresh"; return 7776000000; },
|
|
markRememberLoginSessionFresh: (r, expiresAt) => { r.session.rememberLoginExpiresAt = expiresAt; },
|
|
upsertActiveBrowserSessionCacheEntry: () => {},
|
|
clearRememberLoginCookie: () => {},
|
|
revokeRememberLoginRegistryEntry: async (id) => { rememberRevokes.push(id); return true; },
|
|
logger: { warn: () => {} },
|
|
});
|
|
|
|
const req = { sessionID: "owner-sid-1", session: { user: CANONICAL, accountId: USER_ID, accountEpoch: oldEpoch } };
|
|
const reqSession = req.session;
|
|
reqSession.regenerate = (cb) => {
|
|
binderEvents.push("regenerate");
|
|
for (const key of Object.keys(reqSession)) {
|
|
if (key !== "regenerate" && key !== "save") delete reqSession[key];
|
|
}
|
|
req.sessionID = "owner-sid-2";
|
|
cb(null);
|
|
};
|
|
reqSession.save = (cb) => {
|
|
binderEvents.push("save");
|
|
persistedRecords.push({ sid: String(req.sessionID), record: snapshotSession(reqSession) });
|
|
cb(null);
|
|
};
|
|
|
|
const postChangeUser = { id: USER_ID, email: CANONICAL, password: CHANGED_HASH, session_epoch: newEpoch };
|
|
const { sessionInvalidation } = await realRebinder.rebindOwnerSession(req, {}, { user: postChangeUser });
|
|
|
|
assert.deepStrictEqual(destroyedAs, [postChangeUser], "the user-wide destroy matched on the POST-change material");
|
|
assert.deepStrictEqual(tombstones, ["owner-sid-1"], "the pre-regeneration sid was explicitly tombstoned (no self-exclusion)");
|
|
assert.strictEqual(req.session.user, CANONICAL, "the owner's identity is re-bound");
|
|
assert.strictEqual(req.session.accountId, USER_ID, "the account binding is re-written");
|
|
assert.strictEqual(req.session.accountEpoch, newEpoch, "THE POINT: the rebind binds the NEW epoch the change committed, not the pre-write snapshot's");
|
|
assert.deepStrictEqual(mintCalls, [{ forceFreshId: true }], "the remember re-issue followed the user-wide revoke with forceFreshId (never the just-revoked id)");
|
|
assert.strictEqual(req.session.rememberLoginId, "rid-rebind-fresh", "a FRESH identifier was minted");
|
|
assert.deepStrictEqual(rememberRevokes, [], "nothing to revoke on success");
|
|
assert.ok(binderEvents.includes("regenerate") && binderEvents.includes("save"), "the rebind core ran through the save");
|
|
assert.strictEqual(persistedRecords.length, 1, "the rebind record persisted");
|
|
assert.strictEqual(persistedRecords[0].record.accountEpoch, newEpoch, "the persisted record carries the NEW generation");
|
|
assert.deepStrictEqual(sessionInvalidation, { destroyed: 2, rememberLoginsRevoked: 1, errors: [] }, "the session invalidation result is returned unchanged");
|
|
|
|
// And the mirror-check: the rebind's record PASSES the binding middleware
|
|
// against the post-change row (the owner is not torn down as stale).
|
|
const postChangeRow = { id: USER_ID, email: CANONICAL, password: CHANGED_HASH, secret: null, totpSealedError: false, suspended: false, session_epoch: newEpoch };
|
|
const b = buildBindingMiddlewareHarness({ rowProvider: () => postChangeRow });
|
|
const { req: req2 } = makeProtectedRequest({ record: persistedRecords[0].record, sid: "owner-sid-2", path: "/api/panel/state" });
|
|
const res2 = makeRecordingRes();
|
|
let nextCalls = 0;
|
|
await b.mw(req2, res2, () => { nextCalls += 1; });
|
|
assert.strictEqual(nextCalls, 1, "the binding middleware lets the NEW-epoch record through");
|
|
assert.strictEqual(res2.statusCode, 0, "no denial response");
|
|
assert.deepStrictEqual(b.tombstones, [], "no tombstone for the owner's fresh record");
|
|
assert.deepStrictEqual(b.revokedIds, [], "no revocation for the owner's fresh record");
|
|
});
|