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(api): close only the realtime connections of sessions ended by back-channel logout

tiran133fb23d6aeac07
diff --git a/apps/api/src/backchannel-logout/controllers/end-provider-sessions.ts b/apps/api/src/backchannel-logout/controllers/end-provider-sessions.ts
index 5b65dc9d3..56ad4d31b 100644
--- a/apps/api/src/backchannel-logout/controllers/end-provider-sessions.ts
+++ b/apps/api/src/backchannel-logout/controllers/end-provider-sessions.ts
@@ -1,7 +1,7 @@
import { createHash } from "node:crypto";
-import { and, eq, gt, inArray } from "drizzle-orm";
+import { and, eq, inArray } from "drizzle-orm";
import db, { schema } from "../../database";
-import { revokeUserConnections } from "../../ws";
+import { revokeSessionConnections } from "../../ws";
import { LogoutTokenRejected } from "../errors";
import {
CLOCK_SKEW_SECONDS,
@@ -44,24 +44,9 @@ async function findCustomAccountUsers(tx: Transaction, accountId: string) {
return [...new Set(accounts.map((account) => account.userId))];
}
-async function hasActiveSession(userId: string) {
- const [session] = await db
- .select({ id: schema.sessionTable.id })
- .from(schema.sessionTable)
- .where(
- and(
- eq(schema.sessionTable.userId, userId),
- gt(schema.sessionTable.expiresAt, new Date()),
- ),
- )
- .limit(1);
- return Boolean(session);
-}
-
-async function closeSignedOutConnections(userIds: string[]) {
- for (const userId of userIds) {
- // Revoked sockets sign out every tab, so wait until no session is left.
- if (!(await hasActiveSession(userId))) await revokeUserConnections(userId);
+async function closeEndedConnections(ended: Map<string, string[]>) {
+ for (const [userId, sessionIds] of ended) {
+ await revokeSessionConnections(userId, sessionIds);
}
}
@@ -71,13 +56,13 @@ export async function endProviderSessions(claims: LogoutTokenClaims) {
throw new Error("A logout needs a session ID or a subject");
}
- const signedOutUserIds = await db.transaction(async (tx) => {
+ const endedSessions = await db.transaction(async (tx) => {
if (!(await claimLogoutToken(tx, claims))) {
throw new LogoutTokenRejected("the logout token was used before");
}
const userIds =
sub === undefined ? undefined : await findCustomAccountUsers(tx, sub);
- if (userIds?.length === 0) return [];
+ if (userIds?.length === 0) return new Map<string, string[]>();
const ended = await tx
.delete(schema.sessionTable)
.where(
@@ -88,11 +73,21 @@ export async function endProviderSessions(claims: LogoutTokenClaims) {
: inArray(schema.sessionTable.userId, userIds),
),
)
- .returning({ userId: schema.sessionTable.userId });
- return [...new Set(ended.map((session) => session.userId))];
+ .returning({
+ id: schema.sessionTable.id,
+ userId: schema.sessionTable.userId,
+ });
+ const byUser = new Map<string, string[]>();
+ for (const session of ended) {
+ byUser.set(session.userId, [
+ ...(byUser.get(session.userId) ?? []),
+ session.id,
+ ]);
+ }
+ return byUser;
});
- await closeSignedOutConnections(signedOutUserIds).catch((error) => {
+ await closeEndedConnections(endedSessions).catch((error) => {
console.error(
"Closing realtime connections after a back-channel logout failed:",
error,
diff --git a/apps/api/src/index.ts b/apps/api/src/index.ts
index f3b5aada6..dfd763e25 100644
--- a/apps/api/src/index.ts
+++ b/apps/api/src/index.ts
@@ -914,12 +914,13 @@ export function createApp() {
assertWebSocketOrigin(c.req.raw.headers);
const userId = c.get("userId");
+ const sessionId = c.get("session")?.id ?? null;
let conn: ReturnType<typeof addUserConnection> | null = null;
return {
onOpen(_evt, ws) {
if (userId) {
- conn = addUserConnection(userId, ws);
+ conn = addUserConnection(userId, ws, sessionId);
void syncWorkspaceAccess(userId, ws);
}
},
@@ -962,6 +963,7 @@ export function createApp() {
const windowId = c.req.query("windowId");
const initiatorId = windowId ? `${userId}:${windowId}` : userId;
+ const sessionId = c.get("session")?.id ?? null;
let conn: ReturnType<typeof addConnection> | null = null;
return {
@@ -973,6 +975,7 @@ export function createApp() {
userId,
initiatorId,
workspaceId,
+ sessionId,
);
}
},
diff --git a/apps/api/src/ws/index.ts b/apps/api/src/ws/index.ts
index 1ebfa1006..7f9447bb4 100644
--- a/apps/api/src/ws/index.ts
+++ b/apps/api/src/ws/index.ts
@@ -6,6 +6,7 @@ import type { WSContext } from "hono/ws";
import db from "../database";
import {
projectTable,
+ sessionTable,
userTable,
workspaceUserTable,
} from "../database/schema";
@@ -43,23 +44,32 @@ type ProjectConnection = {
userId: string;
initiatorId: string;
workspaceId: string;
+ sessionId: string | null;
};
type UserConnection = {
ws: WSContext;
+ sessionId: string | null;
};
+// Only sockets of an ended session get this code, so the web signs out just that browser.
+export const SESSION_ENDED_CLOSE_CODE = 4001;
+
/**
* User-scoped connections: tracks WebSocket connections keyed by userId.
* Used for delivering user-targeted events like NOTIFICATION_CREATED.
*/
const userConnections = new Map<string, Set<UserConnection>>();
-export function addUserConnection(userId: string, ws: WSContext) {
+export function addUserConnection(
+ userId: string,
+ ws: WSContext,
+ sessionId: string | null = null,
+) {
if (!userConnections.has(userId)) {
userConnections.set(userId, new Set());
}
- const conn: UserConnection = { ws };
+ const conn: UserConnection = { ws, sessionId };
userConnections.get(userId)?.add(conn);
return conn;
}
@@ -88,10 +98,44 @@ export function broadcastToUser(userId: string, message: UserBroadcastMessage) {
});
}
+function closeLocalSessionConnections(
+ userId: string,
+ sessionIds: ReadonlySet<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;
+ removeConnection(projectId, conn);
+ try {
+ conn.ws.close(SESSION_ENDED_CLOSE_CODE, "Session ended");
+ } catch {
+ /* Already closed. */
+ }
+ }
+ for (const conn of [...(userConnections.get(userId) ?? [])]) {
+ if (!ended(conn.sessionId)) continue;
+ removeUserConnection(userId, conn);
+ try {
+ conn.ws.close(SESSION_ENDED_CLOSE_CODE, "Session ended");
+ } catch {
+ /* Already closed. */
+ }
+ }
+}
+
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));
+ return;
+ }
if (
message.type === "WORKSPACE_ACCESS_REVOKED" &&
typeof message.workspaceId === "string"
@@ -221,6 +265,7 @@ export async function initializeWebSocketAdapter() {
[...connections].map(({ ws }) => syncWorkspaceAccess(userId, ws)),
),
recheckLocalProjectAccess(),
+ recheckLocalSessions(),
]);
},
);
@@ -375,12 +420,54 @@ async function recheckLocalProjectAccess() {
);
}
+async function recheckLocalSessions() {
+ const sessionsByUser = new Map<string, Set<string>>();
+ const note = (userId: string, sessionId: string | null) => {
+ if (sessionId === null) return;
+ const sessionIds = sessionsByUser.get(userId) ?? new Set<string>();
+ sessionsByUser.set(userId, sessionIds.add(sessionId));
+ };
+ for (const [userId, connections] of userConnections)
+ for (const conn of connections) note(userId, conn.sessionId);
+ for (const connections of projectConnections.values())
+ for (const conn of connections) note(conn.userId, conn.sessionId);
+ const ids = [...sessionsByUser.values()].flatMap((sessionIds) => [
+ ...sessionIds,
+ ]);
+ if (ids.length === 0) return;
+ let existing: Set<string>;
+ try {
+ const rows = await db
+ .select({ id: sessionTable.id })
+ .from(sessionTable)
+ .where(inArray(sessionTable.id, ids));
+ existing = new Set(rows.map((row) => row.id));
+ } catch (error) {
+ console.error("Failed to verify realtime sessions:", error);
+ return;
+ }
+ for (const [userId, sessionIds] of sessionsByUser) {
+ const ended = new Set([...sessionIds].filter((id) => !existing.has(id)));
+ if (ended.size > 0) closeLocalSessionConnections(userId, ended);
+ }
+}
+
export async function revokeUserConnections(userId: string) {
const message = { type: "USER_ACCESS_REVOKED" };
deliverToLocalUserConnections(userId, message);
await revocationDelivery?.send({ userId, message, origin: INSTANCE_ID });
}
+export async function revokeSessionConnections(
+ userId: string,
+ sessionIds: string[],
+) {
+ if (sessionIds.length === 0) return;
+ const message = { type: "SESSIONS_ENDED", sessionIds };
+ deliverToLocalUserConnections(userId, message);
+ await revocationDelivery?.send({ userId, message, origin: INSTANCE_ID });
+}
+
export async function revokeWorkspaceConnections(
userId: string,
workspaceId: string,
@@ -579,11 +666,18 @@ export function addConnection(
userId: string,
initiatorId: string,
workspaceId: string,
+ sessionId: string | null = null,
) {
if (!projectConnections.has(projectId)) {
projectConnections.set(projectId, new Set());
}
- const conn: ProjectConnection = { ws, userId, initiatorId, workspaceId };
+ const conn: ProjectConnection = {
+ ws,
+ userId,
+ initiatorId,
+ workspaceId,
+ sessionId,
+ };
projectConnections.get(projectId)?.add(conn);
return conn;
}
diff --git a/apps/api/src/ws/revocation-delivery.ts b/apps/api/src/ws/revocation-delivery.ts
index 987c65b70..cae4ec256 100644
--- a/apps/api/src/ws/revocation-delivery.ts
+++ b/apps/api/src/ws/revocation-delivery.ts
@@ -47,6 +47,7 @@ export function createRevocationDelivery(
message.userId,
message.message.workspaceId,
message.message.type,
+ message.message.sessionIds,
]);
const entry = { message, shouldRetry };
pending.set(key, entry);
diff --git a/apps/docs/core/social-providers/custom-oauth.mdx b/apps/docs/core/social-providers/custom-oauth.mdx
index d45412587..e03c79e2b 100644
--- a/apps/docs/core/social-providers/custom-oauth.mdx
+++ b/apps/docs/core/social-providers/custom-oauth.mdx
@@ -210,7 +210,7 @@ What a logout signs out:
- Only sign-ins through the provider store a session ID. Sessions of the Kaneo mobile app, the Kaneo CLI and MCP clients have none, even when someone approves them while signed in through the provider. Sessions that started before you upgraded to a Kaneo version with back-channel logout, or without the `openid` scope, have none either. Only a logout token without a session ID ends them.
- API keys are not sessions. They keep working until you revoke them.
-Open Kaneo tabs return to the sign-in page right away once the person has no Kaneo session left. Otherwise, a signed-out tab notices on its next request. With several API instances, this needs [Redis](/core/installation/environment-variables#redis).
+Open Kaneo tabs of an ended session return to the sign-in page right away, while tabs of the person's other sessions stay signed in. A tab without an open connection at that moment notices on its next request. With several API instances, this needs [Redis](/core/installation/environment-variables#redis).
Kaneo answers `200` when it accepts a logout token, also when no session matched, and `400` for an invalid or reused token. It answers `503` when it cannot load the discovery document or the signing keys, and `404` while `CUSTOM_OAUTH_BACKCHANNEL_LOGOUT` is not `true`. Once Kaneo has loaded the signing keys, it keeps using them while they cannot be refreshed, so a token signed with a key the provider added since then answers `400` until the keys load again.
diff --git a/apps/web/src/hooks/use-project-websocket-access.test.tsx b/apps/web/src/hooks/use-project-websocket-access.test.tsx
index bf182c1d1..b817db69c 100644
--- a/apps/web/src/hooks/use-project-websocket-access.test.tsx
+++ b/apps/web/src/hooks/use-project-websocket-access.test.tsx
@@ -139,6 +139,22 @@ describe("project WebSocket access", () => {
expect(navigate).toHaveBeenCalledWith({ to: "/dashboard" });
});
+ it("stops reconnecting after the provider ends the session", () => {
+ renderHook(() => useProjectWebSocket("project-a"));
+ act(() => {
+ TestSocket.instances[0].open();
+ TestSocket.instances[0].onclose?.({
+ code: 4001,
+ reason: "Session ended",
+ });
+ vi.advanceTimersByTime(60_000);
+ });
+ expect(TestSocket.instances).toHaveLength(1);
+ expect(vi.getTimerCount()).toBe(0);
+ expect(client.clear).not.toHaveBeenCalled();
+ expect(navigate).not.toHaveBeenCalled();
+ });
+
it("reconnects after a project move without clearing authorized data", () => {
renderHook(() => useProjectWebSocket("project-a"));
act(() => {
diff --git a/apps/web/src/hooks/use-project-websocket.ts b/apps/web/src/hooks/use-project-websocket.ts
index fa32aa4db..705cd7df5 100644
--- a/apps/web/src/hooks/use-project-websocket.ts
+++ b/apps/web/src/hooks/use-project-websocket.ts
@@ -529,6 +529,12 @@ export function useProjectWebSocket(projectId: string) {
}
activeSocket = null;
+ // The user socket signs this tab out after the provider ended its session.
+ if (event?.code === 4001) {
+ disposed = true;
+ return;
+ }
+
if (
event?.code === 1008 &&
event.reason === "Workspace access revoked"
diff --git a/apps/web/src/hooks/use-user-websocket-lifecycle.test.tsx b/apps/web/src/hooks/use-user-websocket-lifecycle.test.tsx
index 294bc50a8..b5997d720 100644
--- a/apps/web/src/hooks/use-user-websocket-lifecycle.test.tsx
+++ b/apps/web/src/hooks/use-user-websocket-lifecycle.test.tsx
@@ -74,7 +74,7 @@ class TestSocket {
static instances: TestSocket[] = [];
readyState = 0;
onopen: (() => void) | null = null;
- onclose: (() => void) | null = null;
+ onclose: ((event?: { code: number }) => void) | null = null;
onmessage: ((event: { data: string }) => void) | null = null;
send = vi.fn();
close = vi.fn(() => {
@@ -224,6 +224,18 @@ describe("user WebSocket lifecycle", () => {
expect(vi.getTimerCount()).toBe(0);
});
+ it("signs this browser out when the provider ends its session", async () => {
+ renderHook(useUserWebSocket);
+ const socket = TestSocket.instances[0];
+ act(() => socket.open());
+ await act(async () => socket.onclose?.({ code: 4001 }));
+ act(() => vi.advanceTimersByTime(60_000));
+ expect(client.clear).toHaveBeenCalledOnce();
+ expect(auth.signOut).toHaveBeenCalledOnce();
+ expect(navigate).toHaveBeenCalledWith({ to: "/auth/sign-in" });
+ expect(TestSocket.instances).toHaveLength(1);
+ });
+
it("keeps users in their current workspace when an inactive membership is revoked", () => {
auth.workspaceId = "other-workspace";
renderHook(() => useUserWebSocket());
diff --git a/apps/web/src/hooks/use-user-websocket.ts b/apps/web/src/hooks/use-user-websocket.ts
index 18a27bdae..5edc0a46e 100644
--- a/apps/web/src/hooks/use-user-websocket.ts
+++ b/apps/web/src/hooks/use-user-websocket.ts
@@ -164,7 +164,8 @@ export function useUserWebSocket() {
if (disposed || activeSocket !== ws) return;
clearPing();
activeSocket = null;
- if (event?.code === 1008) revokeUserAccess();
+ // 4001 reaches only the sockets of a session the provider ended.
+ if (event?.code === 1008 || event?.code === 4001) revokeUserAccess();
if (userRevoked) return;
const delay = retryDelay;
diff --git a/tests/api-integration/backchannel-logout.test.ts b/tests/api-integration/backchannel-logout.test.ts
index b00c70dfa..ff0a280ec 100644
--- a/tests/api-integration/backchannel-logout.test.ts
+++ b/tests/api-integration/backchannel-logout.test.ts
@@ -12,7 +12,12 @@ import {
import { auth } from "../../apps/api/src/auth";
import db, { schema } from "../../apps/api/src/database";
import { createApp } from "../../apps/api/src/index";
-import { addUserConnection, removeUserConnection } from "../../apps/api/src/ws";
+import {
+ addUserConnection,
+ broadcastToUser,
+ removeUserConnection,
+ SESSION_ENDED_CLOSE_CODE,
+} from "../../apps/api/src/ws";
import { resetTestDatabase } from "./helpers/database";
import {
enableBackchannelLogout,
@@ -117,22 +122,30 @@ describe("API integration: back-channel logout", () => {
it("ends every session of the subject, closes its realtime connections and keeps its API keys", async () => {
const user = await seedUser("kc-user-1");
const other = await seedUser("kc-user-2");
- await seedSession(user.id, "kc-session-1");
- await seedSession(user.id);
+ const providerSession = await seedSession(user.id, "kc-session-1");
+ const appSession = await seedSession(user.id);
const kept = await seedSession(other.id, "kc-session-3");
const { key } = await auth.api.createApiKey({
body: { userId: user.id, name: "Logout test" },
});
const { app } = createApp();
- const socket = fakeSocket();
+ const providerSocket = fakeSocket();
+ const appSocket = fakeSocket();
+ const apiKeySocket = fakeSocket();
const otherSocket = fakeSocket();
- const connection = addUserConnection(
- user.id,
- socket as unknown as WSContext,
- );
+ const connections = [
+ addUserConnection(
+ user.id,
+ providerSocket as unknown as WSContext,
+ providerSession,
+ ),
+ addUserConnection(user.id, appSocket as unknown as WSContext, appSession),
+ addUserConnection(user.id, apiKeySocket as unknown as WSContext),
+ ];
const otherConnection = addUserConnection(
other.id,
otherSocket as unknown as WSContext,
+ kept,
);
try {
const response = await postLogoutToken(
@@ -142,17 +155,20 @@ describe("API integration: back-channel logout", () => {
expect(response.status).toBe(200);
expect(await remainingSessionIds()).toEqual([kept]);
- expect(socket.send).toHaveBeenCalledWith(
- JSON.stringify({ type: "USER_ACCESS_REVOKED" }),
- );
- expect(socket.close).toHaveBeenCalledWith(1008, "User access revoked");
+ for (const socket of [providerSocket, appSocket])
+ expect(socket.close).toHaveBeenCalledWith(
+ SESSION_ENDED_CLOSE_CODE,
+ "Session ended",
+ );
+ expect(apiKeySocket.close).not.toHaveBeenCalled();
expect(otherSocket.close).not.toHaveBeenCalled();
expect(
(await app.request("/api/user/me", { headers: { "x-api-key": key } }))
.status,
).toBe(200);
} finally {
- removeUserConnection(user.id, connection);
+ for (const connection of connections)
+ removeUserConnection(user.id, connection);
removeUserConnection(other.id, otherConnection);
}
});
@@ -172,15 +188,16 @@ describe("API integration: back-channel logout", () => {
expect(await remainingSessionIds()).toEqual([kept]);
});
- it("keeps the realtime connections while the user has another session", async () => {
+ it("closes only the ended session's realtime connections while the user has another session", async () => {
const user = await seedUser("kc-user-1");
- await seedSession(user.id, "kc-session-1");
+ const ended = await seedSession(user.id, "kc-session-1");
const kept = await seedSession(user.id, "kc-session-2");
- const socket = fakeSocket();
- const connection = addUserConnection(
- user.id,
- socket as unknown as WSContext,
- );
+ const endedSocket = fakeSocket();
+ const keptSocket = fakeSocket();
+ const connections = [
+ addUserConnection(user.id, endedSocket as unknown as WSContext, ended),
+ addUserConnection(user.id, keptSocket as unknown as WSContext, kept),
+ ];
try {
const response = await postLogoutToken(
createApp().app,
@@ -189,9 +206,24 @@ describe("API integration: back-channel logout", () => {
expect(response.status).toBe(200);
expect(await remainingSessionIds()).toEqual([kept]);
- expect(socket.close).not.toHaveBeenCalled();
+ expect(endedSocket.close).toHaveBeenCalledWith(
+ SESSION_ENDED_CLOSE_CODE,
+ "Session ended",
+ );
+ expect(keptSocket.close).not.toHaveBeenCalled();
+ expect(keptSocket.send).not.toHaveBeenCalled();
+
+ broadcastToUser(user.id, { type: "NOTIFICATION_CREATED" });
+
+ await vi.waitFor(() =>
+ expect(keptSocket.send).toHaveBeenCalledWith(
+ JSON.stringify({ type: "NOTIFICATION_CREATED" }),
+ ),
+ );
+ expect(endedSocket.send).not.toHaveBeenCalled();
} finally {
- removeUserConnection(user.id, connection);
+ for (const connection of connections)
+ removeUserConnection(user.id, connection);
}
});
diff --git a/tests/api/backchannel-logout/end-provider-sessions.test.ts b/tests/api/backchannel-logout/end-provider-sessions.test.ts
index 1e00ea418..54030bad1 100644
--- a/tests/api/backchannel-logout/end-provider-sessions.test.ts
+++ b/tests/api/backchannel-logout/end-provider-sessions.test.ts
@@ -11,8 +11,7 @@ const mocks = vi.hoisted(() => {
const rows = {
claimed: [] as Array<{ id: string }>,
accounts: [] as Array<{ userId: string }>,
- ended: [] as Array<{ userId: string }>,
- activeSessions: [] as Array<{ id: string }>,
+ ended: [] as Array<{ id: string; userId: string }>,
};
const deleteWhere = vi.fn(() => ({ returning: async () => rows.ended }));
const tx = {
@@ -30,13 +29,8 @@ const mocks = vi.hoisted(() => {
transaction: vi.fn(async (callback: (transaction: typeof tx) => unknown) =>
callback(tx),
),
- select: vi.fn(() => ({
- from: () => ({
- where: () => ({ limit: async () => rows.activeSessions }),
- }),
- })),
};
- return { rows, tx, db, deleteWhere, revokeUserConnections: vi.fn() };
+ return { rows, tx, db, deleteWhere, revokeSessionConnections: vi.fn() };
});
vi.mock("../../../apps/api/src/database", async () => ({
@@ -45,7 +39,7 @@ vi.mock("../../../apps/api/src/database", async () => ({
}));
vi.mock("../../../apps/api/src/ws", () => ({
- revokeUserConnections: mocks.revokeUserConnections,
+ revokeSessionConnections: mocks.revokeSessionConnections,
}));
import { endProviderSessions } from "../../../apps/api/src/backchannel-logout/controllers/end-provider-sessions";
@@ -60,8 +54,7 @@ const TOKEN = {
beforeEach(() => {
mocks.rows.claimed = [{ id: "claim" }];
mocks.rows.accounts = [{ userId: "user-1" }];
- mocks.rows.ended = [{ userId: "user-1" }];
- mocks.rows.activeSessions = [];
+ mocks.rows.ended = [{ id: "session-1", userId: "user-1" }];
});
afterEach(() => {
@@ -97,7 +90,7 @@ describe("endProviderSessions", () => {
expect(mocks.tx.insert).toHaveBeenCalledOnce();
expect(mocks.tx.delete).not.toHaveBeenCalled();
- expect(mocks.revokeUserConnections).not.toHaveBeenCalled();
+ expect(mocks.revokeSessionConnections).not.toHaveBeenCalled();
});
it("ends sessions by session ID without looking up an account", async () => {
@@ -107,26 +100,41 @@ describe("endProviderSessions", () => {
expect(mocks.deleteWhere).toHaveBeenCalledWith(expect.anything());
});
- it("closes the realtime connections of users without a session left", async () => {
- mocks.rows.ended = [{ userId: "user-1" }, { userId: "user-1" }];
+ it("closes the connections of every session a subject logout ended", async () => {
+ mocks.rows.ended = [
+ { id: "session-1", userId: "user-1" },
+ { id: "session-3", userId: "user-1" },
+ ];
await endProviderSessions({ ...TOKEN, sub: "kc-user-1" });
- expect(mocks.revokeUserConnections).toHaveBeenCalledOnce();
- expect(mocks.revokeUserConnections).toHaveBeenCalledWith("user-1");
+ expect(mocks.revokeSessionConnections).toHaveBeenCalledOnce();
+ expect(mocks.revokeSessionConnections).toHaveBeenCalledWith("user-1", [
+ "session-1",
+ "session-3",
+ ]);
});
- it("keeps the connections of users who still have a session", async () => {
- mocks.rows.activeSessions = [{ id: "session-2" }];
+ it("closes the ended sessions' connections of each user", async () => {
+ mocks.rows.ended = [
+ { id: "session-1", userId: "user-1" },
+ { id: "session-2", userId: "user-2" },
+ ];
await endProviderSessions({ ...TOKEN, sid: "kc-session-1" });
- expect(mocks.revokeUserConnections).not.toHaveBeenCalled();
+ expect(mocks.revokeSessionConnections).toHaveBeenCalledTimes(2);
+ expect(mocks.revokeSessionConnections).toHaveBeenCalledWith("user-1", [
+ "session-1",
+ ]);
+ expect(mocks.revokeSessionConnections).toHaveBeenCalledWith("user-2", [
+ "session-2",
+ ]);
});
it("logs, but does not fail, when closing connections fails", async () => {
const error = vi.spyOn(console, "error").mockImplementation(() => {});
- mocks.revokeUserConnections.mockRejectedValueOnce(new Error("socket"));
+ mocks.revokeSessionConnections.mockRejectedValueOnce(new Error("socket"));
await expect(
endProviderSessions({ ...TOKEN, sub: "kc-user-1" }),
diff --git a/tests/api/ws/connections.test.ts b/tests/api/ws/connections.test.ts
index 5e51db0fd..66cc6c921 100644
--- a/tests/api/ws/connections.test.ts
+++ b/tests/api/ws/connections.test.ts
@@ -60,6 +60,7 @@ describe("addConnection / removeConnection", () => {
userId: "user-1",
initiatorId: "init-1",
workspaceId: "workspace",
+ sessionId: null,
});
});
diff --git a/tests/api/ws/revocation-delivery.test.ts b/tests/api/ws/revocation-delivery.test.ts
new file mode 100644
index 000000000..f16adb785
--- /dev/null
+++ b/tests/api/ws/revocation-delivery.test.ts
@@ -0,0 +1,40 @@
+import { afterEach, describe, expect, it, vi } from "vite-plus/test";
+import type { UserBroadcast } from "../../../apps/api/src/ws/broadcast-adapter";
+import { createRevocationDelivery } from "../../../apps/api/src/ws/revocation-delivery";
+
+describe("createRevocationDelivery", () => {
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it("retries every ended session set of one user after Redis recovers", async () => {
+ vi.useFakeTimers();
+ let redisDown = true;
+ const published: UserBroadcast[] = [];
+ const delivery = createRevocationDelivery({
+ async publishToUser(message) {
+ if (redisDown) throw new Error("redis is down");
+ published.push(message);
+ },
+ });
+ try {
+ for (const sessionIds of [["session-a"], ["session-b"]])
+ await delivery.send({
+ userId: "user-1",
+ message: { type: "SESSIONS_ENDED", sessionIds },
+ });
+ await vi.advanceTimersByTimeAsync(0);
+ expect(published).toEqual([]);
+
+ redisDown = false;
+ await vi.advanceTimersByTimeAsync(1_000);
+
+ expect(published.map(({ message }) => message.sessionIds)).toEqual([
+ ["session-a"],
+ ["session-b"],
+ ]);
+ } finally {
+ delivery.stop();
+ }
+ });
+});
diff --git a/tests/api/ws/session-connections.test.ts b/tests/api/ws/session-connections.test.ts
new file mode 100644
index 000000000..987b0d60b
--- /dev/null
+++ b/tests/api/ws/session-connections.test.ts
@@ -0,0 +1,135 @@
+import {
+ afterEach,
+ beforeEach,
+ describe,
+ expect,
+ it,
+ vi,
+} from "vite-plus/test";
+
+vi.mock("../../../apps/api/src/events", () => ({
+ subscribeToEvent: vi.fn(),
+ publishEvent: vi.fn(),
+}));
+
+import {
+ addConnection,
+ addUserConnection,
+ broadcastToUser,
+ initializeWebSocketAdapter,
+ removeConnection,
+ removeUserConnection,
+ revokeSessionConnections,
+ SESSION_ENDED_CLOSE_CODE,
+ shutdownWebSocketAdapter,
+} from "../../../apps/api/src/ws/index";
+
+function makeFakeWs() {
+ return {
+ send: vi.fn(),
+ close: vi.fn(),
+ readyState: 1,
+ raw: undefined,
+ url: null,
+ protocol: null,
+ } as never;
+}
+
+function mocksOf(ws: unknown) {
+ return ws as {
+ send: ReturnType<typeof vi.fn>;
+ close: ReturnType<typeof vi.fn>;
+ };
+}
+
+describe("revokeSessionConnections", () => {
+ const originalRedisUrl = process.env.REDIS_URL;
+
+ beforeEach(async () => {
+ delete process.env.REDIS_URL;
+ await initializeWebSocketAdapter();
+ });
+
+ afterEach(async () => {
+ await shutdownWebSocketAdapter();
+ if (originalRedisUrl === undefined) {
+ delete process.env.REDIS_URL;
+ } else {
+ process.env.REDIS_URL = originalRedisUrl;
+ }
+ });
+
+ it("closes only the sockets of the ended session and keeps delivering to the others", async () => {
+ const firstTab = makeFakeWs();
+ const secondTab = makeFakeWs();
+ const phone = makeFakeWs();
+ const apiKey = makeFakeWs();
+ const endedBoard = makeFakeWs();
+ const phoneBoard = makeFakeWs();
+ const connections = [
+ addUserConnection("user-1", firstTab, "session-a"),
+ addUserConnection("user-1", secondTab, "session-a"),
+ addUserConnection("user-1", phone, "session-b"),
+ addUserConnection("user-1", apiKey),
+ ];
+ const boards = [
+ addConnection(
+ "project-1",
+ endedBoard,
+ "user-1",
+ "user-1:a",
+ "ws-1",
+ "session-a",
+ ),
+ addConnection(
+ "project-1",
+ phoneBoard,
+ "user-1",
+ "user-1:b",
+ "ws-1",
+ "session-b",
+ ),
+ ];
+
+ await revokeSessionConnections("user-1", ["session-a"]);
+
+ for (const ws of [firstTab, secondTab, endedBoard]) {
+ expect(mocksOf(ws).close).toHaveBeenCalledWith(
+ SESSION_ENDED_CLOSE_CODE,
+ "Session ended",
+ );
+ expect(mocksOf(ws).send).not.toHaveBeenCalled();
+ }
+ for (const ws of [phone, apiKey, phoneBoard]) {
+ expect(mocksOf(ws).close).not.toHaveBeenCalled();
+ expect(mocksOf(ws).send).not.toHaveBeenCalled();
+ }
+
+ broadcastToUser("user-1", { type: "NOTIFICATION_CREATED" });
+
+ await vi.waitFor(
+ () => {
+ for (const ws of [phone, apiKey])
+ expect(mocksOf(ws).send).toHaveBeenCalledWith(
+ JSON.stringify({ type: "NOTIFICATION_CREATED" }),
+ );
+ },
+ { timeout: 300 },
+ );
+ expect(mocksOf(firstTab).send).not.toHaveBeenCalled();
+ expect(mocksOf(secondTab).send).not.toHaveBeenCalled();
+
+ for (const conn of connections) removeUserConnection("user-1", conn);
+ for (const conn of boards) removeConnection("project-1", conn);
+ });
+
+ it("does nothing without session IDs", async () => {
+ const ws = makeFakeWs();
+ const conn = addUserConnection("user-1", ws, "session-a");
+
+ await revokeSessionConnections("user-1", []);
+
+ expect(mocksOf(ws).close).not.toHaveBeenCalled();
+ removeUserConnection("user-1", conn);
+ });
+});
diff --git a/tests/api/ws/user-broadcast-redis-failure.test.ts b/tests/api/ws/user-broadcast-redis-failure.test.ts
index 606fe9cf1..5745c8af8 100644
--- a/tests/api/ws/user-broadcast-redis-failure.test.ts
+++ b/tests/api/ws/user-broadcast-redis-failure.test.ts
@@ -18,6 +18,22 @@ vi.mock("../../../apps/api/src/ws/workspace-access", () => ({
syncWorkspaceAccess: accessSync,
hasWorkspaceAccess: hasAccess,
}));
+const sessionRows = 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 () => [],
+ }),
+ }),
+ },
+ schema,
+ };
+});
const publish = vi.fn();
const listeners: Array<(p: string, c: string, d: string) => void> = [];
const subscriber = {
@@ -48,6 +64,8 @@ import {
broadcastToUser,
initializeWebSocketAdapter,
removeUserConnection,
+ revokeSessionConnections,
+ SESSION_ENDED_CLOSE_CODE,
shutdownWebSocketAdapter,
} from "../../../apps/api/src/ws/index";
@@ -68,6 +86,10 @@ function sendMock(ws: unknown) {
return (ws as { send: ReturnType<typeof vi.fn> }).send;
}
+function closeMock(ws: unknown) {
+ return (ws as { close: ReturnType<typeof vi.fn> }).close;
+}
+
function emitUserBroadcast(payload: unknown, channelUserId = "user-1") {
const data = JSON.stringify(payload);
for (const fn of [...listeners]) {
@@ -165,6 +187,109 @@ describe("broadcastToUser with the redis adapter", () => {
});
});
+describe("ended sessions with the redis adapter", () => {
+ beforeEach(async () => {
+ publish.mockReset().mockResolvedValue(1);
+ listeners.length = 0;
+ await initializeWebSocketAdapter();
+ });
+
+ afterEach(async () => {
+ await shutdownWebSocketAdapter();
+ sessionRows.mockReset().mockResolvedValue([]);
+ });
+
+ it("publishes the ended session IDs to the other instances", async () => {
+ await revokeSessionConnections("user-1", ["session-a"]);
+
+ await vi.waitFor(() => expect(publish).toHaveBeenCalledOnce());
+ expect(JSON.parse(publish.mock.calls[0][1])).toMatchObject({
+ userId: "user-1",
+ message: { type: "SESSIONS_ENDED", sessionIds: ["session-a"] },
+ });
+ });
+
+ it("closes only the ended session's sockets when another instance ends it", () => {
+ const ended = makeFakeWs();
+ const kept = makeFakeWs();
+ const endedBoard = makeFakeWs();
+ const connections = [
+ addUserConnection("user-1", ended, "session-a"),
+ addUserConnection("user-1", kept, "session-b"),
+ ];
+ const board = addConnection(
+ "project",
+ endedBoard,
+ "user-1",
+ "window",
+ "workspace",
+ "session-a",
+ );
+ try {
+ emitUserBroadcast({
+ userId: "user-1",
+ origin: "other-instance",
+ message: { type: "SESSIONS_ENDED", sessionIds: ["session-a"] },
+ });
+
+ for (const ws of [ended, endedBoard])
+ expect(closeMock(ws)).toHaveBeenCalledWith(
+ SESSION_ENDED_CLOSE_CODE,
+ "Session ended",
+ );
+ expect(closeMock(kept)).not.toHaveBeenCalled();
+ expect(sendMock(kept)).not.toHaveBeenCalled();
+ } finally {
+ for (const conn of connections) removeUserConnection("user-1", conn);
+ removeConnection("project", board);
+ }
+ });
+
+ it("closes the sockets of sessions that ended while the subscriber was away", async () => {
+ sessionRows.mockResolvedValue([{ id: "session-b" }]);
+ const ended = makeFakeWs();
+ const kept = makeFakeWs();
+ const apiKey = makeFakeWs();
+ const endedBoard = makeFakeWs();
+ const connections = [
+ addUserConnection("user-1", ended, "session-a"),
+ addUserConnection("user-1", kept, "session-b"),
+ addUserConnection("user-1", apiKey),
+ ];
+ const board = addConnection(
+ "project",
+ endedBoard,
+ "user-1",
+ "window",
+ "workspace",
+ "session-c",
+ );
+ try {
+ const ready = subscriber.on.mock.calls
+ .filter(([event]) => event === "ready")
+ .at(-1)?.[1];
+ ready?.("", "", "");
+
+ await vi.waitFor(() =>
+ expect(closeMock(ended)).toHaveBeenCalledWith(
+ SESSION_ENDED_CLOSE_CODE,
+ "Session ended",
+ ),
+ );
+ expect(closeMock(endedBoard)).toHaveBeenCalledWith(
+ SESSION_ENDED_CLOSE_CODE,
+ "Session ended",
+ );
+ expect(closeMock(kept)).not.toHaveBeenCalled();
+ expect(closeMock(apiKey)).not.toHaveBeenCalled();
+ expect(sessionRows).toHaveBeenCalledOnce();
+ } finally {
+ for (const conn of connections) removeUserConnection("user-1", conn);
+ removeConnection("project", board);
+ }
+ });
+});
+
it("resynchronizes healthy browser sockets after the Redis subscriber recovers", async () => {
await initializeWebSocketAdapter();
const ws = makeFakeWs();