Skip to content

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

bound sudo to session other than user

Thiago Araujo da Silva0e9bf54a06d4
diff --git a/backend/src/keystore/keystore.ts b/backend/src/keystore/keystore.ts
index c03d3cc0be..00b4deb32a 100644
--- a/backend/src/keystore/keystore.ts
+++ b/backend/src/keystore/keystore.ts
@@ -95,7 +95,7 @@ export const KeyStorePrefixes = {
UserMfaUnlockEmailSent: (userId: string) => `user-mfa-unlock-email-sent:${userId}` as const,
UserStepUpMfaAttempts: (userId: string) => `user-step-up-mfa-attempts:${userId}` as const,
UserStepUpMfaLockout: (userId: string) => `user-step-up-mfa-lockout:${userId}` as const,
- RecentMfaAuth: (userId: string) => `recent-mfa-auth:${userId}` as const,
+ RecentMfaAuth: (tokenVersionId: string) => `recent-mfa-auth:${tokenVersionId}` as const,
UsedTotpCode: (userId: string, code: string) => `used-totp-code:${userId}:${code}` as const,
UsedAccountRecoveryToken: (userId: string, jti: string) => `used-account-recovery-token:${userId}:${jti}` as const,
UsedGitHubManifestState: (jti: string) => `used-github-manifest-state:${jti}` as const,
diff --git a/backend/src/server/routes/mfa-step-up-fns.ts b/backend/src/server/routes/mfa-step-up-fns.ts
index a4d07c63ae..ec7d88da68 100644
--- a/backend/src/server/routes/mfa-step-up-fns.ts
+++ b/backend/src/server/routes/mfa-step-up-fns.ts
@@ -1,10 +1,23 @@
-import { BadRequestError } from "@app/lib/errors";
-import { MfaMethod } from "@app/services/auth/auth-type";
+import { FastifyRequest } from "fastify";
+
+import { BadRequestError, UnauthorizedError } from "@app/lib/errors";
+import { AuthMode, MfaMethod } from "@app/services/auth/auth-type";
import { MfaStepUpResource, TMfaStepUpResource } from "@app/services/mfa-session/mfa-session-types";
export { MfaStepUpResource };
export type { TMfaStepUpResource };
+// The step-up grace is scoped to the CURRENT login session (tokenVersionId), never the
+// user, so proving MFA in one session can't authorize another. All step-up-gated routes
+// are JWT-only, so the request always carries a session id; this narrows req.auth to
+// read it (and rejects any non-user auth mode defensively).
+export const getStepUpSessionId = (req: FastifyRequest): string => {
+ if (req.auth.authMode !== AuthMode.JWT) {
+ throw new UnauthorizedError({ message: "This action requires a user session" });
+ }
+ return req.auth.tokenVersionId;
+};
+
/**
* Enforces that the caller has completed a fresh MFA challenge before a sensitive
* action, reusing the Redis-backed step-up MFA session primitive (mirrors the PAM
@@ -29,6 +42,7 @@ export const ensureStepUpMfa = async (
{
userId,
orgId,
+ tokenVersionId,
resourceId,
mfaSessionId,
message,
@@ -36,6 +50,7 @@ export const ensureStepUpMfa = async (
}: {
userId: string;
orgId: string;
+ tokenVersionId: string;
resourceId: TMfaStepUpResource;
mfaSessionId?: string;
message: string;
@@ -53,7 +68,10 @@ export const ensureStepUpMfa = async (
return;
}
- if (resourceId === MfaStepUpResource.MfaManagement && (await server.services.mfaSession.hasRecentMfaAuth(userId))) {
+ if (
+ resourceId === MfaStepUpResource.MfaManagement &&
+ (await server.services.mfaSession.hasRecentMfaAuth(tokenVersionId))
+ ) {
return;
}
diff --git a/backend/src/server/routes/v1/user-router.ts b/backend/src/server/routes/v1/user-router.ts
index db170ee112..ef64c309f1 100644
--- a/backend/src/server/routes/v1/user-router.ts
+++ b/backend/src/server/routes/v1/user-router.ts
@@ -8,7 +8,7 @@ import { authRateLimit, readLimit, writeLimit } from "@app/server/config/rateLim
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
import { AuthMode } from "@app/services/auth/auth-type";
-import { ensureStepUpMfa, MfaStepUpResource } from "../mfa-step-up-fns";
+import { ensureStepUpMfa, getStepUpSessionId, MfaStepUpResource } from "../mfa-step-up-fns";
const SantizedUserSchema = UsersSchema.omit({
hashedPassword: true
@@ -237,6 +237,7 @@ export const registerUserRouter = async (server: FastifyZodProvider) => {
await ensureStepUpMfa(server, {
userId: req.permission.id,
orgId: req.permission.orgId,
+ tokenVersionId: getStepUpSessionId(req),
resourceId: MfaStepUpResource.MfaManagement,
mfaSessionId: req.query.mfaSessionId,
message: "MFA verification is required to remove your authenticator app"
@@ -321,6 +322,7 @@ export const registerUserRouter = async (server: FastifyZodProvider) => {
await ensureStepUpMfa(server, {
userId: req.permission.id,
orgId: req.permission.orgId,
+ tokenVersionId: getStepUpSessionId(req),
resourceId: MfaStepUpResource.MfaManagement,
mfaSessionId: req.query.mfaSessionId,
message: "MFA verification is required to access recovery codes"
@@ -356,6 +358,7 @@ export const registerUserRouter = async (server: FastifyZodProvider) => {
await ensureStepUpMfa(server, {
userId: req.permission.id,
orgId: req.permission.orgId,
+ tokenVersionId: getStepUpSessionId(req),
resourceId: MfaStepUpResource.MfaManagement,
mfaSessionId: req.body?.mfaSessionId,
message: "MFA verification is required to access recovery codes"
@@ -585,6 +588,7 @@ export const registerUserRouter = async (server: FastifyZodProvider) => {
await ensureStepUpMfa(server, {
userId: req.permission.id,
orgId: req.permission.orgId,
+ tokenVersionId: getStepUpSessionId(req),
resourceId: MfaStepUpResource.MfaManagement,
mfaSessionId: req.query.mfaSessionId,
message: "MFA verification is required to remove a passkey"
diff --git a/backend/src/server/routes/v2/mfa-session-router.ts b/backend/src/server/routes/v2/mfa-session-router.ts
index 8122303f56..02665390fe 100644
--- a/backend/src/server/routes/v2/mfa-session-router.ts
+++ b/backend/src/server/routes/v2/mfa-session-router.ts
@@ -1,5 +1,6 @@
import { z } from "zod";
+import { UnauthorizedError } from "@app/lib/errors";
import { 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";
@@ -31,9 +32,14 @@ export const registerMfaSessionRouter = async (server: FastifyZodProvider) => {
},
onRequest: verifyAuth([AuthMode.JWT]),
handler: async (req) => {
+ if (req.auth.authMode !== AuthMode.JWT) {
+ throw new UnauthorizedError({ message: "MFA session verification requires a user session" });
+ }
+
const result = await server.services.mfaSession.verifyMfaSession({
mfaSessionId: req.params.mfaSessionId,
userId: req.permission.id,
+ tokenVersionId: req.auth.tokenVersionId,
mfaToken: req.body.mfaToken,
mfaMethod: req.body.mfaMethod
});
diff --git a/backend/src/server/routes/v2/user-router.ts b/backend/src/server/routes/v2/user-router.ts
index 7e1f71b242..74b92a45de 100644
--- a/backend/src/server/routes/v2/user-router.ts
+++ b/backend/src/server/routes/v2/user-router.ts
@@ -8,7 +8,7 @@ import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
import { AuthMethod, AuthMode, MfaMethod } from "@app/services/auth/auth-type";
import { sanitizedOrganizationSchema } from "@app/services/org/org-schema";
-import { ensureStepUpMfa, MfaStepUpResource } from "../mfa-step-up-fns";
+import { ensureStepUpMfa, getStepUpSessionId, MfaStepUpResource } from "../mfa-step-up-fns";
import { SanitizedUserSchema } from "../sanitizedSchemas";
export const registerUserRouter = async (server: FastifyZodProvider) => {
@@ -60,6 +60,7 @@ export const registerUserRouter = async (server: FastifyZodProvider) => {
await ensureStepUpMfa(server, {
userId: req.permission.id,
orgId: req.permission.orgId,
+ tokenVersionId: getStepUpSessionId(req),
resourceId: MfaStepUpResource.MfaManagement,
mfaSessionId: req.body.mfaSessionId,
message: "MFA verification is required to change your preferred two-factor method"
@@ -187,6 +188,7 @@ export const registerUserRouter = async (server: FastifyZodProvider) => {
await ensureStepUpMfa(server, {
userId: req.permission.id,
orgId: req.permission.orgId,
+ tokenVersionId: getStepUpSessionId(req),
resourceId: MfaStepUpResource.MfaActivation,
mfaMethod: selectedMfaMethod,
mfaSessionId: req.body.mfaSessionId,
@@ -235,6 +237,7 @@ export const registerUserRouter = async (server: FastifyZodProvider) => {
await ensureStepUpMfa(server, {
userId: req.permission.id,
orgId: req.permission.orgId,
+ tokenVersionId: getStepUpSessionId(req),
resourceId: MfaStepUpResource.MfaManagement,
mfaSessionId: req.body?.mfaSessionId,
message: "MFA verification is required to disable two-factor authentication"
diff --git a/backend/src/services/auth/auth-login-service.ts b/backend/src/services/auth/auth-login-service.ts
index 7adff915b4..025083bab7 100644
--- a/backend/src/services/auth/auth-login-service.ts
+++ b/backend/src/services/auth/auth-login-service.ts
@@ -297,7 +297,7 @@ export const authLoginServiceFactory = ({
{ expiresIn: refreshTokenExpiresIn }
);
- return { access: accessToken, refresh: refreshToken };
+ return { access: accessToken, refresh: refreshToken, tokenVersionId: tokenSession.id };
};
const processProviderCallback = async ({
@@ -716,8 +716,6 @@ export const authLoginServiceFactory = ({
await mfaLockoutService.resetMfaLockStatus(userId);
- await mfaLockoutService.recordRecentMfaAuth(userId);
-
const token = await generateUserTokens({
userId: user.id,
ip,
@@ -728,6 +726,12 @@ export const authLoginServiceFactory = ({
mfaMethod
});
+ // Open the grace window for THIS session only (the one that just proved MFA), so
+ // MFA-management step-up isn't re-prompted right after login - including recovery-code
+ // logins, which is what lets a user with a lost factor still manage their MFA. Keyed
+ // by the new session's tokenVersionId so no other session inherits it.
+ await mfaLockoutService.recordRecentMfaAuth(token.tokenVersionId);
+
if (isRecoveryCode && userEnc.email) {
await smtpService
.sendMail({
diff --git a/backend/src/services/auth/mfa-lockout-service.ts b/backend/src/services/auth/mfa-lockout-service.ts
index a89de52d26..1f4167edde 100644
--- a/backend/src/services/auth/mfa-lockout-service.ts
+++ b/backend/src/services/auth/mfa-lockout-service.ts
@@ -193,19 +193,25 @@ export const mfaLockoutServiceFactory = ({
await keyStore.deleteItem(KeyStorePrefixes.UserStepUpMfaLockout(userId));
};
- // Records that the user just completed a full MFA login. A completed login proves a
- // second factor at least as strong as any step-up challenge (it satisfies the org's
- // required method, or is a recovery code that bypasses it), so within this window an
- // MFA-management step-up is redundant. This is what lets a user who lost their only
- // configured factor, and logged in via a recovery code, still reach their MFA
- // settings to disable it or switch the preferred method. It self-clears on TTL; if
- // the window lapses, another login re-opens it.
- const recordRecentMfaAuth = async (userId: string) => {
- await keyStore.setItemWithExpiry(KeyStorePrefixes.RecentMfaAuth(userId), KeyStoreTtls.MfaSessionInSeconds, "1");
+ // Records that a specific login SESSION just completed a full MFA login. A completed
+ // login proves a second factor at least as strong as any step-up challenge (it
+ // satisfies the org's required method, or is a recovery code that bypasses it), so
+ // within this window an MFA-management step-up on that same session is redundant. This
+ // is what lets a user who lost their only configured factor, and logged in via a
+ // recovery code, still reach their MFA settings to disable it or switch the preferred
+ // method. Keyed by tokenVersionId (the session), NOT the user, so proving MFA in one
+ // session never authorizes another (older/stolen) session. Self-clears on TTL; if the
+ // window lapses, another login on that session re-opens it.
+ const recordRecentMfaAuth = async (tokenVersionId: string) => {
+ await keyStore.setItemWithExpiry(
+ KeyStorePrefixes.RecentMfaAuth(tokenVersionId),
+ KeyStoreTtls.MfaSessionInSeconds,
+ "1"
+ );
};
- const hasRecentMfaAuth = async (userId: string): Promise<boolean> => {
- return Boolean(await keyStore.getItem(KeyStorePrefixes.RecentMfaAuth(userId)));
+ const hasRecentMfaAuth = async (tokenVersionId: string): Promise<boolean> => {
+ return Boolean(await keyStore.getItem(KeyStorePrefixes.RecentMfaAuth(tokenVersionId)));
};
return {
diff --git a/backend/src/services/mfa-session/mfa-session-service.ts b/backend/src/services/mfa-session/mfa-session-service.ts
index a7dadcd989..680cbfabfb 100644
--- a/backend/src/services/mfa-session/mfa-session-service.ts
+++ b/backend/src/services/mfa-session/mfa-session-service.ts
@@ -106,7 +106,13 @@ export const mfaSessionServiceFactory = ({
});
};
- const verifyMfaSession = async ({ mfaSessionId, userId, mfaToken, mfaMethod }: TVerifyMfaSessionDTO) => {
+ const verifyMfaSession = async ({
+ mfaSessionId,
+ userId,
+ tokenVersionId,
+ mfaToken,
+ mfaMethod
+ }: TVerifyMfaSessionDTO) => {
const mfaSession = await getMfaSession(mfaSessionId);
if (!mfaSession) {
@@ -172,7 +178,7 @@ export const mfaSessionServiceFactory = ({
await updateMfaSession(mfaSession, KeyStoreTtls.MfaSessionInSeconds);
if (mfaSession.resourceId === MfaStepUpResource.MfaManagement) {
- await mfaLockoutService.recordRecentMfaAuth(userId);
+ await mfaLockoutService.recordRecentMfaAuth(tokenVersionId);
}
return {
@@ -232,10 +238,11 @@ export const mfaSessionServiceFactory = ({
await mfaLockoutService.enforceStepUpMfaLockStatus(userId);
};
- // True when the user completed a full MFA login recently, so an MFA-management
- // step-up can be skipped within the grace window (see recordRecentMfaAuth).
- const hasRecentMfaAuth = async (userId: string): Promise<boolean> => {
- return mfaLockoutService.hasRecentMfaAuth(userId);
+ // True when THIS session (tokenVersionId) completed a full MFA login or management
+ // step-up recently, so an MFA-management step-up can be skipped within the grace
+ // window (see recordRecentMfaAuth). Session-scoped, never user-scoped.
+ const hasRecentMfaAuth = async (tokenVersionId: string): Promise<boolean> => {
+ return mfaLockoutService.hasRecentMfaAuth(tokenVersionId);
};
return {
diff --git a/backend/src/services/mfa-session/mfa-session-types.ts b/backend/src/services/mfa-session/mfa-session-types.ts
index cee7e32542..45f71cf8f4 100644
--- a/backend/src/services/mfa-session/mfa-session-types.ts
+++ b/backend/src/services/mfa-session/mfa-session-types.ts
@@ -29,6 +29,7 @@ export type TCreateMfaSessionDTO = {
export type TVerifyMfaSessionDTO = {
mfaSessionId: string;
userId: string;
+ tokenVersionId: string;
mfaToken: string;
mfaMethod: MfaMethod;
};