⚡ 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): close live connections of revoked API keys
Tin87743b19c63e
diff --git a/apps/api/src/admin/controllers/revoke-user-api-key.ts b/apps/api/src/admin/controllers/revoke-user-api-key.tsindex 7693cab8f..20237c4e1 100644--- a/apps/api/src/admin/controllers/revoke-user-api-key.ts+++ b/apps/api/src/admin/controllers/revoke-user-api-key.ts@@ -4,11 +4,12 @@ import db from "../../database";import { apikeyTable } from "../../database/schema";import type { AdminAuditRequest } from "../audit/admin-audit-request";import { recordAdminAction } from "../audit/record-admin-action";+import { revokeApiKeyConnections } from "../../ws";import { findAdminTargetUser } from "../find-admin-target-user";/*** Delete a user's API key, as the owner's own settings do. Requests with it- * fail at once; open sockets stop receiving events at the next delivery check.+ * fail and its open sockets close at once.*/async function revokeUserApiKey({ userId, apiKeyId }: { userId: string; apiKeyId: string },@@ -35,6 +36,7 @@ async function revokeUserApiKey(tx,);});+ await revokeApiKeyConnections(userId, [apiKeyId]);return { revoked: 1 };}diff --git a/apps/api/src/auth.ts b/apps/api/src/auth.tsindex 0dcb71476..5a1f606dc 100644--- a/apps/api/src/auth.ts+++ b/apps/api/src/auth.ts@@ -1,4 +1,5 @@import {+ revokeApiKeyConnections,revokeSessionConnections,revokeUserConnections,revokeWorkspaceConnections,@@ -24,6 +25,7 @@ import {APIError,createAuthMiddleware,getSessionFromCtx,+ isAPIError,} from "better-auth/api";import {admin as adminPlugin,@@ -1073,6 +1075,13 @@ export const auth = betterAuth({}),after: createAuthMiddleware(async (ctx) => {await recordAuthAdminAudit(ctx);+ if (ctx.path === "/api-key/delete" && !isAPIError(ctx.context.returned)) {+ const keyId = (ctx.body as { keyId?: unknown } | undefined)?.keyId;+ // better-auth only deletes the caller's own keys.+ const viewer = await getSessionFromCtx(ctx);+ if (viewer && typeof keyId === "string")+ await revokeApiKeyConnections(viewer.user.id, [keyId]);+ }if ((ctx.path === "/organization/list" ||ctx.path === "/organization/list-user-teams") &&diff --git a/apps/api/src/index.ts b/apps/api/src/index.tsindex fecd2bd82..13e554063 100644--- a/apps/api/src/index.ts+++ b/apps/api/src/index.ts@@ -876,12 +876,13 @@ export function createApp() {const userId = c.get("userId");const sessionId = c.get("session")?.id ?? null;+ const apiKeyId = c.get("apiKey")?.id;let conn: ReturnType<typeof addUserConnection> | null = null;return {onOpen(_evt, ws) {if (userId) {- conn = addUserConnection(userId, ws, sessionId);+ conn = addUserConnection(userId, ws, sessionId, apiKeyId);void syncWorkspaceAccess(userId, ws);}},diff --git a/apps/api/src/ws/index.ts b/apps/api/src/ws/index.tsindex 1df57fc57..49539dd56 100644--- a/apps/api/src/ws/index.ts+++ b/apps/api/src/ws/index.ts@@ -5,6 +5,7 @@ import { and, eq, inArray } from "drizzle-orm";import type { WSContext } from "hono/ws";import db from "../database";import {+ apikeyTable,projectTable,sessionTable,userTable,@@ -52,6 +53,7 @@ type ProjectConnection = {type UserConnection = {ws: WSContext;sessionId: string | null;+ apiKeyId?: string;};// Only sockets of an ended session get this code, so the web rechecks its cookie.@@ -67,11 +69,16 @@ export function addUserConnection(userId: string,ws: WSContext,sessionId: string | null = null,+ apiKeyId?: string,) {if (!userConnections.has(userId)) {userConnections.set(userId, new Set());}- const conn: UserConnection = { ws, sessionId };+ const conn: UserConnection = {+ ws,+ sessionId,+ ...(apiKeyId ? { apiKeyId } : {}),+ };userConnections.get(userId)?.add(conn);return conn;}@@ -100,42 +107,77 @@ export function broadcastToUser(userId: string, message: UserBroadcastMessage) {});}-function closeLocalSessionConnections(+type Credential = { sessionId: string | null; apiKeyId?: string };++function closeLocalCredentialConnections(userId: string,- sessionIds: ReadonlySet<string>,+ ended: (conn: Credential) => boolean,+ code: number,+ reason: string,) {- const ended = (sessionId: string | null) =>- sessionId !== null && sessionIds.has(sessionId);for (const [projectId, connections] of projectConnections)for (const conn of [...connections]) {- if (conn.userId !== userId || !ended(conn.sessionId)) continue;+ if (conn.userId !== userId || !ended(conn)) continue;removeConnection(projectId, conn);try {- conn.ws.close(SESSION_ENDED_CLOSE_CODE, "Session ended");+ conn.ws.close(code, reason);} catch {/* Already closed. */}}for (const conn of [...(userConnections.get(userId) ?? [])]) {- if (!ended(conn.sessionId)) continue;+ if (!ended(conn)) continue;removeUserConnection(userId, conn);try {- conn.ws.close(SESSION_ENDED_CLOSE_CODE, "Session ended");+ conn.ws.close(code, reason);} catch {/* Already closed. */}}}+function closeLocalSessionConnections(+ userId: string,+ sessionIds: ReadonlySet<string>,+) {+ closeLocalCredentialConnections(+ userId,+ ({ sessionId }) => sessionId !== null && sessionIds.has(sessionId),+ SESSION_ENDED_CLOSE_CODE,+ "Session ended",+ );+}++function closeLocalApiKeyConnections(+ userId: string,+ apiKeyIds: ReadonlySet<string>,+) {+ closeLocalCredentialConnections(+ userId,+ ({ apiKeyId }) => apiKeyId !== undefined && apiKeyIds.has(apiKeyId),+ 1008,+ "API key revoked",+ );+}++const stringIds = (ids: unknown) =>+ Array.isArray(ids)+ ? ids.filter((id): id is string => typeof id === "string")+ : [];+function deliverToLocalUserConnections(userId: string,message: UserBroadcastMessage,) {if (message.type === "SESSIONS_ENDED") {- const sessionIds = Array.isArray(message.sessionIds)- ? message.sessionIds.filter((id): id is string => typeof id === "string")- : [];- closeLocalSessionConnections(userId, new Set(sessionIds));+ closeLocalSessionConnections(+ userId,+ new Set(stringIds(message.sessionIds)),+ );+ return;+ }+ if (message.type === "API_KEYS_REVOKED") {+ closeLocalApiKeyConnections(userId, new Set(stringIds(message.apiKeyIds)));return;}if (@@ -268,6 +310,7 @@ export async function initializeWebSocketAdapter() {),recheckLocalProjectAccess(),recheckLocalSessions(),+ recheckLocalApiKeys(),]);},);@@ -454,6 +497,36 @@ async function recheckLocalSessions() {}}+// Redis may have dropped a key revocation while this instance was disconnected.+async function recheckLocalApiKeys() {+ const keysByUser = new Map<string, Set<string>>();+ const note = (userId: string, apiKeyId?: string) => {+ if (!apiKeyId) return;+ keysByUser.set(userId, (keysByUser.get(userId) ?? new Set()).add(apiKeyId));+ };+ for (const [userId, connections] of userConnections)+ for (const conn of connections) note(userId, conn.apiKeyId);+ for (const connections of projectConnections.values())+ for (const conn of connections) note(conn.userId, conn.apiKeyId);+ const ids = [...keysByUser.values()].flatMap((keyIds) => [...keyIds]);+ if (ids.length === 0) return;+ let existing: Set<string>;+ try {+ const rows = await db+ .select({ id: apikeyTable.id })+ .from(apikeyTable)+ .where(inArray(apikeyTable.id, ids));+ existing = new Set(rows.map((row) => row.id));+ } catch (error) {+ console.error("Failed to verify realtime API keys:", error);+ return;+ }+ for (const [userId, keyIds] of keysByUser) {+ const revoked = new Set([...keyIds].filter((id) => !existing.has(id)));+ if (revoked.size > 0) closeLocalApiKeyConnections(userId, revoked);+ }+}+export async function revokeUserConnections(userId: string) {const message = { type: "USER_ACCESS_REVOKED" };deliverToLocalUserConnections(userId, message);@@ -470,6 +543,17 @@ export async function revokeSessionConnections(await revocationDelivery?.send({ userId, message, origin: INSTANCE_ID });}+/** Close sockets opened with deleted API keys, on every API instance. */+export async function revokeApiKeyConnections(+ userId: string,+ apiKeyIds: string[],+) {+ if (apiKeyIds.length === 0) return;+ const message = { type: "API_KEYS_REVOKED", apiKeyIds };+ deliverToLocalUserConnections(userId, message);+ await revocationDelivery?.send({ userId, message, origin: INSTANCE_ID });+}+export async function revokeWorkspaceConnections(userId: string,workspaceId: string,diff --git a/apps/api/src/ws/revocation-delivery.ts b/apps/api/src/ws/revocation-delivery.tsindex cae4ec256..013317249 100644--- a/apps/api/src/ws/revocation-delivery.ts+++ b/apps/api/src/ws/revocation-delivery.ts@@ -48,6 +48,7 @@ export function createRevocationDelivery(message.message.workspaceId,message.message.type,message.message.sessionIds,+ message.message.apiKeyIds,]);const entry = { message, shouldRetry };pending.set(key, entry);diff --git a/tests/api-integration/api-key-socket-revocation.test.ts b/tests/api-integration/api-key-socket-revocation.test.tsnew file mode 100644index 000000000..9e5c05450--- /dev/null+++ b/tests/api-integration/api-key-socket-revocation.test.ts@@ -0,0 +1,141 @@+import { once } from "node:events";+import { createRequire } from "node:module";+import { afterEach, beforeEach, describe, expect, it } from "vite-plus/test";+import { serve } from "../../apps/api/node_modules/@hono/node-server";+import type { NodeWebSocket } from "../../apps/api/node_modules/@hono/node-ws";+import { auth } from "../../apps/api/src/auth";+import { createApp } from "../../apps/api/src/index";+import { shutdownWebSocketAdapter } from "../../apps/api/src/ws";+import { signUpWithSession } from "./helpers/auth-session";+import { resetTestDatabase } from "./helpers/database";++type Socket = NodeWebSocket["wss"]["clients"] extends Set<infer S> ? S : never;+const apiRequire = createRequire(+ new URL("../../apps/api/package.json", import.meta.url),+);+const nodeWsRequire = createRequire(apiRequire.resolve("@hono/node-ws"));+const WebSocket: new (+ url: string,+ options: { headers: Record<string, string> },+) => Socket = nodeWsRequire("ws").WebSocket;++const ORIGIN = "http://localhost:5173";+type App = ReturnType<typeof createApp>["app"];+type Account = { userId: string; cookies: string };++let app: App;+let server: ReturnType<typeof serve>;+let baseUrl: string;+let admin: Account;+let target: Account;+const sockets: Socket[] = [];++async function connectUserSocket(headers: Record<string, string>) {+ const socket = new WebSocket(`${baseUrl}/api/ws/user`, { headers });+ sockets.push(socket);+ socket.on("error", () => {});+ await once(socket, "open");+ return socket;+}++function closeOf(socket: Socket) {+ return once(socket, "close").then(([code, reason]) => ({+ code,+ reason: String(reason),+ }));+}++/** A ping round trip proves the socket is still open after the revocation. */+async function isOpen(socket: Socket) {+ const pong = once(socket, "pong");+ socket.ping();+ await pong;+ return socket.readyState === 1;+}++beforeEach(async () => {+ await resetTestDatabase();+ const created = createApp();+ app = created.app;+ server = serve({ fetch: app.fetch, hostname: "127.0.0.1", port: 0 });+ created.injectWebSocket(server);+ if (!server.listening) await once(server, "listening");+ const address = server.address();+ if (!address || typeof address === "string") throw new Error("No test port");+ baseUrl = `ws://127.0.0.1:${address.port}`;+ admin = await signUpWithSession(app, {+ email: "[email protected]",+ name: "Ada Admin",+ role: "admin",+ });+ target = await signUpWithSession(app, {+ email: "[email protected]",+ name: "Tom Target",+ role: "user",+ });+});++afterEach(async () => {+ await shutdownWebSocketAdapter();+ for (const socket of sockets.splice(0)) socket.terminate();+ await new Promise<void>((resolve, reject) =>+ server.close((error) => (error ? reject(error) : resolve())),+ );+});++describe("API integration: user sockets of revoked API keys", () => {+ async function connectTargetSockets() {+ const revoked = await auth.api.createApiKey({+ body: { userId: target.userId, name: "CI deploys" },+ });+ const kept = await auth.api.createApiKey({+ body: { userId: target.userId, name: "Laptop" },+ });+ return {+ revoked,+ revokedSocket: await connectUserSocket({ "x-api-key": revoked.key }),+ keptSocket: await connectUserSocket({ "x-api-key": kept.key }),+ sessionSocket: await connectUserSocket({+ cookie: target.cookies,+ origin: ORIGIN,+ }),+ };+ }++ it("closes the key's sockets when an admin revokes it, and only those", async () => {+ const { revoked, revokedSocket, keptSocket, sessionSocket } =+ await connectTargetSockets();+ const closed = closeOf(revokedSocket);++ const response = await app.request(+ `/api/admin/users/${target.userId}/api-keys/${revoked.id}`,+ { method: "DELETE", headers: { cookie: admin.cookies, origin: ORIGIN } },+ );++ expect(response.status).toBe(200);+ expect(await closed).toEqual({ code: 1008, reason: "API key revoked" });+ expect(await isOpen(keptSocket)).toBe(true);+ expect(await isOpen(sessionSocket)).toBe(true);+ });++ it("closes the key's sockets when its owner deletes it", async () => {+ const { revoked, revokedSocket, keptSocket, sessionSocket } =+ await connectTargetSockets();+ const closed = closeOf(revokedSocket);++ const response = await app.request("/api/auth/api-key/delete", {+ method: "POST",+ headers: {+ cookie: target.cookies,+ origin: ORIGIN,+ "content-type": "application/json",+ },+ body: JSON.stringify({ keyId: revoked.id }),+ });++ expect(response.status).toBe(200);+ expect(await closed).toEqual({ code: 1008, reason: "API key revoked" });+ expect(await isOpen(keptSocket)).toBe(true);+ expect(await isOpen(sessionSocket)).toBe(true);+ });+});diff --git a/tests/api/ws/user-broadcast-redis-failure.test.ts b/tests/api/ws/user-broadcast-redis-failure.test.tsindex 214ba048c..97d789e9e 100644--- a/tests/api/ws/user-broadcast-redis-failure.test.ts+++ b/tests/api/ws/user-broadcast-redis-failure.test.ts@@ -21,13 +21,21 @@ vi.mock("../../../apps/api/src/ws/workspace-access", () => ({const sessionRows = vi.hoisted(() =>vi.fn(async (): Promise<Array<{ id: string }>> => []),);+const apiKeyRows = vi.hoisted(() =>+ vi.fn(async (): Promise<Array<{ id: string }>> => []),+);vi.mock("../../../apps/api/src/database", async () => {const schema = await import("../../../apps/api/src/database/schema");return {default: {select: () => ({from: (table: unknown) => ({- where: table === schema.sessionTable ? sessionRows : async () => [],+ where:+ table === schema.sessionTable+ ? sessionRows+ : table === schema.apikeyTable+ ? apiKeyRows+ : async () => [],}),}),},@@ -64,6 +72,7 @@ import {broadcastToUser,initializeWebSocketAdapter,removeUserConnection,+ revokeApiKeyConnections,revokeSessionConnections,SESSION_ENDED_CLOSE_CODE,shutdownWebSocketAdapter,@@ -292,6 +301,100 @@ describe("ended sessions with the redis adapter", () => {});});+describe("revoked API keys with the redis adapter", () => {+ beforeEach(async () => {+ publish.mockReset().mockResolvedValue(1);+ listeners.length = 0;+ await initializeWebSocketAdapter();+ });++ afterEach(async () => {+ await shutdownWebSocketAdapter();+ apiKeyRows.mockReset().mockResolvedValue([]);+ sessionRows.mockReset().mockResolvedValue([]);+ });++ function connectKeySockets() {+ const revoked = makeFakeWs();+ const kept = makeFakeWs();+ const session = makeFakeWs();+ const revokedBoard = makeFakeWs();+ const connections = [+ addUserConnection("user-1", revoked, null, "key-a"),+ addUserConnection("user-1", kept, null, "key-b"),+ addUserConnection("user-1", session, "session-a"),+ ];+ const board = addConnection(+ "project",+ revokedBoard,+ "user-1",+ "window",+ "workspace",+ "key-a",+ );+ return {+ closed: [revoked, revokedBoard],+ open: [kept, session],+ disconnect() {+ for (const conn of connections) removeUserConnection("user-1", conn);+ removeConnection("project", board);+ },+ };+ }++ it("publishes the revoked key IDs to the other instances", async () => {+ await revokeApiKeyConnections("user-1", ["key-a"]);++ await vi.waitFor(() => expect(publish).toHaveBeenCalledOnce());+ expect(JSON.parse(publish.mock.calls[0][1])).toMatchObject({+ userId: "user-1",+ message: { type: "API_KEYS_REVOKED", apiKeyIds: ["key-a"] },+ });+ });++ it("closes only the key's sockets when another instance revokes it", () => {+ const sockets = connectKeySockets();+ try {+ emitUserBroadcast({+ userId: "user-1",+ origin: "other-instance",+ message: { type: "API_KEYS_REVOKED", apiKeyIds: ["key-a"] },+ });++ for (const ws of sockets.closed)+ expect(closeMock(ws)).toHaveBeenCalledWith(1008, "API key revoked");+ for (const ws of sockets.open) {+ expect(closeMock(ws)).not.toHaveBeenCalled();+ expect(sendMock(ws)).not.toHaveBeenCalled();+ }+ } finally {+ sockets.disconnect();+ }+ });++ it("closes the sockets of keys revoked while the subscriber was away", async () => {+ apiKeyRows.mockResolvedValue([{ id: "key-b" }]);+ sessionRows.mockResolvedValue([{ id: "session-a" }]);+ const sockets = connectKeySockets();+ try {+ const ready = subscriber.on.mock.calls+ .filter(([event]) => event === "ready")+ .at(-1)?.[1];+ ready?.("", "", "");++ await vi.waitFor(() => {+ for (const ws of sockets.closed)+ expect(closeMock(ws)).toHaveBeenCalledWith(1008, "API key revoked");+ });+ for (const ws of sockets.open)+ expect(closeMock(ws)).not.toHaveBeenCalled();+ expect(apiKeyRows).toHaveBeenCalledOnce();+ } finally {+ sockets.disconnect();+ }+ });+});+it("resynchronizes healthy browser sockets after the Redis subscriber recovers", async () => {await initializeWebSocketAdapter();const ws = makeFakeWs();