Skip to content

armgit / kaneo

Public Imported from GitHub
0

⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.

fix(admin): reuse workspace transaction for billing checks

Tin88d37178da6c
diff --git a/apps/api/src/workspace/lifecycle/delete-workspace-data.ts b/apps/api/src/workspace/lifecycle/delete-workspace-data.ts
index c936a1afb..cd51ea165 100644
--- a/apps/api/src/workspace/lifecycle/delete-workspace-data.ts
+++ b/apps/api/src/workspace/lifecycle/delete-workspace-data.ts
@@ -26,7 +26,7 @@ export async function deleteWorkspaceData(
const { audience, workspace } = await db.transaction(async (tx) => {
const workspace = await lockWorkspaceRow(tx, workspaceId);
- const billable = await findBillableWorkspaces([workspaceId]);
+ const billable = await findBillableWorkspaces([workspaceId], tx);
if (billable.length > 0) {
throw new ApiError(409, {
code: "WORKSPACE_HAS_ACTIVE_SUBSCRIPTION",
diff --git a/tests/api-integration/admin-user-account-guards.test.ts b/tests/api-integration/admin-user-account-guards.test.ts
index f25b44d62..4de3256b1 100644
--- a/tests/api-integration/admin-user-account-guards.test.ts
+++ b/tests/api-integration/admin-user-account-guards.test.ts
@@ -14,6 +14,7 @@ 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 * as workspaceLock from "../../apps/api/src/workspace/lifecycle/lock-workspace-row";
import { signInWithRole } from "./helpers/admin/instance-roles";
import { readAuditLog } from "./helpers/admin/read-audit-log";
import { resetTestDatabase } from "./helpers/database";
@@ -22,6 +23,9 @@ import { createWorkspaceMember } from "./helpers/fixtures";
beforeAll(() => {
vi.stubEnv("DATABASE_POOL_MAX", "2");
+ vi.stubEnv("KANEO_CLOUD", "true");
+ vi.stubEnv("CREEM_API_KEY", "creem_test_dummy");
+ vi.stubEnv("CREEM_WEBHOOK_SECRET", "whsec_dummy");
});
afterAll(() => {
vi.unstubAllEnvs();
@@ -29,73 +33,88 @@ 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]));
+ it.each(["audit", "billing"])(
+ "deletes an account while its administrator deletes their workspace before %s",
+ async (pauseBefore) => {
+ 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 workspacePaused = Promise.withResolvers<void>();
+ const cleanupStarted = Promise.withResolvers<void>();
+ const lock = workspaceLock.lockWorkspaceRow;
+ vi.spyOn(workspaceLock, "lockWorkspaceRow").mockImplementation(
+ async (...args) => {
+ const workspace = await lock(...args);
+ if (pauseBefore === "billing") {
+ // Account deletion must occupy the other connection before billing.
+ workspacePaused.resolve();
+ await cleanupStarted.promise;
+ }
+ return workspace;
+ },
+ );
+ const record = adminAudit.recordAdminAction;
+ vi.spyOn(adminAudit, "recordAdminAction").mockImplementation(
+ async (input, tx) => {
+ if (pauseBefore === "audit" && input.action === "workspace.deleted") {
+ // Hold the workspace lock until account cleanup has started.
+ workspacePaused.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,
- }),
- ]);
+ const workspaceDeletion = deleteNativeWorkspace(
+ target.workspace.id,
+ target.user.id,
+ { ipAddress: null, userAgent: null },
+ );
+ await workspacePaused.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 });
- });
+ 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);