Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
fix(pam): re-check session validity when privileged access is granted
Andreyadbc6e18aa2a
diff --git a/backend/src/ee/routes/v1/pam-routers/pam-session-router.ts b/backend/src/ee/routes/v1/pam-routers/pam-session-router.tsindex abbe01d41b..331a3baa71 100644--- a/backend/src/ee/routes/v1/pam-routers/pam-session-router.ts+++ b/backend/src/ee/routes/v1/pam-routers/pam-session-router.ts@@ -462,6 +462,8 @@ export const registerPamWebAccessRouter = async (server: FastifyZodProvider) =>actor: req.permission,actorEmail: req.auth.user.email ?? "",actorName: `${req.auth.user.firstName ?? ""} ${req.auth.user.lastName ?? ""}`.trim(),+ tokenVersionId: req.auth.tokenVersionId,+ accessVersion: req.auth.token.accessVersion,auditLogInfo: req.auditLogInfo,reason: req.body.reason,mfaSessionId: req.body.mfaSessionId,@@ -550,6 +552,8 @@ export const registerPamWebAccessRouter = async (server: FastifyZodProvider) =>accountType: z.string(),actorEmail: z.string(),actorName: z.string(),+ tokenVersionId: z.string().uuid(),+ accessVersion: z.number(),reason: z.string().nullable().optional(),maxSessionDurationMs: z.number().optional(),selectedHost: z.string().nullable().optional(),@@ -571,6 +575,12 @@ export const registerPamWebAccessRouter = async (server: FastifyZodProvider) =>return;}+ await server.services.authToken.validateUserSessionFreshness({+ userId,+ tokenVersionId: payload.tokenVersionId,+ accessVersion: payload.accessVersion+ });+await server.services.pamWebAccess.handleWebSocketConnection({socket: connection,accountId: payload.accountId,diff --git a/backend/src/ee/services/pam-session/pam-session-fns.ts b/backend/src/ee/services/pam-session/pam-session-fns.tsindex ef2c894792..02b02034ad 100644--- a/backend/src/ee/services/pam-session/pam-session-fns.ts+++ b/backend/src/ee/services/pam-session/pam-session-fns.ts@@ -13,6 +13,15 @@ import { TUserDALFactory } from "@app/services/user/user-dal";import { PamAccessMethod, PamAccountType, PamSessionEndReason, PamSessionStatus } from "../pam/pam-enums";import { TPamSessionDALFactory } from "./pam-session-dal";+export const LIVE_PAM_SESSION_STATUSES = [PamSessionStatus.Active, PamSessionStatus.Starting];++export const isPamSessionLive = (session: { status: string; expiresAt: Date }) =>+ LIVE_PAM_SESSION_STATUSES.includes(session.status as PamSessionStatus) &&+ new Date(session.expiresAt).getTime() > Date.now();++export const pamSessionRemainingSeconds = (session: { expiresAt: Date }) =>+ Math.max(1, Math.floor((new Date(session.expiresAt).getTime() - Date.now()) / 1000));+export const resolvePamSessionDistinctId = async ({session,userDAL@@ -157,7 +166,7 @@ export const terminatePamSessions = async ({{$in: {id: sessions.map((session) => session.id),- status: [PamSessionStatus.Active, PamSessionStatus.Starting]+ status: LIVE_PAM_SESSION_STATUSES}},{ status: PamSessionStatus.Terminated, endedAt: new Date() },diff --git a/backend/src/ee/services/pam-session/pam-session-service.ts b/backend/src/ee/services/pam-session/pam-session-service.tsindex 69ed090c7a..cd8ea05a8a 100644--- a/backend/src/ee/services/pam-session/pam-session-service.ts+++ b/backend/src/ee/services/pam-session/pam-session-service.ts@@ -72,6 +72,8 @@ import { DEFAULT_SESSION_DURATION_MS } from "./pam-session-constants";import { TPamSessionDALFactory } from "./pam-session-dal";import { TPamSessionExpirationServiceFactory } from "./pam-session-expiration-queue";import {+ isPamSessionLive,+ pamSessionRemainingSeconds,reportPamSessionEnded,resolvePamSessionDistinctId,sendPamSessionCancellationSignal@@ -210,7 +212,7 @@ export const pamSessionServiceFactory = ({throw new NotFoundError({ message: "Session not found" });}- if (session.status !== PamSessionStatus.Starting && session.status !== PamSessionStatus.Active) {+ if (!isPamSessionLive(session)) {throw new BadRequestError({ message: "Session is not active" });}@@ -225,6 +227,7 @@ export const pamSessionServiceFactory = ({const connectionDetails = await decrypt(session.projectId, account.encryptedConnectionDetails);const credentials = await decrypt(session.projectId, account.encryptedCredentials);+ const remainingSeconds = pamSessionRemainingSeconds(session);if (credentials.authMethod === "certificate" && account.encryptedInternalMetadata) {const internalMetadata = parseInternalMetadata(@@ -242,7 +245,7 @@ export const pamSessionServiceFactory = ({clientPublicKey,keyId: `pam-session-${session.id}`,principals: [username],- requestedTtl: `${resolveAccessControls(account.templatePolicies).maxSessionDurationSeconds ?? DEFAULT_SESSION_DURATION_MS / 1000}s`,+ requestedTtl: `${remainingSeconds}s`,certType: SshCertType.USER});@@ -252,7 +255,6 @@ export const pamSessionServiceFactory = ({}if (account.accountType === PamAccountType.GcpServiceAccount) {- const remainingSeconds = Math.max(1, Math.floor((new Date(session.expiresAt).getTime() - Date.now()) / 1000));credentials.token = await mintGcpAccessToken({serviceAccountEmail: connectionDetails.serviceAccountEmail as string,authMethod: credentials.authMethod as string,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.tsindex 23050dfa2b..36fc2462c2 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@@ -157,6 +157,8 @@ export const pamWebAccessServiceFactory = ({actor,actorEmail,actorName,+ tokenVersionId,+ accessVersion,auditLogInfo,reason,mfaSessionId,@@ -259,6 +261,8 @@ export const pamWebAccessServiceFactory = ({accountType: account.accountType,actorEmail,actorName,+ tokenVersionId,+ accessVersion,auditLogInfo,reason: trimmedReason,maxSessionDurationMs,diff --git a/backend/src/ee/services/pam-web-access/pam-web-access-types.ts b/backend/src/ee/services/pam-web-access/pam-web-access-types.tsindex 3e081fa9b9..7544f06601 100644--- a/backend/src/ee/services/pam-web-access/pam-web-access-types.ts+++ b/backend/src/ee/services/pam-web-access/pam-web-access-types.ts@@ -66,6 +66,8 @@ export type TIssueWebSocketTicketDTO = {actor: ProjectServiceActor;actorEmail: string;actorName: string;+ tokenVersionId: string;+ accessVersion: number;auditLogInfo: AuditLogInfo;reason?: string;mfaSessionId?: string;diff --git a/backend/src/services/auth-token/auth-token-service.ts b/backend/src/services/auth-token/auth-token-service.tsindex d79e95c5c7..cadf3e9863 100644--- a/backend/src/services/auth-token/auth-token-service.ts+++ b/backend/src/services/auth-token/auth-token-service.ts@@ -355,14 +355,18 @@ export const tokenServiceFactory = ({ tokenDAL, userDAL, orgDAL, keyStore }: TAureturn { newRefreshToken, updatedSession };};- // to parse jwt identity in inject identity plugin- const fnValidateJwtIdentity = async (token: AuthModeJwtTokenPayload) => {- const session = await tokenDAL.findOneTokenSession({- id: token.tokenVersionId,- userId: token.userId- });+ const validateUserSessionFreshness = async ({+ userId,+ tokenVersionId,+ accessVersion+ }: {+ userId: string;+ tokenVersionId: string;+ accessVersion: number;+ }) => {+ const session = await tokenDAL.findOneTokenSession({ id: tokenVersionId, userId });if (!session) throw new NotFoundError({ name: "Session not found" });- if (token.accessVersion !== session.accessVersion) {+ if (accessVersion !== session.accessVersion) {throw new UnauthorizedError({ name: "StaleSession", message: "User session is stale, please re-authenticate" });}@@ -375,6 +379,17 @@ export const tokenServiceFactory = ({ tokenDAL, userDAL, orgDAL, keyStore }: TAuthrow new UnauthorizedError({ message: "Account is locked" });}+ return { user };+ };++ // to parse jwt identity in inject identity plugin+ const fnValidateJwtIdentity = async (token: AuthModeJwtTokenPayload) => {+ const { user } = await validateUserSessionFreshness({+ userId: token.userId,+ tokenVersionId: token.tokenVersionId,+ accessVersion: token.accessVersion+ });+let orgId = "";let orgName = "";let rootOrgId = "";@@ -527,6 +542,7 @@ export const tokenServiceFactory = ({ tokenDAL, userDAL, orgDAL, keyStore }: TAurevokeSessionsByUserAgent,validateRefreshToken,rotateRefreshToken,+ validateUserSessionFreshness,fnValidateJwtIdentity,getUserTokenSessionById,createEmailSignupToken,