Skip to content

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

fix step up lockout in case of losing MFA access, we keep sudo mode for 10 min after login

Thiago Araujo da Silva742aa9a6dc8f
diff --git a/backend/src/keystore/keystore.ts b/backend/src/keystore/keystore.ts
index a0a14b9041..c03d3cc0be 100644
--- a/backend/src/keystore/keystore.ts
+++ b/backend/src/keystore/keystore.ts
@@ -95,6 +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: (userId: string) => `recent-mfa-auth:${userId}` 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,
@@ -167,7 +168,7 @@ export const KeyStoreTtls = {
IdentityRevocationVersionInSeconds: 604800, // 7 days
ProjectPermissionMarkerTtlSeconds: 10, // 10 seconds - short-lived marker for fingerprint validation
ProjectPermissionDataTtlSeconds: 600, // 10 minutes - longer-lived data payload
- MfaSessionInSeconds: 600, // 10 minutes
+ MfaSessionInSeconds: 300, // 5 minutes
MfaCodeResendCooldownInSeconds: 60, // 1 minute
WebAuthnChallengeInSeconds: 300, // 5 minutes
diff --git a/backend/src/server/routes/mfa-step-up-fns.ts b/backend/src/server/routes/mfa-step-up-fns.ts
index 1c12c90dc7..a4d07c63ae 100644
--- a/backend/src/server/routes/mfa-step-up-fns.ts
+++ b/backend/src/server/routes/mfa-step-up-fns.ts
@@ -1,26 +1,9 @@
import { BadRequestError } from "@app/lib/errors";
import { MfaMethod } from "@app/services/auth/auth-type";
+import { MfaStepUpResource, TMfaStepUpResource } from "@app/services/mfa-session/mfa-session-types";
-// Sensitive account actions that expose or weaken a login second factor require a
-// fresh MFA challenge, not just a valid session token. The session binds to a
-// resource id so a session minted for one flow can't be replayed against an
-// unrelated one (e.g. a PAM account-access session can't be used here).
-//
-// Viewing recovery codes, rotating recovery codes, and disabling MFA are all
-// 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 (10 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",
- MfaActivation: "mfa-activation"
-} as const;
-
-export type TMfaStepUpResource = (typeof MfaStepUpResource)[keyof typeof MfaStepUpResource];
+export { MfaStepUpResource };
+export type { TMfaStepUpResource };
/**
* Enforces that the caller has completed a fresh MFA challenge before a sensitive
@@ -70,6 +53,10 @@ export const ensureStepUpMfa = async (
return;
}
+ if (resourceId === MfaStepUpResource.MfaManagement && (await server.services.mfaSession.hasRecentMfaAuth(userId))) {
+ return;
+ }
+
await server.services.mfaSession.enforceStepUpMfaLockout(userId);
const user = await server.services.user.getMe(userId);
diff --git a/backend/src/services/auth/auth-login-service.ts b/backend/src/services/auth/auth-login-service.ts
index 4e6a4a7793..7adff915b4 100644
--- a/backend/src/services/auth/auth-login-service.ts
+++ b/backend/src/services/auth/auth-login-service.ts
@@ -84,7 +84,10 @@ type TAuthLoginServiceFactoryDep = {
membershipRoleDAL: TMembershipRoleDALFactory;
notificationService: Pick<TNotificationServiceFactory, "createUserNotifications">;
permissionService: Pick<TPermissionServiceFactory, "getOrgPermission">;
- mfaLockoutService: Pick<TMfaLockoutServiceFactory, "handleFailedMfaAttempt" | "resetMfaLockStatus">;
+ mfaLockoutService: Pick<
+ TMfaLockoutServiceFactory,
+ "handleFailedMfaAttempt" | "resetMfaLockStatus" | "recordRecentMfaAuth"
+ >;
};
export type TAuthLoginFactory = ReturnType<typeof authLoginServiceFactory>;
@@ -713,6 +716,8 @@ export const authLoginServiceFactory = ({
await mfaLockoutService.resetMfaLockStatus(userId);
+ await mfaLockoutService.recordRecentMfaAuth(userId);
+
const token = await generateUserTokens({
userId: user.id,
ip,
diff --git a/backend/src/services/auth/mfa-lockout-service.ts b/backend/src/services/auth/mfa-lockout-service.ts
index 8d51425a73..a89de52d26 100644
--- a/backend/src/services/auth/mfa-lockout-service.ts
+++ b/backend/src/services/auth/mfa-lockout-service.ts
@@ -193,11 +193,28 @@ export const mfaLockoutServiceFactory = ({
await keyStore.deleteItem(KeyStorePrefixes.UserStepUpMfaLockout(userId));
};
+ // Records that the user just completed a full MFA login. A completed login proves a
+ // second factor at least as strong as any step-up challenge (it satisfies the org's
+ // required method, or is a recovery code that bypasses it), so within this window an
+ // MFA-management step-up 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. It self-clears on TTL; if
+ // the window lapses, another login re-opens it.
+ const recordRecentMfaAuth = async (userId: string) => {
+ await keyStore.setItemWithExpiry(KeyStorePrefixes.RecentMfaAuth(userId), KeyStoreTtls.MfaSessionInSeconds, "1");
+ };
+
+ const hasRecentMfaAuth = async (userId: string): Promise<boolean> => {
+ return Boolean(await keyStore.getItem(KeyStorePrefixes.RecentMfaAuth(userId)));
+ };
+
return {
handleFailedMfaAttempt,
resetMfaLockStatus,
enforceStepUpMfaLockStatus,
reserveStepUpMfaAttempt,
- resetStepUpMfaLockStatus
+ resetStepUpMfaLockStatus,
+ recordRecentMfaAuth,
+ hasRecentMfaAuth
};
};
diff --git a/backend/src/services/mfa-session/mfa-session-service.ts b/backend/src/services/mfa-session/mfa-session-service.ts
index 3176409a6c..a7dadcd989 100644
--- a/backend/src/services/mfa-session/mfa-session-service.ts
+++ b/backend/src/services/mfa-session/mfa-session-service.ts
@@ -10,6 +10,7 @@ import { TTotpServiceFactory } from "@app/services/totp/totp-service";
import {
MfaSessionStatus,
+ MfaStepUpResource,
TGetMfaSessionStatusDTO,
TIsMfaSessionActiveDTO,
TMfaSession,
@@ -23,7 +24,11 @@ type TMfaSessionServiceFactoryDep = {
totpService: Pick<TTotpServiceFactory, "verifyUserTotp">;
mfaLockoutService: Pick<
TMfaLockoutServiceFactory,
- "enforceStepUpMfaLockStatus" | "reserveStepUpMfaAttempt" | "resetStepUpMfaLockStatus"
+ | "enforceStepUpMfaLockStatus"
+ | "reserveStepUpMfaAttempt"
+ | "resetStepUpMfaLockStatus"
+ | "hasRecentMfaAuth"
+ | "recordRecentMfaAuth"
>;
};
@@ -166,6 +171,10 @@ export const mfaSessionServiceFactory = ({
mfaSession.status = MfaSessionStatus.ACTIVE;
await updateMfaSession(mfaSession, KeyStoreTtls.MfaSessionInSeconds);
+ if (mfaSession.resourceId === MfaStepUpResource.MfaManagement) {
+ await mfaLockoutService.recordRecentMfaAuth(userId);
+ }
+
return {
success: true,
message: "MFA verification successful"
@@ -223,6 +232,12 @@ export const mfaSessionServiceFactory = ({
await mfaLockoutService.enforceStepUpMfaLockStatus(userId);
};
+ // True when the user completed a full MFA login recently, so an MFA-management
+ // step-up can be skipped within the grace window (see recordRecentMfaAuth).
+ const hasRecentMfaAuth = async (userId: string): Promise<boolean> => {
+ return mfaLockoutService.hasRecentMfaAuth(userId);
+ };
+
return {
createMfaSession,
verifyMfaSession,
@@ -231,6 +246,7 @@ export const mfaSessionServiceFactory = ({
getMfaSession,
isMfaSessionActive,
deleteMfaSession,
- enforceStepUpMfaLockout
+ enforceStepUpMfaLockout,
+ hasRecentMfaAuth
};
};
diff --git a/backend/src/services/mfa-session/mfa-session-types.ts b/backend/src/services/mfa-session/mfa-session-types.ts
index e538fa432d..cee7e32542 100644
--- a/backend/src/services/mfa-session/mfa-session-types.ts
+++ b/backend/src/services/mfa-session/mfa-session-types.ts
@@ -5,6 +5,13 @@ export enum MfaSessionStatus {
ACTIVE = "ACTIVE"
}
+export const MfaStepUpResource = {
+ MfaManagement: "mfa-management",
+ MfaActivation: "mfa-activation"
+} as const;
+
+export type TMfaStepUpResource = (typeof MfaStepUpResource)[keyof typeof MfaStepUpResource];
+
export type TMfaSession = {
sessionId: string;
userId: string;
diff --git a/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/useMfaStepUp.ts b/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/useMfaStepUp.ts
index a0b8896ffb..7fdb14b0d2 100644
--- a/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/useMfaStepUp.ts
+++ b/frontend/src/pages/user/PersonalSettingsPage/components/SecuritySection/useMfaStepUp.ts
@@ -9,42 +9,6 @@ import { MfaSessionStatus, TMfaSessionStatusResponse } from "@app/hooks/api/mfaS
const MFA_POLL_INTERVAL = 2000;
const MFA_TIMEOUT = 5 * 60 * 1000;
-// The most recently verified step-up MFA session id, shared across every
-// useMfaStepUp instance. The MFA-management actions (view/rotate recovery codes,
-// disable MFA) live in sibling components with their own hook instances but the
-// backend accepts one step-up session for all of them, so remembering the id lets a
-// challenge completed for one action satisfy the next until it expires. It never
-// drives rendering, and a stale id (e.g. after logout, or a reload past the backend
-// TTL) is harmless: the backend rejects it and a fresh challenge transparently re-runs.
-//
-// Persisted in sessionStorage (not just module scope) so a full page reload doesn't
-// throw away a session the backend still considers active — otherwise every reload
-// forced a brand-new challenge even though the 10-minute window had not elapsed. It is
-// tab-scoped and cleared when the tab closes.
-const STEP_UP_SESSION_STORAGE_KEY = "mfaStepUpSessionId";
-
-const sharedStepUpSession = {
- get id(): string | null {
- try {
- return sessionStorage.getItem(STEP_UP_SESSION_STORAGE_KEY);
- } catch {
- return null;
- }
- },
- set id(value: string | null) {
- try {
- if (value) {
- sessionStorage.setItem(STEP_UP_SESSION_STORAGE_KEY, value);
- } else {
- sessionStorage.removeItem(STEP_UP_SESSION_STORAGE_KEY);
- }
- } catch {
- // Storage can be unavailable (private mode, blocked cookies); degrade to always
- // re-challenging rather than crashing.
- }
- }
-};
-
// An action guarded by step-up MFA. It receives the verified session id (once
// available) so it can replay itself against the backend. When the backend
// requires a fresh challenge it responds with SESSION_MFA_REQUIRED, and the same
@@ -65,9 +29,12 @@ type RunOptions<T> = {
* shared /mfa-session popup, poll its status, and replay the action with the
* verified session id.
*
- * A verified session id is remembered and reused for subsequent actions until the
- * backend rejects it (expired), at which point the popup challenge transparently
- * re-runs. Callers own their own result/UI state; this hook owns the challenge.
+ * Reuse across subsequent actions is handled entirely by the backend: completing a
+ * management challenge (like a full login) opens a short recent-MFA-auth grace window,
+ * so the next action's first attempt (sent with no session id) succeeds without a
+ * fresh challenge until the window elapses. This hook therefore keeps no client-side
+ * session cache; it only tracks the in-flight challenge. Callers own their result/UI
+ * state; this hook owns the challenge.
*/
export const useMfaStepUp = () => {
const [isBusy, setIsBusy] = useState(false);
@@ -114,7 +81,6 @@ export const useMfaStepUp = () => {
try {
const result = await action(mfaSessionId);
- sharedStepUpSession.id = mfaSessionId;
opts.onSuccess(result);
} catch {
createNotification({
@@ -154,12 +120,11 @@ export const useMfaStepUp = () => {
async <T>(action: StepUpAction<T>, opts: RunOptions<T>) => {
setIsBusy(true);
try {
- const result = await action(sharedStepUpSession.id ?? undefined);
+ const result = await action();
opts.onSuccess(result);
setIsBusy(false);
} catch (err) {
if (axios.isAxiosError(err) && err.response?.data?.error === "SESSION_MFA_REQUIRED") {
- sharedStepUpSession.id = null;
const mfaSessionId = err.response.data.details?.mfaSessionId as string | undefined;
if (!mfaSessionId) {