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
bound mfa to session
Thiago Araujo da Silva234b83794099
diff --git a/backend/src/keystore/keystore.ts b/backend/src/keystore/keystore.tsindex 00b4deb32a..ddc497f079 100644--- a/backend/src/keystore/keystore.ts+++ b/backend/src/keystore/keystore.ts@@ -95,7 +95,7 @@ export const KeyStorePrefixes = {UserMfaUnlockEmailSent: (userId: string) => `user-mfa-unlock-email-sent:${userId}` as const,UserStepUpMfaAttempts: (userId: string) => `user-step-up-mfa-attempts:${userId}` as const,UserStepUpMfaLockout: (userId: string) => `user-step-up-mfa-lockout:${userId}` as const,- RecentMfaAuth: (tokenVersionId: string) => `recent-mfa-auth:${tokenVersionId}` as const,+ RecentMfaAuth: (userId: string, tokenVersionId: string) => `recent-mfa-auth:${userId}:${tokenVersionId}` as const,UsedTotpCode: (userId: string, code: string) => `used-totp-code:${userId}:${code}` as const,UsedAccountRecoveryToken: (userId: string, jti: string) => `used-account-recovery-token:${userId}:${jti}` as const,UsedGitHubManifestState: (jti: string) => `used-github-manifest-state:${jti}` as const,@@ -168,7 +168,9 @@ export const KeyStoreTtls = {IdentityRevocationVersionInSeconds: 604800, // 7 daysProjectPermissionMarkerTtlSeconds: 10, // 10 seconds - short-lived marker for fingerprint validationProjectPermissionDataTtlSeconds: 600, // 10 minutes - longer-lived data payload+MfaSessionInSeconds: 300, // 5 minutes+ RecentMfaAuthInSeconds: 600, // 10 minutesMfaCodeResendCooldownInSeconds: 60, // 1 minuteWebAuthnChallengeInSeconds: 300, // 5 minutesdiff --git a/backend/src/server/routes/mfa-step-up-fns.ts b/backend/src/server/routes/mfa-step-up-fns.tsindex ec7d88da68..bbb1883477 100644--- a/backend/src/server/routes/mfa-step-up-fns.ts+++ b/backend/src/server/routes/mfa-step-up-fns.ts@@ -23,7 +23,7 @@ export const getStepUpSessionId = (req: FastifyRequest): string => {* action, reusing the Redis-backed step-up MFA session primitive (mirrors the PAM* account-access flow).*- * A verified session is reusable for the remainder of its TTL (10 min) and is bound+ * A verified session is reusable for the remainder of its TTL (5 min) and is bound* to `resourceId`, so it cannot be replayed against a different action.** - With a valid, verified session for this user + resource: returns immediately.@@ -62,7 +62,8 @@ export const ensureStepUpMfa = async ((await server.services.mfaSession.isMfaSessionActive({mfaSessionId,userId,- resourceId+ resourceId,+ tokenVersionId}))) {return;@@ -70,7 +71,7 @@ export const ensureStepUpMfa = async (if (resourceId === MfaStepUpResource.MfaManagement &&- (await server.services.mfaSession.hasRecentMfaAuth(tokenVersionId))+ (await server.services.mfaSession.hasRecentMfaAuth(userId, tokenVersionId))) {return;}@@ -81,7 +82,12 @@ export const ensureStepUpMfa = async (const mfaMethod = mfaMethodOverride ?? (await server.services.user.getStepUpMfaMethod(userId, orgId));- const newMfaSessionId = await server.services.mfaSession.createMfaSession(userId, resourceId, mfaMethod);+ const newMfaSessionId = await server.services.mfaSession.createMfaSession(+ userId,+ resourceId,+ mfaMethod,+ tokenVersionId+ );if (mfaMethod === MfaMethod.EMAIL && user.email) {await server.services.mfaSession.sendMfaCode(userId, user.email);diff --git a/backend/src/server/routes/v2/mfa-session-router.ts b/backend/src/server/routes/v2/mfa-session-router.tsindex 02665390fe..39e78ceabd 100644--- a/backend/src/server/routes/v2/mfa-session-router.ts+++ b/backend/src/server/routes/v2/mfa-session-router.ts@@ -69,9 +69,14 @@ export const registerMfaSessionRouter = async (server: FastifyZodProvider) => {},onRequest: verifyAuth([AuthMode.JWT]),handler: async (req) => {+ if (req.auth.authMode !== AuthMode.JWT) {+ throw new UnauthorizedError({ message: "MFA session status requires a user session" });+ }+const result = await server.services.mfaSession.getMfaSessionStatus({mfaSessionId: req.params.mfaSessionId,- userId: req.permission.id+ userId: req.permission.id,+ tokenVersionId: req.auth.tokenVersionId});return result;diff --git a/backend/src/services/auth/auth-login-service.ts b/backend/src/services/auth/auth-login-service.tsindex 025083bab7..2c2ae17511 100644--- a/backend/src/services/auth/auth-login-service.ts+++ b/backend/src/services/auth/auth-login-service.ts@@ -730,7 +730,7 @@ export const authLoginServiceFactory = ({// MFA-management step-up isn't re-prompted right after login - including recovery-code// logins, which is what lets a user with a lost factor still manage their MFA. Keyed// by the new session's tokenVersionId so no other session inherits it.- await mfaLockoutService.recordRecentMfaAuth(token.tokenVersionId);+ await mfaLockoutService.recordRecentMfaAuth(user.id, token.tokenVersionId);if (isRecoveryCode && userEnc.email) {await smtpServicediff --git a/backend/src/services/auth/mfa-lockout-service.ts b/backend/src/services/auth/mfa-lockout-service.tsindex 1f4167edde..f0a70fe4b6 100644--- a/backend/src/services/auth/mfa-lockout-service.ts+++ b/backend/src/services/auth/mfa-lockout-service.ts@@ -199,19 +199,20 @@ export const mfaLockoutServiceFactory = ({// within this window an MFA-management step-up on that same session is redundant. This// is what lets a user who lost their only configured factor, and logged in via a// recovery code, still reach their MFA settings to disable it or switch the preferred- // method. Keyed by tokenVersionId (the session), NOT the user, so proving MFA in one- // session never authorizes another (older/stolen) session. Self-clears on TTL; if the- // window lapses, another login on that session re-opens it.- const recordRecentMfaAuth = async (tokenVersionId: string) => {+ // method. Keyed by userId + tokenVersionId (the session), NOT the user alone, so proving+ // MFA in one session never authorizes another (older/stolen) session; the userId prefix+ // namespaces the session id to its owner. Self-clears on TTL; if the window lapses,+ // another login on that session re-opens it.+ const recordRecentMfaAuth = async (userId: string, tokenVersionId: string) => {await keyStore.setItemWithExpiry(- KeyStorePrefixes.RecentMfaAuth(tokenVersionId),- KeyStoreTtls.MfaSessionInSeconds,+ KeyStorePrefixes.RecentMfaAuth(userId, tokenVersionId),+ KeyStoreTtls.RecentMfaAuthInSeconds,"1");};- const hasRecentMfaAuth = async (tokenVersionId: string): Promise<boolean> => {- return Boolean(await keyStore.getItem(KeyStorePrefixes.RecentMfaAuth(tokenVersionId)));+ const hasRecentMfaAuth = async (userId: string, tokenVersionId: string): Promise<boolean> => {+ return Boolean(await keyStore.getItem(KeyStorePrefixes.RecentMfaAuth(userId, tokenVersionId)));};return {diff --git a/backend/src/services/mfa-session/mfa-session-service.ts b/backend/src/services/mfa-session/mfa-session-service.tsindex 680cbfabfb..15b62e1f05 100644--- a/backend/src/services/mfa-session/mfa-session-service.ts+++ b/backend/src/services/mfa-session/mfa-session-service.ts@@ -60,14 +60,27 @@ export const mfaSessionServiceFactory = ({// low-value PAM account) can never be replayed against another (e.g. recovery// codes). verifyMfaSession only flips PENDING -> ACTIVE; the resource binding// is enforced here at the point of use.- const isMfaSessionActive = async ({ mfaSessionId, userId, resourceId }: TIsMfaSessionActiveDTO): Promise<boolean> => {+ const isMfaSessionActive = async ({+ mfaSessionId,+ userId,+ resourceId,+ tokenVersionId+ }: TIsMfaSessionActiveDTO): Promise<boolean> => {const mfaSession = await getMfaSession(mfaSessionId);- return Boolean(- mfaSession &&- mfaSession.userId === userId &&- mfaSession.resourceId === resourceId &&- mfaSession.status === MfaSessionStatus.ACTIVE- );+ if (+ !mfaSession ||+ mfaSession.userId !== userId ||+ mfaSession.resourceId !== resourceId ||+ mfaSession.status !== MfaSessionStatus.ACTIVE+ ) {+ return false;+ }++ if (resourceId === MfaStepUpResource.MfaManagement && mfaSession.initiatingTokenVersionId !== tokenVersionId) {+ return false;+ }++ return true;};// Helper function to update MFA session in Redis@@ -134,6 +147,15 @@ export const mfaSessionServiceFactory = ({});}+ if (+ mfaSession.resourceId === MfaStepUpResource.MfaManagement &&+ mfaSession.initiatingTokenVersionId !== tokenVersionId+ ) {+ throw new ForbiddenRequestError({+ message: "MFA session does not belong to current session"+ });+ }+await mfaLockoutService.enforceStepUpMfaLockStatus(userId);await mfaLockoutService.reserveStepUpMfaAttempt(userId);@@ -178,7 +200,7 @@ export const mfaSessionServiceFactory = ({await updateMfaSession(mfaSession, KeyStoreTtls.MfaSessionInSeconds);if (mfaSession.resourceId === MfaStepUpResource.MfaManagement) {- await mfaLockoutService.recordRecentMfaAuth(tokenVersionId);+ await mfaLockoutService.recordRecentMfaAuth(userId, tokenVersionId);}return {@@ -187,7 +209,7 @@ export const mfaSessionServiceFactory = ({};};- const getMfaSessionStatus = async ({ mfaSessionId, userId }: TGetMfaSessionStatusDTO) => {+ const getMfaSessionStatus = async ({ mfaSessionId, userId, tokenVersionId }: TGetMfaSessionStatusDTO) => {const mfaSession = await getMfaSession(mfaSessionId);if (!mfaSession) {@@ -202,20 +224,35 @@ export const mfaSessionServiceFactory = ({});}+ if (+ mfaSession.resourceId === MfaStepUpResource.MfaManagement &&+ mfaSession.initiatingTokenVersionId !== tokenVersionId+ ) {+ throw new ForbiddenRequestError({+ message: "MFA session does not belong to current session"+ });+ }+return {status: mfaSession.status,mfaMethod: mfaSession.mfaMethod};};- const createMfaSession = async (userId: string, resourceId: string, mfaMethod: MfaMethod): Promise<string> => {+ const createMfaSession = async (+ userId: string,+ resourceId: string,+ mfaMethod: MfaMethod,+ initiatingTokenVersionId?: string+ ): Promise<string> => {const mfaSessionId = crypto.randomBytes(32).toString("hex");const mfaSession: TMfaSession = {sessionId: mfaSessionId,userId,resourceId,status: MfaSessionStatus.PENDING,- mfaMethod+ mfaMethod,+ initiatingTokenVersionId};await keyStore.setItemWithExpiry(@@ -241,8 +278,8 @@ export const mfaSessionServiceFactory = ({// True when THIS session (tokenVersionId) completed a full MFA login or management// step-up recently, so an MFA-management step-up can be skipped within the grace// window (see recordRecentMfaAuth). Session-scoped, never user-scoped.- const hasRecentMfaAuth = async (tokenVersionId: string): Promise<boolean> => {- return mfaLockoutService.hasRecentMfaAuth(tokenVersionId);+ const hasRecentMfaAuth = async (userId: string, tokenVersionId: string): Promise<boolean> => {+ return mfaLockoutService.hasRecentMfaAuth(userId, tokenVersionId);};return {diff --git a/backend/src/services/mfa-session/mfa-session-types.ts b/backend/src/services/mfa-session/mfa-session-types.tsindex 45f71cf8f4..f5f5ede80e 100644--- a/backend/src/services/mfa-session/mfa-session-types.ts+++ b/backend/src/services/mfa-session/mfa-session-types.ts@@ -18,6 +18,12 @@ export type TMfaSession = {resourceId: string; // Generic - can be accountId, documentId, etc.status: MfaSessionStatus;mfaMethod: MfaMethod;+ // The login session (tokenVersionId) that INITIATED this step-up. Only set for+ // MFA-management step-ups; it binds verification, status polling, and consumption+ // to the initiating session so a challenge initiated by one session cannot be+ // completed by another (e.g. tricking a victim into finishing a stolen session's+ // challenge). Undefined for PAM sessions, which are account-scoped and unaffected.+ initiatingTokenVersionId?: string;};export type TCreateMfaSessionDTO = {@@ -37,10 +43,12 @@ export type TVerifyMfaSessionDTO = {export type TGetMfaSessionStatusDTO = {mfaSessionId: string;userId: string;+ tokenVersionId: string;};export type TIsMfaSessionActiveDTO = {mfaSessionId: string;userId: string;resourceId: string;+ tokenVersionId: string;};