Skip to content

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

add verify mfa session active helper

Thiago Araujo da Silva7753c5647ca7
diff --git a/backend/src/db/migrations/20260701120200_add-mfa-recovery-codes.ts b/backend/src/db/migrations/20260701120200_add-mfa-recovery-codes.ts
index 27b9e0702b..eb966f25b0 100644
--- a/backend/src/db/migrations/20260701120200_add-mfa-recovery-codes.ts
+++ b/backend/src/db/migrations/20260701120200_add-mfa-recovery-codes.ts
@@ -66,8 +66,8 @@ export async function up(knex: Knex): Promise<void> {
// Some MFA-enabled users have no pool after the copy above: email-MFA users
// (no TOTP config at all) and users whose TOTP config was never verified.
// Going forward the disabled->enabled transition mints codes, but these
- // pre-existing users would be stuck — unable to finish org-enforced
- // enrollment or use recovery-code login — so generate a fresh pool for them.
+ // pre-existing users would be stuck (unable to finish org-enforced enrollment
+ // or use recovery-code login), so generate a fresh pool for them.
const usersMissingRecoveryCodes = await knex(TableName.Users)
.leftJoin(TableName.UserMfaRecoveryCode, `${TableName.UserMfaRecoveryCode}.userId`, `${TableName.Users}.id`)
.where(`${TableName.Users}.isMfaEnabled`, true)
@@ -91,17 +91,26 @@ export async function up(knex: Knex): Promise<void> {
}
// Recovery codes now live in user_mfa_recovery_codes. The values were copied
- // above, so drop the legacy column from totp_configs.
+ // above, but we intentionally KEEP the legacy totp_configs column and only
+ // relax its NOT NULL constraint rather than dropping it. During a rolling
+ // deploy the previous backend version is still serving and reads this column
+ // unconditionally (getUserTotpConfig / registerUserTotp / verifyUserTotpConfig
+ // and the recovery-code login path); dropping it would 500 those pods for
+ // every TOTP operation until they roll. Making it nullable lets the new code
+ // insert TOTP configs without it while the old code keeps reading the existing
+ // ciphertext. A follow-up migration can drop the column once every pod runs
+ // the new code.
if (await knex.schema.hasColumn(TableName.TotpConfig, "encryptedRecoveryCodes")) {
await knex.schema.alterTable(TableName.TotpConfig, (t) => {
- t.dropColumn("encryptedRecoveryCodes");
+ t.binary("encryptedRecoveryCodes").nullable().alter();
});
}
}
export async function down(knex: Knex): Promise<void> {
- // Recreate the legacy column nullable for now so the backfill below can
- // populate it; the original NOT NULL constraint is restored at the end.
+ // The `up` kept the legacy column (nullable), so it should already exist. Guard
+ // against a missing column defensively; the original NOT NULL constraint is
+ // restored at the end.
if (!(await knex.schema.hasColumn(TableName.TotpConfig, "encryptedRecoveryCodes"))) {
await knex.schema.alterTable(TableName.TotpConfig, (t) => {
t.binary("encryptedRecoveryCodes").nullable();
@@ -109,8 +118,10 @@ export async function down(knex: Knex): Promise<void> {
}
if (await knex.schema.hasTable(TableName.UserMfaRecoveryCode)) {
- // Copy the account-level recovery codes back into the freshly recreated
- // column. Both stores share the same root-key ciphertext, so it is portable.
+ // Copy the account-level recovery codes back into the legacy column so the
+ // user's currently-valid codes (which may have been rotated after the up ran)
+ // keep working under the rolled-back code. Both stores share the same
+ // root-key ciphertext, so it is portable.
await knex.raw(
`UPDATE ?? tc
SET "encryptedRecoveryCodes" = rc."encryptedRecoveryCodes"
@@ -123,19 +134,19 @@ export async function down(knex: Knex): Promise<void> {
await knex.schema.dropTable(TableName.UserMfaRecoveryCode);
}
- // TOTP configs created after the column was dropped (or whose account-level
- // pool was missing) still have NULL. The pre-migration TOTP code decrypts this
- // column unconditionally and the original schema was NOT NULL, so mint a fresh
- // pool for those rows before restoring the constraint — otherwise the rolled-
- // back code throws a 500 on every TOTP settings load / login for those users.
+ // TOTP configs created by the new code (or whose account-level pool was missing)
+ // still have NULL. The pre-migration TOTP code decrypts this column
+ // unconditionally and the original schema was NOT NULL, so mint a fresh pool for
+ // those rows before restoring the constraint. Otherwise the rolled-back code
+ // throws a 500 on every TOTP settings load / login for those users.
const totpConfigsMissingCodes = await knex(TableName.TotpConfig).whereNull("encryptedRecoveryCodes").select("id");
if (totpConfigsMissingCodes.length) {
const encryptWithRoot = await startRootEncryptor(knex);
for (const { id } of totpConfigsMissingCodes) {
- // Raw update: encryptedRecoveryCodes was dropped from the generated schema,
- // so the typed query builder no longer knows the (recreated) column.
+ // Raw update: encryptedRecoveryCodes is not part of the generated totp_configs
+ // schema, so the typed query builder does not know the column.
// eslint-disable-next-line no-await-in-loop
await knex.raw(`UPDATE ?? SET "encryptedRecoveryCodes" = ? WHERE "id" = ?`, [
TableName.TotpConfig,
diff --git a/backend/src/ee/services/pam-account/pam-account-service.ts b/backend/src/ee/services/pam-account/pam-account-service.ts
index 8034cce1a9..53322a7bab 100644
--- a/backend/src/ee/services/pam-account/pam-account-service.ts
+++ b/backend/src/ee/services/pam-account/pam-account-service.ts
@@ -49,7 +49,6 @@ import { TAuthTokenServiceFactory } from "@app/services/auth-token/auth-token-se
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
import { KmsDataKey } from "@app/services/kms/kms-types";
import { TMfaSessionServiceFactory } from "@app/services/mfa-session/mfa-session-service";
-import { MfaSessionStatus } from "@app/services/mfa-session/mfa-session-types";
import { TOrgDALFactory } from "@app/services/org/org-dal";
import { TPamSessionExpirationServiceFactory } from "@app/services/pam-session-expiration/pam-session-expiration-queue";
import { TProjectDALFactory } from "@app/services/project/project-dal";
@@ -940,31 +939,14 @@ export const pamAccountServiceFactory = ({
}
if (mfaSessionId && account.requireMfa) {
- const mfaSession = await mfaSessionService.getMfaSession(mfaSessionId);
- if (!mfaSession) {
- throw new BadRequestError({
- message: "MFA session not found or expired"
- });
- }
-
- // Verify the session belongs to the current user
- if (mfaSession.userId !== actor.id) {
- throw new BadRequestError({
- message: "MFA session does not belong to current user"
- });
- }
-
- // Verify the session is for the same account
- if (mfaSession.resourceId !== account.id) {
- throw new BadRequestError({
- message: "MFA session is for a different account"
- });
- }
-
- // Check if MFA session is active
- if (mfaSession.status !== MfaSessionStatus.ACTIVE) {
+ const isActive = await mfaSessionService.isMfaSessionActive({
+ mfaSessionId,
+ userId: actor.id,
+ resourceId: account.id
+ });
+ if (!isActive) {
throw new BadRequestError({
- message: "MFA session is not active. Please complete MFA verification first."
+ message: "MFA session is invalid or has not been verified. Please complete MFA verification first."
});
}
@@ -1963,21 +1945,15 @@ export const pamAccountServiceFactory = ({
}
if (mfaSessionId && accountWithParent.requireMfa) {
- const mfaSession = await mfaSessionService.getMfaSession(mfaSessionId);
- if (!mfaSession) {
- throw new BadRequestError({ message: "MFA session not found or expired" });
- }
-
- if (mfaSession.userId !== actorId) {
- throw new BadRequestError({ message: "MFA session does not belong to current user" });
- }
-
- if (mfaSession.resourceId !== accountWithParent.id) {
- throw new BadRequestError({ message: "MFA session is for a different account" });
- }
-
- if (mfaSession.status !== MfaSessionStatus.ACTIVE) {
- throw new BadRequestError({ message: "MFA session is not active. Please complete MFA verification first." });
+ const isActive = await mfaSessionService.isMfaSessionActive({
+ mfaSessionId,
+ userId: actorId,
+ resourceId: accountWithParent.id
+ });
+ if (!isActive) {
+ throw new BadRequestError({
+ message: "MFA session is invalid or has not been verified. Please complete MFA verification first."
+ });
}
await mfaSessionService.deleteMfaSession(mfaSessionId);
diff --git a/backend/src/ee/services/pam-web-access/pam-web-access-service.ts b/backend/src/ee/services/pam-web-access/pam-web-access-service.ts
index a05846b59f..1e9cc787f3 100644
--- a/backend/src/ee/services/pam-web-access/pam-web-access-service.ts
+++ b/backend/src/ee/services/pam-web-access/pam-web-access-service.ts
@@ -29,7 +29,6 @@ import { TAuthTokenServiceFactory } from "@app/services/auth-token/auth-token-se
import { TokenType } from "@app/services/auth-token/auth-token-types";
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
import { TMfaSessionServiceFactory } from "@app/services/mfa-session/mfa-session-service";
-import { MfaSessionStatus } from "@app/services/mfa-session/mfa-session-types";
import { TOrgDALFactory } from "@app/services/org/org-dal";
import { TPamSessionExpirationServiceFactory } from "@app/services/pam-session-expiration/pam-session-expiration-queue";
import { TProjectDALFactory } from "@app/services/project/project-dal";
@@ -95,7 +94,7 @@ type TPamWebAccessServiceFactoryDep = {
userDAL: Pick<TUserDALFactory, "findById">;
mfaSessionService: Pick<
TMfaSessionServiceFactory,
- "createMfaSession" | "getMfaSession" | "deleteMfaSession" | "sendMfaCode"
+ "createMfaSession" | "isMfaSessionActive" | "deleteMfaSession" | "sendMfaCode"
>;
approvalPolicyDAL: TApprovalPolicyDALFactory;
approvalRequestGrantsDAL: TApprovalRequestGrantsDALFactory;
@@ -374,13 +373,12 @@ export const pamWebAccessServiceFactory = ({
}
if (account.requireMfa && mfaSessionId) {
- const mfaSession = await mfaSessionService.getMfaSession(mfaSessionId);
- if (
- !mfaSession ||
- mfaSession.userId !== actor.id ||
- mfaSession.resourceId !== account.id ||
- mfaSession.status !== MfaSessionStatus.ACTIVE
- ) {
+ const isActive = await mfaSessionService.isMfaSessionActive({
+ mfaSessionId,
+ userId: actor.id,
+ resourceId: account.id
+ });
+ if (!isActive) {
throw new BadRequestError({ message: "Invalid or expired MFA session" });
}
diff --git a/backend/src/server/routes/v1/user-router.ts b/backend/src/server/routes/v1/user-router.ts
index 8616c7ed17..c700f0df00 100644
--- a/backend/src/server/routes/v1/user-router.ts
+++ b/backend/src/server/routes/v1/user-router.ts
@@ -8,7 +8,6 @@ import { logger } from "@app/lib/logger";
import { authRateLimit, readLimit, writeLimit } from "@app/server/config/rateLimiter";
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
import { AuthMode, MfaMethod } from "@app/services/auth/auth-type";
-import { MfaSessionStatus } from "@app/services/mfa-session/mfa-session-types";
const SantizedUserSchema = UsersSchema.omit({
hashedPassword: true
@@ -37,16 +36,15 @@ const RECOVERY_CODE_MFA_RESOURCE = "mfa-recovery-codes";
* so the client can drive the challenge and retry.
*/
const ensureRecoveryCodeMfa = async (server: FastifyZodProvider, userId: string, mfaSessionId?: string) => {
- if (mfaSessionId) {
- const mfaSession = await server.services.mfaSession.getMfaSession(mfaSessionId);
- if (
- mfaSession &&
- mfaSession.userId === userId &&
- mfaSession.resourceId === RECOVERY_CODE_MFA_RESOURCE &&
- mfaSession.status === MfaSessionStatus.ACTIVE
- ) {
- return;
- }
+ if (
+ mfaSessionId &&
+ (await server.services.mfaSession.isMfaSessionActive({
+ mfaSessionId,
+ userId,
+ resourceId: RECOVERY_CODE_MFA_RESOURCE
+ }))
+ ) {
+ return;
}
const user = await server.services.user.getMe(userId);
diff --git a/backend/src/services/mfa-session/mfa-session-service.ts b/backend/src/services/mfa-session/mfa-session-service.ts
index 11595b255d..d328f81b38 100644
--- a/backend/src/services/mfa-session/mfa-session-service.ts
+++ b/backend/src/services/mfa-session/mfa-session-service.ts
@@ -7,7 +7,13 @@ import { TokenType } from "@app/services/auth-token/auth-token-types";
import { SmtpTemplates, TSmtpService } from "@app/services/smtp/smtp-service";
import { TTotpServiceFactory } from "@app/services/totp/totp-service";
-import { MfaSessionStatus, TGetMfaSessionStatusDTO, TMfaSession, TVerifyMfaSessionDTO } from "./mfa-session-types";
+import {
+ MfaSessionStatus,
+ TGetMfaSessionStatusDTO,
+ TIsMfaSessionActiveDTO,
+ TMfaSession,
+ TVerifyMfaSessionDTO
+} from "./mfa-session-types";
type TMfaSessionServiceFactoryDep = {
keyStore: Pick<TKeyStoreFactory, "getItem" | "setItemWithExpiry" | "deleteItem">;
@@ -36,6 +42,23 @@ export const mfaSessionServiceFactory = ({
return JSON.parse(mfaSessionData) as TMfaSession;
};
+ // Centralized guard that a step-up MFA session is authorized for a specific
+ // resource: it must exist, belong to the given user, target the given
+ // resourceId, and be ACTIVE. Every consumer MUST gate on this rather than
+ // 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.
+ const isMfaSessionActive = async ({ mfaSessionId, userId, resourceId }: TIsMfaSessionActiveDTO): Promise<boolean> => {
+ const mfaSession = await getMfaSession(mfaSessionId);
+ return Boolean(
+ mfaSession &&
+ mfaSession.userId === userId &&
+ mfaSession.resourceId === resourceId &&
+ mfaSession.status === MfaSessionStatus.ACTIVE
+ );
+ };
+
// Helper function to update MFA session in Redis
const updateMfaSession = async (mfaSession: TMfaSession, ttlSeconds: number): Promise<void> => {
const mfaSessionKey = KeyStorePrefixes.MfaSession(mfaSession.sessionId);
@@ -170,6 +193,7 @@ export const mfaSessionServiceFactory = ({
getMfaSessionStatus,
sendMfaCode,
getMfaSession,
+ isMfaSessionActive,
deleteMfaSession
};
};
diff --git a/backend/src/services/mfa-session/mfa-session-types.ts b/backend/src/services/mfa-session/mfa-session-types.ts
index 6dcb45ee90..e538fa432d 100644
--- a/backend/src/services/mfa-session/mfa-session-types.ts
+++ b/backend/src/services/mfa-session/mfa-session-types.ts
@@ -30,3 +30,9 @@ export type TGetMfaSessionStatusDTO = {
mfaSessionId: string;
userId: string;
};
+
+export type TIsMfaSessionActiveDTO = {
+ mfaSessionId: string;
+ userId: string;
+ resourceId: string;
+};
diff --git a/backend/src/services/user/user-service.ts b/backend/src/services/user/user-service.ts
index 22a438d75c..1bab0081a4 100644
--- a/backend/src/services/user/user-service.ts
+++ b/backend/src/services/user/user-service.ts
@@ -47,8 +47,8 @@ type TUserServiceFactoryDep = {
smtpService: Pick<TSmtpService, "sendMail">;
permissionService: TPermissionServiceFactory;
userAliasDAL: Pick<TUserAliasDALFactory, "findOne" | "find" | "updateById" | "delete">;
- totpConfigDAL: Pick<TTotpConfigDALFactory, "delete">;
- webAuthnCredentialDAL: Pick<TWebAuthnCredentialDALFactory, "delete">;
+ totpConfigDAL: Pick<TTotpConfigDALFactory, "delete" | "findOne">;
+ webAuthnCredentialDAL: Pick<TWebAuthnCredentialDALFactory, "delete" | "find">;
mfaRecoveryCodeService: Pick<TMfaRecoveryCodeServiceFactory, "deleteRecoveryCodes" | "rotateRecoveryCodes">;
};
@@ -129,6 +129,24 @@ export const userServiceFactory = ({
}
}
+ if (isMfaEnabled !== false && selectedMfaMethod && selectedMfaMethod !== MfaMethod.EMAIL) {
+ if (selectedMfaMethod === MfaMethod.TOTP) {
+ const totpConfig = await totpConfigDAL.findOne({ userId, isVerified: true });
+ if (!totpConfig) {
+ throw new BadRequestError({
+ message: "Cannot select an authenticator app without a verified authenticator configured"
+ });
+ }
+ } else if (selectedMfaMethod === MfaMethod.WEBAUTHN) {
+ const credentials = await webAuthnCredentialDAL.find({ userId });
+ if (credentials.length === 0) {
+ throw new BadRequestError({
+ message: "Cannot select a passkey without a registered passkey"
+ });
+ }
+ }
+ }
+
let mfaMethods: string[] | undefined;
if (isMfaEnabled === undefined) {
mfaMethods = undefined;