⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.
TypeScript honoissue-managementissue-trackerjira-alternativekanbanlinear-alternativemcpproject-managementreactself-hostedtypescript
fix(admin): order account cleanup before user row locking
Tinfd6f5baee9ad
diff --git a/apps/api/src/admin/controllers/delete-user.ts b/apps/api/src/admin/controllers/delete-user.tsindex b7646a590..a816d24f1 100644--- a/apps/api/src/admin/controllers/delete-user.ts+++ b/apps/api/src/admin/controllers/delete-user.ts@@ -12,7 +12,6 @@ import { hasInstanceAdminRole } from "../../utils/instance-admin-role";import { revokeUserConnections } from "../../ws";import type { AdminAuditRequest } from "../audit/admin-audit-request";import { recordAdminAction } from "../audit/record-admin-action";-import { lockAdminTargetUser } from "../users/lock-admin-target-user";import { rejectSelfAction } from "../users/reject-self-action";/** The same cleanup as self-service account deletion, with its conflicts. */@@ -41,9 +40,20 @@ async function deleteUser("You cannot remove yourself.",);await db.transaction(async (tx) => {- // Match role demotion's lock order, before locking the target user.+ // The advisory lock serializes role removals before account cleanup.const otherAdminRemains = await hasOtherInstanceAdmin(tx);- const target = await lockAdminTargetUser(userId, tx);+ const [target] = await tx+ .select({+ name: userTable.name,+ email: userTable.email,+ role: userTable.role,+ })+ .from(userTable)+ .where(eq(userTable.id, userId))+ .limit(1);+ if (!target) {+ throw new ApiError(404, { code: "NOT_FOUND", message: "User not found" });+ }if (hasInstanceAdminRole(target.role) && !otherAdminRemains) {throw new ApiError(400, {code: "CANNOT_REMOVE_LAST_ADMIN",@@ -51,6 +61,7 @@ async function deleteUser(});}await removeAccountData(userId, tx);+ // Lock the user only after workspaces: their deletion audit locks its actor.await deleteUserSessions(tx, userId, { exceptSessionId: null });await tx.delete(userTable).where(eq(userTable.id, userId));await recordAdminAction(diff --git a/tests/api-integration/admin-user-account-guards.test.ts b/tests/api-integration/admin-user-account-guards.test.tsindex 5ee54f62c..f25b44d62 100644--- a/tests/api-integration/admin-user-account-guards.test.ts+++ b/tests/api-integration/admin-user-account-guards.test.ts@@ -9,8 +9,11 @@ import {vi,} from "vite-plus/test";import deleteUser from "../../apps/api/src/admin/controllers/delete-user";+import * as adminAudit from "../../apps/api/src/admin/audit/record-admin-action";import db, { getDatabasePool, schema } from "../../apps/api/src/database";import { createApp } from "../../apps/api/src/index";+import * as accountCleanup from "../../apps/api/src/user/controllers/delete-account-data";+import { deleteNativeWorkspace } from "../../apps/api/src/workspace/lifecycle/delete-native-workspace";import { signInWithRole } from "./helpers/admin/instance-roles";import { readAuditLog } from "./helpers/admin/read-audit-log";import { resetTestDatabase } from "./helpers/database";@@ -26,6 +29,74 @@ afterAll(() => {beforeEach(resetTestDatabase);describe("admin account guards", () => {+ it("deletes an account while its administrator deletes their workspace", async () => {+ expect(getDatabasePool().options.max).toBe(2);+ const target = await createWorkspaceMember({ role: "owner" });+ const actor = await createWorkspaceMember({ role: "owner" });+ await db+ .update(schema.userTable)+ .set({ role: "user,admin" })+ .where(inArray(schema.userTable.id, [target.user.id, actor.user.id]));++ const workspaceDeleted = Promise.withResolvers<void>();+ const cleanupStarted = Promise.withResolvers<void>();+ const record = adminAudit.recordAdminAction;+ vi.spyOn(adminAudit, "recordAdminAction").mockImplementation(+ async (input, tx) => {+ if (input.action === "workspace.deleted") {+ // Hold the workspace lock until account cleanup has started.+ workspaceDeleted.resolve();+ await cleanupStarted.promise;+ }+ return record(input, tx);+ },+ );+ const cleanup = accountCleanup.default;+ vi.spyOn(accountCleanup, "default").mockImplementation((...args) => {+ cleanupStarted.resolve();+ return cleanup(...args);+ });++ const workspaceDeletion = deleteNativeWorkspace(+ target.workspace.id,+ target.user.id,+ { ipAddress: null, userAgent: null },+ );+ await workspaceDeleted.promise;+ // Both operations have passed authorization. The workspace audit needs a+ // foreign-key lock on its actor, the account being deleted concurrently.+ const results = await Promise.allSettled([+ workspaceDeletion,+ deleteUser(target.user.id, actor.user.id, {+ actorUserId: actor.user.id,+ ipAddress: null,+ userAgent: null,+ }),+ ]);++ for (const result of results) {+ if (result.status === "rejected") throw result.reason;+ }+ expect(+ await db.query.userTable.findFirst({+ where: eq(schema.userTable.id, target.user.id),+ }),+ ).toBeUndefined();+ expect(+ await db.query.workspaceTable.findFirst({+ where: eq(schema.workspaceTable.id, target.workspace.id),+ }),+ ).toBeUndefined();+ const audit = await readAuditLog();+ expect(audit.map((entry) => entry.action).sort()).toEqual([+ "user.deleted",+ "workspace.deleted",+ ]);+ expect(+ audit.find((entry) => entry.action === "workspace.deleted"),+ ).toMatchObject({ actorUserId: null });+ });+it("keeps one administrator and their workspace during concurrent deletions", async () => {expect(getDatabasePool().options.max).toBe(2);const first = await createWorkspaceMember({ role: "owner" });