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): tolerate delivery failures and stale archive revocations

Tin61c9ec16cae2
diff --git a/apps/api/src/admin/controllers/archive-workspace.ts b/apps/api/src/admin/controllers/archive-workspace.ts
index 41dd422d7..c1ccf0329 100644
--- a/apps/api/src/admin/controllers/archive-workspace.ts
+++ b/apps/api/src/admin/controllers/archive-workspace.ts
@@ -40,7 +40,9 @@ async function archiveWorkspace(workspaceId: string, audit: AdminAuditRequest) {
// Open boards and the user socket learn the workspace is gone right away.
await revokeWorkspaceAudience(userIds, workspaceId, "archived");
- await publishEvent("workspace.archived", { workspaceId });
+ await publishEvent("workspace.archived", { workspaceId }).catch((error) => {
+ console.error("Failed to publish workspace archived event:", error);
+ });
return { id: workspaceId, archivedAt: archivedAt.toISOString() };
}
diff --git a/apps/api/src/workspace/lifecycle/delete-workspace-data.ts b/apps/api/src/workspace/lifecycle/delete-workspace-data.ts
index 689f40898..c936a1afb 100644
--- a/apps/api/src/workspace/lifecycle/delete-workspace-data.ts
+++ b/apps/api/src/workspace/lifecycle/delete-workspace-data.ts
@@ -78,7 +78,9 @@ export async function deleteWorkspaceData(
});
await revokeWorkspaceAudience(audience, workspaceId);
- await publishEvent("workspace.deleted", { workspaceId });
+ await publishEvent("workspace.deleted", { workspaceId }).catch((error) => {
+ console.error("Failed to publish workspace deleted event:", error);
+ });
return workspace;
}
diff --git a/apps/api/src/workspace/lifecycle/revoke-workspace-audience.ts b/apps/api/src/workspace/lifecycle/revoke-workspace-audience.ts
index dcc7e4493..05c225eec 100644
--- a/apps/api/src/workspace/lifecycle/revoke-workspace-audience.ts
+++ b/apps/api/src/workspace/lifecycle/revoke-workspace-audience.ts
@@ -8,7 +8,12 @@ export async function revokeWorkspaceAudience(
) {
await Promise.all(
userIds.map((userId) =>
- revokeWorkspaceConnections(userId, workspaceId, { force: true, reason }),
+ revokeWorkspaceConnections(userId, workspaceId, {
+ force: true,
+ reason,
+ }).catch((error) => {
+ console.error("Failed to revoke workspace realtime access:", error);
+ }),
),
);
}
diff --git a/apps/api/src/ws/index.ts b/apps/api/src/ws/index.ts
index 5a74c94b9..d298bf6a6 100644
--- a/apps/api/src/ws/index.ts
+++ b/apps/api/src/ws/index.ts
@@ -1,5 +1,6 @@
import { workspaceIsActive } from "../workspace/archive/active-workspace-sql";
-import { hasWorkspaceAccess, syncWorkspaceAccess } from "./workspace-access";
+import { syncWorkspaceAccess } from "./workspace-access";
+import { workspaceRevocationIsCurrent } from "./workspace-revocation-is-current";
import { createRevocationDelivery } from "./revocation-delivery";
import { randomUUID } from "node:crypto";
import { and, eq, inArray, sql } from "drizzle-orm";
@@ -292,7 +293,11 @@ export async function initializeWebSocketAdapter() {
const retryReceived = createRevocationDelivery({
async publishToUser(msg) {
if (
- await hasWorkspaceAccess(msg.userId, msg.message.workspaceId as string)
+ !(await workspaceRevocationIsCurrent(
+ msg.userId,
+ msg.message.workspaceId as string,
+ msg.message.reason,
+ ))
)
return;
if (receivedRevocations !== retryReceived) return;
@@ -317,12 +322,17 @@ export async function initializeWebSocketAdapter() {
if (
msg.message.type === "WORKSPACE_ACCESS_REVOKED" &&
typeof msg.message.workspaceId === "string" &&
- !msg.message.force
+ (!msg.message.force || msg.message.reason === "archived")
) {
try {
- // Redis can deliver an offline-queued initial publish after this
- // member has been re-added. Check the recipient's current access.
- if (await hasWorkspaceAccess(msg.userId, msg.message.workspaceId))
+ // Queued revocations may arrive after access has been restored.
+ if (
+ !(await workspaceRevocationIsCurrent(
+ msg.userId,
+ msg.message.workspaceId,
+ msg.message.reason,
+ ))
+ )
return;
} catch (error) {
console.error(
@@ -600,6 +610,11 @@ export async function revokeWorkspaceConnections(
reason?: "archived";
} = {},
) {
+ if (
+ options.reason === "archived" &&
+ !(await workspaceRevocationIsCurrent(userId, workspaceId, options.reason))
+ )
+ return;
if (!options.force) {
try {
const [user] =
@@ -631,26 +646,28 @@ export async function revokeWorkspaceConnections(
},
origin: INSTANCE_ID,
},
- options.force
- ? undefined
- : async () => {
- const [[user], members] = await Promise.all([
- db
- .select({ role: userTable.role })
- .from(userTable)
- .where(eq(userTable.id, userId)),
- db
- .select({ userId: workspaceUserTable.userId })
- .from(workspaceUserTable)
- .where(
- and(
- eq(workspaceUserTable.userId, userId),
- eq(workspaceUserTable.workspaceId, workspaceId),
+ options.reason === "archived"
+ ? () => workspaceRevocationIsCurrent(userId, workspaceId, options.reason)
+ : options.force
+ ? undefined
+ : async () => {
+ const [[user], members] = await Promise.all([
+ db
+ .select({ role: userTable.role })
+ .from(userTable)
+ .where(eq(userTable.id, userId)),
+ db
+ .select({ userId: workspaceUserTable.userId })
+ .from(workspaceUserTable)
+ .where(
+ and(
+ eq(workspaceUserTable.userId, userId),
+ eq(workspaceUserTable.workspaceId, workspaceId),
+ ),
),
- ),
- ]);
- return !hasInstanceAdminRole(user?.role) && members.length === 0;
- },
+ ]);
+ return !hasInstanceAdminRole(user?.role) && members.length === 0;
+ },
);
}
diff --git a/apps/api/src/ws/workspace-revocation-is-current.ts b/apps/api/src/ws/workspace-revocation-is-current.ts
new file mode 100644
index 000000000..c124b8f66
--- /dev/null
+++ b/apps/api/src/ws/workspace-revocation-is-current.ts
@@ -0,0 +1,19 @@
+import { eq } from "drizzle-orm";
+import db from "../database";
+import { workspaceTable } from "../database/schema";
+import { hasWorkspaceAccess } from "./workspace-access";
+
+export async function workspaceRevocationIsCurrent(
+ userId: string,
+ workspaceId: string,
+ reason?: unknown,
+) {
+ if (reason === "archived") {
+ const [workspace] = await db
+ .select({ archivedAt: workspaceTable.archivedAt })
+ .from(workspaceTable)
+ .where(eq(workspaceTable.id, workspaceId));
+ return !!workspace?.archivedAt;
+ }
+ return !(await hasWorkspaceAccess(userId, workspaceId));
+}
diff --git a/tests/api-integration/admin-workspace-lifecycle.test.ts b/tests/api-integration/admin-workspace-lifecycle.test.ts
index 699611fd1..b20409b5c 100644
--- a/tests/api-integration/admin-workspace-lifecycle.test.ts
+++ b/tests/api-integration/admin-workspace-lifecycle.test.ts
@@ -1,3 +1,5 @@
+import * as realtime from "../../apps/api/src/ws";
+import * as events from "../../apps/api/src/events";
import * as billing from "../../apps/api/src/billing/controllers/find-billable-workspaces";
import { randomUUID } from "node:crypto";
import { eq } from "drizzle-orm";
@@ -269,6 +271,73 @@ describe("archiving and restoring a workspace", () => {
});
});
+it("ignores an archive revocation after the workspace has been restored", async () => {
+ const { owner, workspace, project } = await workspaceFixture();
+ mockAuthenticatedSession(await createInstanceAdmin());
+ const request = projectAccessApi();
+ expect(
+ (
+ await request(`/admin/workspaces/${workspace.id}/archive`, {
+ method: "POST",
+ })
+ ).status,
+ ).toBe(200);
+ expect(
+ (
+ await request(`/admin/workspaces/${workspace.id}/restore`, {
+ method: "POST",
+ })
+ ).status,
+ ).toBe(200);
+ const socket = fakeSocket();
+ const connection = addConnection(
+ project.id,
+ socket as unknown as WSContext,
+ owner.id,
+ "restored",
+ workspace.id,
+ );
+ try {
+ await realtime.revokeWorkspaceConnections(owner.id, workspace.id, {
+ force: true,
+ reason: "archived",
+ });
+ expect(socket.close).not.toHaveBeenCalled();
+ } finally {
+ removeConnection(project.id, connection);
+ }
+});
+
+describe("committed workspace transitions", () => {
+ it.each(["archive", "delete"] as const)(
+ "returns success for %s even when realtime delivery fails",
+ async (action) => {
+ const { workspace } = await workspaceFixture();
+ mockAuthenticatedSession(await createInstanceAdmin());
+ const error = new Error("Realtime delivery unavailable");
+ vi.spyOn(realtime, "revokeWorkspaceConnections").mockRejectedValue(error);
+ const publish = vi.spyOn(events, "publishEvent").mockRejectedValue(error);
+ const log = vi.spyOn(console, "error").mockImplementation(() => {});
+
+ const response = await projectAccessApi()(
+ `/admin/workspaces/${workspace.id}${action === "archive" ? "/archive" : ""}`,
+ { method: action === "archive" ? "POST" : "DELETE" },
+ );
+
+ expect(response.status).toBe(200);
+ const stored = await readWorkspace(workspace.id);
+ if (action === "archive") expect(stored?.archivedAt).toBeInstanceOf(Date);
+ else expect(stored).toBeUndefined();
+ expect(await readAuditLog()).toHaveLength(1);
+ expect(publish).toHaveBeenCalledWith(
+ `workspace.${action === "archive" ? "archived" : "deleted"}`,
+ { workspaceId: workspace.id },
+ );
+ expect(log).toHaveBeenCalled();
+ },
+ );
+});
+
describe("deleting a workspace", () => {
it("removes the workspace and its data, queues its files, and records one audit entry", async () => {
const { owner, workspace, project } = await workspaceFixture();
diff --git a/tests/api/ws/user-broadcast-redis-failure.test.ts b/tests/api/ws/user-broadcast-redis-failure.test.ts
index 97d789e9e..23d4f2831 100644
--- a/tests/api/ws/user-broadcast-redis-failure.test.ts
+++ b/tests/api/ws/user-broadcast-redis-failure.test.ts
@@ -24,6 +24,9 @@ const sessionRows = vi.hoisted(() =>
const apiKeyRows = vi.hoisted(() =>
vi.fn(async (): Promise<Array<{ id: string }>> => []),
);
+const workspaceRows = vi.hoisted(() =>
+ vi.fn(async (): Promise<Array<{ archivedAt: Date | null }>> => []),
+);
vi.mock("../../../apps/api/src/database", async () => {
const schema = await import("../../../apps/api/src/database/schema");
return {
@@ -35,7 +38,9 @@ vi.mock("../../../apps/api/src/database", async () => {
? sessionRows
: table === schema.apikeyTable
? apiKeyRows
- : async () => [],
+ : table === schema.workspaceTable
+ ? workspaceRows
+ : async () => [],
}),
}),
},
@@ -497,3 +502,62 @@ it.each([true, false])(
}
},
);
+
+it.each([true, false])(
+ "validates a delayed archive revocation against current state (archived=%s)",
+ async (archived) => {
+ vi.useFakeTimers();
+ await initializeWebSocketAdapter();
+ workspaceRows.mockRejectedValue(new Error("database unavailable"));
+ const ws = makeFakeWs();
+ const boardWs = makeFakeWs();
+ const userConnection = addUserConnection("user-1", ws);
+ const boardConnection = addConnection(
+ "project",
+ boardWs,
+ "user-1",
+ "window",
+ "workspace",
+ );
+ try {
+ const revocation = {
+ userId: "user-1",
+ origin: "other-instance",
+ message: {
+ type: "WORKSPACE_ACCESS_REVOKED",
+ workspaceId: "workspace",
+ force: true,
+ reason: "archived",
+ },
+ };
+ emitUserBroadcast(revocation);
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(sendMock(ws)).not.toHaveBeenCalled();
+ expect(closeMock(boardWs)).not.toHaveBeenCalled();
+
+ workspaceRows.mockResolvedValue([
+ { archivedAt: archived ? new Date() : null },
+ ]);
+ await vi.advanceTimersByTimeAsync(2000);
+ expect(sendMock(ws)).toHaveBeenCalledTimes(archived ? 1 : 0);
+ if (archived)
+ expect(closeMock(boardWs)).toHaveBeenCalledWith(
+ 1008,
+ "Workspace archived",
+ );
+ else {
+ // An initial publish queued by Redis must also be ignored after restore.
+ emitUserBroadcast(revocation);
+ await vi.advanceTimersByTimeAsync(0);
+ expect(sendMock(ws)).not.toHaveBeenCalled();
+ expect(closeMock(boardWs)).not.toHaveBeenCalled();
+ }
+ } finally {
+ removeUserConnection("user-1", userConnection);
+ removeConnection("project", boardConnection);
+ await shutdownWebSocketAdapter();
+ workspaceRows.mockReset().mockResolvedValue([]);
+ vi.useRealTimers();
+ }
+ },
+);