Skip to content

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

add lockout logic to step up

Thiago Araujo da Silva6e14873606f5
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 63d5c76721..3c9a24588f 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -250,6 +250,7 @@ import { authDALFactory } from "@app/services/auth/auth-dal";
import { authLoginServiceFactory } from "@app/services/auth/auth-login-service";
import { authPaswordServiceFactory } from "@app/services/auth/auth-password-service";
import { authSignupServiceFactory } from "@app/services/auth/auth-signup-service";
+import { mfaLockoutServiceFactory } from "@app/services/auth/mfa-lockout-service";
import { tokenDALFactory } from "@app/services/auth-token/auth-token-dal";
import { tokenServiceFactory } from "@app/services/auth-token/auth-token-service";
import { certManagerExportServiceFactory } from "@app/services/cert-manager-export/cert-manager-export-service";
@@ -1185,11 +1186,19 @@ export const registerRoutes = async (
keyStore
});
+ const mfaLockoutService = mfaLockoutServiceFactory({
+ userDAL,
+ tokenService,
+ smtpService,
+ keyStore
+ });
+
const mfaSessionService = mfaSessionServiceFactory({
keyStore,
tokenService,
smtpService,
- totpService
+ totpService,
+ mfaLockoutService
});
const loginService = authLoginServiceFactory({
@@ -1204,8 +1213,8 @@ export const registerRoutes = async (
notificationService,
membershipRoleDAL,
membershipUserDAL,
- keyStore,
- permissionService
+ permissionService,
+ mfaLockoutService
});
const samlService = samlConfigServiceFactory({
diff --git a/backend/src/services/auth/auth-login-service.ts b/backend/src/services/auth/auth-login-service.ts
index 82795dea50..1e0aef74bb 100644
--- a/backend/src/services/auth/auth-login-service.ts
+++ b/backend/src/services/auth/auth-login-service.ts
@@ -12,7 +12,6 @@ import { EventType, TAuditLogServiceFactory } from "@app/ee/services/audit-log/a
import { OrgPermissionSsoActions, OrgPermissionSubjects } from "@app/ee/services/permission/org-permission";
import { isAuthMethodSaml } from "@app/ee/services/permission/permission-fns";
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
-import { KeyStorePrefixes, KeyStoreTtls, TKeyStoreFactory } from "@app/keystore/keystore";
import { getConfig } from "@app/lib/config/env";
import { crypto, generateSrpServerKey, srpCheckClientProof } from "@app/lib/crypto";
import { getUserPrivateKey } from "@app/lib/crypto/srp";
@@ -70,6 +69,7 @@ import {
ProviderAuthResult,
TProviderAuthCallback
} from "./auth-type";
+import { TMfaLockoutServiceFactory } from "./mfa-lockout-service";
type TAuthLoginServiceFactoryDep = {
userDAL: TUserDALFactory;
@@ -83,8 +83,8 @@ type TAuthLoginServiceFactoryDep = {
membershipUserDAL: TMembershipUserDALFactory;
membershipRoleDAL: TMembershipRoleDALFactory;
notificationService: Pick<TNotificationServiceFactory, "createUserNotifications">;
- keyStore: Pick<TKeyStoreFactory, "acquireLock" | "setItemWithExpiry" | "getItem">;
permissionService: Pick<TPermissionServiceFactory, "getOrgPermission">;
+ mfaLockoutService: Pick<TMfaLockoutServiceFactory, "handleFailedMfaAttempt" | "resetMfaLockStatus">;
};
export type TAuthLoginFactory = ReturnType<typeof authLoginServiceFactory>;
@@ -100,8 +100,8 @@ export const authLoginServiceFactory = ({
notificationService,
membershipUserDAL,
membershipRoleDAL,
- keyStore,
- permissionService
+ permissionService,
+ mfaLockoutService
}: TAuthLoginServiceFactoryDep) => {
/*
* Private
@@ -636,54 +636,6 @@ export const authLoginServiceFactory = ({
});
};
- const processFailedMfaAttempt = async (userId: string) => {
- try {
- const updatedUser = await userDAL.transaction(async (tx) => {
- const PROGRESSIVE_DELAY_INTERVAL = 3;
- const user = await userDAL.updateById(userId, { $incr: { consecutiveFailedMfaAttempts: 1 } }, tx);
-
- if (!user) {
- throw new Error("User not found");
- }
-
- const progressiveDelaysInMins = [5, 30, 60];
-
- // lock user when failed attempt exceeds threshold
- if (
- user.consecutiveFailedMfaAttempts &&
- user.consecutiveFailedMfaAttempts >= PROGRESSIVE_DELAY_INTERVAL * (progressiveDelaysInMins.length + 1)
- ) {
- return userDAL.updateById(
- userId,
- {
- isLocked: true,
- temporaryLockDateEnd: null
- },
- tx
- );
- }
-
- // delay user only when failed MFA attempts is a multiple of configured delay interval
- if (user.consecutiveFailedMfaAttempts && user.consecutiveFailedMfaAttempts % PROGRESSIVE_DELAY_INTERVAL === 0) {
- const delayIndex = user.consecutiveFailedMfaAttempts / PROGRESSIVE_DELAY_INTERVAL - 1;
- return userDAL.updateById(
- userId,
- {
- temporaryLockDateEnd: new Date(new Date().getTime() + progressiveDelaysInMins[delayIndex] * 60 * 1000)
- },
- tx
- );
- }
-
- return user;
- });
-
- return updatedUser;
- } catch (error) {
- throw new DatabaseError({ error, name: "Process failed MFA Attempt" });
- }
- };
-
/*
* Multi factor authentication verification of code
* Third step of login in which user completes with mfa
@@ -699,7 +651,6 @@ export const authLoginServiceFactory = ({
orgId,
isRecoveryCode = false
}: TVerifyMfaTokenDTO) => {
- const appCfg = getConfig();
const user = await userDAL.findById(userId);
try {
@@ -752,52 +703,7 @@ export const authLoginServiceFactory = ({
});
}
- const updatedUser = await processFailedMfaAttempt(userId);
- if (updatedUser.isLocked) {
- if (updatedUser.email) {
- // Use a keystore lock to prevent sending duplicate unlock emails during concurrent requests
- let lock: Awaited<ReturnType<typeof keyStore.acquireLock>> | undefined;
- try {
- lock = await keyStore.acquireLock([KeyStorePrefixes.UserMfaLockoutLock(userId)], 3000, {
- retryCount: 0
- });
-
- // Check if an unlock email was already sent recently (within 5 minutes)
- const emailAlreadySent = await keyStore.getItem(KeyStorePrefixes.UserMfaUnlockEmailSent(userId));
- if (!emailAlreadySent) {
- const unlockToken = await tokenService.createTokenForUser({
- type: TokenType.TOKEN_USER_UNLOCK,
- userId: updatedUser.id
- });
-
- await smtpService.sendMail({
- template: SmtpTemplates.UnlockAccount,
- subjectLine: "Unlock your Infisical account",
- recipients: [updatedUser.email],
- substitutions: {
- token: unlockToken,
- callback_url: `${appCfg.SITE_URL}/api/v1/user/${updatedUser.id}/unlock`
- }
- });
-
- // Mark that an unlock email was sent, expires after 5 minutes
- await keyStore.setItemWithExpiry(
- KeyStorePrefixes.UserMfaUnlockEmailSent(userId),
- KeyStoreTtls.UserMfaUnlockEmailSentInSeconds,
- "1"
- );
- }
- } catch (lockErr) {
- if (lock) {
- logger.error(lockErr, "Failed to send unlock email");
- }
- } finally {
- if (lock) {
- await lock.release();
- }
- }
- }
- }
+ await mfaLockoutService.handleFailedMfaAttempt(userId);
throw err;
}
@@ -807,11 +713,7 @@ export const authLoginServiceFactory = ({
const userEnc = await userDAL.findById(userId);
if (!userEnc) throw new Error("Failed to authenticate user");
- // reset lock states
- await userDAL.updateById(userId, {
- consecutiveFailedMfaAttempts: 0,
- temporaryLockDateEnd: null
- });
+ await mfaLockoutService.resetMfaLockStatus(userId);
const token = await generateUserTokens({
userId: user.id,
diff --git a/backend/src/services/auth/mfa-lockout-service.ts b/backend/src/services/auth/mfa-lockout-service.ts
new file mode 100644
index 0000000000..a8347eca47
--- /dev/null
+++ b/backend/src/services/auth/mfa-lockout-service.ts
@@ -0,0 +1,158 @@
+import { KeyStorePrefixes, KeyStoreTtls, TKeyStoreFactory } from "@app/keystore/keystore";
+import { getConfig } from "@app/lib/config/env";
+import { DatabaseError } from "@app/lib/errors";
+import { logger } from "@app/lib/logger";
+import { TAuthTokenServiceFactory } from "@app/services/auth-token/auth-token-service";
+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 { enforceUserLockStatus } from "./auth-fns";
+
+const PROGRESSIVE_DELAY_INTERVAL = 5;
+const PROGRESSIVE_DELAYS_IN_MINS = [5, 30, 60];
+
+type TMfaLockoutServiceFactoryDep = {
+ userDAL: Pick<TUserDALFactory, "findById" | "updateById" | "transaction">;
+ tokenService: Pick<TAuthTokenServiceFactory, "createTokenForUser">;
+ smtpService: Pick<TSmtpService, "sendMail">;
+ keyStore: Pick<TKeyStoreFactory, "acquireLock" | "getItem" | "setItemWithExpiry">;
+};
+
+export type TMfaLockoutServiceFactory = ReturnType<typeof mfaLockoutServiceFactory>;
+
+export const mfaLockoutServiceFactory = ({
+ userDAL,
+ tokenService,
+ smtpService,
+ keyStore
+}: TMfaLockoutServiceFactoryDep) => {
+ // Rejects the request when the user is currently locked (permanently or
+ // temporarily) from MFA verification. Fetches the user itself so callers that
+ // don't already hold the row can guard cheaply.
+ const enforceMfaLockStatus = async (userId: string) => {
+ const user = await userDAL.findById(userId);
+ if (!user) return;
+ enforceUserLockStatus(Boolean(user.isLocked), user.temporaryLockDateEnd);
+ };
+
+ // Increments the shared consecutive-failed-MFA counter and, on hitting a
+ // progressive-delay interval, applies an escalating temporary lock; once the
+ // delays are exhausted the account is permanently locked. Returns the updated
+ // user so the caller can react (e.g. send an unlock email).
+ const processFailedMfaAttempt = async (userId: string) => {
+ try {
+ const updatedUser = await userDAL.transaction(async (tx) => {
+ const user = await userDAL.updateById(userId, { $incr: { consecutiveFailedMfaAttempts: 1 } }, tx);
+
+ if (!user) {
+ throw new Error("User not found");
+ }
+
+ // lock user when failed attempt exceeds threshold
+ if (
+ user.consecutiveFailedMfaAttempts &&
+ user.consecutiveFailedMfaAttempts >= PROGRESSIVE_DELAY_INTERVAL * (PROGRESSIVE_DELAYS_IN_MINS.length + 1)
+ ) {
+ return userDAL.updateById(
+ userId,
+ {
+ isLocked: true,
+ temporaryLockDateEnd: null
+ },
+ tx
+ );
+ }
+
+ // delay user only when failed MFA attempts is a multiple of configured delay interval
+ if (user.consecutiveFailedMfaAttempts && user.consecutiveFailedMfaAttempts % PROGRESSIVE_DELAY_INTERVAL === 0) {
+ const delayIndex = user.consecutiveFailedMfaAttempts / PROGRESSIVE_DELAY_INTERVAL - 1;
+ return userDAL.updateById(
+ userId,
+ {
+ temporaryLockDateEnd: new Date(new Date().getTime() + PROGRESSIVE_DELAYS_IN_MINS[delayIndex] * 60 * 1000)
+ },
+ tx
+ );
+ }
+
+ return user;
+ });
+
+ return updatedUser;
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Process failed MFA Attempt" });
+ }
+ };
+
+ // Sends the account-unlock email when the user has just become permanently
+ // locked, debounced (5 min) and guarded by a keystore lock so concurrent
+ // failures don't fan out into duplicate emails.
+ const sendMfaUnlockEmail = async (user: { id: string; email?: string | null; isLocked?: boolean | null }) => {
+ if (!user.isLocked || !user.email) return;
+
+ const appCfg = getConfig();
+
+ let lock: Awaited<ReturnType<typeof keyStore.acquireLock>> | undefined;
+ try {
+ lock = await keyStore.acquireLock([KeyStorePrefixes.UserMfaLockoutLock(user.id)], 3000, {
+ retryCount: 0
+ });
+
+ const emailAlreadySent = await keyStore.getItem(KeyStorePrefixes.UserMfaUnlockEmailSent(user.id));
+ if (!emailAlreadySent) {
+ const unlockToken = await tokenService.createTokenForUser({
+ type: TokenType.TOKEN_USER_UNLOCK,
+ userId: user.id
+ });
+
+ await smtpService.sendMail({
+ template: SmtpTemplates.UnlockAccount,
+ subjectLine: "Unlock your Infisical account",
+ recipients: [user.email],
+ substitutions: {
+ token: unlockToken,
+ callback_url: `${appCfg.SITE_URL}/api/v1/user/${user.id}/unlock`
+ }
+ });
+
+ await keyStore.setItemWithExpiry(
+ KeyStorePrefixes.UserMfaUnlockEmailSent(user.id),
+ KeyStoreTtls.UserMfaUnlockEmailSentInSeconds,
+ "1"
+ );
+ }
+ } catch (lockErr) {
+ if (lock) {
+ logger.error(lockErr, "Failed to send unlock email");
+ }
+ } finally {
+ if (lock) {
+ await lock.release();
+ }
+ }
+ };
+
+ // Records a failed MFA attempt and, if it tipped the account into a locked
+ // state, dispatches the unlock email. Returns the updated user.
+ const handleFailedMfaAttempt = async (userId: string) => {
+ const updatedUser = await processFailedMfaAttempt(userId);
+ await sendMfaUnlockEmail(updatedUser);
+ return updatedUser;
+ };
+
+ // Clears the failed-attempt counter and any temporary lock after a successful
+ // verification.
+ const resetMfaLockStatus = async (userId: string) => {
+ await userDAL.updateById(userId, {
+ consecutiveFailedMfaAttempts: 0,
+ temporaryLockDateEnd: null
+ });
+ };
+
+ return {
+ enforceMfaLockStatus,
+ handleFailedMfaAttempt,
+ resetMfaLockStatus
+ };
+};
diff --git a/backend/src/services/mfa-session/mfa-session-service.ts b/backend/src/services/mfa-session/mfa-session-service.ts
index d5cfbabb18..123eb344c1 100644
--- a/backend/src/services/mfa-session/mfa-session-service.ts
+++ b/backend/src/services/mfa-session/mfa-session-service.ts
@@ -2,6 +2,7 @@ import { KeyStorePrefixes, KeyStoreTtls, TKeyStoreFactory } from "@app/keystore/
import { crypto } from "@app/lib/crypto";
import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
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";
import { TokenType } from "@app/services/auth-token/auth-token-types";
import { SmtpTemplates, TSmtpService } from "@app/services/smtp/smtp-service";
@@ -20,6 +21,10 @@ type TMfaSessionServiceFactoryDep = {
tokenService: Pick<TAuthTokenServiceFactory, "createTokenForUser" | "validateTokenForUser">;
smtpService: Pick<TSmtpService, "sendMail">;
totpService: Pick<TTotpServiceFactory, "verifyUserTotp">;
+ mfaLockoutService: Pick<
+ TMfaLockoutServiceFactory,
+ "enforceMfaLockStatus" | "handleFailedMfaAttempt" | "resetMfaLockStatus"
+ >;
};
export type TMfaSessionServiceFactory = ReturnType<typeof mfaSessionServiceFactory>;
@@ -28,7 +33,8 @@ export const mfaSessionServiceFactory = ({
keyStore,
tokenService,
smtpService,
- totpService
+ totpService,
+ mfaLockoutService
}: TMfaSessionServiceFactoryDep) => {
// Helper function to get MFA session from Redis
const getMfaSession = async (mfaSessionId: string): Promise<TMfaSession | null> => {
@@ -117,6 +123,8 @@ export const mfaSessionServiceFactory = ({
});
}
+ await mfaLockoutService.enforceMfaLockStatus(userId);
+
try {
if (mfaMethod === MfaMethod.EMAIL) {
await tokenService.validateTokenForUser({
@@ -142,11 +150,14 @@ export const mfaSessionServiceFactory = ({
});
}
} catch (error) {
+ await mfaLockoutService.handleFailedMfaAttempt(userId);
throw new BadRequestError({
message: "Invalid MFA code"
});
}
+ await mfaLockoutService.resetMfaLockStatus(userId);
+
mfaSession.status = MfaSessionStatus.ACTIVE;
await updateMfaSession(mfaSession, KeyStoreTtls.MfaSessionInSeconds);
diff --git a/frontend/src/pages/MfaSessionPage/MfaSessionPage.tsx b/frontend/src/pages/MfaSessionPage/MfaSessionPage.tsx
index ab5f73af33..2ffdc31e1c 100644
--- a/frontend/src/pages/MfaSessionPage/MfaSessionPage.tsx
+++ b/frontend/src/pages/MfaSessionPage/MfaSessionPage.tsx
@@ -58,6 +58,7 @@ export const MfaSessionPage = () => {
const [mfaCode, setMfaCode] = useState("");
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
+ const [codeInputKey, setCodeInputKey] = useState(0);
const { data: sessionStatus, isError: isStatusError } = useMfaSessionStatus(mfaSessionId);
const verifyMfaSession = useVerifyMfaSession();
@@ -121,6 +122,7 @@ export const MfaSessionPage = () => {
} catch (err: any) {
setError(err?.response?.data?.message || "Invalid MFA code. Please try again.");
setMfaCode("");
+ setCodeInputKey((key) => key + 1);
} finally {
setIsLoading(false);
}
@@ -263,6 +265,7 @@ export const MfaSessionPage = () => {
<div className="mx-auto hidden md:block" style={{ minWidth: "600px" }}>
<div className="mt-8 mb-6 flex justify-center">
<ReactCodeInput
+ key={`code-input-desktop-${codeInputKey}`}
name=""
inputMode="tel"
type="text"
@@ -277,6 +280,7 @@ export const MfaSessionPage = () => {
<div className="mx-auto mt-4 block md:hidden" style={{ minWidth: "400px" }}>
<div className="mt-4 mb-6 flex justify-center">
<ReactCodeInput
+ key={`code-input-phone-${codeInputKey}`}
name=""
inputMode="tel"
type="text"