Files
Kelx/tests/admin-reset-target-pinning.test.js
T
2026-11-30 16:32:37 +00:00

560 lines
29 KiB
JavaScript

"use strict";
// adpanel:admin-reset-target-pinning — behavior + source pins for the admin
// account-reset surfaces (the 2FA reset service behind both thin adapters and
// the admin recovery-code reset route): BOTH destructive writes must pin the
// LOADED target row's immutable id, decide the outcome from the guarded
// write's affectedRows, and answer an explicit stale-target 409 reusing the
// repo's ONE established stale wire string — WITHOUT touching or disclosing
// anything about a replacement row.
//
// The vulnerability class: both writes were EMAIL-KEYED with no affectedRows
// check. Between the pre-flight lookup and the write, the target account can
// be deleted and recreated — even as an ADMIN sharing the email — and the
// email-keyed UPDATE would land on the replacement row: the 2FA reset would
// clear the replacement admin's credential and evict the replacement's
// sessions, and the recovery-code reset would hand the acting admin the
// REPLACEMENT admin's fresh plaintext codes.
//
// affectedRows faithfully reflects row existence here: the mysql2 pool in
// db.js runs without CLIENT_FOUND_ROWS, so affectedRows counts CHANGED rows,
// and a matched row always changes — the 2FA clear's epoch is a fresh CSPRNG
// value guaranteed different from the row's current generation
// (newSessionEpochDifferentFrom), and the recovery codes are freshly minted
// and bcrypt-hashed with a random salt every call. affectedRows === 1 exactly
// when the loaded row still exists and (for the recovery write) is still
// non-admin.
//
// Harness: the house vm-extraction technique — the REAL service module with
// hand-written deps and the REAL route statements extracted from index.js
// verbatim, over a stateful fake db so a delete/recreate between the lookup
// and the write is a deterministic race.
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 ROOT = path.join(__dirname, "..");
const INDEX_JS = path.join(ROOT, "index.js");
const MODULE_JS = path.join(ROOT, "services", "admin-2fa-reset.js");
const indexSource = fs.readFileSync(INDEX_JS, "utf8");
const moduleSource = fs.readFileSync(MODULE_JS, "utf8");
const commitSource = fs.readFileSync(path.join(ROOT, "services", "account-credentials.js"), "utf8");
const { createAdminTwoFactorResetService, STALE_TARGET_409_MESSAGE } = require(MODULE_JS);
// The repo's established stale wire string (the credential CAS 409, pinned at
// exactly three occurrences in index.js by
// tests/credential-change-atomic-guard.test.js — this repair adds NO fourth
// literal occurrence there; index.js reuses the exported constant).
const STALE_409 = "Your credentials were just changed in another session or by an administrator. Re-verify and try again.";
test("source: the service exports the ONE shared stale wire string (byte-identical to the credential CAS 409)", () => {
assert.strictEqual(typeof STALE_TARGET_409_MESSAGE, "string", "the constant is exported");
assert.strictEqual(STALE_TARGET_409_MESSAGE, STALE_409, "the exported stale-target wire string is byte-identical to the credential CAS 409");
});
function countOccurrences(haystack, needle) {
return haystack.split(needle).length - 1;
}
// Paren-balanced extraction of a full `app.post(...);` statement (skips
// strings and comments so adpanel: comments cannot desync the tracker).
function extractRouteStatement(source, marker) {
const start = source.indexOf(marker);
assert.ok(start >= 0, `route marker not found: ${marker}`);
let i = start;
let depth = 0;
let started = false;
let inString = null;
while (i < source.length) {
const ch = source[i];
if (inString) {
if (ch === "\\") { i += 2; continue; }
if (ch === inString) inString = null;
i += 1;
continue;
}
if (ch === "/" && source[i + 1] === "/") {
const j = source.indexOf("\n", i);
i = j < 0 ? source.length : j;
continue;
}
if (ch === "/" && source[i + 1] === "*") {
const j = source.indexOf("*/", i + 2);
i = j < 0 ? source.length : j + 2;
continue;
}
if (ch === '"' || ch === "'" || ch === "`") { inString = ch; i += 1; continue; }
if (ch === "(") { depth += 1; started = true; }
else if (ch === ")") { depth -= 1; }
if (started && depth === 0) {
let end = i + 1;
while (end < source.length && source[end] === ";") end += 1;
return source.slice(start, end);
}
i += 1;
}
assert.fail(`unbalanced route statement: ${marker}`);
}
const ROUTE_RECOVERY = 'app.post("/api/admin/user/reset-recovery-codes", sessionRevoke2faRateLimiter';
const ROUTE_RESET = 'app.post("/api/admin/user/reset-2fa", sessionRevoke2faRateLimiter';
const ROUTE_CONFIRM = 'app.post("/api/admin/user/confirm-2fa-reset", sessionRevoke2faRateLimiter';
const statements = {
recovery: extractRouteStatement(indexSource, ROUTE_RECOVERY),
reset: extractRouteStatement(indexSource, ROUTE_RESET),
confirm: extractRouteStatement(indexSource, ROUTE_CONFIRM),
};
// ---------------------------------------------------------------------------
// Source pins — the immutable-target writes
// ---------------------------------------------------------------------------
const SERVICE_WRITE = "UPDATE users SET secret = NULL, recovery_codes = NULL, session_epoch = ? WHERE id = ?";
const RECOVERY_WRITE = "UPDATE users SET recovery_codes = ? WHERE id = ? AND admin = 0";
test("source: the 2FA clear pins the loaded row's immutable id and decides from affectedRows", () => {
assert.equal(countOccurrences(commitSource, SERVICE_WRITE), 1, "the destructive clear exists exactly once, id-keyed, with its in-statement epoch bump (adpanel:credential-generation)");
assert.equal(countOccurrences(moduleSource, "WHERE LOWER(email) = LOWER(?)"), 0, "the service module must not key any write by email anymore");
assert.ok(commitSource.includes("withAccountActionTransaction(db, actor, targetUser"), "the write locks the loaded target's immutable id");
assert.match(commitSource, /UPDATE users SET secret = NULL, recovery_codes = NULL, session_epoch = \? WHERE id = \?[\s\S]*?result\?\.affectedRows === 1/);
const commitAt = moduleSource.indexOf("resetAccountTwoFactor(db, targetUser, actingAdmin)");
const stale409At = moduleSource.indexOf("res.status(409)", commitAt);
assert.ok(commitAt >= 0 && stale409At > commitAt && stale409At < moduleSource.indexOf("destroyBrowserSessionsForUser(targetUser)", commitAt), "the 409 answers BEFORE any eviction machinery");
// The stale response carries the shared wire string via the injectable dep.
assert.ok(moduleSource.includes("staleTarget409Message"), "the stale message arrives through the injectable dep");
assert.ok(moduleSource.includes("STALE_TARGET_409_MESSAGE"), "the dep defaults to the module's shared constant");
// House pins mirrored for the new shape: index.js keeps exactly the three
// credential-CAS 409 literals (no fourth from this repair) and stays free of
// epoch-carrying copies of the clear.
assert.equal(countOccurrences(indexSource, STALE_409), 3, "index.js keeps exactly the three credential-CAS stale 409 literals");
assert.deepEqual(indexSource.match(/UPDATE users SET secret = NULL[^"\r\n]*/g) || [], ["UPDATE users SET secret = NULL WHERE secret = ''"], "only startup empty-secret normalization may remain in index.js, never an admin reset copy");
});
test("source: the admin recovery reset pins id with the admin=0 predicate INSIDE the guarded write; codes are returned only after the affectedRows gate", () => {
const stmt = statements.recovery;
assert.ok(commitSource.includes(RECOVERY_WRITE), "the shared write is keyed by immutable id with the admin prohibition folded in");
assert.ok(!stmt.includes("WHERE LOWER(email) = LOWER(?)"), "the email-keyed shape is gone from the route");
const writeAt = stmt.indexOf("resetAccountRecoveryCodes(db, targetUser, recoveryCodesJson, actingAdmin)");
const staleAt = stmt.indexOf("res.status(409)", writeAt);
const codesAt = stmt.indexOf("recoveryCodes: plainRecoveryCodes");
assert.ok(writeAt >= 0 && staleAt > writeAt, "the stale-target outcome is decided by the actor-guarded commit");
assert.ok(codesAt > staleAt, "the plaintext codes are returned only AFTER the affectedRows gate — a stale/failed write never discloses codes");
assert.equal(stmt.indexOf("res.status(409)", writeAt), staleAt, "the stale outcome answers 409");
assert.ok(stmt.includes("STALE_TARGET_409_MESSAGE"), "the stale wire string comes from the shared constant (no new literal in index.js)");
// Epoch-free window (mirrors the house pin in
// tests/credential-change-atomic-guard.test.js): the set replacement must
// not rotate a proof credential.
const litAt = commitSource.indexOf('"' + RECOVERY_WRITE + '"');
assert.ok(litAt >= 0, "the id-keyed recovery write literal exists in the credential service");
assert.ok(!commitSource.slice(litAt, litAt + 220).includes("session_epoch"), "the admin recovery reset's set replacement stays epoch-free");
});
test("source: index.js injects the shared stale wire string into the service and reuses it for the recovery route", () => {
assert.equal(countOccurrences(indexSource, 'require("./services/admin-2fa-reset")'), 1, "the one-way require is untouched");
const requireLineStart = indexSource.indexOf('require("./services/admin-2fa-reset")');
const destructureStart = indexSource.lastIndexOf("const {", requireLineStart);
const destructure = indexSource.slice(destructureStart, requireLineStart);
assert.ok(destructure.includes("STALE_TARGET_409_MESSAGE"), "index.js pulls the shared constant from the service module");
const constructionAt = indexSource.indexOf("createAdminTwoFactorResetService({");
const constructionEnd = indexSource.indexOf("});", constructionAt);
const construction = indexSource.slice(constructionAt, constructionEnd);
assert.ok(construction.includes("staleTarget409Message: STALE_TARGET_409_MESSAGE"), "the construction site injects the shared wire string into the service");
});
// ---------------------------------------------------------------------------
// Behavior harness — the REAL service handler over a stateful fake db
// ---------------------------------------------------------------------------
const TARGET = { id: 42, email: "target@example.test", admin: 0, secret: "sealed:TOTPSEED", session_epoch: 3, recovery_codes: "[]" };
const ADMIN_ACTING = { id: 7, email: "admin@example.test", admin: 1, suspended: 0, session_epoch: 9 };
function makeRes() {
const res = { statusCode: 0, body: null, headersSent: false, cookies: [], endCalls: 0, jsonCalls: 0 };
res.status = (code) => { res.statusCode = code; res.headersSent = true; return res; };
res.json = (body) => { res.jsonCalls += 1; res.body = body; return res; };
res.end = () => { res.endCalls += 1; return res; };
res.cookie = (name, value, opts) => res.cookies.push({ name, value, opts });
return res;
}
function makeReq({ body } = {}) {
return {
body: { expectedTargetId: TARGET.id, ...body },
headers: { "user-agent": "test-agent" },
sessionID: "admin-sid",
session: { user: ADMIN_ACTING.email },
};
}
// Stateful fake db modeling the users table: the UPDATE predicates (id match,
// admin = 0) decide affectedRows exactly like MySQL would for these shapes.
function makeStatefulDb(users) {
const queries = [];
return {
queries,
users,
async query(sql, params) {
queries.push({ sql, params });
if (sql === SERVICE_WRITE) {
const [epoch, id] = params;
const row = users.get(Number(id));
if (!row) return { affectedRows: 0 };
row.secret = null;
row.recovery_codes = null;
row.session_epoch = epoch;
return { affectedRows: 1 };
}
if (sql === RECOVERY_WRITE) {
const [codesJson, id] = params;
const row = users.get(Number(id));
if (!row || row.admin) return { affectedRows: 0 };
row.recovery_codes = codesJson;
return { affectedRows: 1 };
}
throw new Error(`unexpected db.query in test: ${sql}`);
},
};
}
// Runs the adapter the way Express 4 does and reports what Express 4 would
// see: a settled handler (correct) or a rejected promise (the bug). The
// optional variant object is forwarded the way the thin adapters forward it.
async function runAdapter(handler, req, res, variant) {
let rejection = null;
try {
await handler(req, res, variant);
} catch (err) {
rejection = err;
}
return { rejection };
}
function makeServiceDeps({ users, onTargetLookup, db, overrides = {}, logger } = {}) {
const calls = { evictions: [], disconnects: [], activity: [], logs: [], stepUps: [], tokenActions: [], lookups: [] };
const deps = {
isAdmin: async () => true,
requireActionTokenOr403: async (req, res, action) => { calls.tokenActions.push(action); return true; },
findUserByEmail: async (email) => {
calls.lookups.push(email);
if (email === ADMIN_ACTING.email) return ADMIN_ACTING;
if (email === TARGET.email) {
// The lookup returns the row AS OF THE READ; a concurrent
// delete/recreate lands right after the read, before the write.
const snapshot = { ...TARGET };
if (onTargetLookup) onTargetLookup();
return snapshot;
}
return null;
},
requireDestructiveActionStepUp: async (req, res, actingAdmin, subject, options) => {
calls.stepUps.push({ actingAdmin, subject, options });
return { ok: true };
},
db,
destroyBrowserSessionsForUser: async (u) => {
calls.evictions.push(["destroy", u && u.email, u && u.id]);
return { destroyed: 2, rememberLoginsRevoked: 1, errors: [] };
},
disconnectSocketsForUser: (email, reason) => {
calls.disconnects.push([email, reason]);
return 3;
},
recordActivity: (...args) => { calls.activity.push(args); },
getRequestIp: () => "127.0.0.1",
normalizeAdminTargetEmail: (raw) => {
if (typeof raw !== "string") return null;
const email = raw.trim();
if (!email || !email.includes("@") || email.length > 255) return null;
return email;
},
stripLogControlChars: (s) => String(s == null ? "" : s),
logger: logger || {
log: (...args) => calls.logs.push(["log", ...args]),
error: (...args) => calls.logs.push(["error", ...args]),
warn: (...args) => calls.logs.push(["warn", ...args]),
},
};
Object.assign(deps, overrides);
deps.db = require("./helpers/account-transaction").attachAccountTransaction(deps.db, { actor: ADMIN_ACTING, users });
return { deps, calls };
}
// ---------------------------------------------------------------------------
// Behavior — the 2FA reset service pins the ORIGINAL row
// ---------------------------------------------------------------------------
test("2FA reset, normal path: the write lands on the loaded row (id-keyed), epoch bumped, evictions and audit unchanged", async () => {
const users = new Map([[TARGET.id, { ...TARGET }]]);
const db = makeStatefulDb(users);
const { deps, calls } = makeServiceDeps({ users, db });
const service = createAdminTwoFactorResetService(deps);
const res = makeRes();
const { rejection } = await runAdapter(service.handleAdmin2faReset, makeReq({ body: { email: TARGET.email } }), res, { action: "POST /api/admin/user/reset-2fa", proofLabel: "Admin 2FA reset", logSuffix: "" });
assert.equal(rejection, null);
assert.equal(res.statusCode, 0, "answered 200 via res.json");
assert.equal(res.body.ok, true);
assert.equal(db.queries.length, 1, "exactly the one guarded write");
assert.equal(db.queries[0].sql, SERVICE_WRITE, "the write is id-keyed");
assert.equal(db.queries[0].params[1], TARGET.id, "the write keys on the loaded target's immutable id");
assert.ok(Number.isInteger(db.queries[0].params[0]) && db.queries[0].params[0] !== TARGET.session_epoch, "the epoch bump commits a fresh generation in-statement");
assert.equal(users.get(TARGET.id).secret, null, "the ORIGINAL row's secret was cleared");
assert.equal(users.get(TARGET.id).recovery_codes, null, "the ORIGINAL row's recovery codes were revoked in the same write");
assert.deepEqual(calls.evictions, [["destroy", TARGET.email, TARGET.id]], "the session sweep still targets the loaded row");
assert.deepEqual(calls.disconnects, [[TARGET.email, "2fa-reset-by-admin"]], "the socket disconnect still targets the loaded row");
assert.equal(calls.activity.length, 1, "the audit trail is kept");
});
test("2FA reset, delete/recreate race AS AN ADMIN sharing the email: 409 stale, the replacement admin row is untouched, no eviction, no audit, never rejects", async () => {
const users = new Map([[TARGET.id, { ...TARGET }]]);
const db = makeStatefulDb(users);
const { deps, calls } = makeServiceDeps({
users,
db,
onTargetLookup: () => {
// A concurrent delete + recreate lands between the admin's lookup and
// the write — the replacement is an ADMIN sharing the email (new id).
users.delete(TARGET.id);
users.set(43, { id: 43, email: TARGET.email, admin: 1, secret: "sealed:ADMINREPLACEMENT", session_epoch: 5, recovery_codes: "[]" });
},
});
const service = createAdminTwoFactorResetService(deps);
const res = makeRes();
const { rejection } = await runAdapter(service.handleAdmin2faReset, makeReq({ body: { email: TARGET.email } }), res, { action: "POST /api/admin/user/reset-2fa", proofLabel: "Admin 2FA reset", logSuffix: "" });
assert.equal(rejection, null, "the stale outcome must not escape the adapter (Express 4 would hang the request)");
assert.equal(res.statusCode, 409);
assert.deepEqual(res.body, { error: STALE_409 }, "the stale outcome reuses the repo's ONE stale wire string");
assert.equal(users.get(43).secret, "sealed:ADMINREPLACEMENT", "the replacement ADMIN row's credential was NOT cleared");
assert.equal(users.get(43).session_epoch, 5, "the replacement row's generation was NOT bumped");
assert.equal(users.has(TARGET.id), false, "the deleted row stayed deleted (no resurrection)");
assert.deepEqual(calls.evictions, [], "no eviction swept the replacement row's sessions");
assert.deepEqual(calls.disconnects, [], "no socket disconnect hit the replacement row");
assert.deepEqual(calls.activity, [], "no audit entry for a reset that did not happen");
assert.equal(db.queries.length, 0, "the locked missing original target is refused before writing");
assert.equal(deps.db.reads.at(-1).params[0], TARGET.id, "the locking read still keys the ORIGINAL id");
assert.deepEqual(calls.tokenActions, ["POST /api/admin/user/reset-2fa"], "the action-token gate ran before the stale write");
});
test("2FA reset, stale outcome via injected dep without the default: the message is injectable and the default is the shared constant", async () => {
// (a) injected explicit message
const usersA = new Map();
const dbA = makeStatefulDb(usersA);
const injected = "injected stale marker";
const a = makeServiceDeps({ users: usersA, db: dbA, overrides: { staleTarget409Message: injected } });
const serviceA = createAdminTwoFactorResetService(a.deps);
const resA = makeRes();
await runAdapter(serviceA.handleAdmin2faReset, makeReq({ body: { email: TARGET.email } }), resA, { action: "POST /api/admin/user/reset-2fa", proofLabel: "Admin 2FA reset", logSuffix: "" });
assert.equal(resA.statusCode, 409);
assert.deepEqual(resA.body, { error: injected }, "the injected message wins");
// (b) no dep at all: the default is the exported shared constant
const usersB = new Map();
const dbB = makeStatefulDb(usersB);
const b = makeServiceDeps({ users: usersB, db: dbB });
const serviceB = createAdminTwoFactorResetService(b.deps);
const resB = makeRes();
await runAdapter(serviceB.handleAdmin2faReset, makeReq({ body: { email: TARGET.email } }), resB, { action: "POST /api/admin/user/reset-2fa", proofLabel: "Admin 2FA reset", logSuffix: "" });
assert.equal(resB.statusCode, 409);
assert.deepEqual(resB.body, { error: STALE_TARGET_409_MESSAGE }, "the default is the module's shared constant");
});
test("2FA reset containment regression, BOTH thin adapters: an injected db failure at the write answers a bounded 500 through the arrow adapter (never a hang, never a rejection)", async () => {
for (const [key, route] of [["reset", "/api/admin/user/reset-2fa"], ["confirm", "/api/admin/user/confirm-2fa-reset"]]) {
const users = new Map([[TARGET.id, { ...TARGET }]]);
const failingDb = {
async query(sql) {
throw new Error("db down during the write for " + sql);
},
};
const { deps, calls } = makeServiceDeps({ users, db: failingDb });
const service = createAdminTwoFactorResetService(deps);
const captured = [];
const ctx = vm.createContext({
app: { post: (...args) => captured.push(args) },
sessionRevoke2faRateLimiter: { name: "sessionRevoke2faRateLimiter" },
handleAdmin2faReset: service.handleAdmin2faReset,
});
vm.runInContext(statements[key], ctx, { filename: `index.js[${key}]` });
assert.equal(captured.length, 1, "exactly one registration per statement");
const adapter = captured[0][2];
const res = makeRes();
const { rejection } = await runAdapter(adapter, makeReq({ body: { email: TARGET.email } }), res);
assert.equal(rejection, null, `${route}: the injected db failure must NOT escape the adapter`);
assert.equal(res.statusCode, 500, `${route}: the request is answered (no hanging client)`);
assert.deepEqual(res.body, { error: "internal error" }, `${route}: the flat guarded 500 body (no internals leaked)`);
assert.deepEqual(calls.evictions, [], `${route}: no eviction after a failed write`);
assert.deepEqual(calls.activity, [], `${route}: no audit for a reset that did not happen`);
assert.equal(users.get(TARGET.id).secret, "sealed:TOTPSEED", `${route}: the row was not modified`);
}
});
// ---------------------------------------------------------------------------
// Behavior harness — the REAL admin recovery reset route statement
// ---------------------------------------------------------------------------
function makeRecoveryHarness({ users, onTargetLookup, db } = {}) {
const calls = { activity: [], logs: [], stepUps: [], tokenActions: [] };
const captured = [];
const ctx = vm.createContext({
app: { post: (...args) => captured.push(args) },
sessionRevoke2faRateLimiter: { name: "sessionRevoke2faRateLimiter" },
...require("../services/account-actions"),
...require("../services/account-credentials"),
isAdmin: async () => true,
requireActionTokenOr403: async (req, res, action) => { calls.tokenActions.push(action); return true; },
normalizeAdminTargetEmail: (raw) => {
if (typeof raw !== "string") return null;
const email = raw.trim();
if (!email || !email.includes("@") || email.length > 255) return null;
return email;
},
findUserByEmail: async (email) => {
if (email === ADMIN_ACTING.email) return ADMIN_ACTING;
if (email === TARGET.email) {
const snapshot = { ...TARGET };
if (onTargetLookup) onTargetLookup();
return snapshot;
}
return null;
},
requireDestructiveActionStepUp: async (req, res, actingAdmin, subject, options) => {
calls.stepUps.push({ actingAdmin, subject, options });
return { ok: true };
},
crypto: { randomBytes: () => Buffer.from([7]) },
bcrypt: { hash: async (code, rounds) => `hashed(${rounds}):${code}` },
BCRYPT_ROUNDS: 4,
db: require("./helpers/account-transaction").attachAccountTransaction(db, { actor: ADMIN_ACTING, users }),
stripLogControlChars: (s) => String(s == null ? "" : s),
getRequestIp: () => "127.0.0.1",
recordActivity: (...args) => { calls.activity.push(args); },
STALE_TARGET_409_MESSAGE,
console: { log: (...a) => calls.logs.push(["log", ...a]), error: (...a) => calls.logs.push(["error", ...a]) },
JSON,
Promise,
Date,
Object,
String,
Number,
Math,
Error,
Symbol,
});
vm.runInContext(statements.recovery, ctx, { filename: "index.js[recovery]" });
assert.equal(captured.length, 1, "exactly one route registration");
assert.equal(captured[0][1], ctx.sessionRevoke2faRateLimiter, "the shared limiter stays wired");
const handler = captured[0][2];
assert.equal(typeof handler, "function");
return { handler, calls, users, db };
}
function makeRecoveryRes() {
return makeRes();
}
test("recovery reset, normal path: guarded write wins, the plaintext codes are returned exactly once, the hashed set is written id-keyed, audit kept", async () => {
const users = new Map([[TARGET.id, { ...TARGET }]]);
const db = makeStatefulDb(users);
const { handler, calls, db: routeDb } = makeRecoveryHarness({ users, db });
const res = makeRecoveryRes();
const { rejection } = await runAdapter(handler, makeReq({ body: { email: TARGET.email } }), res);
assert.equal(rejection, null);
assert.equal(res.statusCode, 0, "answered 200 via res.json");
assert.equal(res.body.ok, true);
assert.equal(res.body.email, TARGET.email);
assert.ok(Array.isArray(res.body.recoveryCodes) && res.body.recoveryCodes.length === 7, "the winner receives the fresh codes");
const write = routeDb.queries.find((q) => q.sql === RECOVERY_WRITE);
assert.ok(write, "the guarded write ran id-keyed");
assert.equal(write.params[1], TARGET.id, "the write keys on the loaded row's immutable id");
assert.equal(users.get(TARGET.id).recovery_codes, JSON.stringify(["hashed(4):HHHHHHHH", "hashed(4):HHHHHHHH", "hashed(4):HHHHHHHH", "hashed(4):HHHHHHHH", "hashed(4):HHHHHHHH", "hashed(4):HHHHHHHH", "hashed(4):HHHHHHHH"].map((s) => s)), "the hashed set was persisted");
assert.equal(calls.activity.length, 1, "the audit entry is kept for the real reset");
});
test("recovery reset, delete/recreate race AS AN ADMIN sharing the email: 409 stale, ZERO codes disclosed, the replacement admin row untouched, no audit", async () => {
const users = new Map([[TARGET.id, { ...TARGET }]]);
const db = makeStatefulDb(users);
const { handler, calls, db: routeDb } = makeRecoveryHarness({
users,
db,
onTargetLookup: () => {
users.delete(TARGET.id);
users.set(43, { id: 43, email: TARGET.email, admin: 1, secret: "sealed:ADMINREPLACEMENT", session_epoch: 5, recovery_codes: "[]" });
},
});
const res = makeRecoveryRes();
const { rejection } = await runAdapter(handler, makeReq({ body: { email: TARGET.email } }), res);
assert.equal(rejection, null, "the stale outcome must not escape the handler (Express 4 would hang the request)");
assert.equal(res.statusCode, 409);
assert.deepEqual(res.body, { error: STALE_409 }, "the stale wire string is the ONLY body");
assert.equal(res.body.recoveryCodes, undefined, "no plaintext codes are disclosed for a stale target");
assert.equal(users.get(43).recovery_codes, "[]", "the replacement ADMIN row's recovery codes were NOT overwritten");
assert.equal(users.get(43).secret, "sealed:ADMINREPLACEMENT", "the replacement row's credential stands");
assert.deepEqual(calls.activity, [], "no audit entry for a reset that did not happen");
const write = routeDb.queries.find((q) => q.sql === RECOVERY_WRITE);
assert.equal(write, undefined, "the locked missing target is refused before writing");
assert.equal(routeDb.queries.every((q) => q.sql !== 'UPDATE users SET recovery_codes = ? WHERE LOWER(email) = LOWER(?)'), true, "no email-keyed write ran");
});
test("recovery reset, SAME-id admin replacement (paranoid id reuse): the admin = 0 predicate inside the write refuses — 409, zero codes, the admin row's codes untouched", async () => {
const users = new Map([[TARGET.id, { ...TARGET }]]);
const db = makeStatefulDb(users);
const { handler, calls } = makeRecoveryHarness({
users,
db,
onTargetLookup: () => {
// Pathological recreate reusing the id, now as an ADMIN: only the
// admin = 0 predicate inside the guarded write can refuse this one.
users.delete(TARGET.id);
users.set(TARGET.id, { id: TARGET.id, email: TARGET.email, admin: 1, secret: "sealed:ADMINREPLACEMENT", session_epoch: 5, recovery_codes: "[]" });
},
});
const res = makeRecoveryRes();
const { rejection } = await runAdapter(handler, makeReq({ body: { email: TARGET.email } }), res);
assert.equal(rejection, null);
assert.equal(res.statusCode, 409);
assert.deepEqual(res.body, { error: STALE_409 });
assert.equal(res.body.recoveryCodes, undefined, "no codes are disclosed");
assert.equal(users.get(TARGET.id).recovery_codes, "[]", "the replacement admin row's codes were NOT overwritten");
assert.deepEqual(calls.activity, [], "no audit entry");
});
test("recovery reset containment: an injected db failure at the write answers the route's 500 shape with NO codes and NO audit", async () => {
const users = new Map([[TARGET.id, { ...TARGET }]]);
const failingDb = {
async query(sql) {
throw new Error("db down during the write for " + sql);
},
};
const { handler, calls } = makeRecoveryHarness({ users, db: failingDb });
const res = makeRecoveryRes();
const { rejection } = await runAdapter(handler, makeReq({ body: { email: TARGET.email } }), res);
assert.equal(rejection, null, "the write failure must not escape the handler");
assert.equal(res.statusCode, 500);
assert.deepEqual(res.body, { error: "Failed to reset recovery codes" }, "the route's established write-failure shape");
assert.equal(res.body.recoveryCodes, undefined, "no codes ride a failed write");
assert.deepEqual(calls.activity, [], "no audit for a reset that did not happen");
});