Skip to content

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

feat: addressed review comments

=3a53986b80c2
diff --git a/backend/src/services/auth/auth-login-service.ts b/backend/src/services/auth/auth-login-service.ts
index 2f649cdc48..08e9687311 100644
--- a/backend/src/services/auth/auth-login-service.ts
+++ b/backend/src/services/auth/auth-login-service.ts
@@ -95,7 +95,7 @@ type TAuthLoginServiceFactoryDep = {
permissionService: Pick<TPermissionServiceFactory, "getOrgPermission">;
mfaLockoutService: Pick<
TMfaLockoutServiceFactory,
- "handleFailedMfaAttempt" | "resetMfaLockStatus" | "recordRecentMfaAuth"
+ "handleFailedMfaAttempt" | "resetMfaLockStatus" | "recordRecentMfaAuth" | "clearRecentMfaAuth"
>;
};
@@ -257,6 +257,10 @@ export const authLoginServiceFactory = ({
);
if (!tokenSession) throw new Error("Failed to create token");
+ // Logins from the same IP and user agent reuse one session row, so a password-only
+ // login would otherwise inherit the MFA an earlier login proved on it.
+ if (!isMfaVerified) await mfaLockoutService.clearRecentMfaAuth(userId, tokenSession.id);
+
let tokenSessionExpiresIn: string | number = cfg.JWT_AUTH_LIFETIME;
let refreshTokenExpiresIn: string | number = cfg.JWT_REFRESH_LIFETIME;
diff --git a/backend/src/services/auth/mfa-lockout-service.test.ts b/backend/src/services/auth/mfa-lockout-service.test.ts
index 13a56bd3ce..ca959c6a57 100644
--- a/backend/src/services/auth/mfa-lockout-service.test.ts
+++ b/backend/src/services/auth/mfa-lockout-service.test.ts
@@ -138,6 +138,15 @@ describe("mfaLockoutService recent-auth is bound to the session, not the user",
await expect(service.hasRecentMfaAuth(USER_ID, "session-a", [MfaMethod.EMAIL])).resolves.toBe(false);
});
+
+ test("clearing drops only that session's marker", async () => {
+ const keyStore = makeKeyStore();
+ const service = makeService(keyStore);
+
+ await service.clearRecentMfaAuth(USER_ID, "session-a");
+
+ expect(keyStore.deleteItem).toHaveBeenCalledWith(KeyStorePrefixes.RecentMfaAuth(USER_ID, "session-a"));
+ });
});
describe("mfaLockoutService.handleFailedMfaAttempt progressive lockout", () => {
diff --git a/backend/src/services/auth/mfa-lockout-service.ts b/backend/src/services/auth/mfa-lockout-service.ts
index 860d3f1a34..b853e1a96e 100644
--- a/backend/src/services/auth/mfa-lockout-service.ts
+++ b/backend/src/services/auth/mfa-lockout-service.ts
@@ -210,6 +210,10 @@ export const mfaLockoutServiceFactory = ({
);
};
+ const clearRecentMfaAuth = async (userId: string, tokenVersionId: string) => {
+ await keyStore.deleteItem(KeyStorePrefixes.RecentMfaAuth(userId, tokenVersionId));
+ };
+
const hasRecentMfaAuth = async (
userId: string,
tokenVersionId: string,
@@ -226,6 +230,7 @@ export const mfaLockoutServiceFactory = ({
reserveStepUpMfaAttempt,
resetStepUpMfaLockStatus,
recordRecentMfaAuth,
+ clearRecentMfaAuth,
hasRecentMfaAuth
};
};
diff --git a/backend/src/services/user/user-service.test.ts b/backend/src/services/user/user-service.test.ts
index b6a1767f51..89fa0840d7 100644
--- a/backend/src/services/user/user-service.test.ts
+++ b/backend/src/services/user/user-service.test.ts
@@ -381,19 +381,66 @@ describe("getFactorEnrollmentStepUpMfaMethods", () => {
});
});
- test("challenges the preferred factor and accepts any enrolled one", async () => {
+ test("only accepts the factor login asks for, not every registered one", async () => {
const service = buildMfaService({
userRow: { isMfaEnabled: true, selectedMfaMethod: MfaMethod.TOTP },
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 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 () => {
const service = buildMfaService({
memberOrgIds: [ENFORCED_ORG_ID],
@@ -414,4 +461,35 @@ 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]
+ });
+ });
});
diff --git a/backend/src/services/user/user-service.ts b/backend/src/services/user/user-service.ts
index 36cc3b0f08..d0ffff9b37 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 findMfaEnforcingOrgs = async (userId: string) => {
+ const findMemberRootOrgs = async (userId: string) => {
const memberships = await orgDAL.findActiveEffectiveOrgMembershipsByUserId(userId);
if (!memberships.length) return [];
@@ -243,10 +243,12 @@ export const userServiceFactory = ({
$in: { id: unique(memberships.map((membership) => membership.scopeOrgId)) }
});
const rootOrgIds = unique(memberOrgs.map((org) => org.rootOrgId ?? org.id));
- const rootOrgs = await orgDAL.find({ $in: { id: rootOrgIds } });
- return rootOrgs.filter((org) => org.enforceMfa);
+ return orgDAL.find({ $in: { id: rootOrgIds } });
};
+ 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,
@@ -693,29 +695,36 @@ export const userServiceFactory = ({
};
// Adding a factor must be proven with one the account already relies on, or a
- // password-only session could plant its own. Returns null for an account with none,
- // so enforced-MFA onboarding at login can still enroll the first one.
+ // 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, registered ones still beat the password alone. Email is never a fallback:
+ // every account has one, so first-factor onboarding at login would always be challenged.
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, enforcingOrgs] = await Promise.all([
+ const [hasPasskey, hasTotp, hasEmail, rootOrgs] = await Promise.all([
isMfaMethodConfigured(user, MfaMethod.WEBAUTHN),
isMfaMethodConfigured(user, MfaMethod.TOTP),
- findMfaEnforcingOrgs(userId)
+ isMfaMethodConfigured(user, MfaMethod.EMAIL),
+ findMemberRootOrgs(userId)
]);
- 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] : [])
- ];
+
+ 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 accepted = loginFactors.length ? loginFactors : registeredFactors;
if (!accepted.length) return null;
const preferred = accepted.find((method) => method === user.selectedMfaMethod);
diff --git a/frontend/src/hooks/api/users/queries.tsx b/frontend/src/hooks/api/users/queries.tsx
index da79ccbf06..260bb93f39 100644
--- a/frontend/src/hooks/api/users/queries.tsx
+++ b/frontend/src/hooks/api/users/queries.tsx
@@ -414,6 +414,7 @@ export const useRevokeMySessions = () => {
export const useEnrollMfa = () => {
const queryClient = useQueryClient();
return useMutation({
+ meta: { handledErrorCodes: ["SESSION_MFA_REQUIRED"] },
mutationFn: async (
dto:
| { method: MfaMethod.TOTP; totp: string }
diff --git a/frontend/src/hooks/api/webauthn/mutations.tsx b/frontend/src/hooks/api/webauthn/mutations.tsx
index 7e35790920..ec333adc9a 100644
--- a/frontend/src/hooks/api/webauthn/mutations.tsx
+++ b/frontend/src/hooks/api/webauthn/mutations.tsx
@@ -15,6 +15,7 @@ export const useVerifyRegistration = () => {
const queryClient = useQueryClient();
return useMutation({
+ meta: { handledErrorCodes: ["SESSION_MFA_REQUIRED"] },
mutationFn: async (dto: TVerifyRegistrationDTO) => {
const { data } = await apiRequest.post<TVerifyRegistrationResponse>(
"/api/v1/user/me/webauthn/register/verify",