Skip to content

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

check usable mfas before removal

Thiago Araujo da Silvacf21c2cfbf6a
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index bfdc88c906..23122c0bbb 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -1356,14 +1356,16 @@ export const registerRoutes = async (
totpConfigDAL,
userDAL,
kmsService,
- keyStore
+ keyStore,
+ userService
});
const webAuthnService = webAuthnServiceFactory({
webAuthnCredentialDAL,
userDAL,
tokenService,
- keyStore
+ keyStore,
+ userService
});
const mfaLockoutService = mfaLockoutServiceFactory({
diff --git a/backend/src/server/routes/v1/user-router.ts b/backend/src/server/routes/v1/user-router.ts
index b74a8ad0b8..bc98eedd77 100644
--- a/backend/src/server/routes/v1/user-router.ts
+++ b/backend/src/server/routes/v1/user-router.ts
@@ -235,6 +235,7 @@ export const registerUserRouter = async (server: FastifyZodProvider) => {
},
onRequest: verifyAuth([AuthMode.JWT]),
handler: async (req) => {
+ await server.services.user.assertMfaFactorRemovable(req.permission.id, MfaMethod.TOTP);
await ensureStepUpMfa(server, {
userId: req.permission.id,
orgId: req.permission.orgId,
@@ -594,6 +595,9 @@ export const registerUserRouter = async (server: FastifyZodProvider) => {
throw new NotFoundError({ message: "Credential not found" });
}
const isRemovingLastPasskey = credentials.length === 1;
+ if (isRemovingLastPasskey) {
+ await server.services.user.assertMfaFactorRemovable(req.permission.id, MfaMethod.WEBAUTHN);
+ }
await ensureStepUpMfa(server, {
userId: req.permission.id,
diff --git a/backend/src/services/totp/totp-service.ts b/backend/src/services/totp/totp-service.ts
index 5e5d3cb09e..e25ce7c8e0 100644
--- a/backend/src/services/totp/totp-service.ts
+++ b/backend/src/services/totp/totp-service.ts
@@ -6,6 +6,7 @@ import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/
import { MfaMethod } from "../auth/auth-type";
import { TKmsServiceFactory } from "../kms/kms-service";
import { TUserDALFactory } from "../user/user-dal";
+import { TUserServiceFactory } from "../user/user-service";
import { TTotpConfigDALFactory } from "./totp-config-dal";
import {
TDeleteUserTotpConfigDTO,
@@ -20,13 +21,20 @@ type TTotpServiceFactoryDep = {
totpConfigDAL: TTotpConfigDALFactory;
kmsService: TKmsServiceFactory;
keyStore: Pick<TKeyStoreFactory, "setItemWithExpiryNX">;
+ userService: Pick<TUserServiceFactory, "resolveMfaMethodAfterRemoval">;
};
authenticator.options = { window: 1 };
export type TTotpServiceFactory = ReturnType<typeof totpServiceFactory>;
-export const totpServiceFactory = ({ totpConfigDAL, kmsService, userDAL, keyStore }: TTotpServiceFactoryDep) => {
+export const totpServiceFactory = ({
+ totpConfigDAL,
+ kmsService,
+ userDAL,
+ keyStore,
+ userService
+}: TTotpServiceFactoryDep) => {
const getUserTotpConfig = async ({ userId }: TGetUserTotpConfigDTO) => {
const totpConfig = await totpConfigDAL.findOne({
userId
@@ -178,29 +186,20 @@ export const totpServiceFactory = ({ totpConfigDAL, kmsService, userDAL, keyStor
};
const deleteUserTotpConfig = async ({ userId }: TDeleteUserTotpConfigDTO) => {
- await totpConfigDAL.transaction(async (tx) => {
- const totpConfig = await totpConfigDAL.findOne(
- {
- userId
- },
- tx
- );
+ const totpConfig = await totpConfigDAL.findOne({ userId });
- if (!totpConfig) {
- throw new NotFoundError({
- message: "TOTP configuration not found"
- });
- }
+ if (!totpConfig) {
+ throw new NotFoundError({
+ message: "TOTP configuration not found"
+ });
+ }
- await totpConfigDAL.deleteById(totpConfig.id, tx);
+ const replacementMfaMethod = await userService.resolveMfaMethodAfterRemoval(userId, MfaMethod.TOTP);
- // If the user's preferred method is the TOTP config we just removed, reset it
- // so getRequiredMfaMethod doesn't keep challenging for a method that no longer
- // has a verified config, which would force the user back into enrollment. Fall
- // back to email, which is always available.
- const user = await userDAL.findById(userId, tx);
- if (user?.selectedMfaMethod === MfaMethod.TOTP) {
- await userDAL.updateById(userId, { selectedMfaMethod: MfaMethod.EMAIL }, tx);
+ await totpConfigDAL.transaction(async (tx) => {
+ await totpConfigDAL.deleteById(totpConfig.id, tx);
+ if (replacementMfaMethod) {
+ await userDAL.updateById(userId, { selectedMfaMethod: replacementMfaMethod }, tx);
}
});
};
diff --git a/backend/src/services/user/user-service.ts b/backend/src/services/user/user-service.ts
index 94f6044d0a..fac48b30c1 100644
--- a/backend/src/services/user/user-service.ts
+++ b/backend/src/services/user/user-service.ts
@@ -152,6 +152,14 @@ export const userServiceFactory = ({
return credentials.length > 0;
};
+ const findReplacementMfaMethod = async (user: { id: string; email?: string | null }, excludeMethod: MfaMethod) => {
+ const fallbackOrder = [MfaMethod.WEBAUTHN, MfaMethod.TOTP, MfaMethod.EMAIL].filter(
+ (method) => method !== excludeMethod
+ );
+ const configured = await Promise.all(fallbackOrder.map((method) => isMfaMethodConfigured(user, method)));
+ return fallbackOrder.find((_, index) => configured[index]) ?? null;
+ };
+
// A method can only be selected/activated once the user has actually configured
// that factor. EMAIL uses the account email, so it needs no enrollment, but it
// delivers codes over SMTP — which self-hosted instances may not have configured.
@@ -251,6 +259,26 @@ export const userServiceFactory = ({
return hasMfaEnforcingOrg(userId);
};
+ const resolveMfaMethodAfterRemoval = async (userId: string, removedMethod: MfaMethod): Promise<MfaMethod | null> => {
+ const user = await userDAL.findById(userId);
+ if (!user || user.selectedMfaMethod !== removedMethod) return null;
+
+ const replacement = await findReplacementMfaMethod(user, removedMethod);
+ if (replacement) return replacement;
+
+ if (user.isMfaEnabled) {
+ throw new BadRequestError({
+ message:
+ "Cannot remove your only usable two-factor method while two-factor authentication is enabled. Set up a passkey or authenticator app first, or disable two-factor authentication."
+ });
+ }
+ return MfaMethod.EMAIL;
+ };
+
+ const assertMfaFactorRemovable = async (userId: string, method: MfaMethod) => {
+ await resolveMfaMethodAfterRemoval(userId, method);
+ };
+
// Disables MFA. Enrolled factors are preserved so re-enabling does not require
// re-enrollment, but the recovery-code pool is wiped so codes never outlive the
// enabled state; a fresh pool is issued on the next enable.
@@ -630,11 +658,7 @@ export const userServiceFactory = ({
}
if (requiredMfaMethod !== excludeMethod) return requiredMfaMethod;
- const fallbackOrder = [MfaMethod.WEBAUTHN, MfaMethod.TOTP, MfaMethod.EMAIL].filter(
- (method) => method !== excludeMethod
- );
- const configured = await Promise.all(fallbackOrder.map((method) => isMfaMethodConfigured(user, method)));
- return fallbackOrder.find((_, index) => configured[index]) ?? requiredMfaMethod;
+ return (await findReplacementMfaMethod(user, excludeMethod)) ?? requiredMfaMethod;
};
const deleteUser = async (userId: string) => {
@@ -831,6 +855,8 @@ export const userServiceFactory = ({
getMe,
getStepUpMfaMethod,
isStepUpMfaRequired,
+ resolveMfaMethodAfterRemoval,
+ assertMfaFactorRemovable,
createUserAction,
listUserGroups,
getUserAction,
diff --git a/backend/src/services/webauthn/webauthn-service.ts b/backend/src/services/webauthn/webauthn-service.ts
index 483cd987e2..4c836202a6 100644
--- a/backend/src/services/webauthn/webauthn-service.ts
+++ b/backend/src/services/webauthn/webauthn-service.ts
@@ -17,6 +17,7 @@ import { MfaMethod } from "../auth/auth-type";
import { TAuthTokenServiceFactory } from "../auth-token/auth-token-service";
import { TokenType } from "../auth-token/auth-token-types";
import { TUserDALFactory } from "../user/user-dal";
+import { TUserServiceFactory } from "../user/user-service";
import { TWebAuthnCredentialDALFactory } from "./webauthn-credential-dal";
import {
TDeleteWebAuthnCredentialDTO,
@@ -33,6 +34,7 @@ type TWebAuthnServiceFactoryDep = {
webAuthnCredentialDAL: TWebAuthnCredentialDALFactory;
tokenService: TAuthTokenServiceFactory;
keyStore: TKeyStoreFactory;
+ userService: Pick<TUserServiceFactory, "resolveMfaMethodAfterRemoval">;
};
export type TWebAuthnServiceFactory = ReturnType<typeof webAuthnServiceFactory>;
@@ -41,7 +43,8 @@ export const webAuthnServiceFactory = ({
userDAL,
webAuthnCredentialDAL,
tokenService,
- keyStore
+ keyStore,
+ userService
}: TWebAuthnServiceFactoryDep) => {
const storeChallenge = async (userId: string, challenge: string) => {
const challengeKey = KeyStorePrefixes.WebAuthnChallenge(userId);
@@ -337,33 +340,28 @@ export const webAuthnServiceFactory = ({
* Delete a WebAuthn credential
*/
const deleteWebAuthnCredential = async ({ userId, id }: TDeleteWebAuthnCredentialDTO) => {
- await webAuthnCredentialDAL.transaction(async (tx) => {
- const credential = await webAuthnCredentialDAL.findById(id, tx);
+ const credential = await webAuthnCredentialDAL.findById(id);
- if (!credential) {
- throw new NotFoundError({
- message: "Credential not found"
- });
- }
+ if (!credential) {
+ throw new NotFoundError({
+ message: "Credential not found"
+ });
+ }
- if (userId !== credential.userId) {
- throw new ForbiddenRequestError({
- message: "Credential does not belong to this user"
- });
- }
+ if (userId !== credential.userId) {
+ throw new ForbiddenRequestError({
+ message: "Credential does not belong to this user"
+ });
+ }
- await webAuthnCredentialDAL.deleteById(credential.id, tx);
+ const userCredentials = await webAuthnCredentialDAL.find({ userId });
+ const replacementMfaMethod =
+ userCredentials.length === 1 ? await userService.resolveMfaMethodAfterRemoval(userId, MfaMethod.WEBAUTHN) : null;
- // If that was the user's last credential and webauthn is their preferred
- // method, reset the preference so getRequiredMfaMethod doesn't keep
- // challenging for webauthn with no credential left, which would lock the
- // user out. Fall back to email, which is always available.
- const remainingCredentials = await webAuthnCredentialDAL.find({ userId }, { tx });
- if (remainingCredentials.length === 0) {
- const user = await userDAL.findById(userId, tx);
- if (user?.selectedMfaMethod === MfaMethod.WEBAUTHN) {
- await userDAL.updateById(userId, { selectedMfaMethod: MfaMethod.EMAIL }, tx);
- }
+ await webAuthnCredentialDAL.transaction(async (tx) => {
+ await webAuthnCredentialDAL.deleteById(credential.id, tx);
+ if (replacementMfaMethod) {
+ await userDAL.updateById(userId, { selectedMfaMethod: replacementMfaMethod }, tx);
}
});