Skip to content

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

feat: organized backend api changes for email and refresh

=932afe6e9e85
diff --git a/backend/src/db/migrations/20260330072924_auth-revamp.ts b/backend/src/db/migrations/20260330072924_auth-revamp.ts
new file mode 100644
index 0000000000..a08bed996e
--- /dev/null
+++ b/backend/src/db/migrations/20260330072924_auth-revamp.ts
@@ -0,0 +1,88 @@
+import { Knex } from "knex";
+
+import { TableName } from "../schemas";
+import { createOnUpdateTrigger, dropOnUpdateTrigger } from "../utils";
+
+export async function up(knex: Knex): Promise<void> {
+ const hasUserTable = await knex.schema.hasTable(TableName.Users);
+ const hasHashedPasswordColumn = await knex.schema.hasColumn(TableName.Users, "hashedPassword");
+ const hasIsGitHubVerifiedColumn = await knex.schema.hasColumn(TableName.Users, "isGitHubVerified");
+ const hasIsGitlabVerifiedColumn = await knex.schema.hasColumn(TableName.Users, "isGitLabVerified");
+ if (hasUserTable) {
+ await knex.schema.alterTable(TableName.Users, (table) => {
+ if (!hasHashedPasswordColumn) {
+ table.string("hashedPassword").nullable();
+ }
+ if (!hasIsGitHubVerifiedColumn) {
+ table.boolean("isGitHubVerified").nullable();
+ }
+ if (!hasIsGitlabVerifiedColumn) {
+ table.boolean("isGitLabVerified").nullable();
+ }
+ });
+ }
+
+ if (!(await knex.schema.hasTable(TableName.EmailDomains))) {
+ await knex.schema.createTable(TableName.EmailDomains, (t) => {
+ t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());
+
+ t.uuid("orgId").notNullable();
+ t.foreign("orgId").references("id").inTable(TableName.Organization).onDelete("CASCADE");
+
+ t.string("domain", 255).notNullable().unique();
+ t.string("parentDomain", 255);
+
+ // Verification details
+ t.string("verificationMethod", 50).notNullable().defaultTo("dns-txt");
+ t.string("verificationCode", 255).notNullable();
+ t.string("verificationRecordName", 255).notNullable();
+
+ // Status tracking
+ t.string("status", 20).notNullable().defaultTo("pending");
+ t.timestamp("verifiedAt").nullable();
+
+ // Expiry
+ t.timestamp("codeExpiresAt").notNullable();
+
+ t.timestamps(true, true, true);
+
+ // Indexes
+ t.index("parentDomain");
+ t.index("orgId");
+
+ // Check constraint
+ t.check(
+ `:statusColumn: IN ('pending', 'verified', 'expired')`,
+ { statusColumn: "status" },
+ "chk_email_domain_status"
+ );
+ });
+
+ await createOnUpdateTrigger(knex, TableName.EmailDomains);
+ }
+}
+
+export async function down(knex: Knex): Promise<void> {
+ if (await knex.schema.hasTable(TableName.EmailDomains)) {
+ await dropOnUpdateTrigger(knex, TableName.EmailDomains);
+ await knex.schema.dropTable(TableName.EmailDomains);
+ }
+
+ const hasUserTable = await knex.schema.hasTable(TableName.Users);
+ const hasHashedPasswordColumn = await knex.schema.hasColumn(TableName.Users, "hashedPassword");
+ const hasIsGitHubVerifiedColumn = await knex.schema.hasColumn(TableName.Users, "isGitHubVerified");
+ const hasIsGitlabVerifiedColumn = await knex.schema.hasColumn(TableName.Users, "isGitLabVerified");
+ if (hasUserTable) {
+ await knex.schema.alterTable(TableName.Users, (table) => {
+ if (hasHashedPasswordColumn) {
+ table.dropColumn("hashedPassword");
+ }
+ if (hasIsGitHubVerifiedColumn) {
+ table.dropColumn("isGitHubVerified");
+ }
+ if (hasIsGitlabVerifiedColumn) {
+ table.dropColumn("isGitLabVerified");
+ }
+ });
+ }
+}
diff --git a/backend/src/db/schemas/email-domains.ts b/backend/src/db/schemas/email-domains.ts
new file mode 100644
index 0000000000..a747807cee
--- /dev/null
+++ b/backend/src/db/schemas/email-domains.ts
@@ -0,0 +1,27 @@
+// Code generated by automation script, DO NOT EDIT.
+// Automated by pulling database and generating zod schema
+// To update. Just run npm run generate:schema
+// Written by akhilmhdh.
+
+import { z } from "zod";
+
+import { TImmutableDBKeys } from "./models";
+
+export const EmailDomainsSchema = z.object({
+ id: z.string().uuid(),
+ orgId: z.string().uuid(),
+ domain: z.string(),
+ parentDomain: z.string().nullable().optional(),
+ verificationMethod: z.string().default("dns-txt"),
+ verificationCode: z.string(),
+ verificationRecordName: z.string(),
+ status: z.string().default("pending"),
+ verifiedAt: z.date().nullable().optional(),
+ codeExpiresAt: z.date(),
+ createdAt: z.date(),
+ updatedAt: z.date()
+});
+
+export type TEmailDomains = z.infer<typeof EmailDomainsSchema>;
+export type TEmailDomainsInsert = Omit<z.input<typeof EmailDomainsSchema>, TImmutableDBKeys>;
+export type TEmailDomainsUpdate = Partial<Omit<z.input<typeof EmailDomainsSchema>, TImmutableDBKeys>>;
diff --git a/backend/src/db/schemas/models.ts b/backend/src/db/schemas/models.ts
index 33752dd9ef..a193cff97c 100644
--- a/backend/src/db/schemas/models.ts
+++ b/backend/src/db/schemas/models.ts
@@ -2,6 +2,7 @@ import { z } from "zod";
export enum TableName {
Users = "users",
+ EmailDomains = "email_domains",
SshHostGroup = "ssh_host_groups",
SshHostGroupMembership = "ssh_host_group_memberships",
SshHost = "ssh_hosts",
diff --git a/backend/src/db/schemas/users.ts b/backend/src/db/schemas/users.ts
index 1c1f579ead..4b30880cf4 100644
--- a/backend/src/db/schemas/users.ts
+++ b/backend/src/db/schemas/users.ts
@@ -27,7 +27,10 @@ export const UsersSchema = z.object({
isLocked: z.boolean().default(false).nullable().optional(),
temporaryLockDateEnd: z.date().nullable().optional(),
consecutiveFailedPasswordAttempts: z.number().default(0).nullable().optional(),
- selectedMfaMethod: z.string().nullable().optional()
+ selectedMfaMethod: z.string().nullable().optional(),
+ hashedPassword: z.string().nullable().optional(),
+ isGitHubVerified: z.boolean().nullable().optional(),
+ isGitLabVerified: z.boolean().nullable().optional()
});
export type TUsers = z.infer<typeof UsersSchema>;
diff --git a/backend/src/keystore/keystore.ts b/backend/src/keystore/keystore.ts
index f6aba5e0e5..cb0c4788ac 100644
--- a/backend/src/keystore/keystore.ts
+++ b/backend/src/keystore/keystore.ts
@@ -103,7 +103,8 @@ export const KeyStorePrefixes = {
TelemetryIdentifyIdentity: (dedupKey: string) => `telemetry-identify-identity:${dedupKey}` as const,
TelemetryGroupIdentify: (orgId: string) => `telemetry-group-identify:${orgId}` as const,
- SecretEtag: (projectId: string) => `secret-etag:${projectId}` as const
+ SecretEtag: (projectId: string) => `secret-etag:${projectId}` as const,
+ RefreshTokenGrace: (sessionId: string) => `refresh-token-grace:${sessionId}` as const
};
export const KeyStoreTtls = {
@@ -115,7 +116,8 @@ export const KeyStoreTtls = {
MfaSessionInSeconds: 300, // 5 minutes
WebAuthnChallengeInSeconds: 300, // 5 minutes
ProjectSSEConnectionTtlSeconds: 180, // Must be > heartbeat interval (60s) * 2
- TelemetryIdentifyIdentityInSeconds: 86400 // 24 hours
+ TelemetryIdentifyIdentityInSeconds: 86400, // 24 hours
+ RefreshTokenGraceInSeconds: 30
};
type TDeleteItems = {
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 7d51408344..31018cdb89 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -710,7 +710,7 @@ export const registerRoutes = async (
projectEnvDAL
});
- const tokenService = tokenServiceFactory({ tokenDAL: authTokenDAL, userDAL, membershipUserDAL, orgDAL });
+ const tokenService = tokenServiceFactory({ tokenDAL: authTokenDAL, userDAL, membershipUserDAL, orgDAL, keyStore });
const membershipUserService = membershipUserServiceFactory({
licenseService,
diff --git a/backend/src/server/routes/v1/auth-router.ts b/backend/src/server/routes/v1/auth-router.ts
index db4c009963..29650870da 100644
--- a/backend/src/server/routes/v1/auth-router.ts
+++ b/backend/src/server/routes/v1/auth-router.ts
@@ -91,6 +91,7 @@ export const registerAuthRoutes = async (server: FastifyZodProvider) => {
response: {
200: z.object({
token: z.string(),
+ refreshToken: z.string().optional(),
organizationId: z.string().optional(),
subOrganizationId: z.string().optional()
})
@@ -101,8 +102,11 @@ export const registerAuthRoutes = async (server: FastifyZodProvider) => {
let decodedToken;
let tokenVersion;
+ let isGraceHit;
try {
- ({ decodedToken, tokenVersion } = await server.services.authToken.validateRefreshToken(req.cookies.jid));
+ ({ decodedToken, tokenVersion, isGraceHit } = await server.services.authToken.validateRefreshToken(
+ req.cookies.jid
+ ));
} catch (err) {
// Clear the expired/invalid jid cookie so it doesn't cause login loops
// when the browser keeps sending the stale cookie on subsequent requests.
@@ -115,6 +119,17 @@ export const registerAuthRoutes = async (server: FastifyZodProvider) => {
});
throw err;
}
+
+ let newRefreshToken: string | undefined;
+ let sessionForAccessToken = tokenVersion;
+
+ if (!isGraceHit) {
+ // Normal rotation: issue new refresh token and invalidate the old one
+ const rotation = await server.services.authToken.rotateRefreshToken(decodedToken, tokenVersion);
+ newRefreshToken = rotation.newRefreshToken;
+ sessionForAccessToken = rotation.updatedSession;
+ }
+
let expiresIn: string | number = appCfg.JWT_AUTH_LIFETIME;
if (decodedToken.organizationId) {
@@ -135,8 +150,8 @@ export const registerAuthRoutes = async (server: FastifyZodProvider) => {
authMethod: decodedToken.authMethod,
authTokenType: AuthTokenType.ACCESS_TOKEN,
userId: decodedToken.userId,
- tokenVersionId: tokenVersion.id,
- accessVersion: tokenVersion.accessVersion,
+ tokenVersionId: sessionForAccessToken.id,
+ accessVersion: sessionForAccessToken.accessVersion,
organizationId: decodedToken.organizationId,
...(decodedToken.subOrganizationId && { subOrganizationId: decodedToken.subOrganizationId }),
isMfaVerified: decodedToken.isMfaVerified,
@@ -145,7 +160,23 @@ export const registerAuthRoutes = async (server: FastifyZodProvider) => {
appCfg.AUTH_SECRET,
{ expiresIn }
);
- return { token, organizationId: decodedToken.organizationId, subOrganizationId: decodedToken.subOrganizationId };
+
+ // Set rotated refresh token cookie (only when rotation happened, not on grace hits)
+ if (newRefreshToken) {
+ void res.setCookie("jid", newRefreshToken, {
+ httpOnly: true,
+ path: "/",
+ sameSite: "strict",
+ secure: appCfg.HTTPS_ENABLED
+ });
+ }
+
+ return {
+ token,
+ refreshToken: newRefreshToken,
+ organizationId: decodedToken.organizationId,
+ subOrganizationId: decodedToken.subOrganizationId
+ };
}
});
};
diff --git a/backend/src/server/routes/v1/user-router.ts b/backend/src/server/routes/v1/user-router.ts
index 5c51c32ea2..b81869fb09 100644
--- a/backend/src/server/routes/v1/user-router.ts
+++ b/backend/src/server/routes/v1/user-router.ts
@@ -34,6 +34,7 @@ export const registerUserRouter = async (server: FastifyZodProvider) => {
}
});
+ // TODO(auth-revamp): Check for all reference of UsersSchema and remove if hashedPassword is set
server.route({
method: "GET",
url: "/duplicate-accounts",
diff --git a/backend/src/server/routes/v3/login-router.ts b/backend/src/server/routes/v3/login-router.ts
index 05cc17352a..bde563d138 100644
--- a/backend/src/server/routes/v3/login-router.ts
+++ b/backend/src/server/routes/v3/login-router.ts
@@ -78,7 +78,7 @@ export const registerLoginRouter = async (server: FastifyZodProvider) => {
const githubOauthAccessToken = req.cookies[INFISICAL_PROVIDER_GITHUB_ACCESS_TOKEN];
if (githubOauthAccessToken) {
await server.services.githubOrgSync
- .syncUserGroups(req.body.organizationId, tokens.user.userId, githubOauthAccessToken)
+ .syncUserGroups(req.body.organizationId, tokens.user.id, githubOauthAccessToken)
.finally(() => {
void res.setCookie(INFISICAL_PROVIDER_GITHUB_ACCESS_TOKEN, "", {
httpOnly: true,
@@ -92,7 +92,7 @@ export const registerLoginRouter = async (server: FastifyZodProvider) => {
void res.setCookie("jid", tokens.refresh, {
httpOnly: true,
- path: "/",
+ path: "/api",
sameSite: "strict",
secure: cfg.HTTPS_ENABLED
});
@@ -120,11 +120,11 @@ export const registerLoginRouter = async (server: FastifyZodProvider) => {
schema: {
operationId: "loginExchangeClientProofV3",
body: z.object({
- email: z.string().trim(),
+ email: z.string().toLowerCase().trim(),
providerAuthToken: z.string().trim().optional(),
clientProof: z.string().trim(),
captchaToken: z.string().trim().optional(),
- password: z.string().optional()
+ password: z.string().trim()
}),
response: {
200: z.object({
@@ -143,40 +143,30 @@ export const registerLoginRouter = async (server: FastifyZodProvider) => {
handler: async (req, res) => {
const userAgent = req.headers["user-agent"];
if (!userAgent) throw new Error("user agent header is required");
- const appCfg = getConfig();
- const data = await server.services.login.loginExchangeClientProof({
- captchaToken: req.body.captchaToken,
+ const { tokens, user } = await server.services.login.login({
email: req.body.email,
+ password: req.body.password,
ip: req.realIp,
userAgent,
- providerAuthToken: req.body.providerAuthToken,
- clientProof: req.body.clientProof,
- password: req.body.password
+ captchaToken: req.body.captchaToken
});
+ const appCfg = getConfig();
- const login2DistinctId = data.user.username ?? data.user.email ?? "";
- if (login2DistinctId) {
+ const loginDistinctId = user.username ?? user.email ?? "";
+ if (loginDistinctId) {
void server.services.telemetry.identifyUser(
- login2DistinctId,
+ loginDistinctId,
{
- email: data.user.email ?? undefined,
- username: data.user.username,
- userId: data.user.userId
+ email: user.email ?? undefined,
+ username: user.username,
+ userId: user.id
},
{ skipDedup: true }
);
}
- void res.setCookie("jid", data.token.refresh, {
- httpOnly: true,
- path: "/",
- sameSite: "strict",
- secure: appCfg.HTTPS_ENABLED
- });
-
addAuthOriginDomainCookie(res);
-
void res.cookie("infisical-project-assume-privileges", "", {
httpOnly: true,
path: "/",
@@ -185,17 +175,7 @@ export const registerLoginRouter = async (server: FastifyZodProvider) => {
maxAge: 0
});
- return {
- encryptionVersion: data.user.encryptionVersion,
- token: data.token.access,
- publicKey: data.user.publicKey,
- encryptedPrivateKey: data.user.encryptedPrivateKey,
- iv: data.user.iv,
- tag: data.user.tag,
- protectedKey: data.user.protectedKey || null,
- protectedKeyIV: data.user.protectedKeyIV || null,
- protectedKeyTag: data.user.protectedKeyTag || null
- } as const;
+ return { token: tokens.accessToken };
}
});
@@ -211,7 +191,6 @@ export const registerLoginRouter = async (server: FastifyZodProvider) => {
body: z.object({
email: z.string().trim(),
password: z.string().trim(),
- providerAuthToken: z.string().trim().optional(),
captchaToken: z.string().trim().optional()
}),
response: {
@@ -229,7 +208,6 @@ export const registerLoginRouter = async (server: FastifyZodProvider) => {
password: req.body.password,
ip: req.realIp,
userAgent,
- providerAuthToken: req.body.providerAuthToken,
captchaToken: req.body.captchaToken
});
const appCfg = getConfig();
@@ -241,7 +219,7 @@ export const registerLoginRouter = async (server: FastifyZodProvider) => {
{
email: user.email ?? undefined,
username: user.username,
- userId: user.userId
+ userId: user.id
},
{ skipDedup: true }
);
@@ -249,7 +227,7 @@ export const registerLoginRouter = async (server: FastifyZodProvider) => {
void res.setCookie("jid", tokens.refreshToken, {
httpOnly: true,
- path: "/",
+ path: "/api",
sameSite: "strict",
secure: appCfg.HTTPS_ENABLED
});
diff --git a/backend/src/services/auth-token/auth-token-dal.ts b/backend/src/services/auth-token/auth-token-dal.ts
index ca7841d8ee..968bf9ad8b 100644
--- a/backend/src/services/auth-token/auth-token-dal.ts
+++ b/backend/src/services/auth-token/auth-token-dal.ts
@@ -96,6 +96,23 @@ export const tokenDALFactory = (db: TDbClient) => {
}
};
+ const incrementRefreshVersion = async (
+ sessionId: string,
+ userId: string,
+ tx?: Knex
+ ): Promise<TAuthTokenSessions | undefined> => {
+ try {
+ const [session] = await (tx || db)(TableName.AuthTokenSession)
+ .where({ id: sessionId, userId })
+ .increment("refreshVersion", 1)
+ .update({ lastUsed: new Date() })
+ .returning("*");
+ return session;
+ } catch (error) {
+ throw new DatabaseError({ error, name: "IncrementRefreshVersion" });
+ }
+ };
+
const deleteTokenSession = async (filter: Partial<TAuthTokenSessions>, tx?: Knex) => {
try {
const sessions = await (tx || db)(TableName.AuthTokenSession).where(filter).del().returning("*");
@@ -113,6 +130,7 @@ export const tokenDALFactory = (db: TDbClient) => {
findOneTokenSession,
insertTokenSession,
incrementTokenSessionVersion,
+ incrementRefreshVersion,
deleteTokenSession
};
};
diff --git a/backend/src/services/auth-token/auth-token-service.ts b/backend/src/services/auth-token/auth-token-service.ts
index aba1cd434f..331c51d8f3 100644
--- a/backend/src/services/auth-token/auth-token-service.ts
+++ b/backend/src/services/auth-token/auth-token-service.ts
@@ -1,6 +1,7 @@
import { Knex } from "knex";
import { OrgMembershipStatus, TAuthTokens, TAuthTokenSessions } from "@app/db/schemas";
+import { KeyStorePrefixes, KeyStoreTtls, TKeyStoreFactory } from "@app/keystore/keystore";
import { getConfig } from "@app/lib/config/env";
import { crypto } from "@app/lib/crypto/cryptography";
import { BadRequestError, ForbiddenRequestError, NotFoundError, UnauthorizedError } from "@app/lib/errors";
@@ -17,6 +18,7 @@ type TAuthTokenServiceFactoryDep = {
userDAL: Pick<TUserDALFactory, "findById" | "transaction">;
orgDAL: Pick<TOrgDALFactory, "findOne" | "findEffectiveOrgMembership">;
membershipUserDAL: Pick<TMembershipUserDALFactory, "findOne">;
+ keyStore: Pick<TKeyStoreFactory, "setItemWithExpiry" | "getItem" | "deleteItem">;
};
export type TAuthTokenServiceFactory = ReturnType<typeof tokenServiceFactory>;
@@ -95,7 +97,7 @@ export const getTokenConfig = (tokenType: TokenType) => {
}
};
-export const tokenServiceFactory = ({ tokenDAL, userDAL, orgDAL }: TAuthTokenServiceFactoryDep) => {
+export const tokenServiceFactory = ({ tokenDAL, userDAL, orgDAL, keyStore }: TAuthTokenServiceFactoryDep) => {
const createTokenForUser = async ({ type, userId, orgId, aliasId, payload }: TCreateTokenForUserDTO) => {
const { token, ...tkCfg } = getTokenConfig(type);
const appCfg = getConfig();
@@ -199,13 +201,68 @@ export const tokenServiceFactory = ({ tokenDAL, userDAL, orgDAL }: TAuthTokenSer
});
if (decodedToken.refreshVersion !== tokenVersion.refreshVersion) {
+ // Check grace period for multi-tab scenarios
+ const graceKey = KeyStorePrefixes.RefreshTokenGrace(tokenVersion.id);
+ const graceValue = await keyStore.getItem(graceKey);
+
+ if (graceValue && Number(graceValue) === decodedToken.refreshVersion) {
+ // Grace hit: old token used within grace window (e.g. another browser tab)
+ return { decodedToken, tokenVersion, isGraceHit: true };
+ }
+
+ // Reuse detection: old token used outside grace window — potential theft
+ await tokenDAL.deleteTokenSession({ id: tokenVersion.id, userId: decodedToken.userId });
+ await keyStore.deleteItem(graceKey);
+
throw new UnauthorizedError({
- message: "Token version mismatch",
- name: "InvalidToken"
+ message: "Refresh token reuse detected. Session has been revoked for security.",
+ name: "TokenReuse"
});
}
- return { decodedToken, tokenVersion };
+ return { decodedToken, tokenVersion, isGraceHit: false };
+ };
+
+ const rotateRefreshToken = async (decodedToken: AuthModeRefreshJwtTokenPayload, tokenVersion: TAuthTokenSessions) => {
+ const appCfg = getConfig();
+ const oldRefreshVersion = tokenVersion.refreshVersion;
+
+ // Increment refreshVersion in DB
+ const updatedSession = await tokenDAL.incrementRefreshVersion(tokenVersion.id, decodedToken.userId);
+ if (!updatedSession)
+ throw new UnauthorizedError({ message: "Failed to rotate refresh token", name: "RotationFailed" });
+
+ // Store grace entry in Redis so the old token is still accepted briefly
+ const graceKey = KeyStorePrefixes.RefreshTokenGrace(tokenVersion.id);
+ await keyStore.setItemWithExpiry(graceKey, KeyStoreTtls.RefreshTokenGraceInSeconds, String(oldRefreshVersion));
+
+ // Determine refresh token expiry
+ let refreshTokenExpiresIn: string | number = appCfg.JWT_REFRESH_LIFETIME;
+ if (decodedToken.organizationId) {
+ const org = await orgDAL.findOne({ id: decodedToken.organizationId });
+ if (org?.userTokenExpiration) {
+ refreshTokenExpiresIn = org.userTokenExpiration;
+ }
+ }
+
+ // Sign new refresh token
+ const newRefreshToken = crypto.jwt().sign(
+ {
+ authMethod: decodedToken.authMethod,
+ authTokenType: AuthTokenType.REFRESH_TOKEN,
+ userId: decodedToken.userId,
+ tokenVersionId: updatedSession.id,
+ refreshVersion: updatedSession.refreshVersion,
+ organizationId: decodedToken.organizationId,
+ ...(decodedToken.subOrganizationId && { subOrganizationId: decodedToken.subOrganizationId }),
+ isMfaVerified: decodedToken.isMfaVerified,
+ mfaMethod: decodedToken.mfaMethod
+ },
+ appCfg.AUTH_SECRET,
+ { expiresIn: refreshTokenExpiresIn }
+ );
+
+ return { newRefreshToken, updatedSession };
};
// to parse jwt identity in inject identity plugin
@@ -293,6 +350,7 @@ export const tokenServiceFactory = ({ tokenDAL, userDAL, orgDAL }: TAuthTokenSer
revokeAllMySessions,
revokeMySessionById,
validateRefreshToken,
+ rotateRefreshToken,
fnValidateJwtIdentity,
getUserTokenSessionById
};
diff --git a/backend/src/services/auth/auth-fns.ts b/backend/src/services/auth/auth-fns.ts
index d490486cb4..28572e7fd8 100644
--- a/backend/src/services/auth/auth-fns.ts
+++ b/backend/src/services/auth/auth-fns.ts
@@ -1,4 +1,3 @@
-import { TUsers } from "@app/db/schemas";
import { isAuthMethodSaml } from "@app/ee/services/permission/permission-fns";
import { getConfig } from "@app/lib/config/env";
import { request } from "@app/lib/config/request";
@@ -106,13 +105,9 @@ export const enforceUserLockStatus = (isLocked: boolean, temporaryLockDateEnd?:
}
};
-export const verifyCaptcha = async (user: TUsers, captchaToken?: string) => {
+export const verifyCaptcha = async (consecutiveFailedPasswordAttempts?: number | null, captchaToken?: string) => {
const appCfg = getConfig();
- if (
- user.consecutiveFailedPasswordAttempts &&
- user.consecutiveFailedPasswordAttempts >= 10 &&
- Boolean(appCfg.CAPTCHA_SECRET)
- ) {
+ if (consecutiveFailedPasswordAttempts && consecutiveFailedPasswordAttempts >= 10 && Boolean(appCfg.CAPTCHA_SECRET)) {
if (!captchaToken) {
throw new BadRequestError({
name: "Captcha Required",
diff --git a/backend/src/services/auth/auth-login-service.ts b/backend/src/services/auth/auth-login-service.ts
index 1ff0e5cdf6..07b069cc75 100644
--- a/backend/src/services/auth/auth-login-service.ts
+++ b/backend/src/services/auth/auth-login-service.ts
@@ -41,7 +41,6 @@ import { SmtpTemplates, TSmtpService } from "../smtp/smtp-service";
import { LoginMethod } from "../super-admin/super-admin-types";
import { TTotpServiceFactory } from "../totp/totp-service";
import { TUserDALFactory } from "../user/user-dal";
-import { UserEncryption } from "../user/user-types";
import { TUserAliasDALFactory } from "../user-alias/user-alias-dal";
import { UserAliasType } from "../user-alias/user-alias-types";
import { enforceUserLockStatus, getAuthMethodAndOrgId, validateProviderAuthToken, verifyCaptcha } from "./auth-fns";
@@ -49,7 +48,6 @@ import {
TLoginClientProofDTO,
TLoginGenServerPublicKeyDTO,
TOauthLoginDTO,
- TOauthTokenExchangeDTO,
TVerifyMfaTokenDTO
} from "./auth-login-type";
import {
@@ -157,7 +155,7 @@ export const authLoginServiceFactory = ({
*/
const generateUserTokens = async (
{
- user,
+ userId,
ip,
userAgent,
organizationId,
@@ -166,7 +164,7 @@ export const authLoginServiceFactory = ({
isMfaVerified,
mfaMethod
}: {
- user: TUsers;
+ userId: string;
ip: string;
userAgent: string;
organizationId?: string;
@@ -182,7 +180,7 @@ export const authLoginServiceFactory = ({
{
userAgent,
ip,
- userId: user.id
+ userId
},
tx
);
@@ -195,7 +193,7 @@ export const authLoginServiceFactory = ({
const org = await orgDAL.findById(organizationId);
if (org) {
await membershipUserDAL.update(
- { actorUserId: user.id, scopeOrgId: org.id, scope: AccessScope.Organization },
+ { actorUserId: userId, scopeOrgId: org.id, scope: AccessScope.Organization },
{ lastLoginAuthMethod: authMethod, lastLoginTime: new Date() }
);
if (org.userTokenExpiration) {
@@ -209,7 +207,7 @@ export const authLoginServiceFactory = ({
{
authMethod,
authTokenType: AuthTokenType.ACCESS_TOKEN,
- userId: user.id,
+ userId,
tokenVersionId: tokenSession.id,
accessVersion: tokenSession.accessVersion,
organizationId,
@@ -225,7 +223,7 @@ export const authLoginServiceFactory = ({
{
authMethod,
authTokenType: AuthTokenType.REFRESH_TOKEN,
- userId: user.id,
+ userId,
tokenVersionId: tokenSession.id,
refreshVersion: tokenSession.refreshVersion,
organizationId,
@@ -315,7 +313,7 @@ export const authLoginServiceFactory = ({
const cfg = getConfig();
const { authMethod, organizationId } = getAuthMethodAndOrgId(email, providerAuthToken);
- await verifyCaptcha(user, captchaToken);
+ await verifyCaptcha(user.consecutiveFailedPasswordAttempts, captchaToken);
if (!userEnc.salt || !userEnc.verifier) {
throw new BadRequestError({ message: "Salt or verifier not found" });
@@ -380,10 +378,7 @@ export const authLoginServiceFactory = ({
}
const token = await generateUserTokens({
- user: {
- ...userEnc,
- id: userEnc.userId
- },
+ userId: userEnc.userId,
ip,
userAgent,
authMethod,
@@ -398,51 +393,34 @@ export const authLoginServiceFactory = ({
password,
ip,
userAgent,
- providerAuthToken,
captchaToken
}: {
email: string;
password: string;
ip: string;
userAgent: string;
- providerAuthToken?: string;
captchaToken?: string;
}) => {
const appCfg = getConfig();
try {
- const usersByUsername = await userDAL.findUserEncKeyByUsername({
- username: email
- });
- const userEnc =
- usersByUsername?.length > 1 ? usersByUsername.find((el) => el.username === email) : usersByUsername?.[0];
-
- if (!userEnc) throw new BadRequestError({ message: "User not found" });
-
- if (userEnc.encryptionVersion !== UserEncryption.V2) {
- throw new BadRequestError({
- message: "Legacy encryption scheme not supported",
- name: "LegacyEncryptionScheme"
- });
+ const users = await userDAL.findUserByUsername(email);
+ const user = users?.[0];
+ if (!user) {
+ logger.error(`Failed to find user for email ${email}`);
+ throw new BadRequestError({ message: "Invalid credentials" });
}
- if (!userEnc.hashedPassword) {
- if (userEnc.authMethods?.includes(AuthMethod.EMAIL)) {
- throw new BadRequestError({
- message: "Legacy encryption scheme not supported",
- name: "LegacyEncryptionScheme"
- });
- }
-
- throw new BadRequestError({ message: "No password found" });
+ if (!user.authMethods?.includes(AuthMethod.EMAIL) || !user.hashedPassword || !user.isEmailVerified) {
+ logger.error(`User doesn't have email auth enabled ${email}`);
+ throw new BadRequestError({ message: "Invalid credentials" });
}
- const { authMethod, organizationId } = getAuthMethodAndOrgId(email, providerAuthToken);
- await verifyCaptcha(userEnc, captchaToken);
+ await verifyCaptcha(user.consecutiveFailedPasswordAttempts, captchaToken);
- if (!(await crypto.hashing().compareHash(password, userEnc.hashedPassword))) {
+ if (!(await crypto.hashing().compareHash(password, user.hashedPassword))) {
await userDAL.update(
- { id: userEnc.userId },
+ { id: user.id },
{
$incr: {
consecutiveFailedPasswordAttempts: 1
@@ -450,25 +428,20 @@ export const authLoginServiceFactory = ({
}
);
- throw new BadRequestError({ message: "Invalid username or email" });
+ throw new BadRequestError({ message: "Invalid credentials" });
}
const token = await generateUserTokens({
- user: {
- ...userEnc,
- id: userEnc.userId
- },
+ userId: user.id,
ip,
userAgent,
- authMethod,
- organizationId
+ authMethod: AuthMethod.EMAIL
});
if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) {
authAttemptCounter.add(1, {
- "infisical.organization.id": organizationId,
"infisical.user.email": email,
- "infisical.user.id": userEnc.userId,
+ "infisical.user.id": user.id,
"infisical.auth.method": AuthAttemptAuthMethod.EMAIL,
"infisical.auth.result": AuthAttemptAuthResult.SUCCESS,
"client.address": ip,
@@ -476,36 +449,12 @@ export const authLoginServiceFactory = ({
});
}
- if (organizationId) {
- await auditLogService.createAuditLog({
- orgId: organizationId,
- ipAddress: ip,
- userAgent,
- userAgentType: getUserAgentType(userAgent),
- actor: {
- type: ActorType.USER,
- metadata: {
- email: userEnc.email,
- userId: userEnc.userId,
- username: userEnc.username,
- authMethod
- }
- },
- event: {
- type: EventType.USER_LOGIN,
- metadata: {
- organizationId
- }
- }
- });
- }
-
return {
tokens: {
accessToken: token.access,
refreshToken: token.refresh
},
- user: userEnc
+ user
} as const;
} catch (error) {
if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) {
@@ -522,454 +471,175 @@ export const authLoginServiceFactory = ({
}
};
- const selectOrganization = async ({
- userAgent,
- authJwtToken,
- ipAddress,
- organizationId
- }: {
- userAgent: string | undefined;
- authJwtToken: string | undefined;
- ipAddress: string;
- organizationId: string;
- }) => {
- const cfg = getConfig();
+ /*
+ * Multi factor authentication re-send code, Get user id from token
+ * saved in frontend
+ */
+ const resendMfaToken = async (userId: string) => {
+ const user = await userDAL.findById(userId);
+ if (!user || !user.email) return;
+ enforceUserLockStatus(Boolean(user.isLocked), user.temporaryLockDateEnd);
- if (!authJwtToken) throw new UnauthorizedError({ name: "Authorization header is required" });
- if (!userAgent) throw new UnauthorizedError({ name: "User-Agent header is required" });
+ await sendUserMfaCode({
+ userId: user.id,
+ email: user.email
+ });
+ };
- // eslint-disable-next-line no-param-reassign
- authJwtToken = authJwtToken.replace("Bearer ", ""); // remove bearer from token
+ 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);
- // The decoded JWT token, which contains the auth method.
- const decodedToken = crypto.jwt().verify(authJwtToken, cfg.AUTH_SECRET) as AuthModeJwtTokenPayload;
- if (!decodedToken.authMethod) throw new UnauthorizedError({ name: "Auth method not found on existing token" });
+ if (!user) {
+ throw new Error("User not found");
+ }
- const user = await userDAL.findUserEncKeyByUserId(decodedToken.userId);
- if (!user) throw new BadRequestError({ message: "User not found", name: "Find user from token" });
+ const progressiveDelaysInMins = [5, 30, 60];
- // Check user membership in the sub-organization (direct or via group)
- const orgMembership = await orgDAL.findEffectiveOrgMembership({
- actorType: ActorType.USER,
- actorId: user.id,
- orgId: organizationId,
- status: OrgMembershipStatus.Accepted
- });
+ // 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
+ );
+ }
- if (!orgMembership) {
- throw new ForbiddenRequestError({
- message: `User does not have access to the organization with ID ${organizationId}`
+ // 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;
});
- }
- const selectedOrg = await orgDAL.findById(organizationId);
- if (!selectedOrg) {
- throw new NotFoundError({ message: `Organization with ID '${organizationId}' not found` });
+ return updatedUser;
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Process failed MFA Attempt" });
}
+ };
- const isSubOrganization = Boolean(selectedOrg.rootOrgId && selectedOrg.id !== selectedOrg.rootOrgId);
-
- let rootOrg = selectedOrg;
+ /*
+ * Multi factor authentication verification of code
+ * Third step of login in which user completes with mfa
+ * */
+ const verifyMfaToken = async ({
+ userId,
+ mfaToken,
+ mfaMethod,
+ mfaJwtToken,
+ ip,
+ userAgent,
+ orgId,
+ isRecoveryCode = false
+ }: TVerifyMfaTokenDTO) => {
+ const appCfg = getConfig();
+ const user = await userDAL.findById(userId);
- if (isSubOrganization) {
- if (!selectedOrg.rootOrgId) {
- throw new BadRequestError({
- message: "Invalid sub-organization"
+ try {
+ enforceUserLockStatus(Boolean(user.isLocked), user.temporaryLockDateEnd);
+ if (mfaMethod === MfaMethod.EMAIL) {
+ await tokenService.validateTokenForUser({
+ type: TokenType.TOKEN_EMAIL_MFA,
+ userId,
+ code: mfaToken
});
- }
-
- rootOrg = await orgDAL.findById(selectedOrg.rootOrgId);
- if (!rootOrg) {
- throw new BadRequestError({
- message: "Invalid sub-organization"
+ } else if (mfaMethod === MfaMethod.TOTP) {
+ if (isRecoveryCode) {
+ await totpService.verifyWithUserRecoveryCode({
+ userId,
+ recoveryCode: mfaToken
+ });
+ } else {
+ if (mfaToken.length !== 6) {
+ throw new BadRequestError({
+ message: "Please use a valid TOTP code."
+ });
+ }
+ await totpService.verifyUserTotp({
+ userId,
+ totp: mfaToken
+ });
+ }
+ } else if (mfaMethod === MfaMethod.WEBAUTHN) {
+ if (!mfaToken) {
+ throw new BadRequestError({
+ message: "WebAuthn session token is required"
+ });
+ }
+ // Validate the one-time WebAuthn session token (passed as mfaToken)
+ await tokenService.validateTokenForUser({
+ type: TokenType.TOKEN_WEBAUTHN_SESSION,
+ userId,
+ code: mfaToken
});
}
+ } catch (err) {
+ 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 user membership in the root organization
- const rootOrgMembership = await membershipUserDAL.findOne({
- actorUserId: user.id,
- scopeOrgId: selectedOrg.rootOrgId,
- scope: AccessScope.Organization,
- status: OrgMembershipStatus.Accepted
- });
+ // 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
+ });
- if (!rootOrgMembership) {
- throw new ForbiddenRequestError({
- message: "User does not have access to the root organization"
- });
+ 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), 300, "1");
+ }
+ } catch (lockErr) {
+ if (lock) {
+ logger.error(lockErr, "Failed to send unlock email");
+ }
+ } finally {
+ if (lock) {
+ await lock.release();
+ }
+ }
+ }
}
+
+ throw err;
}
- const { permission } = await permissionService.getOrgPermission({
- actor: ActorType.USER,
- actorId: user.id,
- orgId: rootOrg.id,
- actorAuthMethod: decodedToken.authMethod,
- actorOrgId: rootOrg.id,
- scope: OrganizationActionScope.Any
- });
- const canBypassSso =
- rootOrg.bypassOrgAuthEnabled &&
- permission.can(OrgPermissionSsoActions.BypassSsoEnforcement, OrgPermissionSubjects.Sso);
+ const decodedToken = crypto.jwt().verify(mfaJwtToken, getConfig().AUTH_SECRET) as AuthModeMfaJwtTokenPayload;
- if (
- rootOrg.authEnforced &&
- !isAuthMethodSaml(decodedToken.authMethod) &&
- decodedToken.authMethod !== AuthMethod.OIDC &&
- !canBypassSso
- ) {
- throw new BadRequestError({
- message: "Login with the auth method required by your organization."
- });
- }
-
- if (rootOrg.googleSsoAuthEnforced && decodedToken.authMethod !== AuthMethod.GOOGLE) {
- if (!canBypassSso) {
- throw new ForbiddenRequestError({
- message: "Google SSO is enforced for this organization. Please use Google SSO to login.",
- error: "GoogleSsoEnforced"
- });
- }
- }
-
- if (decodedToken.authMethod === AuthMethod.GOOGLE) {
- await orgDAL.updateById(rootOrg.id, {
- googleSsoAuthLastUsed: new Date()
- });
- }
-
- const shouldCheckMfa = rootOrg.enforceMfa || user.isMfaEnabled;
- const orgMfaMethod = rootOrg.enforceMfa ? (rootOrg.selectedMfaMethod ?? MfaMethod.EMAIL) : undefined;
- const userMfaMethod = user.isMfaEnabled ? (user.selectedMfaMethod ?? MfaMethod.EMAIL) : undefined;
- const mfaMethod = orgMfaMethod ?? userMfaMethod;
-
- if (shouldCheckMfa && (!decodedToken.isMfaVerified || decodedToken.mfaMethod !== mfaMethod)) {
- enforceUserLockStatus(Boolean(user.isLocked), user.temporaryLockDateEnd);
-
- const mfaToken = crypto.jwt().sign(
- {
- authMethod: decodedToken.authMethod,
- authTokenType: AuthTokenType.MFA_TOKEN,
- userId: user.id
- },
- cfg.AUTH_SECRET,
- {
- expiresIn: cfg.JWT_MFA_LIFETIME
- }
- );
-
- if (mfaMethod === MfaMethod.EMAIL && user.email) {
- await sendUserMfaCode({
- userId: user.id,
- email: user.email
- });
- }
-
- return { isMfaEnabled: true, mfa: mfaToken, mfaMethod } as const;
- }
-
- await updateUserDeviceSession(user as TUsers, ipAddress, userAgent);
-
- const tokens = await generateUserTokens({
- authMethod: decodedToken.authMethod,
- user,
- userAgent,
- ip: ipAddress,
- organizationId: isSubOrganization ? rootOrg.id : organizationId,
- subOrganizationId: isSubOrganization ? organizationId : undefined,
- isMfaVerified: decodedToken.isMfaVerified,
- mfaMethod: decodedToken.mfaMethod
- });
-
- // In the event of this being a break-glass request (non-saml / non-oidc / non-google, when any is enforced)
- const isAuthEnforcedBypass =
- rootOrg.authEnforced &&
- rootOrg.bypassOrgAuthEnabled &&
- !isAuthMethodSaml(decodedToken.authMethod) &&
- decodedToken.authMethod !== AuthMethod.OIDC &&
- decodedToken.authMethod !== AuthMethod.GOOGLE;
- const isGoogleSsoEnforcedBypass =
- rootOrg.googleSsoAuthEnforced && rootOrg.bypassOrgAuthEnabled && decodedToken.authMethod !== AuthMethod.GOOGLE;
- if (isAuthEnforcedBypass || isGoogleSsoEnforcedBypass) {
- await auditLogService.createAuditLog({
- orgId: organizationId,
- ipAddress,
- userAgent,
- userAgentType: getUserAgentType(userAgent),
- actor: {
- type: ActorType.USER,
- metadata: {
- email: user.email,
- userId: user.id,
- username: user.username
- }
- },
- event: {
- type: EventType.ORG_ADMIN_BYPASS_SSO,
- metadata: {}
- }
- });
-
- // Notify all admins via email (besides the actor)
- const orgAdmins = await orgDAL.findOrgMembersByRole(organizationId, OrgMembershipRole.Admin);
- const adminEmails = orgAdmins
- .filter((admin) => admin.user.id !== user.id)
- .map((admin) => admin.user.email)
- .filter(Boolean) as string[];
-
- if (adminEmails.length > 0) {
- await notificationService.createUserNotifications(
- orgAdmins
- .filter((admin) => admin.user.id !== user.id)
- .map((admin) => ({
- userId: admin.user.id,
- orgId: organizationId,
- type: NotificationType.ADMIN_SSO_BYPASS,
- title: "Security Alert: SSO Bypass",
- body: `The organization member **${user.email}** has bypassed enforced SSO login.`
- }))
- );
-
- await smtpService.sendMail({
- recipients: adminEmails,
- subjectLine: "Security Alert: SSO Bypass",
- substitutions: {
- email: user.email,
- timestamp: new Date().toISOString(),
- ip: ipAddress,
- userAgent,
- siteUrl: removeTrailingSlash(cfg.SITE_URL || "https://app.infisical.com"),
- orgId: organizationId
- },
- template: SmtpTemplates.OrgAdminBreakglassAccess
- });
- }
- }
-
- // Create audit log for organization selection
- if (isSubOrganization) {
- await auditLogService.createAuditLog({
- orgId: organizationId,
- ipAddress,
- userAgent,
- userAgentType: getUserAgentType(userAgent),
- actor: {
- type: ActorType.USER,
- metadata: {
- email: user.email,
- userId: user.id,
- username: user.username,
- authMethod: decodedToken.authMethod
- }
- },
- event: {
- type: EventType.SELECT_SUB_ORGANIZATION,
- metadata: {
- organizationId,
- organizationName: selectedOrg.name,
- rootOrganizationId: selectedOrg.rootOrgId || ""
- }
- }
- });
- } else {
- await auditLogService.createAuditLog({
- orgId: organizationId,
- ipAddress,
- userAgent,
- userAgentType: getUserAgentType(userAgent),
- actor: {
- type: ActorType.USER,
- metadata: {
- email: user.email,
- userId: user.id,
- username: user.username,
- authMethod: decodedToken.authMethod
- }
- },
- event: {
- type: EventType.SELECT_ORGANIZATION,
- metadata: {
- organizationId,
- organizationName: selectedOrg.name
- }
- }
- });
- }
- return {
- ...tokens,
- user,
- isMfaEnabled: false
- };
- };
-
- /*
- * Multi factor authentication re-send code, Get user id from token
- * saved in frontend
- */
- const resendMfaToken = async (userId: string) => {
- const user = await userDAL.findById(userId);
- if (!user || !user.email) return;
- enforceUserLockStatus(Boolean(user.isLocked), user.temporaryLockDateEnd);
- await sendUserMfaCode({
- userId: user.id,
- email: user.email
- });
- };
-
- 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
- * */
- const verifyMfaToken = async ({
- userId,
- mfaToken,
- mfaMethod,
- mfaJwtToken,
- ip,
- userAgent,
- orgId,
- isRecoveryCode = false
- }: TVerifyMfaTokenDTO) => {
- const appCfg = getConfig();
- const user = await userDAL.findById(userId);
-
- try {
- enforceUserLockStatus(Boolean(user.isLocked), user.temporaryLockDateEnd);
- if (mfaMethod === MfaMethod.EMAIL) {
- await tokenService.validateTokenForUser({
- type: TokenType.TOKEN_EMAIL_MFA,
- userId,
- code: mfaToken
- });
- } else if (mfaMethod === MfaMethod.TOTP) {
- if (isRecoveryCode) {
- await totpService.verifyWithUserRecoveryCode({
- userId,
- recoveryCode: mfaToken
- });
- } else {
- if (mfaToken.length !== 6) {
- throw new BadRequestError({
- message: "Please use a valid TOTP code."
- });
- }
- await totpService.verifyUserTotp({
- userId,
- totp: mfaToken
- });
- }
- } else if (mfaMethod === MfaMethod.WEBAUTHN) {
- if (!mfaToken) {
- throw new BadRequestError({
- message: "WebAuthn session token is required"
- });
- }
- // Validate the one-time WebAuthn session token (passed as mfaToken)
- await tokenService.validateTokenForUser({
- type: TokenType.TOKEN_WEBAUTHN_SESSION,
- userId,
- code: mfaToken
- });
- }
- } catch (err) {
- 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), 300, "1");
- }
- } catch (lockErr) {
- if (lock) {
- logger.error(lockErr, "Failed to send unlock email");
- }
- } finally {
- if (lock) {
- await lock.release();
- }
- }
- }
- }
-
- throw err;
- }
-
- const decodedToken = crypto.jwt().verify(mfaJwtToken, getConfig().AUTH_SECRET) as AuthModeMfaJwtTokenPayload;
-
- const userEnc = await userDAL.findUserEncKeyByUserId(userId);
- if (!userEnc) throw new Error("Failed to authenticate user");
+ const userEnc = await userDAL.findUserEncKeyByUserId(userId);
+ if (!userEnc) throw new Error("Failed to authenticate user");
// reset lock states
await userDAL.updateById(userId, {
@@ -978,10 +648,7 @@ export const authLoginServiceFactory = ({
});
const token = await generateUserTokens({
- user: {
- ...userEnc,
- id: userEnc.userId
- },
+ userId: user.id,
ip,
userAgent,
organizationId: orgId,
@@ -1262,172 +929,354 @@ export const authLoginServiceFactory = ({
}
}
- const isUserCompleted = user.isAccepted;
- const providerAuthToken = crypto.jwt().sign(
- {
- authTokenType: AuthTokenType.PROVIDER_TOKEN,
- userId: user.id,
+ const isUserCompleted = user.isAccepted;
+ const providerAuthToken = crypto.jwt().sign(
+ {
+ authTokenType: AuthTokenType.PROVIDER_TOKEN,
+ userId: user.id,
+
+ ...(orgId && orgSlug && orgName !== undefined
+ ? {
+ organizationId: orgId,
+ organizationName: orgName,
+ organizationSlug: orgSlug
+ }
+ : {}),
+
+ username: user.username,
+ email: user.email,
+ isEmailVerified: user.isEmailVerified,
+ firstName: user.firstName,
+ lastName: user.lastName,
+ hasExchangedPrivateKey: true,
+ authMethod,
+ isUserCompleted,
+ ...(callbackPort
+ ? {
+ callbackPort
+ }
+ : {})
+ },
+ appCfg.AUTH_SECRET,
+ {
+ expiresIn: appCfg.JWT_PROVIDER_AUTH_LIFETIME
+ }
+ );
+
+ return { isUserCompleted, providerAuthToken, user, orgId, orgName };
+ };
+
+ /*
+ * logout user by incrementing the version by 1 meaning any old session will become invalid
+ * as there number is behind
+ * */
+ const logout = async (userId: string, sessionId: string) => {
+ await tokenService.clearTokenSessionById(userId, sessionId);
+ };
+
+ const selectOrganization = async ({
+ userAgent,
+ authJwtToken,
+ ipAddress,
+ organizationId
+ }: {
+ userAgent: string | undefined;
+ authJwtToken: string | undefined;
+ ipAddress: string;
+ organizationId: string;
+ }) => {
+ const cfg = getConfig();
+
+ if (!authJwtToken) throw new UnauthorizedError({ name: "Authorization header is required" });
+ if (!userAgent) throw new UnauthorizedError({ name: "User-Agent header is required" });
+
+ // eslint-disable-next-line no-param-reassign
+ authJwtToken = authJwtToken.replace("Bearer ", ""); // remove bearer from token
+
+ // The decoded JWT token, which contains the auth method.
+ const decodedToken = crypto.jwt().verify(authJwtToken, cfg.AUTH_SECRET) as AuthModeJwtTokenPayload;
+ if (!decodedToken.authMethod) throw new UnauthorizedError({ name: "Auth method not found on existing token" });
+
+ const user = await userDAL.findById(decodedToken.userId);
+ if (!user || !user.isAccepted)
+ throw new BadRequestError({ message: "User not found", name: "Find user from token" });
+
+ // Check user membership in the sub-organization (direct or via group)
+ const orgMembership = await orgDAL.findEffectiveOrgMembership({
+ actorType: ActorType.USER,
+ actorId: user.id,
+ orgId: organizationId,
+ status: OrgMembershipStatus.Accepted
+ });
+
+ if (!orgMembership) {
+ throw new ForbiddenRequestError({
+ message: `User does not have access to the organization with ID ${organizationId}`
+ });
+ }
+
+ const selectedOrg = await orgDAL.findById(organizationId);
+ if (!selectedOrg) {
+ throw new NotFoundError({ message: `Organization with ID '${organizationId}' not found` });
+ }
- ...(orgId && orgSlug && orgName !== undefined
- ? {
- organizationId: orgId,
- organizationName: orgName,
- organizationSlug: orgSlug
- }
- : {}),
+ const isSubOrganization = Boolean(selectedOrg.rootOrgId && selectedOrg.id !== selectedOrg.rootOrgId);
- username: user.username,
- email: user.email,
- isEmailVerified: user.isEmailVerified,
- firstName: user.firstName,
- lastName: user.lastName,
- hasExchangedPrivateKey: true,
- authMethod,
- isUserCompleted,
- ...(callbackPort
- ? {
- callbackPort
- }
- : {})
- },
- appCfg.AUTH_SECRET,
- {
- expiresIn: appCfg.JWT_PROVIDER_AUTH_LIFETIME
+ let rootOrg = selectedOrg;
+
+ if (isSubOrganization) {
+ if (!selectedOrg.rootOrgId) {
+ throw new BadRequestError({
+ message: "Invalid sub-organization"
+ });
}
- );
- return { isUserCompleted, providerAuthToken, user, orgId, orgName };
- };
+ rootOrg = await orgDAL.findById(selectedOrg.rootOrgId);
+ if (!rootOrg) {
+ throw new BadRequestError({
+ message: "Invalid sub-organization"
+ });
+ }
- /**
- * Handles OAuth2 token exchange for user login with private key handoff.
- *
- * The process involves exchanging a provider's authorization token for an Infisical access token.
- * The provider token is returned to the client, who then sends it back to obtain the Infisical access token.
- *
- * This approach is used instead of directly sending the access token for the following reasons:
- * 1. To facilitate easier logic changes from SRP OAuth to simple OAuth.
- * 2. To avoid attaching the access token to the URL, which could be logged. The provider token has a very short lifespan, reducing security risks.
- */
- const oauth2TokenExchange = async ({ userAgent, ip, providerAuthToken, email }: TOauthTokenExchangeDTO) => {
- const appCfg = getConfig();
- const decodedProviderToken = validateProviderAuthToken(providerAuthToken, email);
+ // Check user membership in the root organization
+ const rootOrgMembership = await membershipUserDAL.findOne({
+ actorUserId: user.id,
+ scopeOrgId: selectedOrg.rootOrgId,
+ scope: AccessScope.Organization,
+ status: OrgMembershipStatus.Accepted
+ });
- const { authMethod, userName } = decodedProviderToken;
- if (!userName) throw new BadRequestError({ message: "Missing user name" });
- const organizationId =
- (isAuthMethodSaml(authMethod) || [AuthMethod.LDAP, AuthMethod.OIDC].includes(authMethod)) &&
- decodedProviderToken.orgId
- ? decodedProviderToken.orgId
- : undefined;
+ if (!rootOrgMembership) {
+ throw new ForbiddenRequestError({
+ message: "User does not have access to the root organization"
+ });
+ }
+ }
- // akhilmhdh: case sensitive email resolution
- const usersByUsername = await userDAL.findUserEncKeyByUsername({
- username: email
+ const { permission } = await permissionService.getOrgPermission({
+ actor: ActorType.USER,
+ actorId: user.id,
+ orgId: rootOrg.id,
+ actorAuthMethod: decodedToken.authMethod,
+ actorOrgId: rootOrg.id,
+ scope: OrganizationActionScope.Any
});
- const userEnc =
- usersByUsername?.length > 1 ? usersByUsername.find((el) => el.username === email) : usersByUsername?.[0];
+ const canBypassSso =
+ rootOrg.bypassOrgAuthEnabled &&
+ permission.can(OrgPermissionSsoActions.BypassSsoEnforcement, OrgPermissionSubjects.Sso);
+
+ if (
+ rootOrg.authEnforced &&
+ !isAuthMethodSaml(decodedToken.authMethod) &&
+ decodedToken.authMethod !== AuthMethod.OIDC &&
+ !canBypassSso
+ ) {
+ throw new BadRequestError({
+ message: "Login with the auth method required by your organization."
+ });
+ }
- if (!userEnc) throw new BadRequestError({ message: "User encryption not found" });
+ if (rootOrg.googleSsoAuthEnforced && decodedToken.authMethod !== AuthMethod.GOOGLE) {
+ if (!canBypassSso) {
+ throw new ForbiddenRequestError({
+ message: "Google SSO is enforced for this organization. Please use Google SSO to login.",
+ error: "GoogleSsoEnforced"
+ });
+ }
+ }
- // Check MFA before issuing tokens — mirrors the logic in selectOrganization
- const user = await userDAL.findById(userEnc.userId);
- const org = organizationId ? await orgDAL.findById(organizationId) : null;
- // for now check mfa in this state when your token is org scoped. If not we will do it in select org step
- const shouldCheckMfa = org?.enforceMfa || user?.isMfaEnabled;
+ if (decodedToken.authMethod === AuthMethod.GOOGLE) {
+ await orgDAL.updateById(rootOrg.id, {
+ googleSsoAuthLastUsed: new Date()
+ });
+ }
- if (shouldCheckMfa && organizationId) {
+ const isOrgMfaEnforced = rootOrg.enforceMfa;
+ const isUserMfaEnabled = user.isMfaEnabled;
+ const isMfaRequired = isOrgMfaEnforced || isUserMfaEnabled;
+ // Determine which MFA method should be used (org takes precedence)
+ const requiredMfaMethod = isOrgMfaEnforced
+ ? (rootOrg.selectedMfaMethod ?? MfaMethod.EMAIL)
+ : (user.selectedMfaMethod ?? MfaMethod.EMAIL);
+ // Check if organization has changed
+ const hasOrganizationChanged = decodedToken.organizationId !== rootOrg.id;
+ // Check if MFA method has changed
+ const hasMfaMethodChanged = decodedToken.mfaMethod !== requiredMfaMethod;
+ // Trigger MFA if required and either not verified or something changed
+ const shouldTriggerMfa =
+ isMfaRequired && (!decodedToken.isMfaVerified || hasMfaMethodChanged || hasOrganizationChanged);
+
+ if (shouldTriggerMfa) {
enforceUserLockStatus(Boolean(user.isLocked), user.temporaryLockDateEnd);
- const orgMfaMethod = org?.enforceMfa ? (org.selectedMfaMethod ?? MfaMethod.EMAIL) : undefined;
- const userMfaMethod = user.isMfaEnabled ? (user.selectedMfaMethod ?? MfaMethod.EMAIL) : undefined;
- const mfaMethod = orgMfaMethod ?? userMfaMethod;
-
const mfaToken = crypto.jwt().sign(
{
- authMethod,
+ authMethod: decodedToken.authMethod,
authTokenType: AuthTokenType.MFA_TOKEN,
- userId: userEnc.userId,
- organizationId
+ userId: user.id
},
- appCfg.AUTH_SECRET,
+ cfg.AUTH_SECRET,
{
- expiresIn: appCfg.JWT_MFA_LIFETIME
+ expiresIn: cfg.JWT_MFA_LIFETIME
}
);
- if (mfaMethod === MfaMethod.EMAIL && userEnc.email) {
+ if (requiredMfaMethod === MfaMethod.EMAIL && user.email) {
await sendUserMfaCode({
- userId: userEnc.userId,
- email: userEnc.email
+ userId: user.id,
+ email: user.email
});
}
- return {
- token: { access: mfaToken, refresh: "" },
- isMfaEnabled: true,
- mfaMethod,
- user: userEnc,
- decodedProviderToken
- } as const;
+ return { isMfaEnabled: true, mfa: mfaToken, mfaMethod: requiredMfaMethod } as const;
}
- const token = await generateUserTokens({
- user: { ...userEnc, id: userEnc.userId },
- ip,
+ await updateUserDeviceSession(user, ipAddress, userAgent);
+
+ const tokens = await generateUserTokens({
+ authMethod: decodedToken.authMethod,
+ userId: user.id,
userAgent,
- authMethod,
- organizationId
+ ip: ipAddress,
+ organizationId: isSubOrganization ? rootOrg.id : organizationId,
+ subOrganizationId: isSubOrganization ? organizationId : undefined,
+ isMfaVerified: decodedToken.isMfaVerified,
+ mfaMethod: decodedToken.mfaMethod
});
- if (organizationId) {
+ // In the event of this being a break-glass request (non-saml / non-oidc / non-google, when any is enforced)
+ const isAuthEnforcedBypass =
+ rootOrg.authEnforced &&
+ rootOrg.bypassOrgAuthEnabled &&
+ !isAuthMethodSaml(decodedToken.authMethod) &&
+ decodedToken.authMethod !== AuthMethod.OIDC &&
+ decodedToken.authMethod !== AuthMethod.GOOGLE;
+ const isGoogleSsoEnforcedBypass =
+ rootOrg.googleSsoAuthEnforced && rootOrg.bypassOrgAuthEnabled && decodedToken.authMethod !== AuthMethod.GOOGLE;
+ if (isAuthEnforcedBypass || isGoogleSsoEnforcedBypass) {
+ await auditLogService.createAuditLog({
+ orgId: organizationId,
+ ipAddress,
+ userAgent,
+ userAgentType: getUserAgentType(userAgent),
+ actor: {
+ type: ActorType.USER,
+ metadata: {
+ email: user.email,
+ userId: user.id,
+ username: user.username
+ }
+ },
+ event: {
+ type: EventType.ORG_ADMIN_BYPASS_SSO,
+ metadata: {}
+ }
+ });
+
+ // Notify all admins via email (besides the actor)
+ const orgAdmins = await orgDAL.findOrgMembersByRole(organizationId, OrgMembershipRole.Admin);
+ const adminEmails = orgAdmins
+ .filter((admin) => admin.user.id !== user.id)
+ .map((admin) => admin.user.email)
+ .filter(Boolean) as string[];
+
+ if (adminEmails.length > 0) {
+ await notificationService.createUserNotifications(
+ orgAdmins
+ .filter((admin) => admin.user.id !== user.id)
+ .map((admin) => ({
+ userId: admin.user.id,
+ orgId: organizationId,
+ type: NotificationType.ADMIN_SSO_BYPASS,
+ title: "Security Alert: SSO Bypass",
+ body: `The organization member **${user.email}** has bypassed enforced SSO login.`
+ }))
+ );
+
+ await smtpService.sendMail({
+ recipients: adminEmails,
+ subjectLine: "Security Alert: SSO Bypass",
+ substitutions: {
+ email: user.email,
+ timestamp: new Date().toISOString(),
+ ip: ipAddress,
+ userAgent,
+ siteUrl: removeTrailingSlash(cfg.SITE_URL || "https://app.infisical.com"),
+ orgId: organizationId
+ },
+ template: SmtpTemplates.OrgAdminBreakglassAccess
+ });
+ }
+ }
+
+ // Create audit log for organization selection
+ if (isSubOrganization) {
+ await auditLogService.createAuditLog({
+ orgId: organizationId,
+ ipAddress,
+ userAgent,
+ userAgentType: getUserAgentType(userAgent),
+ actor: {
+ type: ActorType.USER,
+ metadata: {
+ email: user.email,
+ userId: user.id,
+ username: user.username,
+ authMethod: decodedToken.authMethod
+ }
+ },
+ event: {
+ type: EventType.SELECT_SUB_ORGANIZATION,
+ metadata: {
+ organizationId,
+ organizationName: selectedOrg.name,
+ rootOrganizationId: selectedOrg.rootOrgId || ""
+ }
+ }
+ });
+ } else {
await auditLogService.createAuditLog({
orgId: organizationId,
- ipAddress: ip,
+ ipAddress,
userAgent,
userAgentType: getUserAgentType(userAgent),
actor: {
type: ActorType.USER,
metadata: {
- email: userEnc.email,
- userId: userEnc.userId,
- username: userEnc.username,
- authMethod: decodedProviderToken.authMethod
+ email: user.email,
+ userId: user.id,
+ username: user.username,
+ authMethod: decodedToken.authMethod
}
},
event: {
- type: EventType.USER_LOGIN,
+ type: EventType.SELECT_ORGANIZATION,
metadata: {
organizationId,
- ...(isAuthMethodSaml(decodedProviderToken.authMethod) && {
- authProvider: decodedProviderToken.authMethod
- })
+ organizationName: selectedOrg.name
}
}
});
}
- return { token, isMfaEnabled: false, user: userEnc, decodedProviderToken } as const;
- };
-
- /*
- * logout user by incrementing the version by 1 meaning any old session will become invalid
- * as there number is behind
- * */
- const logout = async (userId: string, sessionId: string) => {
- await tokenService.clearTokenSessionById(userId, sessionId);
+ return {
+ ...tokens,
+ user,
+ isMfaEnabled: false
+ };
};
return {
- loginGenServerPublicKey,
- loginExchangeClientProof,
+ login,
logout,
oauth2Login,
- oauth2TokenExchange,
resendMfaToken,
verifyMfaToken,
selectOrganization,
generateUserTokens,
- login
+
+ // deprecated completely
+ loginGenServerPublicKey,
+ loginExchangeClientProof
};
};