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
recovery codes touch step-up in exactly one place
Thiago Araujo da Silva4dfb0c33eb27
diff --git a/backend/src/server/routes/mfa-step-up-fns.test.ts b/backend/src/server/routes/mfa-step-up-fns.test.tsnew file mode 100644index 0000000000..a59bd26f0e--- /dev/null+++ b/backend/src/server/routes/mfa-step-up-fns.test.ts@@ -0,0 +1,140 @@+import { describe, expect, test, vi } from "vitest";++import { MfaMethod } from "@app/services/auth/auth-type";++import { ensureStepUpMfa, MfaStepUpResource } from "./mfa-step-up-fns";++const USER_ID = "user-1";+const ORG_ID = "org-1";+const TOKEN_VERSION = "login-session-a";+const SESSION_ID = "mfa-session-1";++type TResolved = { challenge: MfaMethod; accepted: MfaMethod[] };++type ServerPatch = {+ isStepUpMfaRequired?: boolean;+ resolved?: TResolved;+ activeSessionMethod?: MfaMethod;+ recentAuthMethod?: MfaMethod;+};++const makeServer = (patch: ServerPatch = {}) => {+ const mfaSession = {+ isMfaSessionActive: vi.fn(async ({ acceptedMfaMethods }: { acceptedMfaMethods?: MfaMethod[] }) =>+ Boolean(patch.activeSessionMethod && acceptedMfaMethods?.includes(patch.activeSessionMethod))+ ),+ hasRecentMfaAuth: vi.fn(async (_userId: string, _tokenVersionId: string, acceptedMfaMethods: MfaMethod[]) =>+ Boolean(patch.recentAuthMethod && acceptedMfaMethods.includes(patch.recentAuthMethod))+ ),+ enforceStepUpMfaLockout: vi.fn().mockResolvedValue(undefined),+ createMfaSession: vi.fn().mockResolvedValue("new-session"),+ sendMfaCode: vi.fn().mockResolvedValue(undefined)+ };+ const user = {+ isStepUpMfaRequired: vi.fn().mockResolvedValue(patch.isStepUpMfaRequired ?? true),+ getStepUpMfaMethod: vi+ .fn()+ .mockResolvedValue(patch.resolved ?? { challenge: MfaMethod.TOTP, accepted: [MfaMethod.TOTP] }),+ getMe: vi.fn().mockResolvedValue({ id: USER_ID, email: "[email protected]" })+ };+ return { server: { services: { mfaSession, user } } as never, mfaSession, user };+};++const baseArgs = {+ userId: USER_ID,+ orgId: ORG_ID,+ tokenVersionId: TOKEN_VERSION,+ resourceId: MfaStepUpResource.MfaManagement,+ message: "MFA required"+};++const removalResolved: TResolved = { challenge: MfaMethod.EMAIL, accepted: [MfaMethod.TOTP, MfaMethod.EMAIL] };++describe("ensureStepUpMfa binds prior proof to the factors the action would challenge", () => {+ test("resolves the method before consulting any prior proof and passes the accepted set along", async () => {+ const { server, mfaSession, user } = makeServer();++ await expect(ensureStepUpMfa(server, { ...baseArgs, mfaSessionId: SESSION_ID })).rejects.toMatchObject({+ name: "SESSION_MFA_REQUIRED",+ details: { mfaMethod: MfaMethod.TOTP }+ });++ expect(user.getStepUpMfaMethod).toHaveBeenCalledWith(USER_ID, ORG_ID, undefined);+ expect(mfaSession.isMfaSessionActive).toHaveBeenCalledWith(+ expect.objectContaining({ mfaSessionId: SESSION_ID, acceptedMfaMethods: [MfaMethod.TOTP] })+ );+ expect(mfaSession.hasRecentMfaAuth).toHaveBeenCalledWith(USER_ID, TOKEN_VERSION, [MfaMethod.TOTP]);+ });++ test("a factor-removal action challenges the substitute and forwards the excluded factor", async () => {+ const { server, user } = makeServer({ resolved: removalResolved });++ await expect(ensureStepUpMfa(server, { ...baseArgs, excludeMfaMethod: MfaMethod.TOTP })).rejects.toMatchObject({+ name: "SESSION_MFA_REQUIRED",+ details: { mfaMethod: MfaMethod.EMAIL }+ });++ expect(user.getStepUpMfaMethod).toHaveBeenCalledWith(USER_ID, ORG_ID, MfaMethod.TOTP);+ });++ test("a session minted for the removal substitute is not accepted by other management actions", async () => {+ const { server, mfaSession } = makeServer({ activeSessionMethod: MfaMethod.EMAIL });++ await expect(ensureStepUpMfa(server, { ...baseArgs, mfaSessionId: SESSION_ID })).rejects.toMatchObject({+ name: "SESSION_MFA_REQUIRED",+ details: { mfaMethod: MfaMethod.TOTP }+ });+ expect(mfaSession.createMfaSession).toHaveBeenCalledWith(+ USER_ID,+ baseArgs.resourceId,+ MfaMethod.TOTP,+ TOKEN_VERSION+ );+ });++ test("a grace window opened by the removal substitute does not cover other management actions", async () => {+ const { server } = makeServer({ recentAuthMethod: MfaMethod.EMAIL });++ await expect(ensureStepUpMfa(server, baseArgs)).rejects.toMatchObject({ name: "SESSION_MFA_REQUIRED" });+ });++ test("the removal action itself honours a proof of either the required method or the substitute", async () => {+ const viaSubstitute = makeServer({ resolved: removalResolved, recentAuthMethod: MfaMethod.EMAIL });+ await expect(+ ensureStepUpMfa(viaSubstitute.server, { ...baseArgs, excludeMfaMethod: MfaMethod.TOTP })+ ).resolves.toBeUndefined();+ expect(viaSubstitute.mfaSession.createMfaSession).not.toHaveBeenCalled();++ const viaRequired = makeServer({ resolved: removalResolved, recentAuthMethod: MfaMethod.TOTP });+ await expect(+ ensureStepUpMfa(viaRequired.server, { ...baseArgs, excludeMfaMethod: MfaMethod.TOTP })+ ).resolves.toBeUndefined();+ expect(viaRequired.mfaSession.createMfaSession).not.toHaveBeenCalled();+ });++ test("an explicit method override is the only factor prior proof is measured against", async () => {+ const { server, mfaSession, user } = makeServer({ activeSessionMethod: MfaMethod.WEBAUTHN });++ await expect(+ ensureStepUpMfa(server, {+ ...baseArgs,+ resourceId: MfaStepUpResource.MfaActivation,+ mfaMethod: MfaMethod.WEBAUTHN,+ mfaSessionId: SESSION_ID+ })+ ).resolves.toBeUndefined();+ expect(mfaSession.isMfaSessionActive).toHaveBeenCalledWith(+ expect.objectContaining({ acceptedMfaMethods: [MfaMethod.WEBAUTHN] })+ );+ expect(user.getStepUpMfaMethod).not.toHaveBeenCalled();+ expect(mfaSession.hasRecentMfaAuth).not.toHaveBeenCalled();+ });++ test("skips everything when no step-up is required for MFA management", async () => {+ const { server, mfaSession, user } = makeServer({ isStepUpMfaRequired: false });++ await expect(ensureStepUpMfa(server, baseArgs)).resolves.toBeUndefined();+ expect(user.getStepUpMfaMethod).not.toHaveBeenCalled();+ expect(mfaSession.isMfaSessionActive).not.toHaveBeenCalled();+ });+});diff --git a/backend/src/server/routes/mfa-step-up-fns.ts b/backend/src/server/routes/mfa-step-up-fns.tsindex 0e633fe1cc..5b9609f24a 100644--- a/backend/src/server/routes/mfa-step-up-fns.ts+++ b/backend/src/server/routes/mfa-step-up-fns.ts@@ -24,13 +24,16 @@ export const getStepUpSessionId = (req: FastifyRequest): string => {* account-access flow).** A verified session is reusable for the remainder of its TTL (5 min) and is bound- * to `resourceId`, so it cannot be replayed against a different action.+ * to `resourceId` and to the factor it proved, so it cannot be replayed against a+ * different action, nor against one that would not have challenged that factor.*- * - With a valid, verified session for this user + resource: returns immediately.- * - Otherwise (no session id, or one that is missing/expired/unverified/foreign):- * 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.+ * - With a valid, verified session for this user + resource whose proven factor is+ * one this action would challenge: returns immediately.+ * - Otherwise (no session id, or one that is missing/expired/unverified/foreign, or+ * proving a factor this action does not accept): 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@@ -61,30 +64,41 @@ export const ensureStepUpMfa = async (excludeMfaMethod?: MfaMethod;}) => {+ const isMfaManagement = resourceId === MfaStepUpResource.MfaManagement;++ if (isMfaManagement && !(await server.services.user.isStepUpMfaRequired(userId))) return;++ // Resolved before honouring any prior proof: a factor-removal action falls back to a+ // substitute factor, and a proof of that substitute must not satisfy the other+ // management actions, which would never have challenged it.+ const { challenge: mfaMethod, accepted: acceptedMfaMethods } = mfaMethodOverride+ ? { challenge: mfaMethodOverride, accepted: [mfaMethodOverride] }+ : await server.services.user.getStepUpMfaMethod(userId, orgId, excludeMfaMethod);+if (mfaSessionId &&(await server.services.mfaSession.isMfaSessionActive({mfaSessionId,userId,resourceId,- tokenVersionId+ tokenVersionId,+ acceptedMfaMethods}))) {return;}- if (resourceId === MfaStepUpResource.MfaManagement) {- if (await server.services.mfaSession.hasRecentMfaAuth(userId, tokenVersionId)) return;- if (!(await server.services.user.isStepUpMfaRequired(userId))) return;+ if (+ isMfaManagement &&+ (await server.services.mfaSession.hasRecentMfaAuth(userId, tokenVersionId, acceptedMfaMethods))+ ) {+ 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, excludeMfaMethod));-const newMfaSessionId = await server.services.mfaSession.createMfaSession(userId,resourceId,diff --git a/backend/src/services/auth/auth-fns.test.ts b/backend/src/services/auth/auth-fns.test.tsindex 8041f23f69..5ffdd12429 100644--- a/backend/src/services/auth/auth-fns.test.ts+++ b/backend/src/services/auth/auth-fns.test.ts@@ -1,6 +1,11 @@import { LoginMethod } from "../super-admin/super-admin-types";-import { assertOAuthLoginMethodEnabled, isOAuthLoginMethodDisabled } from "./auth-fns";-import { AuthMethod } from "./auth-type";+import {+ assertOAuthLoginMethodEnabled,+ isMfaProofAccepted,+ isOAuthLoginMethodDisabled,+ RECOVERY_CODE_MFA_ASSURANCE+} from "./auth-fns";+import { AuthMethod, MfaMethod } from "./auth-type";describe("OAuth login method policy", () => {test.each([@@ -38,3 +43,22 @@ describe("OAuth login method policy", () => {).not.toThrow();});});++describe("isMfaProofAccepted", () => {+ test("accepts only a factor the action would itself challenge", () => {+ expect(isMfaProofAccepted(MfaMethod.TOTP, [MfaMethod.TOTP])).toBe(true);+ expect(isMfaProofAccepted(MfaMethod.EMAIL, [MfaMethod.TOTP, MfaMethod.EMAIL])).toBe(true);+ expect(isMfaProofAccepted(MfaMethod.EMAIL, [MfaMethod.TOTP])).toBe(false);+ expect(isMfaProofAccepted(MfaMethod.WEBAUTHN, [MfaMethod.TOTP])).toBe(false);+ });++ test("a recovery-code login is accepted everywhere", () => {+ expect(isMfaProofAccepted(RECOVERY_CODE_MFA_ASSURANCE, [MfaMethod.WEBAUTHN])).toBe(true);+ });++ test("a missing or unknown marker is never accepted", () => {+ expect(isMfaProofAccepted(null, [MfaMethod.EMAIL])).toBe(false);+ expect(isMfaProofAccepted(undefined, [MfaMethod.EMAIL])).toBe(false);+ expect(isMfaProofAccepted("1", [MfaMethod.EMAIL])).toBe(false);+ });+});diff --git a/backend/src/services/auth/auth-fns.ts b/backend/src/services/auth/auth-fns.tsindex 839fb7503e..cf03ac1f7b 100644--- a/backend/src/services/auth/auth-fns.ts+++ b/backend/src/services/auth/auth-fns.ts@@ -71,6 +71,12 @@ export const getRequiredMfaMethod = (return { isMfaRequired, requiredMfaMethod };};+export const RECOVERY_CODE_MFA_ASSURANCE = "recovery-code";+export type TMfaAssurance = MfaMethod | typeof RECOVERY_CODE_MFA_ASSURANCE;++export const isMfaProofAccepted = (proven: string | null | undefined, acceptedMethods: MfaMethod[]): boolean =>+ proven === RECOVERY_CODE_MFA_ASSURANCE || acceptedMethods.includes(proven as MfaMethod);+export const extractBearerToken = (token?: string): string => {if (!token) {throw new UnauthorizedError({ message: "Missing Authorization Header in the request header." });diff --git a/backend/src/services/auth/auth-login-service.ts b/backend/src/services/auth/auth-login-service.tsindex 15c2d54a0c..7c4ee58127 100644--- a/backend/src/services/auth/auth-login-service.ts+++ b/backend/src/services/auth/auth-login-service.ts@@ -58,7 +58,8 @@ import {enforceUserLockStatus,getRequiredMfaMethod,isOAuthLoginMethodDisabled,- OAuthAuthMethod+ OAuthAuthMethod,+ RECOVERY_CODE_MFA_ASSURANCE} from "./auth-fns";import {TLoginClientProofDTO,@@ -740,8 +741,13 @@ export const authLoginServiceFactory = ({// Open the grace window for THIS session only (the one that just proved MFA), so// MFA-management step-up isn't re-prompted right after login - including recovery-code// logins, which is what lets a user with a lost factor still manage their MFA. Keyed- // by the new session's tokenVersionId so no other session inherits it.- await mfaLockoutService.recordRecentMfaAuth(user.id, token.tokenVersionId);+ // by the new session's tokenVersionId so no other session inherits it. The factor+ // proven is the required one (anything else was rejected above), so record that.+ await mfaLockoutService.recordRecentMfaAuth(+ user.id,+ token.tokenVersionId,+ isRecoveryCode ? RECOVERY_CODE_MFA_ASSURANCE : requiredMfaMethod+ );if (isRecoveryCode && userEnc.email) {await smtpServicediff --git a/backend/src/services/auth/mfa-lockout-service.test.ts b/backend/src/services/auth/mfa-lockout-service.test.tsindex 8dc17b4f4e..13a56bd3ce 100644--- a/backend/src/services/auth/mfa-lockout-service.test.ts+++ b/backend/src/services/auth/mfa-lockout-service.test.ts@@ -3,6 +3,8 @@ import { describe, expect, type Mocked, test, vi } from "vitest";import { KeyStorePrefixes, TKeyStoreFactory } from "@app/keystore/keystore";import { ForbiddenRequestError } from "@app/lib/errors";+import { RECOVERY_CODE_MFA_ASSURANCE } from "./auth-fns";+import { MfaMethod } from "./auth-type";import { mfaLockoutServiceFactory } from "./mfa-lockout-service";vi.mock("@app/lib/config/env", () => ({@@ -90,27 +92,51 @@ describe("mfaLockoutService.enforceStepUpMfaLockStatus", () => {});describe("mfaLockoutService recent-auth is bound to the session, not the user", () => {- test("records under a key namespaced by both userId and tokenVersionId", async () => {+ test("records the proven factor under a key namespaced by both userId and tokenVersionId", async () => {const keyStore = makeKeyStore();const service = makeService(keyStore);- await service.recordRecentMfaAuth(USER_ID, "session-a");+ await service.recordRecentMfaAuth(USER_ID, "session-a", MfaMethod.TOTP);expect(keyStore.setItemWithExpiry).toHaveBeenCalledWith(KeyStorePrefixes.RecentMfaAuth(USER_ID, "session-a"),expect.any(Number),- "1"+ MfaMethod.TOTP);});test("a different session does not see another session's recent auth", async () => {const keyStore = makeKeyStore({- getItem: vi.fn(async (key: string) => (key === KeyStorePrefixes.RecentMfaAuth(USER_ID, "session-a") ? "1" : null))+ getItem: vi.fn(async (key: string) =>+ key === KeyStorePrefixes.RecentMfaAuth(USER_ID, "session-a") ? MfaMethod.TOTP : null+ )});const service = makeService(keyStore);- await expect(service.hasRecentMfaAuth(USER_ID, "session-a")).resolves.toBe(true);- await expect(service.hasRecentMfaAuth(USER_ID, "session-b")).resolves.toBe(false);+ await expect(service.hasRecentMfaAuth(USER_ID, "session-a", [MfaMethod.TOTP])).resolves.toBe(true);+ await expect(service.hasRecentMfaAuth(USER_ID, "session-b", [MfaMethod.TOTP])).resolves.toBe(false);+ });++ test("a proven factor only covers actions that would challenge it", async () => {+ const keyStore = makeKeyStore({ getItem: vi.fn().mockResolvedValue(MfaMethod.EMAIL) });+ const service = makeService(keyStore);++ await expect(service.hasRecentMfaAuth(USER_ID, "session-a", [MfaMethod.TOTP, MfaMethod.EMAIL])).resolves.toBe(true);+ await expect(service.hasRecentMfaAuth(USER_ID, "session-a", [MfaMethod.TOTP])).resolves.toBe(false);+ });++ test("a recovery-code login covers every action", async () => {+ const keyStore = makeKeyStore({ getItem: vi.fn().mockResolvedValue(RECOVERY_CODE_MFA_ASSURANCE) });+ const service = makeService(keyStore);++ await expect(service.hasRecentMfaAuth(USER_ID, "session-a", [MfaMethod.WEBAUTHN])).resolves.toBe(true);+ });++ test("a legacy marker that carries no factor is not honoured", async () => {+ const keyStore = makeKeyStore({ getItem: vi.fn().mockResolvedValue("1") });+ const service = makeService(keyStore);++ await expect(service.hasRecentMfaAuth(USER_ID, "session-a", [MfaMethod.EMAIL])).resolves.toBe(false);});});diff --git a/backend/src/services/auth/mfa-lockout-service.ts b/backend/src/services/auth/mfa-lockout-service.tsindex f0a70fe4b6..9a712f3896 100644--- a/backend/src/services/auth/mfa-lockout-service.ts+++ b/backend/src/services/auth/mfa-lockout-service.ts@@ -7,6 +7,9 @@ import { TokenType } from "@app/services/auth-token/auth-token-types";import { SmtpTemplates, TSmtpService } from "@app/services/smtp/smtp-service";import { TUserDALFactory } from "@app/services/user/user-dal";+import { isMfaProofAccepted, TMfaAssurance } from "./auth-fns";+import { MfaMethod } from "./auth-type";+const PROGRESSIVE_DELAY_INTERVAL = 5;const PROGRESSIVE_DELAYS_IN_MINS = [5, 30, 60];@@ -193,26 +196,31 @@ export const mfaLockoutServiceFactory = ({await keyStore.deleteItem(KeyStorePrefixes.UserStepUpMfaLockout(userId));};- // Records that a specific login SESSION 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 on that same session 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. Keyed by userId + tokenVersionId (the session), NOT the user alone, so proving- // MFA in one session never authorizes another (older/stolen) session; the userId prefix- // namespaces the session id to its owner. Self-clears on TTL; if the window lapses,- // another login on that session re-opens it.- const recordRecentMfaAuth = async (userId: string, tokenVersionId: string) => {+ // Records that a specific login SESSION just proved a second factor, either at login+ // or in an MFA-management step-up, together with the factor it proved. Within this+ // window an MFA-management step-up on that same session is skipped when the recorded+ // factor is one the route would itself challenge (see isMfaProofAccepted). A+ // recovery-code login is accepted by every route, which is what lets a user who lost+ // their only configured factor still reach their MFA settings to disable it or switch+ // the preferred method. Keyed by userId + tokenVersionId (the session), NOT the user+ // alone, so proving MFA in one session never authorizes another (older/stolen) session;+ // the userId prefix namespaces the session id to its owner. Self-clears on TTL; if the+ // window lapses, another login on that session re-opens it.+ const recordRecentMfaAuth = async (userId: string, tokenVersionId: string, assurance: TMfaAssurance) => {await keyStore.setItemWithExpiry(KeyStorePrefixes.RecentMfaAuth(userId, tokenVersionId),KeyStoreTtls.RecentMfaAuthInSeconds,- "1"+ assurance);};- const hasRecentMfaAuth = async (userId: string, tokenVersionId: string): Promise<boolean> => {- return Boolean(await keyStore.getItem(KeyStorePrefixes.RecentMfaAuth(userId, tokenVersionId)));+ const hasRecentMfaAuth = async (+ userId: string,+ tokenVersionId: string,+ acceptedMfaMethods: MfaMethod[]+ ): Promise<boolean> => {+ const assurance = await keyStore.getItem(KeyStorePrefixes.RecentMfaAuth(userId, tokenVersionId));+ return isMfaProofAccepted(assurance, acceptedMfaMethods);};return {diff --git a/backend/src/services/mfa-session/mfa-session-service.test.ts b/backend/src/services/mfa-session/mfa-session-service.test.tsindex 9713f9a566..8fb44949c0 100644--- a/backend/src/services/mfa-session/mfa-session-service.test.ts+++ b/backend/src/services/mfa-session/mfa-session-service.test.ts@@ -94,6 +94,20 @@ describe("mfaSessionService.isMfaSessionActive binding guard", () => {const service = makeService(makeKeyStore(activeSession({ initiatingTokenVersionId: undefined })));await expect(service.isMfaSessionActive(activeArgs)).resolves.toBe(true);});++ test("rejects replay of a proof against an action that would not challenge that factor", async () => {+ const service = makeService(makeKeyStore(activeSession({ mfaMethod: MfaMethod.EMAIL })));+ await expect(service.isMfaSessionActive({ ...activeArgs, acceptedMfaMethods: [MfaMethod.TOTP] })).resolves.toBe(+ false+ );+ });++ test("accepts a proof of a factor the action would challenge", async () => {+ const service = makeService(makeKeyStore(activeSession({ mfaMethod: MfaMethod.EMAIL })));+ await expect(+ service.isMfaSessionActive({ ...activeArgs, acceptedMfaMethods: [MfaMethod.TOTP, MfaMethod.EMAIL] })+ ).resolves.toBe(true);+ });});describe("mfaSessionService.verifyMfaSession", () => {@@ -111,7 +125,7 @@ describe("mfaSessionService.verifyMfaSession", () => {).rejects.toBeInstanceOf(ForbiddenRequestError);});- test("flips a pending session to active and records recent auth for MFA management", async () => {+ test("flips a pending session to active and records the proven factor for MFA management", async () => {const keyStore = makeKeyStore(activeSession({ status: MfaSessionStatus.PENDING }));const recordRecentMfaAuth = vi.fn().mockResolvedValue(undefined);const service = makeService(keyStore, { recordRecentMfaAuth });@@ -126,6 +140,6 @@ describe("mfaSessionService.verifyMfaSession", () => {const persisted = JSON.parse(keyStore.setItemWithExpiry.mock.calls.at(-1)![2] as string) as TMfaSession;expect(persisted.status).toBe(MfaSessionStatus.ACTIVE);- expect(recordRecentMfaAuth).toHaveBeenCalledWith(USER_ID, TOKEN_VERSION);+ expect(recordRecentMfaAuth).toHaveBeenCalledWith(USER_ID, TOKEN_VERSION, MfaMethod.EMAIL);});});diff --git a/backend/src/services/mfa-session/mfa-session-service.ts b/backend/src/services/mfa-session/mfa-session-service.tsindex 2225e1b22d..c913c4c44f 100644--- a/backend/src/services/mfa-session/mfa-session-service.ts+++ b/backend/src/services/mfa-session/mfa-session-service.ts@@ -1,6 +1,7 @@import { KeyStorePrefixes, KeyStoreTtls, TKeyStoreFactory } from "@app/keystore/keystore";import { crypto } from "@app/lib/crypto";import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";+import { isMfaProofAccepted } from "@app/services/auth/auth-fns";import { MfaMethod } from "@app/services/auth/auth-type";import { TMfaLockoutServiceFactory } from "@app/services/auth/mfa-lockout-service";import { TAuthTokenServiceFactory } from "@app/services/auth-token/auth-token-service";@@ -59,12 +60,16 @@ export const mfaSessionServiceFactory = ({// re-implementing the checks, so a session minted for one resource (e.g. a// low-value PAM account) can never be replayed against another (e.g. recovery// codes). verifyMfaSession only flips PENDING -> ACTIVE; the resource binding- // is enforced here at the point of use.+ // is enforced here at the point of use. Callers whose challenge method varies+ // per action within one resource pass `acceptedMfaMethods`, so a session proven+ // with a factor one action fell back to cannot be replayed against another action+ // that would never have challenged that factor.const isMfaSessionActive = async ({mfaSessionId,userId,resourceId,- tokenVersionId+ tokenVersionId,+ acceptedMfaMethods}: TIsMfaSessionActiveDTO): Promise<boolean> => {const mfaSession = await getMfaSession(mfaSessionId);if (@@ -80,6 +85,10 @@ export const mfaSessionServiceFactory = ({return false;}+ if (acceptedMfaMethods && !isMfaProofAccepted(mfaSession.mfaMethod, acceptedMfaMethods)) {+ return false;+ }+return true;};@@ -197,7 +206,7 @@ export const mfaSessionServiceFactory = ({await updateMfaSession(mfaSession, KeyStoreTtls.MfaSessionInSeconds);if (mfaSession.resourceId === MfaStepUpResource.MfaManagement) {- await mfaLockoutService.recordRecentMfaAuth(userId, tokenVersionId);+ await mfaLockoutService.recordRecentMfaAuth(userId, tokenVersionId, mfaMethod);}return {@@ -270,10 +279,15 @@ export const mfaSessionServiceFactory = ({};// True when THIS session (tokenVersionId) completed a full MFA login or management- // step-up recently, so an MFA-management step-up can be skipped within the grace- // window (see recordRecentMfaAuth). Session-scoped, never user-scoped.- const hasRecentMfaAuth = async (userId: string, tokenVersionId: string): Promise<boolean> => {- return mfaLockoutService.hasRecentMfaAuth(userId, tokenVersionId);+ // step-up recently with one of `acceptedMfaMethods` (or a recovery code), so an+ // MFA-management step-up can be skipped within the grace window (see+ // recordRecentMfaAuth). Session-scoped, never user-scoped.+ const hasRecentMfaAuth = async (+ userId: string,+ tokenVersionId: string,+ acceptedMfaMethods: MfaMethod[]+ ): Promise<boolean> => {+ return mfaLockoutService.hasRecentMfaAuth(userId, tokenVersionId, acceptedMfaMethods);};return {diff --git a/backend/src/services/mfa-session/mfa-session-types.ts b/backend/src/services/mfa-session/mfa-session-types.tsindex 7188c390f9..c94397ce8a 100644--- a/backend/src/services/mfa-session/mfa-session-types.ts+++ b/backend/src/services/mfa-session/mfa-session-types.ts@@ -46,4 +46,5 @@ export type TIsMfaSessionActiveDTO = {userId: string;resourceId: string;tokenVersionId: string;+ acceptedMfaMethods?: MfaMethod[];};diff --git a/backend/src/services/user/user-service.ts b/backend/src/services/user/user-service.tsindex af7902b0b1..3a1e5a1663 100644--- a/backend/src/services/user/user-service.ts+++ b/backend/src/services/user/user-service.ts@@ -648,24 +648,34 @@ export const userServiceFactory = ({// route already proves membership of this org, so no permission check is needed.//// 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). The exception is a factor some accepted org enforces:- // that org has ruled the alternatives insufficient, so the factor itself is still- // challenged and a lost device is recovered via recovery-code login instead. Every- // org is checked, not only the current context, so org switching cannot bypass it.- const getStepUpMfaMethod = async (userId: string, orgId: string, excludeMethod?: MfaMethod): Promise<MfaMethod> => {+ // remove one is that it was lost. Another 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). The exception is a factor some accepted org enforces: that org has ruled+ // the alternatives insufficient, so the factor itself is still challenged and a lost+ // device is recovered via recovery-code login instead. Every org is checked, not only+ // the current context, so org switching cannot bypass it.+ //+ // `accepted` lists every method a prior proof may carry for this action: the required+ // method always, plus the substitute when one is challenged. A proof of the substitute+ // must not be honoured by actions that would never have challenged it.+ const getStepUpMfaMethod = async (+ userId: string,+ orgId: string,+ excludeMethod?: MfaMethod+ ): Promise<{ challenge: MfaMethod; accepted: MfaMethod[] }> => {const [user, org] = await Promise.all([userDAL.findById(userId), orgDAL.findById(orgId)]);const { requiredMfaMethod } = getRequiredMfaMethod(org ?? {}, user ?? {});- if (!user || !excludeMethod) return requiredMfaMethod;+ const asRequired = { challenge: requiredMfaMethod, accepted: [requiredMfaMethod] };+ if (!user || !excludeMethod || requiredMfaMethod !== excludeMethod) return asRequired;const enforcingOrgs = await findMfaEnforcingOrgs(userId);if (enforcingOrgs.some((enforcingOrg) => (enforcingOrg.selectedMfaMethod ?? MfaMethod.EMAIL) === excludeMethod)) {- return excludeMethod;+ return asRequired;}- if (requiredMfaMethod !== excludeMethod) return requiredMfaMethod;- return (await findReplacementMfaMethod(user, excludeMethod)) ?? requiredMfaMethod;+ const replacement = await findReplacementMfaMethod(user, excludeMethod);+ if (!replacement) return asRequired;+ return { challenge: replacement, accepted: [requiredMfaMethod, replacement] };};const deleteUser = async (userId: string) => {