"use strict"; // adpanel:cross-worker-verification — LIVE cross-worker race verification for // the credential-writer / revocation campaign, run against DISPOSABLE shared // MySQL (and optionally Redis) infrastructure. // // The verification gate this file answers: "a process-local lock or a // single-worker mock is not evidence of cross-worker correctness." Every // scenario below therefore drives TWO SEPARATE connection pools (two simulated // panel workers) at the SAME row/queue on one shared server, using the EXACT // SQL writer shapes the shipped code uses (cited per constant below), and the // real shared epoch generator (utils/session-epoch.js — the ONE home, never a // re-implemented fallback). // // ENV GATING (the normal suite stays green without infrastructure): // ADPANEL_TEST_MYSQL_URL e.g. mysql://user:pass@127.0.0.1:3306/adpanel_cwtest // — MUST point at a disposable, empty database the credentials may fully // wipe; this file creates/drops the mirrored tables inside it and, at // cleanup, drops the database itself. Set ADPANEL_TEST_MYSQL_KEEP_DB=1 // to keep the database after the run (repeat local runs). // ADPANEL_TEST_REDIS_URL e.g. redis://127.0.0.1:6379 // — disposable shared Redis for the tombstone-visibility leg. The WRITE // side runs in a spawned child NODE PROCESS and the read side in this // process's own connection, so a pass really is cross-process evidence, // not two pooled sockets sharing one client's command queue. // // When the env vars are absent every test calls t.skip("…") with the reason — // nothing connects, nothing fails. No daemon is ever started or installed by // this file; it only ever dials the URLs it was handed, on localhost. const { test, after } = require("node:test"); const assert = require("node:assert"); const fs = require("node:fs"); const path = require("node:path"); const crypto = require("node:crypto"); const { spawnSync } = require("node:child_process"); const REPO_ROOT = path.join(__dirname, ".."); const INDEX_JS = path.join(REPO_ROOT, "index.js"); const SCHEMA_SQL = path.join(REPO_ROOT, "mysql-schema.sql"); const CREATE_USER_JS = path.join(REPO_ROOT, "scripts", "create-user.js"); const mysqlUrl = String(process.env.ADPANEL_TEST_MYSQL_URL || "").trim(); const redisUrl = String(process.env.ADPANEL_TEST_REDIS_URL || "").trim(); const keepMysqlDb = String(process.env.ADPANEL_TEST_MYSQL_KEEP_DB || "").trim() === "1"; const MYSQL_SKIP_REASON = "ADPANEL_TEST_MYSQL_URL is not set — cross-worker MySQL race scenarios require disposable shared MySQL infrastructure; skipping so the normal suite stays green"; const REDIS_SKIP_REASON = "ADPANEL_TEST_REDIS_URL is not set — cross-worker Redis tombstone visibility requires disposable shared Redis infrastructure; skipping so the normal suite stays green"; // --------------------------------------------------------------------------- // Mirrored writer shapes — every string cites its one true home. A drift-pin // inside the gated tests asserts these exact statements still exist in the // sources, so the mirror can never silently diverge from the shipped SQL. // --------------------------------------------------------------------------- // Credential CAS with the epoch bump riding the SAME statement // (index.js self-service password change ~50344 and settings password change // ~55168; the campaign rule in utils/session-epoch.js lines 8-20: an epoch // change is only meaningful in the SAME SQL statement as the credential it // invalidates, never a second UPDATE). const MIRRORED_PASSWORD_EPOCH_CAS = "UPDATE users SET password = ?, session_epoch = ? WHERE id = ? AND password = ? AND session_epoch = ?"; // claimRecoveryCode's full-array compare-and-swap (index.js:49588-49612): // read the array, splice out the claimed hash, then UPDATE gated on the WHOLE // stored array still being the value the reader saw — two workers claiming // (any) codes from one array cannot both win. const MIRRORED_RECOVERY_CLAIM_CAS = "UPDATE users SET recovery_codes = ? WHERE id = ? AND recovery_codes = ?"; // pending_session_revocations claim-by-conditional-DELETE // (index.js:17622-17626; the unusable-row claim at index.js:17612-17615): // only the worker whose DELETE removes the exact (email, requested_at) row // proceeds; losers see affectedRows 0. const MIRRORED_CLAIM_DELETE = "DELETE FROM pending_session_revocations WHERE email = ? AND requested_at = ?"; // The CLI producer shape (scripts/create-user.js:96-104) — the panel's sweep // requeue (index.js:17658-17661) is the same upsert keyed by email only; the // PRIMARY KEY on email is the cross-process claim mechanism. const MIRRORED_PRODUCER_UPSERT = "INSERT INTO pending_session_revocations (email, requested_at, reason, attempts) VALUES (?, ?, ?, 0)\n" + " ON DUPLICATE KEY UPDATE requested_at = VALUES(requested_at), reason = VALUES(reason), attempts = 0"; // Revoked-sid tombstone Redis writer shape (index.js:4463-4487, key prefix // index.js:4365, TTL index.js:4370). isSessionSidRevoked's Redis leg is a // plain GET where any hit means revoked (index.js:4595-4600). const MIRRORED_TOMBSTONE_REDIS_PREFIX = "adpanel:revoked-sid:"; const MIRRORED_TOMBSTONE_TTL_SECONDS = 370 * 24 * 60 * 60; // index.js:4370 // Mirrored users table — the campaign-relevant subset of mysql-schema.sql // (id/email/password/secret/recovery_codes + session_epoch, same column // types, same utf8mb4_unicode_ci collation so the email unique key behaves // case-insensitively exactly like production). const USERS_TABLE_DDL = ` CREATE TABLE IF NOT EXISTS users ( id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, email VARCHAR(255) NOT NULL, password VARCHAR(255) NOT NULL, secret VARCHAR(255) NULL, recovery_codes TEXT NULL, session_epoch BIGINT UNSIGNED NOT NULL DEFAULT 0, created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (id), UNIQUE KEY uniq_users_email (email) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci`; // Byte-mirror of mysql-schema.sql:317-323 (and index.js // PENDING_SESSION_REVOCATIONS_DDL ~17558-17565, which must stay identical to // it per the comment there). const PENDING_TABLE_DDL = ` CREATE TABLE IF NOT EXISTS pending_session_revocations ( email VARCHAR(255) NOT NULL, requested_at BIGINT UNSIGNED NOT NULL, reason VARCHAR(64) NOT NULL DEFAULT '', attempts INT UNSIGNED NOT NULL DEFAULT 0, PRIMARY KEY (email) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci`; // --------------------------------------------------------------------------- // Shared epoch generation: the REAL one-true-home module, not a re-clone. // --------------------------------------------------------------------------- const { newSessionEpochDifferentFrom, SESSION_EPOCH_MIN, SESSION_EPOCH_MAX } = require( path.join(REPO_ROOT, "utils", "session-epoch.js") ); // --------------------------------------------------------------------------- // Fixture lifecycle // --------------------------------------------------------------------------- const mysql = require("mysql2/promise"); let fixture = null; // { poolA, poolB, dbName, runId } function parseDbName(url) { try { const u = new URL(url); return (u.pathname || "").replace(/^\//, ""); } catch { return ""; } } async function ensureMysqlFixture() { if (fixture) return fixture; assert.ok(mysqlUrl, "fixture requested without ADPANEL_TEST_MYSQL_URL"); const runId = crypto.randomBytes(8).toString("hex"); const poolA = mysql.createPool(mysqlUrl); // simulated worker A const poolB = mysql.createPool(mysqlUrl); // simulated worker B — separate pool, separate connections // Start from a known-empty slate (repeat runs against a kept database). for (const ddl of ["DROP TABLE IF EXISTS pending_session_revocations", "DROP TABLE IF EXISTS users"]) { await poolA.query(ddl); } await poolA.query(USERS_TABLE_DDL); await poolB.query(PENDING_TABLE_DDL); // created through worker B's connection on purpose: shared DDL, either worker fixture = { poolA, poolB, dbName: parseDbName(mysqlUrl), runId }; return fixture; } after(async () => { if (!fixture) return; const { poolA, poolB, dbName } = fixture; fixture = null; await poolA.end().catch(() => {}); await poolB.end().catch(() => {}); // Drop the throwaway schema after() per the verification-gate contract. // ADPANEL_TEST_MYSQL_KEEP_DB=1 opts out for repeat local runs. if (!keepMysqlDb && dbName) { const base = new URL(mysqlUrl); base.pathname = "/"; const bare = mysql.createPool(base.toString()); try { await bare.query(`DROP DATABASE IF EXISTS \`${dbName.replace(/`/g, "")}\``); } finally { await bare.end().catch(() => {}); } } }); // Drift pin (runs only inside gated tests): if the shipped SQL moved, the // mirror above must be consciously updated with it — per AGENTS.md, a // structure pin's assertion is updated deliberately, never weakened. function assertMirrorsStillMatchSources() { const indexSource = fs.readFileSync(INDEX_JS, "utf8"); const commitSource = fs.readFileSync(path.join(REPO_ROOT, "services", "account-credentials.js"), "utf8"); const schemaSource = fs.readFileSync(SCHEMA_SQL, "utf8"); const createUserSource = fs.readFileSync(CREATE_USER_JS, "utf8"); assert.ok( commitSource.includes(MIRRORED_PASSWORD_EPOCH_CAS) && indexSource.includes("await credentialCommitService.commitPassword("), "the shared credential service must own the generation-guarded CAS and the routes must delegate to it" ); assert.ok( indexSource.includes(MIRRORED_RECOVERY_CLAIM_CAS), "index.js no longer contains claimRecoveryCode's full-array CAS — re-align the mirror" ); assert.ok( indexSource.includes(MIRRORED_CLAIM_DELETE), "index.js no longer contains the claim-by-conditional-DELETE — re-align the mirror" ); assert.ok( createUserSource.includes(MIRRORED_PRODUCER_UPSERT), "scripts/create-user.js no longer contains the producer upsert — re-align the mirror" ); assert.ok( indexSource.includes(MIRRORED_TOMBSTONE_REDIS_PREFIX) && indexSource.includes("370 * 24 * 60 * 60"), "index.js revoked-sid tombstone key prefix / TTL changed — re-align the Redis tombstone mirror" ); assert.ok( schemaSource.includes("CREATE TABLE IF NOT EXISTS pending_session_revocations (") && schemaSource.includes("PRIMARY KEY (email)"), "mysql-schema.sql pending_session_revocations shape changed — re-align the mirrored DDL" ); } const EMAIL_RX = /^[^@\s]+@[^@\s]+\.[^@\s]+$/; function testEmail(runId, label) { const email = `cw-${label}-${runId}@crossworker.invalid`; assert.ok(EMAIL_RX.test(email)); return email; } function uniquePassword(runId, label) { // Not a real bcrypt digest on purpose: the CAS never inspects hash format, // and unique-per-writer strings make "whose write landed" collision-free. return `$2b$10$cw-${label}-${runId}-${crypto.randomBytes(6).toString("hex")}`; } // The real generator's contract (utils/session-epoch.js:41-60): in range, // never the 0 default, never equal to the current it replaces. function assertValidEpoch(value, previous) { assert.ok(Number.isFinite(Number(value)), `epoch not finite: ${value}`); const n = Number(value); assert.ok(n >= SESSION_EPOCH_MIN && n <= SESSION_EPOCH_MAX, `epoch out of range: ${n}`); assert.notStrictEqual(n, 0, "a real generation must never be the 0 column default"); if (previous !== undefined) { assert.notStrictEqual(n, Number(previous), "epoch must differ from the generation it replaces"); } } // --------------------------------------------------------------------------- // (a) CAS-loser epoch safety — deterministic interleaving // --------------------------------------------------------------------------- test("cross-worker password CAS: loser pinned on the old password writes NOTHING — winner's epoch stands", async (t) => { if (!mysqlUrl) return t.skip(MYSQL_SKIP_REASON); const { poolA, poolB, runId } = await ensureMysqlFixture(); assertMirrorsStillMatchSources(); const email = testEmail(runId, "cas-loser"); const seedEpoch = newSessionEpochDifferentFrom(0); const [ins] = await poolA.query( "INSERT INTO users (email, password, session_epoch) VALUES (?, ?, ?)", [email, uniquePassword(runId, "seed"), seedEpoch] ); const userId = ins.insertId; // Both workers read the SAME pre-change row (the shape every credential // writer starts from: a row read, then a CAS pinned on what that read saw). const [rowsA] = await poolA.query("SELECT id, password, session_epoch FROM users WHERE id = ?", [userId]); const [rowsB] = await poolB.query("SELECT id, password, session_epoch FROM users WHERE id = ?", [userId]); assert.strictEqual(rowsB[0].password, rowsA[0].password); assert.strictEqual(Number(rowsB[0].session_epoch), Number(rowsA[0].session_epoch)); const seenPassword = rowsA[0].password; const seenEpoch = Number(rowsA[0].session_epoch); // Worker A wins the CAS: its epoch bump rides the SAME statement // (index.js:50344 shape) — never a second UPDATE. const epochA = newSessionEpochDifferentFrom(seenEpoch); const hashA = uniquePassword(runId, "winner-a"); const [winA] = await poolA.query(MIRRORED_PASSWORD_EPOCH_CAS, [hashA, epochA, userId, seenPassword, seenEpoch]); assert.strictEqual(winA.affectedRows, 1, "worker A's CAS must win against the pinned old password"); // Worker B's CAS is pinned on the OLD password its stale read saw — it must // lose with affectedRows 0 and commit nothing (no password, and above all // NO second epoch write: a loser epoch write would re-validate sessions the // winner just tore down, or tear down sessions the winner just minted). const epochB = newSessionEpochDifferentFrom(seenEpoch); const hashB = uniquePassword(runId, "loser-b"); const [losB] = await poolB.query(MIRRORED_PASSWORD_EPOCH_CAS, [hashB, epochB, userId, seenPassword, seenEpoch]); assert.strictEqual(losB.affectedRows, 0, "worker B's stale CAS must lose"); const [after] = await poolB.query("SELECT password, session_epoch FROM users WHERE id = ?", [userId]); assert.strictEqual(after[0].password, hashA, "the row must hold exactly the winner's credential"); assert.strictEqual(Number(after[0].session_epoch), Number(epochA), "the row's epoch must be exactly the winner's in-statement epoch — a loser's epoch write landed nowhere"); assert.notStrictEqual(Number(after[0].session_epoch), seenEpoch, "the epoch must have moved off the pre-change generation"); if (Number(epochB) !== Number(epochA)) { assert.notStrictEqual(Number(after[0].session_epoch), Number(epochB), "the loser's candidate epoch never landed either"); } }); // --------------------------------------------------------------------------- // (a2) The same CAS under real contention — both workers fire from one read // --------------------------------------------------------------------------- test("cross-worker password CAS under contention: exactly one winner per round; row always = winner's (password, epoch) pair", async (t) => { if (!mysqlUrl) return t.skip(MYSQL_SKIP_REASON); const { poolA, poolB, runId } = await ensureMysqlFixture(); assertMirrorsStillMatchSources(); const email = testEmail(runId, "cas-race"); const [ins] = await poolA.query( "INSERT INTO users (email, password, session_epoch) VALUES (?, ?, ?)", [email, uniquePassword(runId, "race-seed"), newSessionEpochDifferentFrom(0)] ); const userId = ins.insertId; const ROUNDS = 12; for (let round = 0; round < ROUNDS; round += 1) { const [beforeRows] = await poolA.query("SELECT password, session_epoch FROM users WHERE id = ?", [userId]); const current = beforeRows[0]; // Each worker generates its own epoch from the row's PRESENT generation // (newSessionEpochDifferentFrom — index.js:50341 shape), then both fire // the CAS concurrently from the same read. const candA = { hash: uniquePassword(runId, `race-a${round}`), epoch: newSessionEpochDifferentFrom(Number(current.session_epoch)) }; const candB = { hash: uniquePassword(runId, `race-b${round}`), epoch: newSessionEpochDifferentFrom(Number(current.session_epoch)) }; const [resA, resB] = await Promise.all([ poolA.query(MIRRORED_PASSWORD_EPOCH_CAS, [candA.hash, candA.epoch, userId, current.password, Number(current.session_epoch)]), poolB.query(MIRRORED_PASSWORD_EPOCH_CAS, [candB.hash, candB.epoch, userId, current.password, Number(current.session_epoch)]), ]); const aWon = resA[0].affectedRows === 1; const bWon = resB[0].affectedRows === 1; assert.strictEqual(aWon + bWon, 1, `round ${round}: exactly one worker may win the credential CAS`); const winner = aWon ? candA : candB; const loser = aWon ? candB : candA; const [afterRows] = await poolB.query("SELECT password, session_epoch FROM users WHERE id = ?", [userId]); assert.strictEqual(afterRows[0].password, winner.hash, `round ${round}: row holds the winner's credential`); assert.strictEqual(Number(afterRows[0].session_epoch), Number(winner.epoch), `round ${round}: row's epoch is exactly the winner's in-statement epoch`); assert.notStrictEqual(afterRows[0].password, loser.hash, `round ${round}: the loser's credential never landed`); assertValidEpoch(Number(afterRows[0].session_epoch), Number(current.session_epoch)); } }); // --------------------------------------------------------------------------- // (b) Epoch monotonic distinctness under contention // --------------------------------------------------------------------------- test("cross-worker epoch distinctness: N sequential changes across independent connections each move the epoch off the previous generation", async (t) => { if (!mysqlUrl) return t.skip(MYSQL_SKIP_REASON); const { poolA, poolB, runId } = await ensureMysqlFixture(); const email = testEmail(runId, "epoch-distinct"); const [ins] = await poolA.query( "INSERT INTO users (email, password, session_epoch) VALUES (?, ?, ?)", [email, uniquePassword(runId, "ep-seed"), newSessionEpochDifferentFrom(0)] ); const userId = ins.insertId; const N = 10; const seenEpochs = new Set(); for (let i = 0; i < N; i += 1) { // Independent connections alternate, as two cluster workers would across // successive credential mutations. const worker = i % 2 === 0 ? poolA : poolB; const [rows] = await worker.query("SELECT password, session_epoch FROM users WHERE id = ?", [userId]); const previousEpoch = Number(rows[0].session_epoch); seenEpochs.add(previousEpoch); const nextEpoch = newSessionEpochDifferentFrom(previousEpoch); assert.notStrictEqual( Number(nextEpoch), previousEpoch, "the generator itself must refuse to land on the row's present generation" ); const [upd] = await worker.query(MIRRORED_PASSWORD_EPOCH_CAS, [ uniquePassword(runId, `ep${i}`), nextEpoch, userId, rows[0].password, previousEpoch, ]); assert.strictEqual(upd.affectedRows, 1, `iteration ${i}: sequential writer wins its own CAS`); const [verify] = await poolB.query("SELECT password, session_epoch FROM users WHERE id = ?", [userId]); const landedEpoch = Number(verify[0].session_epoch); assert.notStrictEqual( landedEpoch, previousEpoch, `iteration ${i}: epoch must differ from the immediately previous one` ); assert.ok( !seenEpochs.has(landedEpoch), `iteration ${i}: epoch must never revisit any generation seen in this run (got ${landedEpoch})` ); assertValidEpoch(landedEpoch); seenEpochs.add(landedEpoch); } }); // --------------------------------------------------------------------------- // (c) pending_session_revocations claim-by-conditional-DELETE queue // --------------------------------------------------------------------------- async function produceRevocationRequest(pool, email, requestedAt, reason) { // Producer shape from scripts/create-user.js:96-104 — the CLI runs outside // the panel workers, so the queue is the only cross-process channel. await pool.query(MIRRORED_PRODUCER_UPSERT, [email, requestedAt, reason]); } test("cross-worker revocation queue: producer upsert stays email-keyed (one row, latest requested_at wins) and the claim DELETE is won by exactly one worker", async (t) => { if (!mysqlUrl) return t.skip(MYSQL_SKIP_REASON); const { poolA, poolB, runId } = await ensureMysqlFixture(); assertMirrorsStillMatchSources(); const email = testEmail(runId, "queue-upsert"); const firstAt = Date.now() - 5; const secondAt = Date.now(); // The CLI producing TWICE (e.g. --update-password then --delete) must leave // ONE row carrying the LATEST requested_at: the PRIMARY KEY on email is the // claim mechanism, so the producer must never stack duplicates. await produceRevocationRequest(poolA, email, firstAt, "cli-password"); await produceRevocationRequest(poolB, email, secondAt, "cli-delete"); const [afterUpserts] = await poolA.query( "SELECT email, requested_at, reason FROM pending_session_revocations WHERE email = ?", [email] ); assert.strictEqual(afterUpserts.length, 1, "the email-keyed upsert must keep exactly one row per email"); assert.strictEqual(Number(afterUpserts[0].requested_at), secondAt, "the surviving row carries the latest requested_at"); assert.strictEqual(afterUpserts[0].reason, "cli-delete", "the surviving row carries the latest reason"); // Deterministic claim race, then a concurrent one — in both, exactly one // worker's conditional DELETE removes the row (affectedRows 1); the loser // sees 0 and must not process the request. for (let round = 0; round < 8; round += 1) { const reqAt = Date.now() + round; await produceRevocationRequest(poolA, email, reqAt, "round"); if (round % 2 === 0) { const [claimA] = await poolA.query(MIRRORED_CLAIM_DELETE, [email, reqAt]); assert.strictEqual(claimA.affectedRows, 1, `round ${round}: the first claimant wins`); const [claimB] = await poolB.query(MIRRORED_CLAIM_DELETE, [email, reqAt]); assert.strictEqual(claimB.affectedRows, 0, `round ${round}: the second claimant loses once the row is gone`); } else { const [claimA, claimB] = await Promise.all([ poolA.query(MIRRORED_CLAIM_DELETE, [email, reqAt]), poolB.query(MIRRORED_CLAIM_DELETE, [email, reqAt]), ]); const total = claimA[0].affectedRows + claimB[0].affectedRows; assert.strictEqual(total, 1, `round ${round}: exactly one of two concurrent claimants may remove the row`); } const [left] = await poolB.query("SELECT email FROM pending_session_revocations WHERE email = ?", [email]); assert.strictEqual(left.length, 0, `round ${round}: claimed rows are gone — no double-processing and no residue`); } // The sweep's newer-request guard (index.js:17653-17657) reads its shape // off the same table: a row with a strictly greater requested_at must be // discoverable so a failing eviction never requeues over a fresh CLI request. const olderAt = Date.now() - 1000; const newerAt = Date.now() + 1000; await produceRevocationRequest(poolA, email, olderAt, "old"); await produceRevocationRequest(poolB, email, newerAt, "new"); const [newer] = await poolA.query( "SELECT email FROM pending_session_revocations WHERE email = ? AND requested_at > ? LIMIT 1", [email, olderAt] ); assert.strictEqual(newer.length, 1, "the newer-request guard must see the fresh CLI request over the stale one"); // Leave the table empty for later tests. await poolA.query(MIRRORED_CLAIM_DELETE, [email, newerAt]); }); // --------------------------------------------------------------------------- // (d) claimRecoveryCode full-array CAS — single-use enforcement cross-worker // --------------------------------------------------------------------------- async function mirroredClaimRecoveryCode(pool, userId, codeHash) { // Index.js:49588-49612 verbatim shape (read → parse → splice → full-array // CAS → affectedRows gate). db.query there returns rows directly; pool.query // returns [rows, fields]. const [rows] = await pool.query("SELECT recovery_codes FROM users WHERE id = ? LIMIT 1", [userId]); const row = rows[0]; if (!row || !row.recovery_codes) return { ok: false }; const currentArray = JSON.parse(row.recovery_codes); if (!Array.isArray(currentArray)) return { ok: false }; const matchedIndex = currentArray.indexOf(codeHash); if (matchedIndex === -1) return { ok: false }; const updated = currentArray.slice(); updated.splice(matchedIndex, 1); const [result] = await pool.query(MIRRORED_RECOVERY_CLAIM_CAS, [ JSON.stringify(updated), userId, JSON.stringify(currentArray), ]); if (!result || result.affectedRows !== 1) return { ok: false }; return { ok: true, remaining: updated.length }; } test("cross-worker recovery-code claims: two workers claiming DIFFERENT codes from one array — exactly one wins and only the winner's code is consumed", async (t) => { if (!mysqlUrl) return t.skip(MYSQL_SKIP_REASON); const { poolA, poolB, runId } = await ensureMysqlFixture(); assertMirrorsStillMatchSources(); const email = testEmail(runId, "recovery-diff"); const [ins] = await poolA.query( "INSERT INTO users (email, password, session_epoch) VALUES (?, ?, ?)", [email, uniquePassword(runId, "rc-seed"), newSessionEpochDifferentFrom(0)] ); const userId = ins.insertId; const codeA = `RC${runId.toUpperCase()}AAAAAA`.slice(0, 24); const codeB = `RC${runId.toUpperCase()}BBBBBB`.slice(0, 24); for (let round = 0; round < 8; round += 1) { const fullArray = JSON.stringify([codeA, codeB]); await poolA.query("UPDATE users SET recovery_codes = ? WHERE id = ?", [fullArray, userId]); const [epochBefore] = await poolA.query("SELECT session_epoch FROM users WHERE id = ?", [userId]); // Both workers read the SAME stored array, then race their claims on // different codes — the full-array CAS is the only serialization point. const [resA, resB] = await Promise.all([ mirroredClaimRecoveryCode(poolA, userId, codeA), mirroredClaimRecoveryCode(poolB, userId, codeB), ]); const wins = (resA.ok ? 1 : 0) + (resB.ok ? 1 : 0); assert.strictEqual(wins, 1, `round ${round}: exactly one of two concurrent claims may win the full-array CAS`); const [finalRows] = await poolB.query("SELECT recovery_codes, session_epoch FROM users WHERE id = ?", [userId]); const finalArray = JSON.parse(finalRows[0].recovery_codes); assert.strictEqual(finalArray.length, 1, `round ${round}: exactly one code remains after the winning claim`); if (resA.ok) { assert.deepStrictEqual(finalArray, [codeB], `round ${round}: A won — only B's code remains (A's removal committed wholesale, B's rejected wholesale)`); } else { assert.deepStrictEqual(finalArray, [codeA], `round ${round}: B won — only A's code remains`); } const winnerRemaining = resA.ok ? resA.remaining : resB.remaining; assert.strictEqual(winnerRemaining, 1, "winner reports the post-splice remaining count"); const loser = resA.ok ? resB : resA; assert.strictEqual(loser.ok, false, "loser reports ok:false per claimRecoveryCode's contract"); // Session-epoch rule (utils/session-epoch.js:17-20): a recovery-code burn // is epoch-free — a lost CAS must not have already bumped anything. assert.strictEqual( Number(finalRows[0].session_epoch), Number(epochBefore[0].session_epoch), "recovery-code claims must never move session_epoch" ); } }); test("cross-worker recovery-code claims: two workers claiming the SAME code — single-use holds, exactly one consumption", async (t) => { if (!mysqlUrl) return t.skip(MYSQL_SKIP_REASON); const { poolA, poolB, runId } = await ensureMysqlFixture(); const email = testEmail(runId, "recovery-same"); const [ins] = await poolA.query( "INSERT INTO users (email, password, session_epoch) VALUES (?, ?, ?)", [email, uniquePassword(runId, "rc2-seed"), newSessionEpochDifferentFrom(0)] ); const userId = ins.insertId; const codeA = `RC${runId.toUpperCase()}CCCCCC`.slice(0, 24); const codeB = `RC${runId.toUpperCase()}DDDDDD`.slice(0, 24); for (let round = 0; round < 8; round += 1) { await poolA.query("UPDATE users SET recovery_codes = ? WHERE id = ?", [ JSON.stringify([codeA, codeB]), userId, ]); const [resA, resB] = await Promise.all([ mirroredClaimRecoveryCode(poolA, userId, codeA), mirroredClaimRecoveryCode(poolB, userId, codeA), ]); const wins = (resA.ok ? 1 : 0) + (resB.ok ? 1 : 0); assert.strictEqual(wins, 1, `round ${round}: a recovery code is single-use cluster-wide — exactly one claim of the same code may succeed`); const [finalRows] = await poolB.query("SELECT recovery_codes FROM users WHERE id = ?", [userId]); assert.deepStrictEqual(JSON.parse(finalRows[0].recovery_codes), [codeB], `round ${round}: the claimed code is gone, the other code untouched`); } }); // --------------------------------------------------------------------------- // Redis tombstone visibility across two OS PROCESSES // --------------------------------------------------------------------------- test("cross-worker sid tombstone: a tombstone written by a spawned child process (worker A's SET EX shape) is visible to worker B's isSessionSidRevoked GET shape", { timeout: 30000 }, async (t) => { if (!redisUrl) return t.skip(REDIS_SKIP_REASON); const redis = require("redis"); const clientB = redis.createClient({ url: redisUrl }); // worker B, THIS process clientB.on("error", () => {}); // required listener — a client without one crashes the worker on socket errors const connectTimeout = new Promise((_, reject) => setTimeout(() => reject(new Error("redis connect timeout")), 10000)); await Promise.race([clientB.connect(), connectTimeout]); try { const sid = `cwtest-${crypto.randomBytes(12).toString("hex")}`; const key = MIRRORED_TOMBSTONE_REDIS_PREFIX + sid; // Worker A: a separate OS process performing index.js writeRevokedSidTombstone's // durable leg (rememberRevokedSidTombstoneLocally + redisClient.set(key, "1", { EX: TTL })). const childScript = ` const { createClient } = require("redis"); (async () => { const c = createClient({ url: process.env.ADPANEL_TEST_REDIS_URL }); c.on("error", () => {}); await c.connect(); await c.set(process.argv[1], "1", { EX: Number(process.argv[2]) }); await c.quit(); })().catch((e) => { console.error(e && e.message); process.exit(1); }); `; const child = spawnSync(process.execPath, ["-e", childScript, key, String(MIRRORED_TOMBSTONE_TTL_SECONDS)], { cwd: REPO_ROOT, env: { ...process.env, ADPANEL_TEST_REDIS_URL: redisUrl }, encoding: "utf8", timeout: 15000, }); assert.strictEqual(child.status, 0, `worker A's tombstone write process must succeed (stderr: ${child.stderr})`); // Worker B: isSessionSidRevoked's Redis leg (index.js:4595-4600) — any // GET hit means revoked; the local-Map fast path cannot mask the answer // because this worker never wrote the sid itself. const hit = await clientB.get(key); assert.strictEqual(hit, "1", "worker B must see worker A's tombstone"); const ttl = await clientB.ttl(key); assert.ok(ttl > 0, "the tombstone must carry the writer's EX lifetime (non-expiring tombstones are not the shipped shape)"); // The un-revoked branch: a sid no worker tombstoned must read as null. const miss = await clientB.get(MIRRORED_TOMBSTONE_REDIS_PREFIX + `cwtest-absent-${crypto.randomBytes(8).toString("hex")}`); assert.strictEqual(miss, null, "an un-tombstoned sid must not read as revoked"); await clientB.del(key); } finally { await clientB.quit().catch(() => {}); } });