Files
Kelx/utils/totp-claim.test.js
2026-11-30 16:32:37 +00:00

214 lines
11 KiB
JavaScript

"use strict";
// adpanel:totp-atomic-claim — unit pins for the ONE cross-worker TOTP step
// claim module. The claim must be a true atomic compare-and-set on the
// monotonic step: two concurrent claims of the same step resolve to exactly
// one winner (the loser's UPDATE matches zero rows and writes nothing), a
// claim that cannot be adjudicated (DB rejection, synchronous adapter throw,
// timeout) fails CLOSED, the legacy-schema ER_BAD_FIELD_ERROR degrades OPEN
// exactly once per process with a loud log, malformed arguments are refused
// without touching the database, and the claim function NEVER REJECTS (callers
// await it inside Express 4 handlers, where an unhandled rejection is a hung
// request / crash class) — even when the injected logger itself throws
// synchronously on every call, which these pins drive through every logging
// path.
const test = require("node:test");
const assert = require("node:assert");
const { createTotpStepClaimer } = require("./totp-claim");
const EXPECTED_CLAIM_SQL =
"UPDATE users SET totp_last_counter = ? WHERE id = ? AND (totp_last_counter IS NULL OR totp_last_counter < ?)";
// Fake db modeling the ONE property the claim depends on: the UPDATE is a
// serialized read-modify-write (InnoDB row lock). The read-back happens after
// an await with NO interleaving point inside the read-modify-write, so two
// overlapping query() calls serialize exactly like concurrent row-locked
// UPDATEs on the same row. `writes` records every row actually changed, so a
// losing claim is proven to have written nothing.
function createFakeDb(initial = null, behavior = {}) {
const state = { counter: initial, writes: [], queries: 0, lastSql: "", lastParams: null };
const db = {
state,
query(sql, params) {
state.lastSql = sql;
state.lastParams = params;
state.queries++;
if (behavior.throwSync) throw behavior.throwSync;
if (behavior.hangMs !== undefined) {
return new Promise((_, reject) => {
setTimeout(() => reject(behavior.hangRejection || new Error("late db failure")), behavior.hangMs);
});
}
return (async () => {
await new Promise((resolve) => setTimeout(resolve, behavior.delayMs ?? 2));
if (behavior.reject) throw behavior.reject;
const step = Number(params[0]);
if (state.counter === null || state.counter < step) {
state.counter = step;
state.writes.push({ step, userId: params[1] });
return { affectedRows: 1 };
}
return { affectedRows: 0 };
})();
},
};
return db;
}
function createLogger() {
const errors = [];
return { errors, error(...args) { errors.push(args.map(String).join(" ")); } };
}
// A logger whose error method throws synchronously on every call — the fault
// the NEVER-REJECTS contract must survive (an injected logger is arbitrary
// deps; the shipped console default can never do this, so the module's own
// logging is fault-isolated against a broken one).
function createThrowingLogger() {
return {
error() { throw new Error("logger is broken"); },
};
}
test("claim SQL is the exact atomic compare-and-set (pin against drift)", async () => {
const db = createFakeDb(null);
const claim = createTotpStepClaimer({ db, timeoutMs: 200 });
await claim(42, 30000);
assert.strictEqual(db.state.lastSql, EXPECTED_CLAIM_SQL);
assert.deepStrictEqual(db.state.lastParams, [30000, 42, 30000]);
});
test("two concurrent claims of the same step: exactly one wins, the loser writes nothing", async () => {
const db = createFakeDb(null);
const claim = createTotpStepClaimer({ db, timeoutMs: 2000 });
const [a, b] = await Promise.all([claim(42, 30000), claim(42, 30000)]);
const winners = [a, b].filter((r) => r.won);
assert.strictEqual(winners.length, 1, "exactly one of two racers may win the step");
assert.strictEqual(winners[0].degraded, undefined, "a normal win is not a degraded win");
const losers = [a, b].filter((r) => !r.won);
assert.strictEqual(losers.length, 1);
assert.strictEqual(losers[0].failed, undefined, "a clean race loss is a normal outcome, not a failure");
assert.strictEqual(db.state.writes.length, 1, "the losing claim must not write anything");
assert.strictEqual(db.state.counter, 30000);
});
test("the claim is monotonic: equal or lower steps lose after a win, a higher step wins", async () => {
const db = createFakeDb(null);
const claim = createTotpStepClaimer({ db, timeoutMs: 200 });
const first = await claim(7, 30000);
assert.deepStrictEqual(first, { won: true });
const equal = await claim(7, 30000);
assert.strictEqual(equal.won, false, "an equal step is already consumed");
const lower = await claim(7, 29999);
assert.strictEqual(lower.won, false, "a lower step can never re-authorize");
const higher = await claim(7, 30001);
assert.strictEqual(higher.won, true);
assert.strictEqual(db.state.writes.length, 2, "only the two winning claims wrote");
});
test("a NULL counter (never consumed) wins the first claim", async () => {
const db = createFakeDb(null);
const claim = createTotpStepClaimer({ db, timeoutMs: 200 });
const result = await claim(9, 30000);
assert.deepStrictEqual(result, { won: true });
assert.strictEqual(db.state.writes.length, 1);
});
test("a DB rejection fails closed and the claim never rejects", async () => {
const db = createFakeDb(null, { reject: new Error("connection refused") });
const logger = createLogger();
const claim = createTotpStepClaimer({ db, logger, timeoutMs: 200 });
const result = await claim(9, 30000);
assert.deepStrictEqual(result, { won: false, failed: true });
assert.ok(logger.errors.length >= 1, "a fail-closed claim must be logged");
assert.strictEqual(db.state.writes.length, 0);
});
test("a synchronous throw from a broken adapter fails closed and never rejects", async () => {
const db = createFakeDb(null, { throwSync: new Error("adapter is not a function") });
const claim = createTotpStepClaimer({ db, timeoutMs: 200 });
const result = await claim(9, 30000);
assert.deepStrictEqual(result, { won: false, failed: true });
assert.strictEqual(db.state.writes.length, 0);
});
test("a slow DB times out, fails closed, and the late rejection is absorbed", async () => {
// The hung query rejects 250ms later — AFTER the claim already resolved.
// If the boundary were missing, node --test reports an unhandled rejection.
const db = createFakeDb(null, { hangMs: 250 });
const logger = createLogger();
const claim = createTotpStepClaimer({ db, logger, timeoutMs: 20 });
const result = await claim(9, 30000);
assert.deepStrictEqual(result, { won: false, failed: true });
assert.ok(logger.errors.some((line) => line.includes("timed out")), "a timeout must be logged loudly");
// Give the late rejection its chance to surface as unhandled.
await new Promise((resolve) => setTimeout(resolve, 300));
assert.strictEqual(db.state.writes.length, 0);
});
test("ER_BAD_FIELD_ERROR degrades open, logs loudly ONCE per process, never writes", async () => {
const legacyErr = Object.assign(new Error("Unknown column 'totp_last_counter' in 'where clause'"), { code: "ER_BAD_FIELD_ERROR" });
const db = createFakeDb(null, { reject: legacyErr });
const logger = createLogger();
const claim = createTotpStepClaimer({ db, logger, timeoutMs: 200 });
const first = await claim(9, 30000);
assert.deepStrictEqual(first, { won: true, degraded: true });
const second = await claim(9, 30001);
assert.deepStrictEqual(second, { won: true, degraded: true });
const degradedLogs = logger.errors.filter((line) => line.includes("degrading OPEN"));
assert.strictEqual(degradedLogs.length, 1, "the legacy-schema degradation must log once, not per claim");
assert.strictEqual(db.state.writes.length, 0);
});
test("a synchronously-throwing logger cannot reject the claim (sync-throw path)", async () => {
// The sync-throw catch classifies OUTSIDE the awaited try, so without
// fault-isolated logging a throwing logger would escape as a rejection.
const db = createFakeDb(null, { throwSync: new Error("adapter is not a function") });
const logger = createThrowingLogger();
const claim = createTotpStepClaimer({ db, logger, timeoutMs: 200 });
const result = await claim(9, 30000);
assert.deepStrictEqual(result, { won: false, failed: true });
assert.strictEqual(db.state.writes.length, 0);
});
test("a synchronously-throwing logger cannot reject the claim (timeout path)", async () => {
// The timeout branch logs, then a throwing logger falls into the catch,
// whose classification logs again — the second throw must still not reject.
const db = createFakeDb(null, { hangMs: 250 });
const logger = createThrowingLogger();
const claim = createTotpStepClaimer({ db, logger, timeoutMs: 20 });
const result = await claim(9, 30000);
assert.deepStrictEqual(result, { won: false, failed: true });
// Give the late rejection its chance to surface as unhandled.
await new Promise((resolve) => setTimeout(resolve, 300));
assert.strictEqual(db.state.writes.length, 0);
});
test("a synchronously-throwing logger cannot reject the claim (db-rejection and degraded-open paths)", async () => {
const legacyErr = Object.assign(new Error("Unknown column 'totp_last_counter' in 'where clause'"), { code: "ER_BAD_FIELD_ERROR" });
const logger = createThrowingLogger();
const failingClaim = createTotpStepClaimer({ db: createFakeDb(null, { reject: new Error("connection refused") }), logger, timeoutMs: 200 });
assert.deepStrictEqual(await failingClaim(9, 30000), { won: false, failed: true });
const degradedClaim = createTotpStepClaimer({ db: createFakeDb(null, { reject: legacyErr }), logger, timeoutMs: 200 });
assert.deepStrictEqual(await degradedClaim(9, 30000), { won: true, degraded: true });
const second = await degradedClaim(9, 30001);
assert.deepStrictEqual(second, { won: true, degraded: true }, "the log-once flag still flips even when the log itself throws");
});
test("malformed arguments are refused fail-closed without touching the database", async () => {
const db = createFakeDb(null);
const claim = createTotpStepClaimer({ db, timeoutMs: 200 });
for (const [userId, step] of [[null, 30000], [undefined, 30000], [9, NaN], [9, Infinity], [9, "not-a-step"], ["", 30000]]) {
const result = await claim(userId, step);
assert.deepStrictEqual(result, { won: false, failed: true }, `(${String(userId)}, ${String(step)}) must be refused`);
}
assert.strictEqual(db.state.queries, 0, "a refused claim must not issue any query");
});
test("the factory rejects a db without a query method at creation time", () => {
assert.throws(() => createTotpStepClaimer({}), /requires a db dependency/);
assert.throws(() => createTotpStepClaimer(), /requires a db dependency/);
});