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
step up on enabling to validate the MFA being used
Thiago Araujo da Silva88e6b3d3e09f
diff --git a/backend/src/server/routes/mfa-step-up-fns.ts b/backend/src/server/routes/mfa-step-up-fns.tsindex 96ff367b08..0c7a0b91ce 100644--- a/backend/src/server/routes/mfa-step-up-fns.ts+++ b/backend/src/server/routes/mfa-step-up-fns.ts@@ -10,8 +10,14 @@ import { MfaMethod } from "@app/services/auth/auth-type";// MFA-management actions of comparable risk, so they intentionally share a single// resource id: one fresh challenge covers all of them for the session TTL (5 min)// rather than re-prompting the user for each action in quick succession.+//+// Enabling MFA is kept on its own resource id (never folded into MfaManagement):+// it is challenged against the method the user is *enabling* (which may be weaker+// than an org's enforced method), so a session verified for enablement must not be+// replayable against MfaManagement actions that are gated on the enforced method.export const MfaStepUpResource = {- MfaManagement: "mfa-management"+ MfaManagement: "mfa-management",+ MfaActivation: "mfa-activation"} as const;export type TMfaStepUpResource = (typeof MfaStepUpResource)[keyof typeof MfaStepUpResource];@@ -29,6 +35,11 @@ export type TMfaStepUpResource = (typeof MfaStepUpResource)[keyof typeof MfaStep* mints a fresh pending session (emailing the code when the required method is* email) and throws `SESSION_MFA_REQUIRED` carrying the new session id + method* so the client can drive the challenge and retry.+ *+ * By default the challenged method is the one the current org context requires (the+ * 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.*/export const ensureStepUpMfa = async (server: FastifyZodProvider,@@ -37,13 +48,15 @@ export const ensureStepUpMfa = async (orgId,resourceId,mfaSessionId,- message+ message,+ mfaMethod: mfaMethodOverride}: {userId: string;orgId: string;resourceId: TMfaStepUpResource;mfaSessionId?: string;message: string;+ mfaMethod?: MfaMethod;}) => {if (@@ -61,7 +74,7 @@ export const ensureStepUpMfa = async (const user = await server.services.user.getMe(userId);- const mfaMethod = await server.services.user.getStepUpMfaMethod(userId, orgId);+ const mfaMethod = mfaMethodOverride ?? (await server.services.user.getStepUpMfaMethod(userId, orgId));const newMfaSessionId = await server.services.mfaSession.createMfaSession(userId, resourceId, mfaMethod);diff --git a/backend/src/server/routes/v2/user-router.ts b/backend/src/server/routes/v2/user-router.tsindex 62f4a4017f..7e1f71b242 100644--- a/backend/src/server/routes/v2/user-router.ts+++ b/backend/src/server/routes/v2/user-router.ts@@ -2,6 +2,7 @@ import type { RegistrationResponseJSON } from "@simplewebauthn/server";import { z } from "zod";import { AuthTokenSessionsSchema } from "@app/db/schemas";+import { UnauthorizedError } from "@app/lib/errors";import { readLimit, smtpRateLimit, writeLimit } from "@app/server/config/rateLimiter";import { verifyAuth } from "@app/server/plugins/auth/verify-auth";import { AuthMethod, AuthMode, MfaMethod } from "@app/services/auth/auth-type";@@ -142,18 +143,17 @@ export const registerUserRouter = async (server: FastifyZodProvider) => {// client can surface them.//// Recovery codes bypass any org-required MFA method at login, so they must never- // be mintable by a session that has not itself completed that method. This route- // requires an org-scoped token (requireOrg:true): a token for an MFA-enforcing org- // can only exist after that org's MFA challenge was completed (see- // selectOrganization), so reaching this handler already proves the org-required- // method. The transient post-password no-org token used during login/onboarding- // is rejected here and cannot obtain recovery codes.+ // be mintable by a session that has not itself proven a second factor. An org-scoped+ // token alone is NOT sufficient: it may belong to an org that does not enforce MFA+ // (isMfaVerified=false), which would let a password-only attacker mint account-wide+ // recovery codes through the weaker org and replay them against a stronger org's+ // enforced challenge. So:+ // - isMfaVerified token (login MFA already completed): enable directly.+ // - otherwise: require a fresh step-up challenge against the method being enabled+ // (proving possession of that factor) before issuing codes.//- // This is enable-only: the org-scoped token proves the org method was completed at- // login but NOT a fresh step-up challenge, so re-running it on an already-enabled- // account would mint fresh recovery codes without the step-up gate the recovery-code- // endpoints enforce. The service rejects already-enabled accounts; rotating codes on- // an enabled account goes through the step-up-gated POST /me/mfa/recovery-codes route.+ // The service rejects already-enabled accounts; rotating codes on an enabled account+ // goes through the step-up-gated POST /me/mfa/recovery-codes route.server.route({method: "POST",url: "/me/mfa/activate",@@ -163,7 +163,8 @@ export const registerUserRouter = async (server: FastifyZodProvider) => {schema: {operationId: "activateUserMfa",body: z.object({- selectedMfaMethod: z.nativeEnum(MfaMethod).optional()+ selectedMfaMethod: z.nativeEnum(MfaMethod).optional(),+ mfaSessionId: z.string().trim().optional()}),response: {200: z.object({@@ -174,9 +175,28 @@ export const registerUserRouter = async (server: FastifyZodProvider) => {},preHandler: verifyAuth([AuthMode.JWT]),handler: async (req) => {+ if (req.auth.authMode !== AuthMode.JWT) {+ throw new UnauthorizedError({ message: "Invalid auth mode" });+ }++ const me = await server.services.user.getMe(req.permission.id);+ const selectedMfaMethod =+ req.body.selectedMfaMethod ?? (me.selectedMfaMethod as MfaMethod | null) ?? MfaMethod.EMAIL;++ if (!req.auth.isMfaVerified) {+ await ensureStepUpMfa(server, {+ userId: req.permission.id,+ orgId: req.permission.orgId,+ resourceId: MfaStepUpResource.MfaActivation,+ mfaMethod: selectedMfaMethod,+ mfaSessionId: req.body.mfaSessionId,+ message: "MFA verification is required to enable two-factor authentication"+ });+ }+const { user, recoveryCodes } = await server.services.user.activateMfa({userId: req.permission.id,- selectedMfaMethod: req.body.selectedMfaMethod+ selectedMfaMethod});return { user, recoveryCodes };@@ -207,6 +227,11 @@ export const registerUserRouter = async (server: FastifyZodProvider) => {},preHandler: verifyAuth([AuthMode.JWT]),handler: async (req) => {+ // Enforce the org-enforcement rule before the step-up challenge so a user in an+ // MFA-enforcing org gets a clean rejection instead of being made to complete an+ // MFA challenge only to be denied. deactivateMfa re-checks it authoritatively.+ await server.services.user.assertMfaDisableAllowed(req.permission.id);+await ensureStepUpMfa(server, {userId: req.permission.id,orgId: req.permission.orgId,diff --git a/backend/src/services/user/user-service.ts b/backend/src/services/user/user-service.tsindex ca63546ff5..de98cd1c95 100644--- a/backend/src/services/user/user-service.ts+++ b/backend/src/services/user/user-service.ts@@ -172,6 +172,28 @@ 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 userOrgMemberships = await membershipUserDAL.find({+ actorUserId: userId,+ scope: AccessScope.Organization+ });+ if (!userOrgMemberships.length) return;++ const orgIds = userOrgMemberships.map((membership) => membership.scopeOrgId);+ const organizations = await orgDAL.find({ $in: { id: orgIds } });+ if (organizations.some((org) => org.enforceMfa)) {+ throw new ForbiddenRequestError({+ message: "Two-factor authentication is required by your organization and cannot be disabled"+ });+ }+ };+// 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.@@ -179,21 +201,7 @@ export const userServiceFactory = ({const user = await userDAL.findById(userId);if (!user) throw new BadRequestError({ name: "Failed to disable MFA" });- // 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.- const userOrgMemberships = await membershipUserDAL.find({- actorUserId: userId,- scope: AccessScope.Organization- });- if (userOrgMemberships.length) {- const orgIds = userOrgMemberships.map((membership) => membership.scopeOrgId);- const organizations = await orgDAL.find({ $in: { id: orgIds } });- if (organizations.some((org) => org.enforceMfa)) {- throw new ForbiddenRequestError({- message: "Two-factor authentication is required by your organization and cannot be disabled"- });- }- }+ await assertMfaDisableAllowed(userId);const updatedUser = await userDAL.transaction(async (tx) => {const updated = await userDAL.updateById(userId, { isMfaEnabled: false }, tx);@@ -655,6 +663,7 @@ export const userServiceFactory = ({sendEmailVerificationCode,activateMfa,deactivateMfa,+ assertMfaDisableAllowed,setSelectedMfaMethod,updateUserName,updateAuthMethods,diff --git a/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/MFASection.tsx b/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/MFASection.tsxindex d3ddbc4147..c2bb4d6d25 100644--- a/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/MFASection.tsx+++ b/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/MFASection.tsx@@ -2,7 +2,6 @@ import { useState } from "react";import { CircleAlertIcon, PowerIcon, ShieldCheckIcon } from "lucide-react";import { MFA_METHOD_ICONS, MFA_METHOD_LABELS, RecoveryCodesView } from "@app/components/mfa/setup";-import { createNotification } from "@app/components/notifications";import { ContentLoader } from "@app/components/v2";import {AlertDialog,@@ -26,7 +25,7 @@ import {SelectTrigger,SelectValue} from "@app/components/v3";-import { useActivateMfa, useGetOrganizations, useGetUser } from "@app/hooks/api";+import { useGetOrganizations, useGetUser } from "@app/hooks/api";import { MfaMethod } from "@app/hooks/api/auth/types";import { useFetchServerStatus } from "@app/hooks/api/serverDetails";import { useGetUserTotpConfiguration } from "@app/hooks/api/users";@@ -37,13 +36,14 @@ import { MfaMethodsCard } from "./MfaMethodsCard";import { RecoveryOptionsCard } from "./RecoveryOptionsCard";import { useChangePreferredMfa } from "./useChangePreferredMfa";import { useDisableMfa } from "./useDisableMfa";+import { useEnableMfa } from "./useEnableMfa";const LEARN_MORE_URL = "https://infisical.com/docs/documentation/platform/mfa";export const MFASection = () => {const { data: user, isPending } = useGetUser();const { changePreferredMfa } = useChangePreferredMfa();- const { mutateAsync: activateMfa, isPending: isEnabling } = useActivateMfa();+ const { isBusy: isEnabling, enableMfa } = useEnableMfa();const { isBusy: isDisabling, disableMfa } = useDisableMfa();const { data: totpConfiguration } = useGetUserTotpConfiguration();const { data: webAuthnCredentials = [] } = useGetWebAuthnCredentials();@@ -96,17 +96,10 @@ export const MFASection = () => {const hasRecoveryCodes = user.isMfaEnabled;- const handleEnable = async () => {- try {- const { recoveryCodes } = await activateMfa({ selectedMfaMethod: selectedMethod });- setIsEnableOpen(false);- setNewRecoveryCodes(recoveryCodes);- } catch (error: any) {- createNotification({- text: error?.response?.data?.message || "Failed to enable two-factor authentication",- type: "error"- });- }+ const handleEnable = () => {+ if (!selectedMethod) return;+ setIsEnableOpen(false);+ enableMfa(selectedMethod, (recoveryCodes) => setNewRecoveryCodes(recoveryCodes));};// Changing the preferred method is sensitive, so it goes through the step-up MFAdiff --git a/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/useEnableMfa.ts b/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/useEnableMfa.tsnew file mode 100644index 0000000000..21e7566426--- /dev/null+++ b/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/useEnableMfa.ts@@ -0,0 +1,51 @@+import { useCallback } from "react";+import { useQueryClient } from "@tanstack/react-query";++import { apiRequest } from "@app/config/request";+import { MfaMethod } from "@app/hooks/api/auth/types";+import { userKeys } from "@app/hooks/api/users/query-keys";++import { useMfaStepUp } from "./useMfaStepUp";++/**+ * Enabling MFA mints an account-wide recovery-code pool, and those codes bypass any+ * org-enforced MFA at login. A session that has not itself proven a second factor+ * (isMfaVerified=false — e.g. a token from an org that does not enforce MFA) must+ * therefore pass a fresh step-up challenge against the method being enabled before+ * the backend issues codes. This wraps the shared {@link useMfaStepUp} driver with+ * the activate request and surfaces the freshly minted recovery codes once.+ *+ * Calls apiRequest directly (rather than a mutation) so the expected+ * SESSION_MFA_REQUIRED 400 doesn't surface a global mutation error toast.+ */+export const useEnableMfa = () => {+ const queryClient = useQueryClient();+ const { isBusy, runWithMfa } = useMfaStepUp();++ const enableMfa = useCallback(+ (selectedMfaMethod: MfaMethod, onEnabled: (recoveryCodes: string[]) => void) =>+ runWithMfa(+ async (mfaSessionId) => {+ const { data } = await apiRequest.post<{ recoveryCodes: string[] }>(+ "/api/v2/users/me/mfa/activate",+ {+ selectedMfaMethod,+ ...(mfaSessionId ? { mfaSessionId } : {})+ }+ );+ return data.recoveryCodes;+ },+ {+ onSuccess: (recoveryCodes) => {+ queryClient.invalidateQueries({ queryKey: userKeys.getUser });+ queryClient.invalidateQueries({ queryKey: userKeys.mfaRecoveryCodes });+ onEnabled(recoveryCodes);+ },+ errorText: "Failed to enable two-factor authentication"+ }+ ),+ [runWithMfa, queryClient]+ );++ return { isBusy, enableMfa };+};