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
improvement: send email on email change account exists
Scott Wilson40dc71b6b858
diff --git a/backend/src/services/smtp/emails/EmailChangeExistingAccountTemplate.tsx b/backend/src/services/smtp/emails/EmailChangeExistingAccountTemplate.tsxnew file mode 100644index 0000000000..2f98fac08d--- /dev/null+++ b/backend/src/services/smtp/emails/EmailChangeExistingAccountTemplate.tsx@@ -0,0 +1,69 @@+import { Heading, Section, Text } from "@react-email/components";+import React from "react";++import { BaseEmailWrapper, BaseEmailWrapperProps } from "./BaseEmailWrapper";+import { BaseLink } from "./BaseLink";++interface EmailChangeExistingAccountTemplateProps+ extends Omit<BaseEmailWrapperProps, "title" | "preview" | "children"> {+ email: string;+ isCloud: boolean;+}++export const EmailChangeExistingAccountTemplate = ({+ email,+ siteUrl,+ isCloud+}: EmailChangeExistingAccountTemplateProps) => {+ return (+ <BaseEmailWrapper+ title="Email Change Request Received"+ preview="An email change was requested for an address that already has an Infisical account."+ siteUrl={siteUrl}+ >+ <Heading className="text-black text-[18px] leading-[28px] text-center font-normal p-0 mx-0">+ <strong>Email Change Request Received</strong>+ </Heading>+ <Section className="px-[24px] mt-[36px] pt-[12px] pb-[8px] text-[14px] border border-solid border-gray-200 rounded-md bg-gray-50">+ <Text className="text-[14px]">+ A request was made to change the email address of an Infisical account to <strong>{email}</strong>.+ </Text>+ <Text className="text-[14px]">+ Because this address already belongs to an existing Infisical account, the change was not completed. No+ verification code was sent and no accounts have been modified.+ </Text>+ <Text className="text-[14px]">+ If this was you trying to move another of your accounts to this address, first delete the account that+ currently uses this address from Personal Settings (or pick a different address), then request the email+ change again.+ </Text>+ </Section>+ <Section className="px-[24px] mb-[28px] mt-[28px] pt-[12px] pb-[8px] border border-solid border-gray-200 rounded-md bg-gray-50">+ <Text className="text-[14px]">+ If you did not request this, you can safely ignore this message. Your account is unaffected.+ </Text>+ </Section>+ <Section className="mt-[24px] bg-gray-50 pt-[2px] pb-[16px] border border-solid border-gray-200 px-[24px] rounded-md text-gray-800">+ <Text className="mb-[0px]">+ <strong>Need help?</strong>{" "}+ {isCloud ? (+ <>+ Contact us at <BaseLink href="mailto:[email protected]">[email protected]</BaseLink>+ </>+ ) : (+ "Contact your administrator"+ )}+ .+ </Text>+ </Section>+ </BaseEmailWrapper>+ );+};++export default EmailChangeExistingAccountTemplate;++EmailChangeExistingAccountTemplate.PreviewProps = {+ email: "[email protected]",+ isCloud: true,+ siteUrl: "https://infisical.com"+} as EmailChangeExistingAccountTemplateProps;diff --git a/backend/src/services/smtp/emails/index.ts b/backend/src/services/smtp/emails/index.tsindex ec25b70835..08c62104b2 100644--- a/backend/src/services/smtp/emails/index.ts+++ b/backend/src/services/smtp/emails/index.ts@@ -6,6 +6,7 @@ export * from "./AccountDeletionConfirmationTemplate";export * from "./AuditLogMigrationAlertTemplate";export * from "./AuditReportTemplate";export * from "./CredentialRotationFailedTemplate";+export * from "./EmailChangeExistingAccountTemplate";export * from "./EmailChangeRequestNotificationTemplate";export * from "./EmailMfaTemplate";export * from "./EmailVerificationTemplate";diff --git a/backend/src/services/smtp/smtp-service.ts b/backend/src/services/smtp/smtp-service.tsindex 1d5e767a55..08e806d4de 100644--- a/backend/src/services/smtp/smtp-service.ts+++ b/backend/src/services/smtp/smtp-service.ts@@ -16,6 +16,7 @@ import {AuditLogMigrationAlertTemplate,AuditReportTemplate,CredentialRotationFailedTemplate,+ EmailChangeExistingAccountTemplate,EmailChangeRequestNotificationTemplate,EmailMfaTemplate,EmailVerificationTemplate,@@ -77,6 +78,7 @@ export enum SmtpTemplates {SignupExistingAccount = "signupExistingAccount",EmailVerification = "emailVerification",EmailChangeRequestNotification = "emailChangeRequestNotification",+ EmailChangeExistingAccount = "emailChangeExistingAccount",SecretReminder = "secretReminder",EmailMfa = "emailMfa",MfaRecoveryCodeUsed = "mfaRecoveryCodeUsed",@@ -146,6 +148,7 @@ const EmailTemplateMap: Record<SmtpTemplates, React.FC<any>> = {[SmtpTemplates.AccessApprovalRequestUpdated]: AccessApprovalRequestUpdatedTemplate,[SmtpTemplates.EmailVerification]: EmailVerificationTemplate,[SmtpTemplates.EmailChangeRequestNotification]: EmailChangeRequestNotificationTemplate,+ [SmtpTemplates.EmailChangeExistingAccount]: EmailChangeExistingAccountTemplate,[SmtpTemplates.ExternalImportFailed]: ExternalImportFailedTemplate,[SmtpTemplates.ExternalImportStarted]: ExternalImportStartedTemplate,[SmtpTemplates.ExternalImportSuccessful]: ExternalImportSucceededTemplate,diff --git a/backend/src/services/user/user-service.ts b/backend/src/services/user/user-service.tsindex de98cd1c95..6c6f66a08d 100644--- a/backend/src/services/user/user-service.ts+++ b/backend/src/services/user/user-service.ts@@ -32,6 +32,17 @@ import {TVerifyCurrentEmailOTPDTO} from "./user-types";+// Enforce a minimum execution time so response timing cannot disclose whether an email+// address already has an account.+const enforceMinimumExecutionTime = async (startTime: Date, minimumMs = 2000) => {+ const elapsedMs = new Date().getTime() - startTime.getTime();+ if (elapsedMs < minimumMs) {+ await new Promise((resolve) => {+ setTimeout(resolve, minimumMs - elapsedMs);+ });+ }+};+type TUserServiceFactoryDep = {userDAL: Pick<TUserDALFactory,@@ -288,6 +299,13 @@ export const userServiceFactory = ({});}+ if (normalizedNewEmail === user.email.toLowerCase() || normalizedNewEmail === user.username.toLowerCase()) {+ throw new BadRequestError({+ message: "The new email address must be different from your current email address.",+ name: "RequestEmailChangeOTP"+ });+ }+const hasScimRestriction = await checkUserScimRestriction(userId, tx);if (hasScimRestriction) {throw new BadRequestError({@@ -296,44 +314,39 @@ export const userServiceFactory = ({});}- // Silently check if another user already has this email - don't send OTP if email is taken- const existingUser = await userDAL.findOne({ username: normalizedNewEmail }, tx);- if (!existingUser) {- // Step 1 of 2: send OTP to the CURRENT email so the legitimate owner must approve- // the change before any code is sent to the new address.- const otpCode = await tokenService.createTokenForUser({- type: TokenType.TOKEN_EMAIL_CHANGE_CURRENT_OTP,- userId,- payload: newEmail.toLowerCase()- });+ // Availability of the requested address is deliberately NOT checked here: step 1+ // behaves identically whether or not the address is taken (anti-enumeration). The+ // outcome is only ever disclosed to the requested address itself, in step 2.- await smtpService.sendMail({- template: SmtpTemplates.EmailChangeRequestNotification,- subjectLine: "Confirm your Infisical email change",- recipients: [user.email],- substitutions: {- currentEmail: user.email,- requestedEmail: newEmail.toLowerCase(),- code: otpCode- }- });- }+ // Step 1 of 2: send OTP to the CURRENT email so the legitimate owner must approve+ // the change before anything is sent to the new address.+ const otpCode = await tokenService.createTokenForUser({+ type: TokenType.TOKEN_EMAIL_CHANGE_CURRENT_OTP,+ userId,+ payload: newEmail.toLowerCase()+ });++ await smtpService.sendMail({+ template: SmtpTemplates.EmailChangeRequestNotification,+ subjectLine: "Confirm your Infisical email change",+ recipients: [user.email],+ substitutions: {+ currentEmail: user.email,+ requestedEmail: newEmail.toLowerCase(),+ code: otpCode+ }+ });return { success: true, message: "Verification code sent to current email address" };});- // Force this function to have a minimum execution time of 2 seconds to avoid possible information disclosure about existing users- const endTime = new Date();- const timeDiff = endTime.getTime() - startTime.getTime();- if (timeDiff < 2000) {- await new Promise((resolve) => {- setTimeout(resolve, 2000 - timeDiff);- });- }+ // Keep response timing uniform so it cannot disclose anything about existing users+ await enforceMinimumExecutionTime(startTime);return changeEmailOTP;};const verifyCurrentEmailOTP = async ({ userId, otpCode }: TVerifyCurrentEmailOTPDTO) => {- return userDAL.transaction(async (tx) => {+ const startTime = new Date();+ const result = await userDAL.transaction(async (tx) => {const user = await userDAL.findById(userId, tx);if (!user)throw new NotFoundError({ message: `User with ID '${userId}' not found`, name: "VerifyCurrentEmailOTP" });@@ -366,30 +379,44 @@ export const userServiceFactory = ({throw new BadRequestError({ message: "Invalid verification code", name: "VerifyCurrentEmailOTP" });}- // Re-check availability — someone else may have claimed this email since the request was issued+ // Step 2 of 2: current-email control is proven, so only now is availability of the+ // requested address consulted. The API response stays identical whether the address+ // is taken or free (anti-enumeration); the outcome is disclosed only to the requested+ // address itself: a verification code if it is free, or an explanatory notice if it+ // already belongs to an account (its owner is the one party who already knows that+ // account exists).const existingUser = await userDAL.findOne({ username: newEmail }, tx);if (existingUser) {- throw new BadRequestError({ message: "Email is no longer available", name: "VerifyCurrentEmailOTP" });- }-- // Step 2 of 2: now that current-email control is proven, send OTP to the NEW address- const newEmailOtpCode = await tokenService.createTokenForUser({- type: TokenType.TOKEN_EMAIL_CHANGE_OTP,- userId,- payload: newEmail- });+ await smtpService.sendMail({+ template: SmtpTemplates.EmailChangeExistingAccount,+ subjectLine: "Email Change Request for Your Infisical Account",+ recipients: [newEmail],+ substitutions: {+ email: newEmail+ }+ });+ } else {+ const newEmailOtpCode = await tokenService.createTokenForUser({+ type: TokenType.TOKEN_EMAIL_CHANGE_OTP,+ userId,+ payload: newEmail+ });- await smtpService.sendMail({- template: SmtpTemplates.EmailVerification,- subjectLine: "Infisical email change verification",- recipients: [newEmail],- substitutions: {- code: newEmailOtpCode- }- });+ await smtpService.sendMail({+ template: SmtpTemplates.EmailVerification,+ subjectLine: "Infisical email change verification",+ recipients: [newEmail],+ substitutions: {+ code: newEmailOtpCode+ }+ });+ }return { success: true, newEmail };});+ // Keep response timing uniform between the taken/free branches (anti-enumeration)+ await enforceMinimumExecutionTime(startTime);+ return result;};const updateUserEmail = async ({diff --git a/frontend/src/pages/user/PersonalSettingsPage/components/ChangeEmailSection/ChangeEmailSection.tsx b/frontend/src/pages/user/PersonalSettingsPage/components/ChangeEmailSection/ChangeEmailSection.tsxindex 710cdcee00..c4ce5c4009 100644--- a/frontend/src/pages/user/PersonalSettingsPage/components/ChangeEmailSection/ChangeEmailSection.tsx+++ b/frontend/src/pages/user/PersonalSettingsPage/components/ChangeEmailSection/ChangeEmailSection.tsx@@ -135,7 +135,7 @@ export const ChangeEmailSection = () => {setOtpStep("newEmail");createNotification({- text: "Confirmed. A second verification code has been sent to your new email address.",+ text: "Confirmed. Check the inbox of your new email address to continue.",type: "success"});};@@ -248,6 +248,13 @@ export const ChangeEmailSection = () => {className="mb-4"/></div>+ {otpStep === "newEmail" && (+ <p className="text-center text-xs text-mineshaft-400">+ Didn't get a code? If the new address already belongs to another Infisical+ account, we've sent it an email explaining why the change can't be+ completed.+ </p>+ )}<div className="flex gap-2"><Button colorSchema="secondary" variant="outline" onClick={closeOtpModal}>Cancel