"use strict"; // adpanel:last-admin-guard — behavioral pins for the transactional // administrator-survival guard inside deleteUserAccountAtomically. // // The defect this file pins shut: two already-authenticated admins deleting // each other BOTH committed (each transaction checked nothing about the admin // set), leaving the panel with zero administrators. withServersIndexWriteLock // is a per-process promise chain that does NOT serialize pm2 cluster workers, // so only InnoDB can arbitrate the race — the fix is a locking read // (`SELECT id, admin, suspended FROM users WHERE admin = 1 FOR UPDATE`) taken // inside the delete transaction AFTER the target re-read and BEFORE any // destructive cleanup, plus two in-transaction conditions: the ACTING // administrator must still be usable (admin = 1 AND suspended = 0 — isAdmin() // requires !suspended && admin, so a suspended admin cannot administer the // panel), and at least ONE usable administrator other than the target must // remain. The acting admin themself is a legitimate survivor (self-delete is // refused upstream), which is what makes the mutual-deletion race safe: // whichever delete commits first wins, the second resumes after that commit, // re-counts on fresh committed state and rolls back. // // Harness: index.js is a ~56k-line bundle with DB/network side effects at // require time — never require() it. The REAL `deleteUserAccountAtomically` // (and the REAL delete route handler, for the 409 mapping) are vm-extracted // as source and run against a fake DB that emulates the InnoDB semantics the // guard's correctness rests on: // * a transaction's writes stay in a per-connection overlay; COMMIT // publishes them, ROLLBACK discards them; // * plain reads see committed state plus the connection's own overlay; // * `SELECT ... FOR UPDATE` on users acquires an engine-level JS mutex held // until commit/rollback (reentrant for the owning connection) and reads // the LATEST COMMITTED state after acquiring — a competitor that resumes // after the holder's commit observes the post-commit rows; // * DELETE FROM users takes the same mutex before evaluating affectedRows. // Two "cluster workers" are emulated as two concurrent connections with the // process-local index lock passed through (the chain does not serialize // cross-process); the interleaving is driven by pre-armed statement gates on // the fake connections, so it is deterministic rather than microtask-luck. 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_SRC = fs.readFileSync(path.join(ROOT, "index.js"), "utf8"); const ADMIN_GUARD_SQL = "SELECT id, admin, suspended, session_epoch FROM users WHERE admin = 1 ORDER BY id FOR UPDATE"; const LAST_ADMIN_409 = { error: "cannot delete the last active administrator account", lastAdmin: true }; const TARGET_GONE_409 = { error: "account state changed; reload accounts and try again" }; // ─── source extraction (same slicing discipline as the other audit tests) ─── function windowToLineClose(src, anchor, label) { const start = src.indexOf(anchor); assert.notStrictEqual(start, -1, `${label}: anchor not found: ${anchor}`); const end = src.indexOf("\n}", start); assert.notStrictEqual(end, -1, `${label}: no closing brace after: ${anchor}`); return src.slice(start, end + 2); } function windowInclusive(src, startAnchor, endAnchor, label) { const start = src.indexOf(startAnchor); assert.notStrictEqual(start, -1, `${label}: start anchor not found: ${startAnchor}`); const end = src.indexOf(endAnchor, start); assert.notStrictEqual(end, -1, `${label}: end anchor not found: ${endAnchor}`); return src.slice(start, end + endAnchor.length); } const USER_OWNED_TABLES_SRC = windowInclusive(INDEX_SRC, "const USER_OWNED_TABLES = [", "];", "USER_OWNED_TABLES"); const PARSE_DB_JSON_SRC = windowToLineClose(INDEX_SRC, "function parseDbJson(", "parseDbJson"); const TO_DB_JSON_SRC = windowToLineClose(INDEX_SRC, "function toDbJson(", "toDbJson"); const STRIP_ACL_SRC = windowToLineClose(INDEX_SRC, "function stripAclEntriesWhere(", "stripAclEntriesWhere"); const INDEX_LOCK_SRC = windowToLineClose(INDEX_SRC, "let _serversIndexWriteChain = Promise.resolve();", "withServersIndexWriteLock"); const ATOMIC_FN_SRC = windowToLineClose(INDEX_SRC, "async function deleteUserAccountAtomically(", "deleteUserAccountAtomically"); const HANDLER_START = 'app.delete("/api/settings/accounts/:email"'; const HANDLER_END = 'app.post("/api/settings/accounts/:email/change-password"'; const routeStart = INDEX_SRC.indexOf(HANDLER_START); const routeEnd = INDEX_SRC.indexOf(HANDLER_END); assert.notStrictEqual(routeStart, -1, "delete route marker not found in index.js"); assert.ok(routeEnd > routeStart, "change-password route marker not found after the delete route"); const ROUTE_SRC = INDEX_SRC.slice(routeStart, routeEnd); // ─── fake InnoDB engine ────────────────────────────────────────────────────── class FakeConn { constructor(engine, id) { this.engine = engine; this.id = id; this.overlays = new Map(); this.sqlLog = []; this.committed = false; this.rolledBack = false; this.released = false; this.failOn = null; // regex — throws before dispatch when matched this._holdPatterns = []; this.holdFiredCount = 0; this._holdResolve = null; this._holdAnnounce = null; } // Holds the connection before dispatching the FIRST statement matching each // pattern, in order, until proceedHold() is called. holdAt(...patterns) { this._holdPatterns = [...patterns]; } proceedHold() { if (this._holdResolve) { const resolve = this._holdResolve; this._holdResolve = null; resolve(); } } readTable(name) { if (this.overlays.has(name)) return this.overlays.get(name); return this.engine.tables[name] || []; } writeTable(name) { if (!this.overlays.has(name)) { this.overlays.set(name, (this.engine.tables[name] || []).map((row) => ({ ...row }))); } return this.overlays.get(name); } async acquireUsersLock() { const eng = this.engine; for (;;) { if (eng.usersLockOwner === null || eng.usersLockOwner === this.id) { eng.usersLockOwner = this.id; return; } if (!eng.lockWaiters.includes(this.id)) eng.lockWaiters.push(this.id); await new Promise((resolve) => eng.lockQueue.push(resolve)); } } releaseUsersLock() { const eng = this.engine; if (eng.usersLockOwner !== this.id) return; eng.usersLockOwner = null; const queue = eng.lockQueue; eng.lockQueue = []; for (const wake of queue) wake(); } async execute(sql, params = []) { const statement = String(sql); this.sqlLog.push(statement.replace(/\s+/g, " ").trim()); if (this._holdPatterns.length > 0 && this._holdPatterns[0].test(statement)) { this._holdPatterns.shift(); this.holdFiredCount++; await new Promise((resolve) => { this._holdResolve = resolve; if (this._holdAnnounce) this._holdAnnounce(); }); } if (this.failOn && this.failOn.test(statement)) { throw new Error(`injected harness failure at: ${statement.slice(0, 60)}`); } return this.dispatch(statement, params); } async dispatch(statement, params) { // Target re-read (plain read: committed state plus own overlay). if (/^SELECT id FROM users WHERE id = \? LIMIT 1$/.test(statement)) { const rows = this.readTable("users").filter((row) => Number(row.id) === Number(params[0])); return [rows.map((row) => ({ id: row.id }))]; } // The last-admin guard's locking read: acquire the mutex FIRST, then read // the latest committed admin rows. if (statement === ADMIN_GUARD_SQL) { await this.acquireUsersLock(); const rows = this.readTable("users").filter((row) => Number(row.admin) === 1); return [rows.map((row) => ({ id: row.id, admin: row.admin, suspended: row.suspended, session_epoch: row.session_epoch }))]; } if (/^SELECT id, email FROM users WHERE id = \? FOR UPDATE$/.test(statement)) { return [this.readTable("users").filter((row) => Number(row.id) === Number(params[0])).map((row) => ({ id: row.id, email: row.email }))]; } if (/^SELECT name, acl FROM servers ORDER BY id FOR UPDATE$/.test(statement)) { return [this.readTable("servers").map((row) => ({ name: row.name, acl: row.acl }))]; } if (/^UPDATE servers SET acl = \? WHERE name = \?$/.test(statement)) { const rows = this.writeTable("servers"); const row = rows.find((candidate) => candidate.name === params[1]); if (row) row.acl = params[0]; return [{ affectedRows: row ? 1 : 0 }]; } const ownedDelete = /^DELETE FROM ([A-Za-z_]+) WHERE user_id = \?$/.exec(statement); if (ownedDelete) { const before = this.readTable(ownedDelete[1]).length; const kept = this.readTable(ownedDelete[1]).filter((row) => Number(row.user_id) !== Number(params[0])); this.overlays.set(ownedDelete[1], kept); return [{ affectedRows: before - kept.length }]; } if (/^SELECT id, server_name FROM server_planner_items WHERE prompt_author_id = \? OR \(prompt_author_id IS NULL AND created_by_email = \?\)$/.test(statement)) { const rows = this.readTable("server_planner_items").filter((row) => row.prompt_author_id == null ? row.created_by_email === params[1] : Number(row.prompt_author_id) === Number(params[0])); return [rows.map((row) => ({ id: row.id, server_name: row.server_name }))]; } // The planner retract's queued-jobs JOIN: the harness seeds no queued jobs, // so the retract block is a no-op in every scenario below. if (/FROM ai_agent_jobs j/.test(statement) && /JOIN server_planner_items i/.test(statement)) { return [[]]; } if (/^SELECT id FROM ai_chats WHERE id IN /.test(statement)) { const ids = params.slice(0, params.length - 1).map(Number); const excludedOwnerId = Number(params[params.length - 1]); const rows = this.readTable("ai_chats").filter( (row) => ids.includes(Number(row.id)) && row.created_by != null && Number(row.created_by) !== excludedOwnerId ); return [rows.map((row) => ({ id: row.id }))]; } if (/^UPDATE ai_agent_jobs SET status = 'cancelled'/.test(statement)) { return [{ affectedRows: 0 }]; } if (/^INSERT INTO ai_messages /.test(statement)) { const rows = this.writeTable("ai_messages"); rows.push({ chat_id: params[0], role: params[1], content: params[2], model: params[6] }); return [{ affectedRows: 1, insertId: rows.length }]; } if (/^DELETE FROM ai_messages WHERE chat_id IN \(SELECT id FROM ai_chats WHERE created_by = \?\)$/.test(statement)) { const doomedChatIds = new Set( this.readTable("ai_chats").filter((row) => Number(row.created_by) === Number(params[0])).map((row) => Number(row.id)) ); const before = this.readTable("ai_messages").length; const kept = this.readTable("ai_messages").filter((row) => !doomedChatIds.has(Number(row.chat_id))); this.overlays.set("ai_messages", kept); return [{ affectedRows: before - kept.length }]; } if (/^DELETE FROM ai_chats WHERE created_by = \?$/.test(statement)) { const before = this.readTable("ai_chats").length; const kept = this.readTable("ai_chats").filter((row) => Number(row.created_by) !== Number(params[0])); this.overlays.set("ai_chats", kept); return [{ affectedRows: before - kept.length }]; } if (/^DELETE FROM server_planner_items WHERE prompt_author_id = \? OR \(prompt_author_id IS NULL AND created_by_email = \?\)$/.test(statement)) { const before = this.readTable("server_planner_items").length; const kept = this.readTable("server_planner_items").filter((row) => row.prompt_author_id == null ? row.created_by_email !== params[1] : Number(row.prompt_author_id) !== Number(params[0])); this.overlays.set("server_planner_items", kept); return [{ affectedRows: before - kept.length }]; } if (/^DELETE FROM users WHERE id = \?$/.test(statement)) { await this.acquireUsersLock(); const rows = this.readTable("users"); const row = rows.find((candidate) => Number(candidate.id) === Number(params[0])); if (!row) return [{ affectedRows: 0 }]; this.overlays.set("users", rows.filter((candidate) => candidate !== row)); return [{ affectedRows: 1 }]; } if (statement.startsWith("SELECT id FROM dashboard_assistant_chats")) { const error = new Error("dashboard_assistant_chats not installed in this fixture"); error.code = "ER_NO_SUCH_TABLE"; throw error; } throw new Error(`fake engine: unsupported statement: ${statement.slice(0, 120)}`); } async beginTransaction() { // no per-connection state needed beyond the overlay lifecycle } async commit() { for (const [name, rows] of this.overlays) this.engine.tables[name] = rows; this.overlays.clear(); this.releaseUsersLock(); this.committed = true; } async rollback() { this.overlays.clear(); this.releaseUsersLock(); this.rolledBack = true; } release() { this.released = true; } } function createFakeEngine(seed = {}) { const engine = { tables: { users: (seed.users || []).map((row) => ({ session_epoch: 11, ...row })), servers: (seed.servers || []).map((row) => ({ ...row })), user_access: (seed.user_access || []).map((row) => ({ ...row })), user_status: (seed.user_status || []).map((row) => ({ ...row })), sftp_credentials: (seed.sftp_credentials || []).map((row) => ({ ...row })), user_ai_model_selections: (seed.user_ai_model_selections || []).map((row) => ({ ...row })), destructive_action_grants: (seed.destructive_action_grants || []).map((row) => ({ ...row })), ai_agent_jobs: (seed.ai_agent_jobs || []).map((row) => ({ ...row })), server_planner_items: (seed.server_planner_items || []).map((row) => ({ ...row })), ai_chats: (seed.ai_chats || []).map((row) => ({ ...row })), ai_messages: (seed.ai_messages || []).map((row) => ({ ...row })), }, usersLockOwner: null, lockQueue: [], lockWaiters: [], preArmed: [], conns: [], connSeq: 0, }; return engine; } async function waitFor(predicate, label) { for (let i = 0; i < 2000; i++) { if (predicate()) return; await new Promise((resolve) => setImmediate(resolve)); } throw new Error(`harness timeout waiting for: ${label}`); } // Builds a vm context holding the REAL extracted sources against a fake DB. // lockMode "passthrough" emulates separate pm2 cluster workers (the // process-local chain does not serialize cross-process); "real" keeps the // extracted withServersIndexWriteLock source for the single-process contracts. function buildHarness({ seed = {}, lockMode = "passthrough", routeView = {} } = {}) { const engine = createFakeEngine(seed); const makeConn = () => { const conn = new FakeConn(engine, ++engine.connSeq); engine.conns.push(conn); return conn; }; const db = { pool: { getConnection: async () => { if (engine.preArmed.length > 0) return engine.preArmed.shift(); return makeConn(); }, }, query: async () => ({ affectedRows: 0 }), }; const lockSource = lockMode === "passthrough" ? "async function withServersIndexWriteLock(task) { return await task(); }" : INDEX_LOCK_SRC; const sandbox = { ...require("../services/account-actions"), db, app: { delete: (routePath, middleware, handler) => { sandbox.__deleteRouteHandler = handler; } }, sessionRevoke2faRateLimiter: (req, res, next) => next(), isAdmin: async () => true, requireActionTokenOr403: async () => true, findUserByEmail: async (email) => { const user = routeView[String(email || "").trim().toLowerCase()]; return user ? { session_epoch: 11, ...user } : null; }, lockAccountActor: require("../services/account-actions").lockAccountActor, deleteAccountAssistantHistory: require("../services/dashboard-assistant-history").deleteAccountAssistantHistory, deleteAccountServerAgentChats: require("../services/server-agent-chat-ownership").deleteAccountServerAgentChats, requireDestructiveActionStepUp: async () => ({ ok: true, graceExpiresAt: 0 }), issueActionToken: () => "harness-token", getVerifiedSessionRevokeGraceState: async () => null, destroyBrowserSessionsForUser: async () => ({ destroyed: 1, skipped: 0, rememberLoginsRevoked: 0, errors: [], scanIncomplete: false }), disconnectSocketsForUser: () => 3, cancelSchedulesCreatedBy: async () => undefined, stripLogControlChars: (value) => String(value == null ? "" : value), getRequestIp: () => "127.0.0.1", invalidateServerIndexCache: () => undefined, console, setTimeout, __capture: {}, }; const script = [ USER_OWNED_TABLES_SRC, PARSE_DB_JSON_SRC, TO_DB_JSON_SRC, STRIP_ACL_SRC, lockSource, ATOMIC_FN_SRC, ROUTE_SRC, "__capture.deleteUserAccountAtomically = deleteUserAccountAtomically;", ].join("\n"); vm.createContext(sandbox); vm.runInContext(script, sandbox, { filename: "extracted-delete-pipeline.js" }); return { engine, db, makeConn, deleteUserAccountAtomically: (userId, email, options = {}) => sandbox.__capture.deleteUserAccountAtomically(userId, email, { actingAdminEpoch: 11, ...options }), deleteRouteHandler: sandbox.__deleteRouteHandler, }; } function makeRes() { return { // Express sends 200 when the handler never calls res.status() — the // delete route's success path is such a res.json(). statusCode: 200, body: null, set() { return this; }, status(code) { this.statusCode = code; return this; }, json(payload) { this.body = payload; return this; }, }; } function usableAdminRows(engine) { return engine.tables.users.filter((row) => Number(row.admin) === 1 && Number(row.suspended) === 0); } // ─── the mutual-deletion race ──────────────────────────────────────────────── test("two mutually-deleting admins cannot both succeed: the second transaction resumes after the first commits, finds no usable survivor, and rolls back", async () => { const harness = buildHarness({ seed: { users: [ { id: 1, email: "a@example.com", admin: 1, suspended: 0 }, { id: 2, email: "b@example.com", admin: 1, suspended: 0 }, ], }, }); const { engine, deleteUserAccountAtomically } = harness; // Worker one (admin A deletes admin B): pre-arm its connection and hold it // mid-transaction at its users DELETE — past its guard, admin-row mutex held. const conn1 = harness.makeConn(); engine.preArmed.push(conn1); conn1.holdAt(/^DELETE FROM users WHERE id = \?$/); const pending1 = deleteUserAccountAtomically(2, "b@example.com", { actingAdminId: 1 }); await waitFor(() => conn1.holdFiredCount >= 1, "worker one held at its users DELETE"); // Worker two (admin B deletes admin A) starts while worker one is mid-tx. let outcome2; const pending2 = deleteUserAccountAtomically(1, "a@example.com", { actingAdminId: 2 }).then((value) => { outcome2 = value; return value; }); await waitFor(() => engine.conns.length >= 2, "worker two connection created"); const conn2 = engine.conns[1]; // Give worker two a macrotask to progress; it either settles (pre-fix hole: // no locking read, nothing to block on) or parks on the admin-row mutex // (post-fix: FOR UPDATE waits for worker one's commit/rollback). await new Promise((resolve) => setImmediate(resolve)); if (outcome2 === undefined) { await waitFor(() => engine.lockWaiters.includes(conn2.id), "worker two blocked on the admin-row mutex"); } conn1.proceedHold(); const outcome1 = await pending1; await pending2; // Exactly one delete wins; the loser must be the distinguishable last-admin // refusal with NOTHING committed — no users DELETE on its connection. const winners = [outcome1, outcome2].filter((outcome) => outcome && outcome.deleted === true); assert.equal( winners.length, 1, `exactly one of the two mutually-deleting admins may commit — got outcomes: ${JSON.stringify([outcome1, outcome2])}; ` + `users left: ${JSON.stringify(engine.tables.users)}` ); const loser = outcome1 && outcome1.deleted === true ? outcome2 : outcome1; const loserConn = outcome1 && outcome1.deleted === true ? conn2 : conn1; assert.ok( loserConn.sqlLog.some((s) => s === ADMIN_GUARD_SQL), "the losing transaction must have taken the admin-row locking read" ); assert.deepEqual(loser, { deleted: false, reason: "last-admin" }); assert.equal(loserConn.rolledBack, true, "the losing transaction must roll back"); assert.equal(loserConn.committed, false, "the losing transaction must not commit"); assert.equal( loserConn.sqlLog.some((statement) => /^DELETE FROM users WHERE id = \?$/.test(statement)), false, "the losing transaction must never execute its users DELETE" ); assert.ok(engine.lockWaiters.includes(conn2.id), "the second transaction must have serialized on the admin-row mutex (FOR UPDATE)"); assert.equal(usableAdminRows(engine).length, 1, `exactly one usable administrator must remain — got: ${JSON.stringify(engine.tables.users)}`); assert.deepEqual( engine.tables.users.map((row) => row.id).sort(), [1], "the surviving administrator is the one whose delete committed first" ); }); // ─── normal deletions must keep working ────────────────────────────────────── test("a normal (non-admin-target) deletion still succeeds with the guard read and all cleanup orderings intact", async () => { const harness = buildHarness({ seed: { users: [ { id: 1, email: "a@example.com", admin: 1, suspended: 0 }, { id: 5, email: "d@example.com", admin: 0, suspended: 0 }, { id: 6, email: "s@example.com", admin: 1, suspended: 1 }, ], servers: [ { name: "s1", acl: JSON.stringify({ "d@example.com": { level: "user" }, "keep@example.com": { level: "admin" } }) }, ], user_access: [ { user_id: 5, server_name: "s1" }, { user_id: 1, server_name: "s1" }, ], user_status: [{ user_id: 5, status: "idle" }], sftp_credentials: [{ user_id: 5, host: "h" }], user_ai_model_selections: [{ user_id: 5, model: "m" }], destructive_action_grants: [{ user_id: 5, scope: "x" }], ai_agent_jobs: [{ user_id: 5, status: "queued" }], server_planner_items: [ { id: 7, prompt_author_id: 5, created_by_email: "prior-address@example.com", server_name: "s1" }, { id: 8, prompt_author_id: 1, created_by_email: "d@example.com", server_name: "s1" }, { id: 9, prompt_author_id: null, created_by_email: "d@example.com", server_name: "s1" }, ], ai_chats: [ { id: 10, created_by: 5, user_email: "prior-address@example.com" }, { id: 11, created_by: 1, user_email: "d@example.com" }, { id: 12, created_by: null, user_email: "d@example.com" }, ], ai_messages: [ { chat_id: 10, role: "user", content: "one" }, { chat_id: 10, role: "assistant", content: "two" }, { chat_id: 11, role: "user", content: "keep" }, { chat_id: 12, role: "user", content: "unattributed" }, ], }, }); const { engine, deleteUserAccountAtomically } = harness; const conn = harness.makeConn(); engine.preArmed.push(conn); const outcome = await deleteUserAccountAtomically(5, "d@example.com", { actingAdminId: 1 }); assert.deepEqual(outcome, { deleted: true }); // The account row is gone; the suspended admin (not usable) and the acting // admin remain untouched. assert.deepEqual(engine.tables.users.map((row) => row.id).sort(), [1, 6]); // ACL entries for the deleted email are stripped; the co-user's survive. const acl = JSON.parse(engine.tables.servers[0].acl); assert.deepEqual(Object.keys(acl), ["keep@example.com"]); // Every user-owned table loses the target's rows and keeps the acting admin's. assert.equal(engine.tables.user_access.some((row) => Number(row.user_id) === 5), false); assert.equal(engine.tables.user_access.some((row) => Number(row.user_id) === 1), true); for (const table of ["user_status", "sftp_credentials", "user_ai_model_selections", "destructive_action_grants", "ai_agent_jobs"]) { assert.equal(engine.tables[table].length, 0, `${table} rows for the deleted account must be gone`); } // The target's chat is reaped by ID despite its older address. A different // owner's chat and an unattributed chat cannot be selected by email reuse. assert.deepEqual(engine.tables.ai_chats.map((row) => row.id), [11, 12]); assert.deepEqual(engine.tables.ai_messages.map((row) => row.content), ["keep", "unattributed"]); assert.deepEqual(engine.tables.server_planner_items.map((row) => row.id), [8]); // Orderings: target re-read -> guard read -> ACL rewrite -> user_id-keyed // loop -> chat and planner deletes (messages before chats) -> users DELETE. const idx = (pattern) => conn.sqlLog.findIndex((statement) => pattern.test(statement)); const idxTarget = idx(/^SELECT id FROM users WHERE id = \? LIMIT 1$/); const idxGuard = idx(/^SELECT id, admin, suspended, session_epoch FROM users WHERE admin = 1 ORDER BY id FOR UPDATE$/); const idxServers = idx(/^SELECT name, acl FROM servers ORDER BY id FOR UPDATE$/); const idxOwnedLoop = idx(/^DELETE FROM user_access WHERE user_id = \?$/); const idxMessages = idx(/^DELETE FROM ai_messages WHERE chat_id IN/); const idxChats = idx(/^DELETE FROM ai_chats WHERE created_by = \?$/); const idxPlanner = idx(/^DELETE FROM server_planner_items WHERE prompt_author_id = \? OR \(prompt_author_id IS NULL AND created_by_email = \?\)$/); const idxUsers = idx(/^DELETE FROM users WHERE id = \?$/); for (const [name, at] of [["target", idxTarget], ["guard", idxGuard], ["servers", idxServers], ["ownedLoop", idxOwnedLoop], ["messages", idxMessages], ["chats", idxChats], ["planner", idxPlanner], ["users", idxUsers]]) { assert.notStrictEqual(at, -1, `the deletion must execute the ${name} step`); } assert.ok(idxTarget < idxGuard, "the guard's locking read must run AFTER the target re-read"); assert.ok(idxGuard < idxServers, "the guard's locking read must run BEFORE any destructive cleanup (ACL rewrite)"); assert.ok(idxServers < idxOwnedLoop, "the ACL rewrite precedes the user_id-keyed loop"); assert.ok(idxOwnedLoop < idxMessages && idxMessages < idxChats && idxChats < idxPlanner && idxPlanner < idxUsers, "chat and planner deletes (ai_messages BEFORE ai_chats) must precede the users DELETE"); assert.equal(conn.committed, true); assert.equal(conn.released, true); }); test("deleting the last OTHER usable admin succeeds: the acting admin is a legitimate survivor", async () => { const harness = buildHarness({ seed: { users: [ { id: 1, email: "a@example.com", admin: 1, suspended: 0 }, { id: 2, email: "b@example.com", admin: 1, suspended: 0 }, ], }, }); const outcome = await harness.deleteUserAccountAtomically(2, "b@example.com", { actingAdminId: 1 }); assert.deepEqual(outcome, { deleted: true }); assert.deepEqual( harness.engine.tables.users.map((row) => row.id), [1], "the acting administrator remains and administers the panel" ); }); // ─── the actor re-check ────────────────────────────────────────────────────── test("the guard fires when the acting admin was concurrently demoted/suspended before the locking read", async () => { const harness = buildHarness({ seed: { users: [ { id: 1, email: "a@example.com", admin: 1, suspended: 0 }, { id: 2, email: "b@example.com", admin: 1, suspended: 0 }, ], }, }); const { engine, deleteUserAccountAtomically } = harness; const conn = harness.makeConn(); engine.preArmed.push(conn); conn.holdAt(/^SELECT id, admin, suspended, session_epoch FROM users WHERE admin = 1 ORDER BY id FOR UPDATE$/); const pending = deleteUserAccountAtomically(2, "b@example.com", { actingAdminId: 1 }); await waitFor(() => conn.holdFiredCount >= 1, "delete held just before its locking read"); // A concurrent transaction (already committed) suspended the ACTING admin. engine.tables.users.find((row) => row.id === 1).suspended = 1; conn.proceedHold(); const outcome = await pending; assert.deepEqual( outcome, { deleted: false, reason: "last-admin" }, "a suspended acting administrator must fail the actor re-check" ); assert.equal(conn.rolledBack, true); assert.equal(conn.committed, false); assert.deepEqual( engine.tables.users.map((row) => `${row.id}:${row.admin}:${row.suspended}`).sort(), ["1:1:1", "2:1:0"], "nothing may be deleted when the actor re-check fails" ); }); // ─── fail-closed contract ──────────────────────────────────────────────────── test("deletion refuses an administrator whose verified generation changed", async () => { const harness = buildHarness({ seed: { users: [ { id: 1, email: "a@example.com", admin: 1, suspended: 0, session_epoch: 12 }, { id: 5, email: "d@example.com", admin: 0, suspended: 0 } ] } }); const outcome = await harness.deleteUserAccountAtomically(5, "d@example.com", { actingAdminId: 1, actingAdminEpoch: 11 }); assert.deepEqual(outcome, { deleted: false, reason: "last-admin" }); assert.equal(harness.engine.tables.users.length, 2); assert.equal(harness.engine.conns[0].committed, false); }); test("the guard fails closed when the caller omits actingAdminId", async () => { const harness = buildHarness({ seed: { users: [ { id: 1, email: "a@example.com", admin: 1, suspended: 0 }, { id: 5, email: "d@example.com", admin: 0, suspended: 0 }, ], }, }); const outcome = await harness.deleteUserAccountAtomically(5, "d@example.com"); assert.deepEqual(outcome, { deleted: false, reason: "last-admin" }); assert.equal(harness.engine.tables.users.length, 2, "nothing may be deleted without an acting-admin re-check"); }); // ─── rollback / release contracts ──────────────────────────────────────────── test("an injected mid-transaction error still rolls back, releases the connection and leaves the index lock chain healthy", async () => { const harness = buildHarness({ seed: { users: [ { id: 1, email: "a@example.com", admin: 1, suspended: 0 }, { id: 5, email: "d@example.com", admin: 0, suspended: 0 }, { id: 6, email: "s@example.com", admin: 1, suspended: 1 }, ], servers: [ { name: "s1", acl: JSON.stringify({ "d@example.com": { level: "user" } }) }, ], user_access: [{ user_id: 5, server_name: "s1" }], }, lockMode: "real", }); const { engine, deleteUserAccountAtomically } = harness; const conn = harness.makeConn(); engine.preArmed.push(conn); conn.failOn = /^UPDATE servers SET acl/; await assert.rejects( deleteUserAccountAtomically(5, "d@example.com", { actingAdminId: 1 }), /injected harness failure/ ); assert.equal(conn.rolledBack, true, "the error path must roll the transaction back"); assert.equal(conn.committed, false, "the error path must not commit"); assert.equal(conn.released, true, "the connection must be released in finally"); // Committed state is untouched: the ACL strip and the owned-table deletes // never published. assert.equal(engine.tables.users.length, 3); const acl = JSON.parse(engine.tables.servers[0].acl); assert.deepEqual(Object.keys(acl), ["d@example.com"]); assert.equal(engine.tables.user_access.length, 1); // The real per-process chain swallowed the rejection and stays usable — and // the aborted transaction released its admin-row lock, or this follow-up // delete would block forever on the fake mutex. const followUpConn = harness.makeConn(); engine.preArmed.push(followUpConn); const outcome = await Promise.race([ deleteUserAccountAtomically(5, "d@example.com", { actingAdminId: 1 }), new Promise((resolve, reject) => setTimeout(() => reject(new Error("follow-up delete hung: the aborted transaction leaked its lock")), 2000)), ]); assert.deepEqual(outcome, { deleted: true }); }); // ─── the route's outcome mapping ───────────────────────────────────────────── function makeReq(sessionUser, targetEmail) { return { session: { user: sessionUser }, params: { email: targetEmail }, body: { expectedTargetId: targetEmail === "a@example.com" ? 1 : targetEmail === "b@example.com" ? 2 : 5 } }; } test("the delete route maps reason:'last-admin' to a 409 that names the constraint, and keeps the target-gone 409 verbatim", async () => { // Case A: the target exists but the acting administrator was concurrently // deleted by their peer (the mutual-deletion endgame): the transaction // refuses with reason "last-admin" and the route must surface the explicit // last-admin 409 — not the generic target-gone message. const lastAdminHarness = buildHarness({ seed: { users: [{ id: 1, email: "a@example.com", admin: 1, suspended: 0 }] }, routeView: { "b@example.com": { id: 2, email: "b@example.com", admin: 1, suspended: 0 }, "a@example.com": { id: 1, email: "a@example.com", admin: 1, suspended: 0 }, }, }); let nextCalled = false; const resA = makeRes(); await lastAdminHarness.deleteRouteHandler( makeReq("b@example.com", "a@example.com"), resA, () => { nextCalled = true; } ); assert.equal(resA.statusCode, 409, `the last-admin refusal must be a 409 — got ${resA.statusCode}: ${JSON.stringify(resA.body)}`); assert.deepEqual(resA.body, LAST_ADMIN_409); assert.equal(nextCalled, false); // Case B: the route's target lookup raced a concurrent delete — the route // saw the user but the transaction's re-read finds the row gone. The // pre-existing 409 body must stay byte-identical (no lastAdmin flag). const targetGoneHarness = buildHarness({ seed: { users: [] }, routeView: { "b@example.com": { id: 2, email: "b@example.com", admin: 1, suspended: 0 }, "a@example.com": { id: 1, email: "a@example.com", admin: 0, suspended: 0 }, }, }); const resB = makeRes(); await targetGoneHarness.deleteRouteHandler(makeReq("b@example.com", "a@example.com"), resB, () => {}); assert.equal(resB.statusCode, 409); assert.deepEqual(resB.body, TARGET_GONE_409, "the existing target-gone 409 body must remain untouched"); }); test("the delete route still completes a normal deletion (proving actingAdminId flows into the transaction)", async () => { const harness = buildHarness({ seed: { users: [ { id: 1, email: "a@example.com", admin: 1, suspended: 0 }, { id: 5, email: "d@example.com", admin: 0, suspended: 0 }, ], servers: [{ name: "s1", acl: JSON.stringify({ "d@example.com": { level: "user" } }) }], }, routeView: { "a@example.com": { id: 1, email: "a@example.com", admin: 1, suspended: 0 }, "d@example.com": { id: 5, email: "d@example.com", admin: 0, suspended: 0 }, }, }); const res = makeRes(); await harness.deleteRouteHandler(makeReq("a@example.com", "d@example.com"), res, () => { assert.fail("the success path must not call next()"); }); assert.equal(res.statusCode, 200, `a normal deletion must succeed — got ${res.statusCode}: ${JSON.stringify(res.body)}`); assert.equal(res.body.ok, true); assert.equal(res.body.message, "User deleted successfully"); // The acting admin here is the ONLY usable administrator and the target is // a non-admin: this path only succeeds when the route passed // { actingAdminId: currentUser.id } and the guard counted the acting admin // as the legitimate survivor. A route that dropped the option would fail // closed with the last-admin 409 instead. assert.deepEqual(harness.engine.tables.users.map((row) => row.id), [1]); });