Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

fix(pam): web session lifecycle cleanup (#6439)

Saif Ur Rahman56448cac0baf
diff --git a/backend/src/ee/services/pam-session/pam-session-dal.ts b/backend/src/ee/services/pam-session/pam-session-dal.ts
index f8dc7f9fec..eab7676d02 100644
--- a/backend/src/ee/services/pam-session/pam-session-dal.ts
+++ b/backend/src/ee/services/pam-session/pam-session-dal.ts
@@ -79,6 +79,18 @@ export const pamSessionDALFactory = (db: TDbClient) => {
return updatedCount;
};
+ const endExpiredWebSessions = async (userId: string, projectId: string, tx?: Knex): Promise<number> => {
+ const now = new Date();
+ const updatedCount = await (tx || db)(TableName.PamSession)
+ .where("userId", userId)
+ .where("projectId", projectId)
+ .where("accessMethod", "web")
+ .whereIn("status", [PamSessionStatus.Active, PamSessionStatus.Starting])
+ .where("expiresAt", "<", now)
+ .update({ status: PamSessionStatus.Ended, endedAt: now });
+ return updatedCount;
+ };
+
const findByProjectId = async (projectId: string, tx?: Knex) => {
const sessions = await (tx || db.replicaNode())(TableName.PamSession)
.leftJoin(TableName.PamAccount, `${TableName.PamSession}.accountId`, `${TableName.PamAccount}.id`)
@@ -206,6 +218,7 @@ export const pamSessionDALFactory = (db: TDbClient) => {
findById,
findByProjectId,
expireSessionById,
+ endExpiredWebSessions,
countActiveWebSessions,
countActiveByProjectId,
countDailyByProjectId,
diff --git a/backend/src/ee/services/pam-session/pam-session-service.ts b/backend/src/ee/services/pam-session/pam-session-service.ts
index c9a0767f23..cf6f87f9cd 100644
--- a/backend/src/ee/services/pam-session/pam-session-service.ts
+++ b/backend/src/ee/services/pam-session/pam-session-service.ts
@@ -247,14 +247,16 @@ export const pamSessionServiceFactory = ({
}
const updatedSession = await pamSessionDAL.endSessionById(sessionId);
- if (!updatedSession) {
- if (session.status !== PamSessionStatus.Ended && session.status !== PamSessionStatus.Terminated) {
- throw new BadRequestError({ message: "Cannot end sessions that are not active or starting" });
- }
- return { session, projectId: session.projectId, alreadyEnded: true };
+
+ if (
+ !updatedSession &&
+ session.status !== PamSessionStatus.Ended &&
+ session.status !== PamSessionStatus.Terminated
+ ) {
+ throw new BadRequestError({ message: "Cannot end sessions that are not active or starting" });
}
- // Fire-and-forget AI summarization
+ // Always queue — the gateway calling end means logs are uploaded.
void (async () => {
try {
await pamSessionAiSummaryService.queueAiSummary(sessionId, session.projectId);
@@ -263,7 +265,7 @@ export const pamSessionServiceFactory = ({
}
})();
- return { session: updatedSession, projectId: session.projectId, alreadyEnded: false };
+ return { session: updatedSession ?? session, projectId: session.projectId, alreadyEnded: !updatedSession };
};
const terminateSessionById = async (sessionId: string, actor: OrgServiceActor) => {
diff --git a/backend/src/ee/services/pam-web-access/pam-postgres-session-handler.test.ts b/backend/src/ee/services/pam-web-access/pam-postgres-session-handler.test.ts
index 51e1317ccd..ceb3125a61 100644
--- a/backend/src/ee/services/pam-web-access/pam-postgres-session-handler.test.ts
+++ b/backend/src/ee/services/pam-web-access/pam-postgres-session-handler.test.ts
@@ -8,12 +8,7 @@ import { beforeEach, describe, expect, test, vi } from "vitest";
import type WebSocket from "ws";
import { PostgresClientMessageType, PostgresServerMessageType } from "./pam-postgres-ws-types";
-import {
- SessionEndReason,
- TerminalServerMessageType,
- type TSessionContext,
- type TWebSocketServerMessage
-} from "./pam-web-access-types";
+import { TerminalServerMessageType, type TSessionContext, type TWebSocketServerMessage } from "./pam-web-access-types";
vi.mock("@app/lib/logger", () => ({
logger: {
@@ -159,20 +154,18 @@ describe("handlePostgresSession", () => {
expect(pg.Client).toHaveBeenCalledTimes(1);
});
- test("tears down the WS when reachability check fails", async () => {
+ test("throws when reachability check fails so the service catch block handles cleanup", async () => {
clientScripts.push({
connect: async () => {
throw new Error("connection refused");
}
});
const ctx = createMockContext();
- const result = await handlePostgresSession(ctx, mockParams);
- expect(ctx.sendSessionEnd).toHaveBeenCalledWith(SessionEndReason.SetupFailed);
+ await expect(handlePostgresSession(ctx, mockParams)).rejects.toThrow("connection refused");
expect(ctx.sendMessage).not.toHaveBeenCalledWith(
expect.objectContaining({ type: TerminalServerMessageType.Ready })
);
- expect(result.cleanup).toBeDefined();
});
test("open-connection creates a controller and returns connectionId + backendPid", async () => {
@@ -378,9 +371,9 @@ describe("handlePostgresSession", () => {
});
test("concurrent open-connection requests cannot bypass the cap", async () => {
- // Simulates a client firing 25 opens at once. Without the pendingOpens
- // counter, each check against controllers.size would see 0 before any
- // controller finished connecting, and all 25 would succeed.
+ // Simulates a client firing 25 opens at once. Without null-slot
+ // reservation, each check against controllers.size would see 0 before
+ // any controller finished connecting, and all 25 would succeed.
const ctx = createMockContext();
await handlePostgresSession(ctx, mockParams);
@@ -422,6 +415,54 @@ describe("handlePostgresSession", () => {
});
});
+ test("in-flight opens self-dispose when cleanup runs before they resolve", async () => {
+ const ctx = createMockContext();
+ const result = await handlePostgresSession(ctx, mockParams);
+
+ // Delay the pg.Client connect for the NEXT client created so the open is
+ // still in flight when cleanup runs. Pushed AFTER handlePostgresSession so
+ // the reachability client consumes a normal (instant) script.
+ let resolveConnect!: () => void;
+ clientScripts.push({
+ connect: () =>
+ new Promise<void>((resolve) => {
+ resolveConnect = resolve;
+ })
+ });
+
+ // Kick off an open — it will be stuck at pgClient.connect().
+ const onMessage = getMessageHandler(ctx);
+ onMessage(
+ Buffer.from(
+ JSON.stringify({ type: PostgresClientMessageType.OpenConnection, id: "11111111-1111-1111-1111-111111111111" })
+ )
+ );
+
+ // Let the synchronous part of openTabConnection run (reserves the null
+ // slot), but the await hasn't resolved yet.
+ await new Promise<void>((r) => {
+ setTimeout(r, 10);
+ });
+
+ // Session tears down while the open is in flight.
+ await result.cleanup();
+
+ // Now let the connect resolve — the open should self-dispose.
+ resolveConnect();
+ await new Promise<void>((r) => {
+ setTimeout(r, 50);
+ });
+
+ // The controller's pg.Client should have been disposed (end called).
+ // The delayed client is the second one created (first is the reachability check).
+ const delayedClient = createdClients[1];
+ expect(delayedClient.end).toHaveBeenCalled();
+
+ // No connection-opened should have been sent.
+ const opened = getSentResponses(ctx).filter((r) => r.type === PostgresServerMessageType.ConnectionOpened);
+ expect(opened).toHaveLength(0);
+ });
+
test("two tab controllers have independent backendPids", async () => {
const ctx = createMockContext();
await handlePostgresSession(ctx, mockParams);
diff --git a/backend/src/ee/services/pam-web-access/pam-postgres-session-handler.ts b/backend/src/ee/services/pam-web-access/pam-postgres-session-handler.ts
index cbf3272638..ec131509c4 100644
--- a/backend/src/ee/services/pam-web-access/pam-postgres-session-handler.ts
+++ b/backend/src/ee/services/pam-web-access/pam-postgres-session-handler.ts
@@ -52,23 +52,7 @@ export const handlePostgresSession = async (
database: connectionDetails.database
};
- // Early reachability check — fail fast before sending ready, preserving the
- // early "Connection error" UX the FE relies on.
- try {
- await verifyReachabilityOneShot(oneShotOpts);
- } catch (err) {
- logger.error(err, `Postgres reachability check failed [sessionId=${sessionId}]`);
- sendSessionEnd(SessionEndReason.SetupFailed);
- onCleanup();
- try {
- socket.close();
- } catch {
- // ignore
- }
- return {
- cleanup: async () => {}
- };
- }
+ await verifyReachabilityOneShot(oneShotOpts);
sendMessage({
type: TerminalServerMessageType.Ready,
@@ -87,11 +71,9 @@ export const handlePostgresSession = async (
}
};
- const controllers = new Map<string, TPostgresConnectionController>();
- // Reserved slots for in-flight opens — counted against the cap so a burst of
- // open-connection messages can't all pass the check before any of them
- // finishes inserting into `controllers`.
- let pendingOpens = 0;
+ // Null = slot reserved for an in-flight open; cleanup clears the map so
+ // the open's post-await .has() check fails and it self-disposes.
+ const controllers = new Map<string, TPostgresConnectionController | null>();
// Metadata requests (get-schemas / get-tables) are processed outside any
// controller queue so sidebar refreshes don't block tab work.
@@ -100,7 +82,7 @@ export const handlePostgresSession = async (
// --- Per-message handlers ---
const openTabConnection = async (requestId: string) => {
- if (controllers.size + pendingOpens >= MAX_CONNECTIONS_PER_WS) {
+ if (controllers.size >= MAX_CONNECTIONS_PER_WS) {
sendResponse({
type: PostgresServerMessageType.ConnectionOpenFailed,
id: requestId,
@@ -109,8 +91,8 @@ export const handlePostgresSession = async (
return;
}
- pendingOpens += 1;
const connectionId = crypto.randomUUID();
+ controllers.set(connectionId, null);
try {
const controller = await createPostgresConnectionController({
relayPort,
@@ -129,6 +111,10 @@ export const handlePostgresSession = async (
});
}
});
+ if (!controllers.has(connectionId)) {
+ controller.dispose();
+ return;
+ }
controllers.set(connectionId, controller);
sendResponse({
type: PostgresServerMessageType.ConnectionOpened,
@@ -137,6 +123,7 @@ export const handlePostgresSession = async (
backendPid: controller.backendPid
});
} catch (err) {
+ controllers.delete(connectionId);
const msg = err instanceof Error ? err.message : "Failed to open connection";
logger.error(err, `Failed to open tab connection [sessionId=${sessionId}]`);
sendResponse({
@@ -144,8 +131,6 @@ export const handlePostgresSession = async (
id: requestId,
error: msg
});
- } finally {
- pendingOpens -= 1;
}
};
@@ -266,14 +251,15 @@ export const handlePostgresSession = async (
return {
cleanup: async () => {
- // dispose() is synchronous and fire-and-forget — no await needed.
const snapshot = Array.from(controllers.values());
controllers.clear();
for (const controller of snapshot) {
- try {
- controller.dispose();
- } catch (err) {
- logger.debug(err, `Error disposing controller [sessionId=${sessionId}]`);
+ if (controller) {
+ try {
+ controller.dispose();
+ } catch (err) {
+ logger.debug(err, `Error disposing controller [sessionId=${sessionId}]`);
+ }
}
}
}
diff --git a/backend/src/ee/services/pam-web-access/pam-web-access-service.ts b/backend/src/ee/services/pam-web-access/pam-web-access-service.ts
index 3e4fe6dcd0..bb7fe83b12 100644
--- a/backend/src/ee/services/pam-web-access/pam-web-access-service.ts
+++ b/backend/src/ee/services/pam-web-access/pam-web-access-service.ts
@@ -86,7 +86,7 @@ type TPamWebAccessServiceFactoryDep = {
tokenService: Pick<TAuthTokenServiceFactory, "createTokenForUser">;
pamSessionDAL: Pick<
TPamSessionDALFactory,
- "create" | "updateById" | "countActiveWebSessions" | "endSessionById" | "activateSession"
+ "create" | "updateById" | "countActiveWebSessions" | "endSessionById" | "activateSession" | "endExpiredWebSessions"
>;
pamSessionExpirationService: Pick<TPamSessionExpirationServiceFactory, "scheduleSessionExpiration">;
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPAMConnectionDetails">;
@@ -246,6 +246,9 @@ export const pamWebAccessServiceFactory = ({
accountIdentity = `${domainConnectionDetails.domain}:${account.name}`;
}
+ // Sessions that outlived their expiresAt may still show as active — end them so that they don't count against the session limit.
+ await pamSessionDAL.endExpiredWebSessions(actor.id, projectId);
+
const activeWebSessionCount = await pamSessionDAL.countActiveWebSessions(actor.id, projectId);
if (activeWebSessionCount >= MAX_WEB_SESSIONS_PER_USER) {
throw new BadRequestError({
@@ -489,16 +492,33 @@ export const pamWebAccessServiceFactory = ({
}
if (session) {
+ const sessionId = session.id;
try {
- await pamSessionDAL.endSessionById(session.id);
+ const updated = await pamSessionDAL.endSessionById(sessionId);
+ if (updated) {
+ await auditLogService.createAuditLog({
+ ...auditLogInfo,
+ orgId,
+ projectId,
+ event: {
+ type: EventType.PAM_SESSION_END,
+ metadata: {
+ sessionId,
+ accountName
+ }
+ }
+ });
+ }
} catch (err) {
- logger.debug(err, "Error marking session ended in cleanup");
+ logger.error(err, `Failed to end session in DB [sessionId=${sessionId}]`);
} finally {
session = null;
}
}
- // Best-effort: triggers gateway-side cleanup (fire-and-forget)
+ // Best-effort ALPN session cancellation (fire-and-forget).
+ // Triggers gateway-side cleanup: log upload, and session end via API.
+ // If this fails, the scheduled queue job will expire the session at expiresAt time.
if (relayCerts) {
const certs = relayCerts;
relayCerts = null;
@@ -567,6 +587,9 @@ export const pamWebAccessServiceFactory = ({
throw new BadRequestError({ message: "Gateway not configured for this resource" });
}
+ // Sessions that outlived their expiresAt may still show as active — end them so that they don't count against the session limit.
+ await pamSessionDAL.endExpiredWebSessions(userId, projectId);
+
// Check web session limit
const activeCount = await pamSessionDAL.countActiveWebSessions(userId, projectId);
if (activeCount >= MAX_WEB_SESSIONS_PER_USER) {