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
require MFA for every 2fa removal/disabling operation
Thiago Araujo da Silvade8d95eab2e3
diff --git a/backend/src/server/routes/v1/user-router.ts b/backend/src/server/routes/v1/user-router.tsindex 6260494e28..db170ee112 100644--- a/backend/src/server/routes/v1/user-router.ts+++ b/backend/src/server/routes/v1/user-router.ts@@ -227,10 +227,20 @@ export const registerUserRouter = async (server: FastifyZodProvider) => {rateLimit: writeLimit},schema: {- operationId: "deleteUserTotpConfig"+ operationId: "deleteUserTotpConfig",+ querystring: z.object({+ mfaSessionId: z.string().trim().optional()+ })},onRequest: verifyAuth([AuthMode.JWT]),handler: async (req) => {+ await ensureStepUpMfa(server, {+ userId: req.permission.id,+ orgId: req.permission.orgId,+ resourceId: MfaStepUpResource.MfaManagement,+ mfaSessionId: req.query.mfaSessionId,+ message: "MFA verification is required to remove your authenticator app"+ });return server.services.totp.deleteUserTotpConfig({userId: req.permission.id});@@ -561,6 +571,9 @@ export const registerUserRouter = async (server: FastifyZodProvider) => {params: z.object({id: z.string()}),+ querystring: z.object({+ mfaSessionId: z.string().trim().optional()+ }),response: {200: z.object({success: z.boolean()@@ -569,6 +582,13 @@ export const registerUserRouter = async (server: FastifyZodProvider) => {},onRequest: verifyAuth([AuthMode.JWT]),handler: async (req) => {+ await ensureStepUpMfa(server, {+ userId: req.permission.id,+ orgId: req.permission.orgId,+ resourceId: MfaStepUpResource.MfaManagement,+ mfaSessionId: req.query.mfaSessionId,+ message: "MFA verification is required to remove a passkey"+ });await server.services.webAuthn.deleteWebAuthnCredential({userId: req.permission.id,id: req.params.iddiff --git a/backend/src/server/routes/v2/user-router.ts b/backend/src/server/routes/v2/user-router.tsindex 4a5e48913a..62f4a4017f 100644--- a/backend/src/server/routes/v2/user-router.ts+++ b/backend/src/server/routes/v2/user-router.ts@@ -45,7 +45,8 @@ export const registerUserRouter = async (server: FastifyZodProvider) => {schema: {operationId: "updateUserMfaMethod",body: z.object({- selectedMfaMethod: z.nativeEnum(MfaMethod)+ selectedMfaMethod: z.nativeEnum(MfaMethod),+ mfaSessionId: z.string().trim().optional()}),response: {200: z.object({@@ -55,6 +56,14 @@ export const registerUserRouter = async (server: FastifyZodProvider) => {},preHandler: verifyAuth([AuthMode.JWT]),handler: async (req) => {+ await ensureStepUpMfa(server, {+ userId: req.permission.id,+ orgId: req.permission.orgId,+ resourceId: MfaStepUpResource.MfaManagement,+ mfaSessionId: req.body.mfaSessionId,+ message: "MFA verification is required to change your preferred two-factor method"+ });+const user = await server.services.user.setSelectedMfaMethod({userId: req.permission.id,selectedMfaMethod: req.body.selectedMfaMethoddiff --git a/frontend/src/hooks/api/users/index.tsx b/frontend/src/hooks/api/users/index.tsxindex 24768dd50b..13e27390fb 100644--- a/frontend/src/hooks/api/users/index.tsx+++ b/frontend/src/hooks/api/users/index.tsx@@ -1,6 +1,5 @@export {useAddUserToWsNonE2EE,- useDeleteUserTotpConfiguration,useRemoveMyDuplicateAccounts,useRequestEmailChangeOTP,useRevokeMySessionById,@@ -30,7 +29,6 @@ export {useLogoutUser,useRegisterUserAction,useRevokeMySessions,- useSetMfaMethod,useUpdateOrgMembership,useUpdateUserAuthMethods} from "./queries";diff --git a/frontend/src/hooks/api/users/mutation.tsx b/frontend/src/hooks/api/users/mutation.tsxindex c3856fd7c8..860292c182 100644--- a/frontend/src/hooks/api/users/mutation.tsx+++ b/frontend/src/hooks/api/users/mutation.tsx@@ -65,22 +65,6 @@ export const useUpdateUserProjectFavorites = () => {});};-export const useDeleteUserTotpConfiguration = () => {- const queryClient = useQueryClient();- return useMutation({- mutationFn: async () => {- await apiRequest.delete("/api/v1/user/me/totp");-- return {};- },- onSuccess: () => {- queryClient.invalidateQueries({ queryKey: userKeys.totpConfiguration });- queryClient.removeQueries({ queryKey: userKeys.totpRegistration });- queryClient.invalidateQueries({ queryKey: userKeys.getUser });- }- });-};-export const useResendOrgMemberInvitation = () => {return useMutation({mutationFn: async (dto: { membershipId: string }) => {diff --git a/frontend/src/hooks/api/users/queries.tsx b/frontend/src/hooks/api/users/queries.tsxindex 0079b8f58c..837712a9b2 100644--- a/frontend/src/hooks/api/users/queries.tsx+++ b/frontend/src/hooks/api/users/queries.tsx@@ -457,23 +457,6 @@ export const useActivateMfa = () => {});};-// Set the preferred challenge method among already-configured factors.-export const useSetMfaMethod = () => {- const queryClient = useQueryClient();- return useMutation({- mutationFn: async ({ selectedMfaMethod }: { selectedMfaMethod: MfaMethod }) => {- const { data } = await apiRequest.patch<{ user: unknown }>("/api/v2/users/me/mfa", {- selectedMfaMethod- });-- return { user: data.user };- },- onSuccess() {- queryClient.invalidateQueries({ queryKey: userKeys.getUser });- }- });-};-export const fetchMyOrganizationProjects = async (orgId: string) => {const {data: { workspaces }diff --git a/frontend/src/hooks/api/webauthn/index.tsx b/frontend/src/hooks/api/webauthn/index.tsxindex df0f1e19b7..1db2260fc3 100644--- a/frontend/src/hooks/api/webauthn/index.tsx+++ b/frontend/src/hooks/api/webauthn/index.tsx@@ -1,5 +1,4 @@export {- useDeleteWebAuthnCredential,useGenerateAuthenticationOptions,useGenerateRegistrationOptions,useUpdateWebAuthnCredential,diff --git a/frontend/src/hooks/api/webauthn/mutations.tsx b/frontend/src/hooks/api/webauthn/mutations.tsxindex bed98a9bd8..b7581e8aac 100644--- a/frontend/src/hooks/api/webauthn/mutations.tsx+++ b/frontend/src/hooks/api/webauthn/mutations.tsx@@ -1,11 +1,9 @@import { useMutation, useQueryClient } from "@tanstack/react-query";import { apiRequest } from "@app/config/request";-import { userKeys } from "@app/hooks/api/users/query-keys";import { webAuthnKeys } from "./queries";import {- TDeleteWebAuthnCredentialDTO,TGenerateAuthenticationOptionsResponse,TGenerateRegistrationOptionsResponse,TUpdateWebAuthnCredentialDTO,@@ -63,23 +61,6 @@ export const useVerifyAuthentication = () =>}});-export const useDeleteWebAuthnCredential = () => {- const queryClient = useQueryClient();-- return useMutation({- mutationFn: async ({ id }: TDeleteWebAuthnCredentialDTO) => {- const { data } = await apiRequest.delete<{ success: boolean }>(- `/api/v1/user/me/webauthn/${id}`- );- return data;- },- onSuccess: () => {- queryClient.invalidateQueries({ queryKey: webAuthnKeys.credentials });- queryClient.invalidateQueries({ queryKey: userKeys.getUser });- }- });-};-export const useUpdateWebAuthnCredential = () => {const queryClient = useQueryClient();diff --git a/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/MFASection.tsx b/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/MFASection.tsxindex 56b4392791..d3ddbc4147 100644--- a/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/MFASection.tsx+++ b/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/MFASection.tsx@@ -26,7 +26,7 @@ import {SelectTrigger,SelectValue} from "@app/components/v3";-import { useActivateMfa, useGetOrganizations, useGetUser, useSetMfaMethod } from "@app/hooks/api";+import { useActivateMfa, 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";@@ -35,13 +35,14 @@ import { useGetWebAuthnCredentials } from "@app/hooks/api/webauthn";import { MfaMethodsCard } from "./MfaMethodsCard";import { RecoveryOptionsCard } from "./RecoveryOptionsCard";+import { useChangePreferredMfa } from "./useChangePreferredMfa";import { useDisableMfa } from "./useDisableMfa";const LEARN_MORE_URL = "https://infisical.com/docs/documentation/platform/mfa";export const MFASection = () => {const { data: user, isPending } = useGetUser();- const { mutateAsync: setMfaMethod } = useSetMfaMethod();+ const { changePreferredMfa } = useChangePreferredMfa();const { mutateAsync: activateMfa, isPending: isEnabling } = useActivateMfa();const { isBusy: isDisabling, disableMfa } = useDisableMfa();const { data: totpConfiguration } = useGetUserTotpConfiguration();@@ -108,17 +109,10 @@ export const MFASection = () => {}};- const handlePreferredMethodChange = async (method: MfaMethod) => {- try {- await setMfaMethod({ selectedMfaMethod: method });- createNotification({ text: "Updated preferred 2FA method", type: "success" });- } catch (error: any) {- createNotification({- text: error?.response?.data?.message || "Failed to update preferred method",- type: "error"- });- }- };+ // Changing the preferred method is sensitive, so it goes through the step-up MFA+ // challenge; the dropdown reflects the new value once getUser is invalidated on+ // success.+ const handlePreferredMethodChange = (method: MfaMethod) => changePreferredMfa(method);// Disabling is a sensitive action, so it requires a fresh MFA challenge (same// step-up flow as viewing recovery codes) before it goes through.diff --git a/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/MfaMethodsCard.tsx b/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/MfaMethodsCard.tsxindex fdc40c482d..508f232ebe 100644--- a/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/MfaMethodsCard.tsx+++ b/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/MfaMethodsCard.tsx@@ -3,7 +3,6 @@ import { useQueryClient } from "@tanstack/react-query";import { LucideIcon } from "lucide-react";import { MFA_METHOD_ICONS, MFA_METHOD_LABELS } from "@app/components/mfa/setup";-import { createNotification } from "@app/components/notifications";import {AlertDialog,AlertDialogAction,@@ -19,11 +18,12 @@ import {import { userKeys } from "@app/hooks/api";import { MfaMethod } from "@app/hooks/api/auth/types";import { useFetchServerStatus } from "@app/hooks/api/serverDetails";-import { useDeleteUserTotpConfiguration, useGetUserTotpConfiguration } from "@app/hooks/api/users";+import { useGetUserTotpConfiguration } from "@app/hooks/api/users";import { useGetWebAuthnCredentials } from "@app/hooks/api/webauthn";import { MethodSetupDialog } from "./MethodSetupDialog";import { PasskeyManagerDialog } from "./PasskeyManagerDialog";+import { useRemoveTotp } from "./useRemoveTotp";type MethodRowProps = {icon: LucideIcon;@@ -54,7 +54,7 @@ export const MfaMethodsCard = () => {const { data: totpConfiguration } = useGetUserTotpConfiguration();const { data: webAuthnCredentials = [] } = useGetWebAuthnCredentials();const { data: serverDetails } = useFetchServerStatus();- const { mutateAsync: deleteTotp, isPending: isDeletingTotp } = useDeleteUserTotpConfiguration();+ const { removeTotp, isBusy: isRemovingTotp } = useRemoveTotp();const isEmailMfaAvailable = Boolean(serverDetails?.emailConfigured);@@ -65,18 +65,10 @@ export const MfaMethodsCard = () => {const isTotpConfigured = Boolean(totpConfiguration?.isVerified);const passkeyCount = webAuthnCredentials.length;- const handleRemoveTotp = async () => {- try {- await deleteTotp();- setIsRemoveTotpOpen(false);- createNotification({ text: "Authenticator app removed", type: "success" });- } catch (error: any) {- createNotification({- text: error?.response?.data?.message || "Failed to remove authenticator app",- type: "error"- });- }- };+ // Removing weakens a login second factor, so it goes through the step-up MFA+ // challenge; the dialog stays open until the challenge completes and the removal+ // succeeds.+ const handleRemoveTotp = () => removeTotp(() => setIsRemoveTotpOpen(false));return (<div className="p-6">@@ -163,7 +155,7 @@ export const MfaMethodsCard = () => {<AlertDialogCancel>Cancel</AlertDialogCancel><AlertDialogActionvariant="danger"- isPending={isDeletingTotp}+ isPending={isRemovingTotp}onClick={handleRemoveTotp}>Removediff --git a/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/PasskeyManagerDialog.tsx b/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/PasskeyManagerDialog.tsxindex e3d7854198..b10e1eaeb2 100644--- a/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/PasskeyManagerDialog.tsx+++ b/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/PasskeyManagerDialog.tsx@@ -1,7 +1,6 @@import { useState } from "react";import { FingerprintIcon, PlusIcon, TrashIcon } from "lucide-react";-import { createNotification } from "@app/components/notifications";import { ContentLoader } from "@app/components/v2";import {AlertDialog,@@ -20,11 +19,9 @@ import {SheetHeader,SheetTitle} from "@app/components/v3";-import {- useDeleteWebAuthnCredential,- useGetWebAuthnCredentials,- useRegisterPasskey-} from "@app/hooks/api/webauthn";+import { useGetWebAuthnCredentials, useRegisterPasskey } from "@app/hooks/api/webauthn";++import { useRemovePasskey } from "./useRemovePasskey";type Props = {isOpen: boolean;@@ -34,7 +31,7 @@ type Props = {export const PasskeyManagerDialog = ({ isOpen, onOpenChange }: Props) => {const { data: credentials = [], isPending } = useGetWebAuthnCredentials();const { registerPasskey, isRegistering } = useRegisterPasskey();- const { mutateAsync: deleteCredential, isPending: isDeleting } = useDeleteWebAuthnCredential();+ const { removePasskey, isBusy: isRemoving } = useRemovePasskey();const [name, setName] = useState("");const [credentialToRemove, setCredentialToRemove] = useState<{ id: string; name: string } | null>(@@ -47,18 +44,12 @@ export const PasskeyManagerDialog = ({ isOpen, onOpenChange }: Props) => {}};- const handleDelete = async () => {+ // Removing weakens a login second factor, so it goes through the step-up MFA+ // challenge; the confirm dialog stays open until the challenge completes and the+ // removal succeeds.+ const handleDelete = () => {if (!credentialToRemove) return;- try {- await deleteCredential({ id: credentialToRemove.id });- setCredentialToRemove(null);- createNotification({ text: "Passkey removed", type: "success" });- } catch (error: any) {- createNotification({- text: error?.response?.data?.message || "Failed to remove passkey",- type: "error"- });- }+ removePasskey(credentialToRemove.id, () => setCredentialToRemove(null));};return (@@ -146,7 +137,7 @@ export const PasskeyManagerDialog = ({ isOpen, onOpenChange }: Props) => {</AlertDialogHeader><AlertDialogFooter><AlertDialogCancel>Cancel</AlertDialogCancel>- <AlertDialogAction variant="danger" isPending={isDeleting} onClick={handleDelete}>+ <AlertDialogAction variant="danger" isPending={isRemoving} onClick={handleDelete}>Remove</AlertDialogAction></AlertDialogFooter>diff --git a/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/useChangePreferredMfa.ts b/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/useChangePreferredMfa.tsnew file mode 100644index 0000000000..a68db73af7--- /dev/null+++ b/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/useChangePreferredMfa.ts@@ -0,0 +1,43 @@+import { useCallback } from "react";+import { useQueryClient } from "@tanstack/react-query";++import { createNotification } from "@app/components/notifications";+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";++/**+ * Changing the preferred second factor is a sensitive account action, so it is+ * gated behind a fresh step-up MFA challenge (the same primitive used to+ * view/rotate recovery codes). Calls apiRequest directly (rather than a mutation)+ * so the expected SESSION_MFA_REQUIRED 400 doesn't surface a global mutation error+ * toast.+ */+export const useChangePreferredMfa = () => {+ const queryClient = useQueryClient();+ const { isBusy, runWithMfa } = useMfaStepUp();++ const changePreferredMfa = useCallback(+ (selectedMfaMethod: MfaMethod) =>+ runWithMfa(+ async (mfaSessionId) => {+ await apiRequest.patch("/api/v2/users/me/mfa", {+ selectedMfaMethod,+ ...(mfaSessionId ? { mfaSessionId } : {})+ });+ },+ {+ onSuccess: () => {+ queryClient.invalidateQueries({ queryKey: userKeys.getUser });+ createNotification({ text: "Updated preferred 2FA method", type: "success" });+ },+ errorText: "Failed to update preferred method"+ }+ ),+ [runWithMfa, queryClient]+ );++ return { isBusy, changePreferredMfa };+};diff --git a/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/useRemovePasskey.ts b/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/useRemovePasskey.tsnew file mode 100644index 0000000000..94804b1783--- /dev/null+++ b/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/useRemovePasskey.ts@@ -0,0 +1,43 @@+import { useCallback } from "react";+import { useQueryClient } from "@tanstack/react-query";++import { createNotification } from "@app/components/notifications";+import { apiRequest } from "@app/config/request";+import { userKeys } from "@app/hooks/api/users/query-keys";+import { webAuthnKeys } from "@app/hooks/api/webauthn/queries";++import { useMfaStepUp } from "./useMfaStepUp";++/**+ * Removing a passkey weakens a login second factor, so it is gated behind a fresh+ * step-up MFA challenge (the same primitive used to view/rotate recovery codes).+ * Calls apiRequest directly (rather than a mutation) so the expected+ * SESSION_MFA_REQUIRED 400 doesn't surface a global mutation error toast.+ */+export const useRemovePasskey = () => {+ const queryClient = useQueryClient();+ const { isBusy, runWithMfa } = useMfaStepUp();++ const removePasskey = useCallback(+ (id: string, onRemoved?: () => void) =>+ runWithMfa(+ async (mfaSessionId) => {+ await apiRequest.delete(`/api/v1/user/me/webauthn/${id}`, {+ params: mfaSessionId ? { mfaSessionId } : undefined+ });+ },+ {+ onSuccess: () => {+ queryClient.invalidateQueries({ queryKey: webAuthnKeys.credentials });+ queryClient.invalidateQueries({ queryKey: userKeys.getUser });+ createNotification({ text: "Passkey removed", type: "success" });+ onRemoved?.();+ },+ errorText: "Failed to remove passkey"+ }+ ),+ [runWithMfa, queryClient]+ );++ return { isBusy, removePasskey };+};diff --git a/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/useRemoveTotp.ts b/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/useRemoveTotp.tsnew file mode 100644index 0000000000..de09e6fc9a--- /dev/null+++ b/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/useRemoveTotp.ts@@ -0,0 +1,43 @@+import { useCallback } from "react";+import { useQueryClient } from "@tanstack/react-query";++import { createNotification } from "@app/components/notifications";+import { apiRequest } from "@app/config/request";+import { userKeys } from "@app/hooks/api/users/query-keys";++import { useMfaStepUp } from "./useMfaStepUp";++/**+ * Removing the authenticator app weakens a login second factor, so it is gated+ * behind a fresh step-up MFA challenge (the same primitive used to view/rotate+ * recovery codes). Calls apiRequest directly (rather than a mutation) so the+ * expected SESSION_MFA_REQUIRED 400 doesn't surface a global mutation error toast.+ */+export const useRemoveTotp = () => {+ const queryClient = useQueryClient();+ const { isBusy, runWithMfa } = useMfaStepUp();++ const removeTotp = useCallback(+ (onRemoved?: () => void) =>+ runWithMfa(+ async (mfaSessionId) => {+ await apiRequest.delete("/api/v1/user/me/totp", {+ params: mfaSessionId ? { mfaSessionId } : undefined+ });+ },+ {+ onSuccess: () => {+ queryClient.invalidateQueries({ queryKey: userKeys.totpConfiguration });+ queryClient.removeQueries({ queryKey: userKeys.totpRegistration });+ queryClient.invalidateQueries({ queryKey: userKeys.getUser });+ createNotification({ text: "Authenticator app removed", type: "success" });+ onRemoved?.();+ },+ errorText: "Failed to remove authenticator app"+ }+ ),+ [runWithMfa, queryClient]+ );++ return { isBusy, removeTotp };+};