Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

require step up on enable

Thiago Araujo da Silva42e573e24a4c
diff --git a/backend/src/server/routes/mfa-step-up-fns.ts b/backend/src/server/routes/mfa-step-up-fns.ts
index 286de2693b..0453f61747 100644
--- a/backend/src/server/routes/mfa-step-up-fns.ts
+++ b/backend/src/server/routes/mfa-step-up-fns.ts
@@ -8,7 +8,8 @@ import { MfaMethod } from "@app/services/auth/auth-type";
// disabling MFA).
export const MfaStepUpResource = {
RecoveryCodes: "mfa-recovery-codes",
- DisableMfa: "mfa-disable"
+ DisableMfa: "mfa-disable",
+ EnableMfa: "mfa-enable"
} as const;
export type TMfaStepUpResource = (typeof MfaStepUpResource)[keyof typeof MfaStepUpResource];
@@ -33,8 +34,15 @@ export const ensureStepUpMfa = async (
userId,
resourceId,
mfaSessionId,
- message
- }: { userId: string; resourceId: TMfaStepUpResource; mfaSessionId?: string; message: string }
+ message,
+ mfaMethod: mfaMethodOverride
+ }: {
+ userId: string;
+ resourceId: TMfaStepUpResource;
+ mfaSessionId?: string;
+ message: string;
+ mfaMethod?: MfaMethod;
+ }
) => {
if (
mfaSessionId &&
@@ -48,7 +56,7 @@ export const ensureStepUpMfa = async (
}
const user = await server.services.user.getMe(userId);
- const mfaMethod = (user.selectedMfaMethod as MfaMethod | null) ?? MfaMethod.EMAIL;
+ const mfaMethod = mfaMethodOverride ?? (user.selectedMfaMethod as MfaMethod | null) ?? MfaMethod.EMAIL;
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.ts
index 82e8098df9..a1b1aafac5 100644
--- a/backend/src/server/routes/v2/user-router.ts
+++ b/backend/src/server/routes/v2/user-router.ts
@@ -66,7 +66,9 @@ export const registerUserRouter = async (server: FastifyZodProvider) => {
// Enroll a factor: proves possession of the factor in-request and persists it.
// This does NOT mint recovery codes; those are issued only when MFA is enabled
- // (POST /me/mfa/activate).
+ // (POST /me/mfa/activate). Because proving the factor here is itself proof of the
+ // factor, a verified EnableMfa step-up session is minted and returned so the
+ // enrollment wizard can immediately enable MFA without a redundant challenge.
server.route({
method: "POST",
url: "/me/mfa/enroll",
@@ -104,7 +106,9 @@ export const registerUserRouter = async (server: FastifyZodProvider) => {
})
]),
response: {
- 200: z.object({})
+ 200: z.object({
+ mfaSessionId: z.string()
+ })
}
},
preHandler: verifyAuth([AuthMode.JWT], { requireOrg: false }),
@@ -127,9 +131,13 @@ export const registerUserRouter = async (server: FastifyZodProvider) => {
});
}
- // Enrollment only proves/persists the factor. Recovery codes are minted
- // solely when MFA is enabled (POST /me/mfa/activate), not here.
- return {};
+ const mfaSessionId = await server.services.mfaSession.createVerifiedMfaSession(
+ req.permission.id,
+ MfaStepUpResource.EnableMfa,
+ req.body.method
+ );
+
+ return { mfaSessionId };
}
});
@@ -161,7 +169,10 @@ export const registerUserRouter = async (server: FastifyZodProvider) => {
// Enable MFA. Requires the selected method to be configured (email always is),
// and issues a fresh recovery-code pool (invalidating any prior codes), returned
- // once so the client can surface them to the user.
+ // once so the client can surface them to the user. Because the user chooses the
+ // method before enabling, enabling is gated behind a fresh step-up MFA challenge
+ // against that method — this proves the user can actually satisfy the factor they
+ // just turned on, so they can't lock themselves out.
server.route({
method: "POST",
url: "/me/mfa/activate",
@@ -171,7 +182,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({
@@ -182,6 +194,14 @@ export const registerUserRouter = async (server: FastifyZodProvider) => {
},
preHandler: verifyAuth([AuthMode.JWT], { requireOrg: false }),
handler: async (req) => {
+ await ensureStepUpMfa(server, {
+ userId: req.permission.id,
+ resourceId: MfaStepUpResource.EnableMfa,
+ mfaSessionId: req.body.mfaSessionId,
+ mfaMethod: req.body.selectedMfaMethod,
+ 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
diff --git a/backend/src/services/mfa-session/mfa-session-service.ts b/backend/src/services/mfa-session/mfa-session-service.ts
index d5cfbabb18..7900cc104b 100644
--- a/backend/src/services/mfa-session/mfa-session-service.ts
+++ b/backend/src/services/mfa-session/mfa-session-service.ts
@@ -196,12 +196,39 @@ export const mfaSessionServiceFactory = ({
return mfaSessionId;
};
+ // Mints a session that is already ACTIVE, for flows where the factor was just
+ // proven in the same request (e.g. enrolling a factor proves possession of it),
+ // so the caller can satisfy a step-up gate without a redundant second challenge.
+ const createVerifiedMfaSession = async (
+ userId: string,
+ resourceId: string,
+ mfaMethod: MfaMethod
+ ): Promise<string> => {
+ const mfaSessionId = crypto.randomBytes(32).toString("hex");
+ const mfaSession: TMfaSession = {
+ sessionId: mfaSessionId,
+ userId,
+ resourceId,
+ status: MfaSessionStatus.ACTIVE,
+ mfaMethod
+ };
+
+ await keyStore.setItemWithExpiry(
+ KeyStorePrefixes.MfaSession(mfaSessionId),
+ KeyStoreTtls.MfaSessionInSeconds,
+ JSON.stringify(mfaSession)
+ );
+
+ return mfaSessionId;
+ };
+
const deleteMfaSession = async (mfaSessionId: string) => {
await keyStore.deleteItem(KeyStorePrefixes.MfaSession(mfaSessionId));
};
return {
createMfaSession,
+ createVerifiedMfaSession,
verifyMfaSession,
getMfaSessionStatus,
sendMfaCode,
diff --git a/frontend/src/components/mfa/MfaEnrollment.tsx b/frontend/src/components/mfa/MfaEnrollment.tsx
index 7fbfd0e5f6..46cd3b573e 100644
--- a/frontend/src/components/mfa/MfaEnrollment.tsx
+++ b/frontend/src/components/mfa/MfaEnrollment.tsx
@@ -34,9 +34,12 @@ export const MfaEnrollment = ({ method, onComplete }: Props) => {
SecurityClient.setMfaToken("");
}, []);
- const handleVerified = async () => {
+ const handleVerified = async (mfaSessionId?: string) => {
try {
- const { recoveryCodes: codes } = await activateMfa({ selectedMfaMethod: method });
+ const { recoveryCodes: codes } = await activateMfa({
+ selectedMfaMethod: method,
+ mfaSessionId
+ });
setRecoveryCodes(codes);
setPhase("recovery");
} catch (error: any) {
diff --git a/frontend/src/components/mfa/setup/RecoveryCodesView.tsx b/frontend/src/components/mfa/setup/RecoveryCodesView.tsx
index a0a656af13..1e5135f1ac 100644
--- a/frontend/src/components/mfa/setup/RecoveryCodesView.tsx
+++ b/frontend/src/components/mfa/setup/RecoveryCodesView.tsx
@@ -41,7 +41,7 @@ export const RecoveryCodesView = ({ recoveryCodes, onSaved }: Props) => {
<div className="rounded-lg border border-border bg-container p-4">
<div className="grid grid-cols-2 gap-x-6 gap-y-2 font-mono text-sm">
{recoveryCodes.map((code, index) => (
- <div key={code} className="flex items-center text-foreground">
+ <div key={`${code}-${index}`} className="flex items-center text-foreground">
<span className="w-6 text-right text-muted">{index + 1}.</span>
<span className="pl-2">{code}</span>
</div>
diff --git a/frontend/src/components/mfa/setup/VerifyStep.tsx b/frontend/src/components/mfa/setup/VerifyStep.tsx
index d9e83bec8e..7bc6600b13 100644
--- a/frontend/src/components/mfa/setup/VerifyStep.tsx
+++ b/frontend/src/components/mfa/setup/VerifyStep.tsx
@@ -15,7 +15,7 @@ import { useRegisterPasskey } from "@app/hooks/api/webauthn";
type Props = {
method: MfaMethod;
- onVerified: () => void | Promise<void>;
+ onVerified: (mfaSessionId?: string) => void | Promise<void>;
};
const TotpVerify = ({ onVerified }: { onVerified: Props["onVerified"] }) => {
@@ -36,9 +36,9 @@ const TotpVerify = ({ onVerified }: { onVerified: Props["onVerified"] }) => {
const handleVerify = async () => {
try {
- await enrollMfa({ method: MfaMethod.TOTP, totp: totp.trim() });
+ const { mfaSessionId } = await enrollMfa({ method: MfaMethod.TOTP, totp: totp.trim() });
createNotification({ text: "Authenticator app configured", type: "success" });
- await onVerified();
+ await onVerified(mfaSessionId);
} catch (error: any) {
createNotification({
text: error?.response?.data?.message || "Invalid verification code",
@@ -104,9 +104,9 @@ const EmailVerify = ({ onVerified }: { onVerified: Props["onVerified"] }) => {
const handleVerify = async () => {
try {
- await enrollMfa({ method: MfaMethod.EMAIL, code: code.trim() });
+ const { mfaSessionId } = await enrollMfa({ method: MfaMethod.EMAIL, code: code.trim() });
createNotification({ text: "Email authentication configured", type: "success" });
- await onVerified();
+ await onVerified(mfaSessionId);
} catch (error: any) {
createNotification({
text: error?.response?.data?.message || "Invalid verification code",
@@ -150,15 +150,16 @@ const WebAuthnVerify = ({ onVerified }: { onVerified: Props["onVerified"] }) =>
const [name, setName] = useState("");
const handleRegister = async () => {
+ let mfaSessionId: string | undefined;
const ok = await registerPasskey(name, async (registrationResponse, resolvedName) => {
- await enrollMfa({
+ ({ mfaSessionId } = await enrollMfa({
method: MfaMethod.WEBAUTHN,
registrationResponse,
name: resolvedName
- });
+ }));
});
if (ok) {
- await onVerified();
+ await onVerified(mfaSessionId);
}
};
diff --git a/frontend/src/hooks/api/users/queries.tsx b/frontend/src/hooks/api/users/queries.tsx
index ba740224d7..f6af79ee0f 100644
--- a/frontend/src/hooks/api/users/queries.tsx
+++ b/frontend/src/hooks/api/users/queries.tsx
@@ -424,7 +424,11 @@ export const useEnrollMfa = () => {
name?: string;
}
) => {
- await apiRequest.post("/api/v2/users/me/mfa/enroll", dto);
+ const { data } = await apiRequest.post<{ mfaSessionId: string }>(
+ "/api/v2/users/me/mfa/enroll",
+ dto
+ );
+ return { mfaSessionId: data.mfaSessionId };
},
onSuccess() {
queryClient.invalidateQueries({ queryKey: userKeys.getUser });
@@ -450,11 +454,18 @@ export const useSendMfaEnrollmentEmailCode = () =>
export const useActivateMfa = () => {
const queryClient = useQueryClient();
return useMutation({
- mutationFn: async ({ selectedMfaMethod }: { selectedMfaMethod?: MfaMethod }) => {
+ mutationFn: async ({
+ selectedMfaMethod,
+ mfaSessionId
+ }: {
+ selectedMfaMethod?: MfaMethod;
+ mfaSessionId?: string;
+ }) => {
const { data } = await apiRequest.post<{ user: unknown; recoveryCodes: string[] }>(
"/api/v2/users/me/mfa/activate",
{
- selectedMfaMethod
+ selectedMfaMethod,
+ mfaSessionId
}
);
diff --git a/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/MFASection.tsx b/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/MFASection.tsx
index fa1b691bc4..fbdeb87115 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 {
SheetHeader,
SheetTitle
} from "@app/components/v3";
-import { useActivateMfa, useGetOrganizations, useGetUser, useSetMfaMethod } from "@app/hooks/api";
+import { useGetOrganizations, useGetUser, useSetMfaMethod } from "@app/hooks/api";
import { MfaMethod } from "@app/hooks/api/auth/types";
import { useGetUserTotpConfiguration } from "@app/hooks/api/users";
import { AuthMethod } from "@app/hooks/api/users/types";
@@ -35,13 +35,14 @@ import { useGetWebAuthnCredentials } from "@app/hooks/api/webauthn";
import { MfaMethodsCard } from "./MfaMethodsCard";
import { RecoveryOptionsCard } from "./RecoveryOptionsCard";
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 { mutateAsync: setMfaMethod } = useSetMfaMethod();
- const { mutateAsync: activateMfa } = useActivateMfa();
+ const { isBusy: isEnabling, enableMfa } = useEnableMfa();
const { isBusy: isDisabling, disableMfa } = useDisableMfa();
const { data: totpConfiguration } = useGetUserTotpConfiguration();
const { data: webAuthnCredentials = [] } = useGetWebAuthnCredentials();
@@ -83,18 +84,7 @@ export const MFASection = () => {
// MFA is currently enabled.
const hasRecoveryCodes = user.isMfaEnabled;
- const handleEnable = async () => {
- try {
- const { recoveryCodes } = await activateMfa({ selectedMfaMethod: selectedMethod });
- setNewRecoveryCodes(recoveryCodes);
- createNotification({ text: "Two-factor authentication enabled", type: "success" });
- } catch (error: any) {
- createNotification({
- text: error?.response?.data?.message || "Failed to enable two-factor authentication",
- type: "error"
- });
- }
- };
+ const handleEnable = () => enableMfa(selectedMethod, setNewRecoveryCodes);
const handlePreferredMethodChange = async (method: MfaMethod) => {
try {
@@ -112,45 +102,38 @@ export const MFASection = () => {
// step-up flow as viewing recovery codes) before it goes through.
const handleDisable = () => disableMfa(() => setIsDisableOpen(false));
- const disabledBanner = (
- <div className="rounded-lg border border-border bg-card p-6">
- <div className="flex items-start justify-between">
- <h2 className="text-lg font-medium text-foreground">Two-factor Authentication</h2>
- <Badge variant="danger">
- <CircleAlertIcon /> Not enabled
- </Badge>
- </div>
- <p className="mt-2 max-w-2xl text-sm text-muted">
- Two-factor authentication adds an additional layer of security to your account by requiring
- more than just a password to sign in. Want to learn more about two-factor authentication?{" "}
- <a
- href={LEARN_MORE_URL}
- target="_blank"
- rel="noopener noreferrer"
- className="underline underline-offset-2 hover:text-foreground"
- >
- Click here
- </a>
- </p>
- <div className="mt-5">
- <Button variant="org" onClick={handleEnable}>
- <ShieldCheckIcon /> Enable two-factor authentication
- </Button>
- </div>
- </div>
- );
-
- const enabledBanner = (
+ const banner = (
<div className="rounded-lg border border-border bg-card p-6">
<div className="flex items-start justify-between">
<h2 className="text-lg font-medium text-foreground">Two-factor Authentication</h2>
- <Badge variant="success">
- <ShieldCheckIcon /> Enabled
- </Badge>
+ {user.isMfaEnabled ? (
+ <Badge variant="success">
+ <ShieldCheckIcon /> Enabled
+ </Badge>
+ ) : (
+ <Badge variant="danger">
+ <CircleAlertIcon /> Not enabled
+ </Badge>
+ )}
</div>
<p className="mt-2 max-w-2xl text-sm text-muted">
- Two-factor authentication is protecting your account. Manage your methods and recovery
- options below.
+ {user.isMfaEnabled ? (
+ "Two-factor authentication is protecting your account. Manage your methods and recovery options below."
+ ) : (
+ <>
+ Two-factor authentication adds an additional layer of security to your account by
+ requiring more than just a password to sign in. Want to learn more about two-factor
+ authentication?{" "}
+ <a
+ href={LEARN_MORE_URL}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="underline underline-offset-2 hover:text-foreground"
+ >
+ Click here
+ </a>
+ </>
+ )}
</p>
<div className="mt-6 border-t border-border pt-6">
@@ -184,14 +167,31 @@ export const MFASection = () => {
</div>
<div className="mt-6 flex items-center justify-between gap-4 border-t border-border pt-6">
- <p className="text-sm text-muted">
- {isMfaEnforced
- ? "Your organization requires two-factor authentication, so it can't be disabled."
- : "Turning this off keeps your configured methods, but your recovery codes are invalidated and a new set is issued when you re-enable."}
- </p>
- <Button variant="danger" isDisabled={isMfaEnforced} onClick={() => setIsDisableOpen(true)}>
- <PowerIcon /> Disable two-factor authentication
- </Button>
+ {user.isMfaEnabled ? (
+ <>
+ <p className="text-sm text-muted">
+ {isMfaEnforced
+ ? "Your organization requires two-factor authentication, so it can't be disabled."
+ : "Turning this off keeps your configured methods, but your recovery codes are invalidated and a new set is issued when you re-enable."}
+ </p>
+ <Button
+ variant="danger"
+ isDisabled={isMfaEnforced}
+ onClick={() => setIsDisableOpen(true)}
+ >
+ <PowerIcon /> Disable two-factor authentication
+ </Button>
+ </>
+ ) : (
+ <>
+ <p className="text-sm text-muted">
+ Choose your preferred method above, then enable two-factor authentication.
+ </p>
+ <Button variant="org" isPending={isEnabling} onClick={handleEnable}>
+ <ShieldCheckIcon /> Enable two-factor authentication
+ </Button>
+ </>
+ )}
</div>
</div>
);
@@ -199,7 +199,7 @@ export const MFASection = () => {
return (
<>
<div className="mb-6 flex flex-col gap-6">
- {user.isMfaEnabled ? enabledBanner : disabledBanner}
+ {banner}
<MfaMethodsCard />
{hasRecoveryCodes && <RecoveryOptionsCard />}
</div>
diff --git a/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/useEnableMfa.ts b/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/useEnableMfa.ts
new file mode 100644
index 0000000000..3b3bf17701
--- /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 { 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";
+
+/**
+ * Enabling MFA turns on a second factor the user selected beforehand, so it is
+ * gated behind a fresh step-up MFA challenge against that method. This proves the
+ * user can actually satisfy the factor they are about to enforce (so they can't
+ * lock themselves out) and mirrors the disable flow. It calls apiRequest directly
+ * (rather than a mutation) so the expected SESSION_MFA_REQUIRED 400 doesn't surface
+ * a global mutation error toast. The fresh recovery codes are handed back to the
+ * caller so they can be shown once.
+ */
+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 });
+ createNotification({
+ text: "Two-factor authentication enabled",
+ type: "success"
+ });
+ onEnabled?.(recoveryCodes);
+ },
+ errorText: "Failed to enable two-factor authentication"
+ }
+ ),
+ [runWithMfa, queryClient]
+ );
+
+ return { isBusy, enableMfa };
+};