Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
feat(auth): reapply and adapt #6029 to match the new auth system (#6072)
Matheus Nogueira2b788013ba8d
diff --git a/backend/src/services/auth/auth-login-service.ts b/backend/src/services/auth/auth-login-service.tsindex b8c5cf8fca..8c86549a1f 100644--- a/backend/src/services/auth/auth-login-service.ts+++ b/backend/src/services/auth/auth-login-service.ts@@ -38,7 +38,7 @@ import { TNotificationServiceFactory } from "../notification/notification-servicimport { NotificationType } from "../notification/notification-types";import { TOrgDALFactory } from "../org/org-dal";import { getDefaultOrgMembershipRole } from "../org/org-role-fns";-import { SmtpTemplates, TSmtpService } from "../smtp/smtp-service";+import { SmtpTemplates, throwIfSmtpError, 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";@@ -115,17 +115,19 @@ export const authLoginServiceFactory = ({]);if (user.email) {- await smtpService.sendMail({- template: SmtpTemplates.NewDeviceJoin,- subjectLine: "Successful login from new device",- recipients: [user.email],- substitutions: {- email: user.email,- timestamp: new Date().toString(),- ip,- userAgent- }- });+ await smtpService+ .sendMail({+ template: SmtpTemplates.NewDeviceJoin,+ subjectLine: "Successful login from new device",+ recipients: [user.email],+ substitutions: {+ email: user.email,+ timestamp: new Date().toString(),+ ip,+ userAgent+ }+ })+ .catch((err) => logger.error(err, "Failed to send new device login email"));}}};@@ -140,14 +142,16 @@ export const authLoginServiceFactory = ({userId});- await smtpService.sendMail({- template: SmtpTemplates.EmailMfa,- subjectLine: "Infisical MFA code",- recipients: [email],- substitutions: {- code- }- });+ await smtpService+ .sendMail({+ template: SmtpTemplates.EmailMfa,+ subjectLine: "Infisical MFA code",+ recipients: [email],+ substitutions: {+ code+ }+ })+ .catch((err) => throwIfSmtpError(err, "Failed to send MFA code email"));};/*@@ -1314,19 +1318,21 @@ export const authLoginServiceFactory = ({})));- 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- });+ 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+ })+ .catch((err) => logger.error(err, "Failed to send SSO bypass alert email"));}}diff --git a/backend/src/services/auth/auth-signup-service.ts b/backend/src/services/auth/auth-signup-service.tsindex 2025ed5759..23c2c98b91 100644--- a/backend/src/services/auth/auth-signup-service.ts+++ b/backend/src/services/auth/auth-signup-service.ts@@ -2,13 +2,14 @@ import { AccessScope, OrgMembershipStatus } from "@app/db/schemas";import { getConfig } from "@app/lib/config/env";import { crypto } from "@app/lib/crypto/cryptography";import { BadRequestError, UnauthorizedError } from "@app/lib/errors";+import { logger } from "@app/lib/logger";import { isDisposableEmail, sanitizeEmail, validateEmail } from "@app/lib/validator";import { TAuthTokenServiceFactory } from "../auth-token/auth-token-service";import { TokenType } from "../auth-token/auth-token-types";import { TOrgDALFactory } from "../org/org-dal";import { TOrgServiceFactory } from "../org/org-service";-import { SmtpTemplates, TSmtpService } from "../smtp/smtp-service";+import { SmtpTemplates, throwIfSmtpError, TSmtpService } from "../smtp/smtp-service";import { TUserDALFactory } from "../user/user-dal";import { TUserAliasDALFactory } from "../user-alias/user-alias-dal";import { TAuthDALFactory } from "./auth-dal";@@ -56,16 +57,20 @@ export const authSignupServiceFactory = ({// Send informational email for existing accounts instead of throwing error// This prevents user enumeration vulnerabilityconst appCfg = getConfig();- await smtpService.sendMail({- template: SmtpTemplates.SignupExistingAccount,- subjectLine: "Sign-up Request for Your Infisical Account",- recipients: [sanitizedEmail],- substitutions: {- email: sanitizedEmail,- loginUrl: `${appCfg.SITE_URL}/login`,- resetPasswordUrl: `${appCfg.SITE_URL}/account-recovery`- }- });+ await smtpService+ .sendMail({+ template: SmtpTemplates.SignupExistingAccount,+ subjectLine: "Sign-up Request for Your Infisical Account",+ recipients: [sanitizedEmail],+ substitutions: {+ email: sanitizedEmail,+ loginUrl: `${appCfg.SITE_URL}/login`,+ resetPasswordUrl: `${appCfg.SITE_URL}/account-recovery`+ }+ })+ .catch((err) =>+ logger.error(err, "Failed to send existing account email — swallowing to prevent user enumeration")+ );return;}@@ -84,14 +89,16 @@ export const authSignupServiceFactory = ({userId: user.id});- await smtpService.sendMail({- template: SmtpTemplates.SignupEmailVerification,- subjectLine: "Infisical confirmation code",- recipients: [sanitizedEmail],- substitutions: {- code: token- }- });+ await smtpService+ .sendMail({+ template: SmtpTemplates.SignupEmailVerification,+ subjectLine: "Infisical confirmation code",+ recipients: [sanitizedEmail],+ substitutions: {+ code: token+ }+ })+ .catch((err) => throwIfSmtpError(err, "Failed to send signup verification email"));};const verifyEmailSignup = async (email: string, code: string) => {diff --git a/backend/src/services/smtp/smtp-service.ts b/backend/src/services/smtp/smtp-service.tsindex 3449029836..cbdc8cde5b 100644--- a/backend/src/services/smtp/smtp-service.ts+++ b/backend/src/services/smtp/smtp-service.ts@@ -4,6 +4,7 @@ import SMTPTransport from "nodemailer/lib/smtp-transport";import React from "react";import { getConfig } from "@app/lib/config/env";+import { InternalServerError } from "@app/lib/errors";import { logger } from "@app/lib/logger";import {@@ -212,3 +213,16 @@ export const smtpServiceFactory = (cfg: TSmtpConfig) => {return { sendMail, verify };};++export const throwIfSmtpError = (err: unknown, logMessage: string) => {+ logger.error(err, logMessage);+ const { isCloud } = getConfig();+ // We must always throw so the user is not left waiting for an email that never arrives.+ // On cloud, we show a generic message to avoid exposing internal misconfiguration details.+ throw new InternalServerError({+ message: isCloud+ ? "We could not send you an email. Please try again later."+ : "Failed to send email. This is likely due to a misconfigured SMTP server. Please check your SMTP settings and try again.",+ name: "SmtpError"+ });+};diff --git a/frontend/src/pages/auth/LoginPage/components/InitialStep/InitialStep.tsx b/frontend/src/pages/auth/LoginPage/components/InitialStep/InitialStep.tsxindex 9057c0f53d..4d66eca9e0 100644--- a/frontend/src/pages/auth/LoginPage/components/InitialStep/InitialStep.tsx+++ b/frontend/src/pages/auth/LoginPage/components/InitialStep/InitialStep.tsx@@ -190,10 +190,6 @@ export const InitialStep = ({ setSection, isAdmin }: Props) => {if (isLoginSuccessful) {saveLastLogin({ method: LoginMethod.EMAIL });navigateToSelectOrganization(callbackPort || undefined, isAdmin);- createNotification({- text: "Successfully logged in",- type: "success"- });} else {handleLoginFailure();}diff --git a/frontend/src/pages/auth/SelectOrgPage/SelectOrgPage.tsx b/frontend/src/pages/auth/SelectOrgPage/SelectOrgPage.tsxindex 450684487c..36c47066d9 100644--- a/frontend/src/pages/auth/SelectOrgPage/SelectOrgPage.tsx+++ b/frontend/src/pages/auth/SelectOrgPage/SelectOrgPage.tsx@@ -190,6 +190,11 @@ export const SelectOrgPage = () => {isMfaEnabled = result.isMfaEnabled;mfaMethod = result.mfaMethod;} catch (error: any) {+ if (error?.response?.data?.error === "SmtpError") {+ // Global MutationCache.onError already showed the SMTP error toast — just log out silently.+ await handleLogout();+ return;+ }const message = error?.response?.data?.message || "Failed to select organization.";createNotification({ text: message, type: "error" });return;@@ -235,6 +240,7 @@ export const SelectOrgPage = () => {navigate({ to: "/cli-redirect" });} else {setAuthToken(token);+ createNotification({ text: "Successfully logged in", type: "success" });navigateUserToOrg({ navigate, organizationId: targetOrgId });}};diff --git a/frontend/src/pages/auth/SelectOrgPage/route.tsx b/frontend/src/pages/auth/SelectOrgPage/route.tsxindex 617bc67449..7b46bba999 100644--- a/frontend/src/pages/auth/SelectOrgPage/route.tsx+++ b/frontend/src/pages/auth/SelectOrgPage/route.tsx@@ -3,15 +3,16 @@ import { zodValidator } from "@tanstack/zod-adapter";import { addSeconds, formatISO } from "date-fns";import { z } from "zod";+import { createNotification } from "@app/components/notifications";import { SessionStorageKeys } from "@app/const";-import { selectOrganization } from "@app/hooks/api/auth/queries";+import { authKeys, selectOrganization } from "@app/hooks/api/auth/queries";import { UserAgentType } from "@app/hooks/api/auth/types";import {fetchOrganizationsWithSubOrgs,organizationKeys} from "@app/hooks/api/organization/queries";-import { setAuthToken } from "@app/hooks/api/reactQuery";-import { fetchUserDetails } from "@app/hooks/api/users/queries";+import { onRequestError, setAuthToken } from "@app/hooks/api/reactQuery";+import { fetchUserDetails, logoutUser } from "@app/hooks/api/users/queries";import { SelectOrgPage } from "./SelectOrgPage";@@ -98,6 +99,7 @@ export const Route = createFileRoute("/_restrict-login-signup/login/select-organ}setAuthToken(result.token);+ createNotification({ text: "Successfully logged in", type: "success" });throw redirect({to: "/organizations/$orgId/projects",params: { orgId }@@ -109,7 +111,26 @@ export const Route = createFileRoute("/_restrict-login-signup/login/select-organif (error instanceof Error && error.message === "REDIRECT") throw error;// For redirect objects from TanStack Routerif (typeof error === "object" && error !== null && "to" in error) throw error;- // Otherwise let the page render and handle errors+ // selectOrganization is called directly (not via mutation hook), so MutationCache.onError+ // never fires for it — surface SMTP errors manually and log the user out.+ if (typeof error === "object" && error !== null && "response" in error) {+ const { response } = error as {+ response?: { data?: { error?: string; message?: string } };+ };+ if (response?.data?.error === "SmtpError") {+ onRequestError(error);+ // We can't use the useLogoutUser hook here (beforeLoad runs outside React),+ // so we replicate its mutationFn manually:+ // - setAuthToken("") stops outgoing requests from carrying the stale token.+ // - removeQueries drops the cached auth token so the restrict-login-signup+ // middleware doesn't find it and redirect back to select-organization.+ // - logoutUser() invalidates the session on the server.+ setAuthToken("");+ context.queryClient.removeQueries({ queryKey: authKeys.getAuthToken });+ await logoutUser().catch(() => {}); // best-effort — redirect must always fire+ throw redirect({ to: "/login" });+ }+ }}}});