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
avoid account lockout on mfa management
Thiago Araujo da Silva5feb10fa24a1
diff --git a/backend/src/server/routes/mfa-step-up-fns.ts b/backend/src/server/routes/mfa-step-up-fns.tsindex bbb1883477..0e633fe1cc 100644--- a/backend/src/server/routes/mfa-step-up-fns.ts+++ b/backend/src/server/routes/mfa-step-up-fns.ts@@ -36,6 +36,8 @@ export const getStepUpSessionId = (req: FastifyRequest): string => {* enforced method, or the user's preference otherwise). Pass `mfaMethod` to override* this when the action dictates the method independently of org enforcement — e.g.* enabling MFA challenges the factor being enabled, not a stronger org-enforced one.+ * Pass `excludeMfaMethod` when the action removes a factor, so the challenge never+ * demands the factor being removed (which is usually the one the user has lost).*/export const ensureStepUpMfa = async (server: FastifyZodProvider,@@ -46,7 +48,8 @@ export const ensureStepUpMfa = async (resourceId,mfaSessionId,message,- mfaMethod: mfaMethodOverride+ mfaMethod: mfaMethodOverride,+ excludeMfaMethod}: {userId: string;orgId: string;@@ -55,6 +58,7 @@ export const ensureStepUpMfa = async (mfaSessionId?: string;message: string;mfaMethod?: MfaMethod;+ excludeMfaMethod?: MfaMethod;}) => {if (@@ -69,18 +73,17 @@ export const ensureStepUpMfa = async (return;}- if (- resourceId === MfaStepUpResource.MfaManagement &&- (await server.services.mfaSession.hasRecentMfaAuth(userId, tokenVersionId))- ) {- return;+ if (resourceId === MfaStepUpResource.MfaManagement) {+ if (await server.services.mfaSession.hasRecentMfaAuth(userId, tokenVersionId)) return;+ if (!(await server.services.user.isStepUpMfaRequired(userId))) return;}await server.services.mfaSession.enforceStepUpMfaLockout(userId);const user = await server.services.user.getMe(userId);- const mfaMethod = mfaMethodOverride ?? (await server.services.user.getStepUpMfaMethod(userId, orgId));+ const mfaMethod =+ mfaMethodOverride ?? (await server.services.user.getStepUpMfaMethod(userId, orgId, excludeMfaMethod));const newMfaSessionId = await server.services.mfaSession.createMfaSession(userId,diff --git a/backend/src/server/routes/v1/user-router.ts b/backend/src/server/routes/v1/user-router.tsindex a45aed39a6..183de52088 100644--- a/backend/src/server/routes/v1/user-router.ts+++ b/backend/src/server/routes/v1/user-router.ts@@ -6,7 +6,7 @@ import { getConfig } from "@app/lib/config/env";import { logger } from "@app/lib/logger";import { authRateLimit, readLimit, writeLimit } from "@app/server/config/rateLimiter";import { verifyAuth } from "@app/server/plugins/auth/verify-auth";-import { AuthMode } from "@app/services/auth/auth-type";+import { AuthMode, MfaMethod } from "@app/services/auth/auth-type";import { ensureStepUpMfa, getStepUpSessionId, MfaStepUpResource } from "../mfa-step-up-fns";@@ -240,7 +240,8 @@ export const registerUserRouter = async (server: FastifyZodProvider) => {tokenVersionId: getStepUpSessionId(req),resourceId: MfaStepUpResource.MfaManagement,mfaSessionId: req.query.mfaSessionId,- message: "MFA verification is required to remove your authenticator app"+ message: "MFA verification is required to remove your authenticator app",+ excludeMfaMethod: MfaMethod.TOTP});return server.services.totp.deleteUserTotpConfig({userId: req.permission.id@@ -591,7 +592,8 @@ export const registerUserRouter = async (server: FastifyZodProvider) => {tokenVersionId: getStepUpSessionId(req),resourceId: MfaStepUpResource.MfaManagement,mfaSessionId: req.query.mfaSessionId,- message: "MFA verification is required to remove a passkey"+ message: "MFA verification is required to remove a passkey",+ excludeMfaMethod: MfaMethod.WEBAUTHN});await server.services.webAuthn.deleteWebAuthnCredential({userId: req.permission.id,diff --git a/backend/src/services/user/user-service.ts b/backend/src/services/user/user-service.tsindex 0d72de18a2..7997a9bbd1 100644--- a/backend/src/services/user/user-service.ts+++ b/backend/src/services/user/user-service.ts@@ -141,6 +141,17 @@ export const userServiceFactory = ({});};+ const isMfaMethodConfigured = async (user: { id: string; email?: string | null }, method: MfaMethod) => {+ if (method === MfaMethod.EMAIL) {+ return Boolean(user.email) && getConfig().isSmtpConfigured;+ }+ if (method === MfaMethod.TOTP) {+ return Boolean(await totpConfigDAL.findOne({ userId: user.id, isVerified: true }));+ }+ const credentials = await webAuthnCredentialDAL.find({ userId: user.id });+ return credentials.length > 0;+ };+// A method can only be selected/activated once the user has actually configured// that factor. EMAIL uses the account email, so it needs no enrollment, but it// delivers codes over SMTP — which self-hosted instances may not have configured.@@ -201,28 +212,42 @@ export const userServiceFactory = ({return { user: updatedUser, recoveryCodes };};- // MFA cannot be turned off while any organization the user belongs to enforces it,- // since doing so would lock them out of that org on the next login. This is the- // authoritative backend rule (the UI only greys out the button as a hint) and is- // enforced both up front in the disable route — so the user isn't put through a- // step-up challenge only to be rejected — and again here in deactivateMfa as the- // single source of truth that actually gates the state change.- const assertMfaDisableAllowed = async (userId: string) => {+ const hasMfaEnforcingOrg = async (userId: string) => {const userOrgMemberships = await membershipUserDAL.find({actorUserId: userId,scope: AccessScope.Organization});- if (!userOrgMemberships.length) return;+ if (!userOrgMemberships.length) return false;const orgIds = userOrgMemberships.map((membership) => membership.scopeOrgId);const organizations = await orgDAL.find({ $in: { id: orgIds } });- if (organizations.some((org) => org.enforceMfa)) {+ return organizations.some((org) => org.enforceMfa);+ };++ // MFA cannot be turned off while any organization the user belongs to enforces it,+ // since doing so would lock them out of that org on the next login. This is the+ // authoritative backend rule (the UI only greys out the button as a hint) and is+ // enforced both up front in the disable route — so the user isn't put through a+ // step-up challenge only to be rejected — and again here in deactivateMfa as the+ // single source of truth that actually gates the state change.+ const assertMfaDisableAllowed = async (userId: string) => {+ if (await hasMfaEnforcingOrg(userId)) {throw new ForbiddenRequestError({message: "Two-factor authentication is required by your organization and cannot be disabled"});}};+ // With MFA required nowhere, login is password-only, so challenging here protects+ // nothing: the same session could just enrol and enable its own factor instead.+ // Every org is checked, not only the current one, so switching to a non-enforcing+ // org is not a way to strip a factor another org relies on.+ const isStepUpMfaRequired = async (userId: string) => {+ const user = await userDAL.findById(userId);+ if (user?.isMfaEnabled) return true;+ return hasMfaEnforcingOrg(userId);+ };+// Disables MFA. Enrolled factors are preserved so re-enabling does not require// re-enrollment, but the recovery-code pool is wiped so codes never outlive the// enabled state; a fresh pool is issued on the next enable.@@ -583,10 +608,21 @@ export const userServiceFactory = ({// Mirrors login via the shared getRequiredMfaMethod: an org enforcing MFA dictates// the method, otherwise the user's own preference applies. Reaching a step-up-gated// route already proves membership of this org, so no permission check is needed.- const getStepUpMfaMethod = async (userId: string, orgId: string): Promise<MfaMethod> => {+ //+ // Removing a factor is never gated on that same factor, since the usual reason to+ // remove one is that it was lost. The strongest other configured factor stands in,+ // falling back to the required method when nothing else is set up (e.g. no SMTP on+ // a self-hosted instance).+ const getStepUpMfaMethod = async (userId: string, orgId: string, excludeMethod?: MfaMethod): Promise<MfaMethod> => {const [user, org] = await Promise.all([userDAL.findById(userId), orgDAL.findById(orgId)]);const { requiredMfaMethod } = getRequiredMfaMethod(org ?? {}, user ?? {});- return requiredMfaMethod;+ if (!user || !excludeMethod || requiredMfaMethod !== excludeMethod) return requiredMfaMethod;++ const fallbackOrder = [MfaMethod.WEBAUTHN, MfaMethod.TOTP, MfaMethod.EMAIL].filter(+ (method) => method !== excludeMethod+ );+ const configured = await Promise.all(fallbackOrder.map((method) => isMfaMethodConfigured(user, method)));+ return fallbackOrder.find((_, index) => configured[index]) ?? requiredMfaMethod;};const deleteUser = async (userId: string) => {@@ -782,6 +818,7 @@ export const userServiceFactory = ({deleteUser,getMe,getStepUpMfaMethod,+ isStepUpMfaRequired,createUserAction,listUserGroups,getUserAction,