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
feat: addressed review comment
=8b7d3557ec2d
diff --git a/backend/src/services/user/user-service.test.ts b/backend/src/services/user/user-service.test.tsindex 6df5c42030..00f803e6af 100644--- a/backend/src/services/user/user-service.test.ts+++ b/backend/src/services/user/user-service.test.ts@@ -381,53 +381,22 @@ describe("getFactorEnrollmentStepUpMfaMethods", () => {});});- test("only accepts the factor login asks for, not every registered one", async () => {+ test("challenges the preferred factor and accepts any of the user's factors", async () => {const service = buildMfaService({userRow: { isMfaEnabled: true, selectedMfaMethod: MfaMethod.TOTP },+ memberOrgIds: [ENFORCED_ORG_ID],+ orgs: [{ id: ENFORCED_ORG_ID, enforceMfa: true, selectedMfaMethod: MfaMethod.WEBAUTHN }],hasTotp: true,passkeyCount: 2});- await expect(service.getFactorEnrollmentStepUpMfaMethods(USER_ID)).resolves.toEqual({- challenge: MfaMethod.TOTP,- accepted: [MfaMethod.TOTP]- });- });-- test("accepts every factor some org's login asks for", async () => {- const service = buildMfaService({- userRow: { isMfaEnabled: true, selectedMfaMethod: MfaMethod.TOTP },- memberOrgIds: [ENFORCED_ORG_ID, "loose-org"],- orgs: [- { id: ENFORCED_ORG_ID, enforceMfa: true, selectedMfaMethod: MfaMethod.WEBAUTHN },- { id: "loose-org", enforceMfa: false }- ],- hasTotp: true,- passkeyCount: 1- });-await expect(service.getFactorEnrollmentStepUpMfaMethods(USER_ID)).resolves.toEqual({challenge: MfaMethod.TOTP,accepted: [MfaMethod.WEBAUTHN, MfaMethod.TOTP]});});- test("an old authenticator app can't stand in for the passkey an org enforces", async () => {- const service = buildMfaService({- userRow: { isMfaEnabled: true, selectedMfaMethod: MfaMethod.TOTP },- memberOrgIds: [ENFORCED_ORG_ID],- orgs: [{ id: ENFORCED_ORG_ID, enforceMfa: true, selectedMfaMethod: MfaMethod.WEBAUTHN }],- hasTotp: true,- passkeyCount: 1- });-- await expect(service.getFactorEnrollmentStepUpMfaMethods(USER_ID)).resolves.toEqual({- challenge: MfaMethod.WEBAUTHN,- accepted: [MfaMethod.WEBAUTHN]- });- });-- test("falls back to email MFA the user turned on when the org requires a factor they lack", async () => {+ test("counts email MFA the user turned on, even where an org requires a factor they lack", async () => {const service = buildMfaService({userRow: { isMfaEnabled: true, selectedMfaMethod: MfaMethod.EMAIL },memberOrgIds: [ENFORCED_ORG_ID],@@ -440,31 +409,7 @@ describe("getFactorEnrollmentStepUpMfaMethods", () => {});});- test("never challenges an account that has not turned MFA on and has no factor", async () => {- const service = buildMfaService({- userRow: { isMfaEnabled: false, selectedMfaMethod: null },- memberOrgIds: [ENFORCED_ORG_ID],- orgs: [{ id: ENFORCED_ORG_ID, enforceMfa: true, selectedMfaMethod: MfaMethod.WEBAUTHN }]- });-- await expect(service.getFactorEnrollmentStepUpMfaMethods(USER_ID)).resolves.toBeNull();- });-- test("falls back to registered factors when the user has none that login asks for", async () => {- const service = buildMfaService({- userRow: { isMfaEnabled: true, selectedMfaMethod: MfaMethod.TOTP },- memberOrgIds: [ENFORCED_ORG_ID],- orgs: [{ id: ENFORCED_ORG_ID, enforceMfa: true, selectedMfaMethod: MfaMethod.WEBAUTHN }],- hasTotp: true- });-- await expect(service.getFactorEnrollmentStepUpMfaMethods(USER_ID)).resolves.toEqual({- challenge: MfaMethod.TOTP,- accepted: [MfaMethod.TOTP]- });- });-- test("counts email as a factor when login already requires it", async () => {+ test("counts email when an org's login requires it", async () => {const service = buildMfaService({memberOrgIds: [ENFORCED_ORG_ID],orgs: [{ id: ENFORCED_ORG_ID, enforceMfa: true, selectedMfaMethod: MfaMethod.EMAIL }]@@ -484,106 +429,4 @@ describe("getFactorEnrollmentStepUpMfaMethods", () => {await expect(service.getFactorEnrollmentStepUpMfaMethods(USER_ID)).resolves.toBeNull();});-- test("does not count an email preference that an enforcing org overrides at login", async () => {- const service = buildMfaService({- userRow: { isMfaEnabled: true, selectedMfaMethod: MfaMethod.EMAIL },- memberOrgIds: [ENFORCED_ORG_ID],- orgs: [{ id: ENFORCED_ORG_ID, enforceMfa: true, selectedMfaMethod: MfaMethod.WEBAUTHN }],- passkeyCount: 1- });-- await expect(service.getFactorEnrollmentStepUpMfaMethods(USER_ID)).resolves.toEqual({- challenge: MfaMethod.WEBAUTHN,- accepted: [MfaMethod.WEBAUTHN]- });- });-- test("counts an email preference while some org leaves the method to the user", async () => {- const service = buildMfaService({- userRow: { isMfaEnabled: true, selectedMfaMethod: MfaMethod.EMAIL },- memberOrgIds: [ENFORCED_ORG_ID, "loose-org"],- orgs: [- { id: ENFORCED_ORG_ID, enforceMfa: true, selectedMfaMethod: MfaMethod.WEBAUTHN },- { id: "loose-org", enforceMfa: false }- ],- passkeyCount: 1- });-- await expect(service.getFactorEnrollmentStepUpMfaMethods(USER_ID)).resolves.toEqual({- challenge: MfaMethod.EMAIL,- accepted: [MfaMethod.WEBAUTHN, MfaMethod.EMAIL]- });- });-});--describe("getFactorEnrollmentStepUpMfaMethods rules hold for every combination", () => {- const { WEBAUTHN, TOTP, EMAIL } = MfaMethod;- type TOrg = { id: string; enforceMfa: boolean; selectedMfaMethod?: MfaMethod };- const orgSetups: TOrg[][] = [- [],- [{ id: "org-w", enforceMfa: true, selectedMfaMethod: WEBAUTHN }],- [{ id: "org-t", enforceMfa: true, selectedMfaMethod: TOTP }],- [{ id: "org-e", enforceMfa: true, selectedMfaMethod: EMAIL }],- [{ id: "org-loose", enforceMfa: false }],- [- { id: "org-w", enforceMfa: true, selectedMfaMethod: WEBAUTHN },- { id: "org-loose", enforceMfa: false }- ],- [- { id: "org-w", enforceMfa: true, selectedMfaMethod: WEBAUTHN },- { id: "org-t", enforceMfa: true, selectedMfaMethod: TOTP }- ]- ];-- const cases = orgSetups.flatMap((orgs) =>- [true, false].flatMap((isMfaEnabled) =>- [null, EMAIL, TOTP, WEBAUTHN].flatMap((selectedMfaMethod) =>- [true, false].flatMap((hasPasskey) =>- [true, false].flatMap((hasTotp) =>- [true, false].map((smtp) => ({ orgs, isMfaEnabled, selectedMfaMethod, hasPasskey, hasTotp, smtp }))- )- )- )- )- );- const validCases = cases.filter(- (c) => (c.selectedMfaMethod !== TOTP || c.hasTotp) && (c.selectedMfaMethod !== WEBAUTHN || c.hasPasskey)- );-- test.each(validCases)("%j", async ({ orgs, isMfaEnabled, selectedMfaMethod, hasPasskey, hasTotp, smtp }) => {- const service = buildMfaService({- userRow: { isMfaEnabled, selectedMfaMethod },- memberOrgIds: orgs.map((org) => org.id),- orgs,- hasTotp,- passkeyCount: hasPasskey ? 1 : 0,- smtp- });- const result = await service.getFactorEnrollmentStepUpMfaMethods(USER_ID);-- const userLoginMethod = isMfaEnabled ? (selectedMfaMethod ?? EMAIL) : null;- const loginAsks = new Set(- (orgs.length ? orgs : [{ enforceMfa: false } as TOrg])- .map((org) => (org.enforceMfa ? (org.selectedMfaMethod ?? EMAIL) : userLoginMethod))- .filter(Boolean)- );- const held = [...(hasPasskey ? [WEBAUTHN] : []), ...(hasTotp ? [TOTP] : []), ...(smtp ? [EMAIL] : [])];- const heldThatLoginAsks = held.filter((method) => loginAsks.has(method));-- // 1. A user holding a factor some login asks for is held to exactly those.- if (heldThatLoginAsks.length) {- expect(result?.accepted.slice().sort()).toEqual(heldThatLoginAsks.slice().sort());- }-- // 2. An account with a factor of its own is always challenged.- const hasOwnFactor = hasPasskey || hasTotp || (smtp && isMfaEnabled && (selectedMfaMethod ?? EMAIL) === EMAIL);- if (hasOwnFactor) expect(result).not.toBeNull();-- // 3. First-factor setup is never challenged.- if (!hasOwnFactor && !heldThatLoginAsks.length) expect(result).toBeNull();-- // 4. The challenge is one of the accepted factors.- if (result) expect(result.accepted).toContain(result.challenge);- });});diff --git a/backend/src/services/user/user-service.ts b/backend/src/services/user/user-service.tsindex be2de8ff3b..3d033df5a8 100644--- a/backend/src/services/user/user-service.ts+++ b/backend/src/services/user/user-service.ts@@ -235,7 +235,7 @@ export const userServiceFactory = ({return { user: updatedUser, recoveryCodes };};- const findMemberRootOrgs = async (userId: string) => {+ const findMfaEnforcingOrgs = async (userId: string) => {const memberships = await orgDAL.findActiveEffectiveOrgMembershipsByUserId(userId);if (!memberships.length) return [];@@ -243,12 +243,10 @@ export const userServiceFactory = ({$in: { id: unique(memberships.map((membership) => membership.scopeOrgId)) }});const rootOrgIds = unique(memberOrgs.map((org) => org.rootOrgId ?? org.id));- return orgDAL.find({ $in: { id: rootOrgIds } });+ const rootOrgs = await orgDAL.find({ $in: { id: rootOrgIds } });+ return rootOrgs.filter((org) => org.enforceMfa);};- const findMfaEnforcingOrgs = async (userId: string) =>- (await findMemberRootOrgs(userId)).filter((org) => org.enforceMfa);-const hasMfaEnforcingOrg = async (userId: string) => (await findMfaEnforcingOrgs(userId)).length > 0;// MFA cannot be turned off while any organization the user belongs to enforces it,@@ -694,42 +692,31 @@ export const userServiceFactory = ({return { challenge: replacement, accepted: [requiredMfaMethod, replacement] };};- // Adding a factor must be proven with one the account already relies on, or a- // password-only session could plant its own. A factor only counts if some org's login- // would ask for it (an enforcing org overrides the user's preference), otherwise a- // factor login ignores could be used to get around that org's enforcement. Without any- // such factor, the user's own factors still beat the password alone. Email only counts- // there if the user turned email MFA on: every account has an address, so counting it- // otherwise would challenge every first-factor onboarding at login.+ // Adding a factor must be proven with one the account already has, or a password-only+ // session could plant its own. Any of the user's factors will do: org enforcement governs+ // how a user logs in, not which factor proves it is them. Returns null for an account+ // with none, so enforced-MFA onboarding at login can still enroll the first one.const getFactorEnrollmentStepUpMfaMethods = async (userId: string): Promise<{ challenge: MfaMethod; accepted: MfaMethod[] } | null> => {const user = await userDAL.findById(userId);if (!user) throw new NotFoundError({ message: "User not found" });- const [hasPasskey, hasTotp, hasEmail, rootOrgs] = await Promise.all([+ const [hasPasskey, hasTotp, enforcingOrgs] = await Promise.all([isMfaMethodConfigured(user, MfaMethod.WEBAUTHN),isMfaMethodConfigured(user, MfaMethod.TOTP),- isMfaMethodConfigured(user, MfaMethod.EMAIL),- findMemberRootOrgs(userId)+ findMfaEnforcingOrgs(userId)]);-- const loginMfaMethods = new Set(- (rootOrgs.length ? rootOrgs : [{}])- .map((org) => getRequiredMfaMethod(org, user))- .filter(({ isMfaRequired }) => isMfaRequired)- .map(({ requiredMfaMethod }) => requiredMfaMethod)- );- const registeredFactors = [...(hasPasskey ? [MfaMethod.WEBAUTHN] : []), ...(hasTotp ? [MfaMethod.TOTP] : [])];- const loginFactors = [...registeredFactors, ...(hasEmail ? [MfaMethod.EMAIL] : [])].filter((method) =>- loginMfaMethods.has(method)- );-- const hasPersonalEmailMfa =- hasEmail && user.isMfaEnabled && (user.selectedMfaMethod ?? MfaMethod.EMAIL) === MfaMethod.EMAIL;- const accepted = loginFactors.length- ? loginFactors- : [...registeredFactors, ...(hasPersonalEmailMfa ? [MfaMethod.EMAIL] : [])];+ const isEmailRequiredAtLogin =+ (user.isMfaEnabled && (user.selectedMfaMethod ?? MfaMethod.EMAIL) === MfaMethod.EMAIL) ||+ enforcingOrgs.some((org) => (org.selectedMfaMethod ?? MfaMethod.EMAIL) === MfaMethod.EMAIL);+ const hasEmail = isEmailRequiredAtLogin && (await isMfaMethodConfigured(user, MfaMethod.EMAIL));++ const accepted = [+ ...(hasPasskey ? [MfaMethod.WEBAUTHN] : []),+ ...(hasTotp ? [MfaMethod.TOTP] : []),+ ...(hasEmail ? [MfaMethod.EMAIL] : [])+ ];if (!accepted.length) return null;const preferred = accepted.find((method) => method === user.selectedMfaMethod);diff --git a/frontend/src/components/auth/Mfa.tsx b/frontend/src/components/auth/Mfa.tsxindex f64e186d60..95dc3a0538 100644--- a/frontend/src/components/auth/Mfa.tsx+++ b/frontend/src/components/auth/Mfa.tsx@@ -33,7 +33,7 @@ import { getMfaTempToken } from "@app/hooks/api/reactQuery";import { fetchUserDetails } from "@app/hooks/api/users/queries";import { useGenerateAuthenticationOptions, useVerifyAuthentication } from "@app/hooks/api/webauthn";-import { RecoveryCodesStep } from "../mfa/setup";+import { MFA_METHOD_LABELS, RecoveryCodesStep } from "../mfa/setup";import { AuthPageLayout } from "./AuthPageLayout";import { AuthPagePanel } from "./AuthPagePanel";import { waitForMinimumAuthVerificationLoading } from "./authTiming";@@ -64,6 +64,10 @@ export const Mfa = ({ successCallback, closeMfa, email, method, onChangeAccountconst [newRecoveryCodes, setNewRecoveryCodes] = useState<string[] | null>(null);const [hasSavedRecoveryCodes, setHasSavedRecoveryCodes] = useState(false);const wasMfaEnabledRef = useRef(true);+ // Factor setup clears the MFA token so its calls run on the access token; a recovery-code+ // login out of setup needs it back.+ const mfaTokenRef = useRef(getMfaTempToken());+ const [isRecoveringFromSetup, setIsRecoveringFromSetup] = useState(false);const { mutateAsync: activateMfa } = useActivateMfa();const logout = useLogoutUser();@@ -106,7 +110,21 @@ export const Mfa = ({ successCallback, closeMfa, email, method, onChangeAccountconst isCodeComplete = mfaCode.length === getExpectedCodeLength();+ const showFactorSetup = () => {+ if (method === MfaMethod.TOTP) setShouldShowTotpRegistration(true);+ else setShouldShowWebAuthnRegistration(true);+ };++ const switchToRecoveryCode = () => {+ SecurityClient.setMfaToken(mfaTokenRef.current);+ setShouldShowTotpRegistration(false);+ setShouldShowWebAuthnRegistration(false);+ setShowRecoveryCodeInput(true);+ setIsRecoveringFromSetup(true);+ };+const getRecoveryToggleLabel = () => {+ if (isRecoveringFromSetup) return "Back to setup";if (!showRecoveryCodeInput) return "Use a recovery code";if (method === MfaMethod.WEBAUTHN) return "Use passkey instead";if (method === MfaMethod.EMAIL) return "Use email code";@@ -118,6 +136,14 @@ export const Mfa = ({ successCallback, closeMfa, email, method, onChangeAccountif (closeMfa) {closeMfa();}+ // The recovery code got the user in, but the method the org requires is still not set up.+ if (isRecoveringFromSetup) {+ createNotification({+ text: `Set up your ${MFA_METHOD_LABELS[method].toLowerCase()} now. Your organization requires it to sign in.`,+ type: "info"+ });+ navigate({ to: "/personal-settings", search: { selectedTab: "authentication" } });+ }};// Runs only after MFA verification has already succeeded: the MFA token is consumed@@ -328,6 +354,7 @@ export const Mfa = ({ successCallback, closeMfa, email, method, onChangeAccountsetShouldShowWebAuthnRegistration(false);await successCallback();}}+ onUseRecoveryCode={switchToRecoveryCode}/></AuthPageLayout>);@@ -392,8 +419,15 @@ export const Mfa = ({ successCallback, closeMfa, email, method, onChangeAccount<buttontype="button"onClick={() => {- setShowRecoveryCodeInput(!showRecoveryCodeInput);setMfaCode("");+ if (isRecoveringFromSetup) {+ SecurityClient.setMfaToken("");+ setShowRecoveryCodeInput(false);+ setIsRecoveringFromSetup(false);+ showFactorSetup();+ return;+ }+ setShowRecoveryCodeInput(!showRecoveryCodeInput);}}className="ml-auto cursor-pointer text-foreground/95 underline decoration-project/60 underline-offset-2 transition-colors duration-200 hover:decoration-project">diff --git a/frontend/src/components/mfa/MfaEnrollment.tsx b/frontend/src/components/mfa/MfaEnrollment.tsxindex c914b7aae3..134b426157 100644--- a/frontend/src/components/mfa/MfaEnrollment.tsx+++ b/frontend/src/components/mfa/MfaEnrollment.tsx@@ -9,6 +9,7 @@ import { MFA_METHOD_LABELS, VerifyStep } from "./setup";type Props = {method: MfaMethod;onComplete: () => void | Promise<void>;+ onUseRecoveryCode: () => void;};// Guided factor setup shown at login when an org enforces MFA but the user has not@@ -16,7 +17,7 @@ type Props = {// factor (proves and persists it). It deliberately does NOT enable MFA or mint// recovery codes: those happen when the user completes the org MFA challenge next// (verifyMfaToken), so a pre-MFA session can never bootstrap recovery codes.-export const MfaEnrollment = ({ method, onComplete }: Props) => {+export const MfaEnrollment = ({ method, onComplete, onUseRecoveryCode }: Props) => {const hasPrepared = useRef(false);useEffect(() => {@@ -41,6 +42,17 @@ export const MfaEnrollment = ({ method, onComplete }: Props) => {</div><VerifyStep method={method} onVerified={handleVerified} />++ <p className="text-center text-sm text-muted">+ Can't access your other two-factor method?{" "}+ <button+ type="button"+ onClick={onUseRecoveryCode}+ className="cursor-pointer text-foreground/95 underline decoration-project/60 underline-offset-2 transition-colors duration-200 hover:decoration-project"+ >+ Use a recovery code+ </button>+ </p></div>);};