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
change email only if both domains are owned by the org
Thiago Araujo da Silva6dee75a28e6d
diff --git a/backend/CLAUDE.md b/backend/CLAUDE.mdindex 4459b5fde6..f1685606ce 100644--- a/backend/CLAUDE.md+++ b/backend/CLAUDE.md@@ -443,6 +443,13 @@ Two invariants:- **It never fails a login.** A rename that could not be applied leaves stale data, which is what wealready had; a throw locks the person out of an org that has no other way in. Every failure pathreturns the unchanged user.+- **It only renames an address the org owns, onto another address the org owns.** Both halves are+ checked in the helper against the org's verified domains. The user row is global rather than+ org-scoped, so without the first half an org could rename an account that merely carries one of+ its aliases and rewrite the identity every other org of that user sees. Every login path+ establishes both already (`verifyEmailDomainOwnership` is a positive check: the domain must be+ verified *for this org*, and the alias branch runs it against the existing account's username),+ so the helper's copy is there to keep the rename from outliving those checks.- **It never renames onto an occupied address.** `users.username` is globally unique and the row isglobal rather than org-scoped, so the asserted address may already be a personal signup or anunmerged duplicate. The conflict is recorded (`SSO_USER_PROFILE_SYNC_CONFLICT`) and the email isdiff --git a/backend/src/ee/services/ldap-config/ldap-config-service.ts b/backend/src/ee/services/ldap-config/ldap-config-service.tsindex e08d06de5b..7970566929 100644--- a/backend/src/ee/services/ldap-config/ldap-config-service.ts+++ b/backend/src/ee/services/ldap-config/ldap-config-service.ts@@ -760,6 +760,7 @@ export const ldapConfigServiceFactory = ({isAuthEnforced: Boolean(organization.authEnforced),userDAL,userAliasDAL,+ emailDomainDAL,auditLogService});diff --git a/backend/src/ee/services/oidc/oidc-config-service.ts b/backend/src/ee/services/oidc/oidc-config-service.tsindex d75e80169e..db81715fb2 100644--- a/backend/src/ee/services/oidc/oidc-config-service.ts+++ b/backend/src/ee/services/oidc/oidc-config-service.ts@@ -554,6 +554,7 @@ export const oidcConfigServiceFactory = ({isAuthEnforced: Boolean(organization.authEnforced),userDAL,userAliasDAL,+ emailDomainDAL,auditLogService});diff --git a/backend/src/ee/services/saml-config/saml-config-service.ts b/backend/src/ee/services/saml-config/saml-config-service.tsindex 30a8aa5150..8b513b69c7 100644--- a/backend/src/ee/services/saml-config/saml-config-service.ts+++ b/backend/src/ee/services/saml-config/saml-config-service.ts@@ -809,6 +809,7 @@ export const samlConfigServiceFactory = ({isAuthEnforced: Boolean(organization.authEnforced),userDAL,userAliasDAL,+ emailDomainDAL,auditLogService});diff --git a/backend/src/services/user-alias/user-alias-fns.test.ts b/backend/src/services/user-alias/user-alias-fns.test.tsindex e6ee989506..f95279a2dd 100644--- a/backend/src/services/user-alias/user-alias-fns.test.ts+++ b/backend/src/services/user-alias/user-alias-fns.test.ts@@ -326,7 +326,11 @@ const makeAlias = (overrides: Partial<TUserAliases> = {}) =>type TAuditLogArg = { orgId: string; event: { type: string; metadata: Record<string, unknown> } };-const makeDeps = ({ conflictingUser = null as TUsers | null, updateError = null as Error | null } = {}) => {+const makeDeps = ({+ conflictingUser = null as TUsers | null,+ updateError = null as Error | null,+ orgVerifiedDomains = ["example.com"] as string[]+} = {}) => {const updatedRows: Record<string, unknown>[] = [];const userDAL = {findOne: vi.fn().mockResolvedValue(conflictingUser),@@ -338,11 +342,18 @@ const makeDeps = ({ conflictingUser = null as TUsers | null, updateError = nulltransaction: vi.fn().mockImplementation((cb: (tx: unknown) => unknown) => cb({}))};const userAliasDAL = { updateById: vi.fn().mockResolvedValue(undefined) };+ const emailDomainDAL = {+ findOne: vi+ .fn()+ .mockImplementation(({ domain }: { domain: string }) =>+ orgVerifiedDomains.includes(domain) ? { id: "domain-1", domain } : undefined+ )+ };const auditLogService = {createAuditLog: vi.fn<(arg: TAuditLogArg) => Promise<void>>().mockResolvedValue(undefined)};- return { userDAL, userAliasDAL, auditLogService, updatedRows };+ return { userDAL, userAliasDAL, emailDomainDAL, auditLogService, updatedRows };};const sync = (args: Record<string, unknown>, deps: ReturnType<typeof makeDeps>) =>@@ -354,6 +365,7 @@ const sync = (args: Record<string, unknown>, deps: ReturnType<typeof makeDeps>)isAuthEnforced: true,userDAL: deps.userDAL,userAliasDAL: deps.userAliasDAL,+ emailDomainDAL: deps.emailDomainDAL,auditLogService: deps.auditLogService,...args} as Parameters<typeof syncSsoUserProfile>[0]);@@ -458,4 +470,22 @@ describe("syncSsoUserProfile", () => {expect(user.username).toBe("[email protected]");expect(deps.auditLogService.createAuditLog).not.toHaveBeenCalled();});++ test("skips the email but keeps the name when the org does not own the address being replaced", async () => {+ const deps = makeDeps({ orgVerifiedDomains: ["new-corp.com"] });+ const user = await sync({ assertedEmail: "[email protected]", assertedFirstName: "Bob" }, deps);++ expect(user.username).toBe("[email protected]");+ expect(user.firstName).toBe("Bob");+ expect(deps.updatedRows[0]).toEqual({ firstName: "Bob" });+ });++ test("skips the email when the org does not own the address being written", async () => {+ const deps = makeDeps({ orgVerifiedDomains: ["example.com"] });+ const user = await sync({ assertedEmail: "[email protected]" }, deps);++ expect(user.username).toBe("[email protected]");+ expect(deps.userDAL.updateById).not.toHaveBeenCalled();+ expect(deps.userDAL.findOne).not.toHaveBeenCalled();+ });});diff --git a/backend/src/services/user-alias/user-alias-fns.ts b/backend/src/services/user-alias/user-alias-fns.tsindex ee3f0b6763..8c406d6fd9 100644--- a/backend/src/services/user-alias/user-alias-fns.ts+++ b/backend/src/services/user-alias/user-alias-fns.ts@@ -2,6 +2,8 @@ import { Knex } from "knex";import { AccessScope, TableName, TUserAliases, TUsers } from "@app/db/schemas";import { EventType, TAuditLogServiceFactory } from "@app/ee/services/audit-log/audit-log-types";+import { TEmailDomainDALFactory } from "@app/ee/services/email-domain/email-domain-dal";+import { verifyEmailDomainOwnership } from "@app/ee/services/email-domain/email-domain-fns";import { DatabaseErrorCode } from "@app/lib/error-codes";import { DatabaseError, ForbiddenRequestError } from "@app/lib/errors";import { unique } from "@app/lib/fn";@@ -107,6 +109,7 @@ type TSyncSsoUserProfileDTO = {isAuthEnforced: boolean;userDAL: Pick<TUserDALFactory, "findOne" | "updateById" | "transaction">;userAliasDAL: Pick<TUserAliasDALFactory, "updateById">;+ emailDomainDAL: Pick<TEmailDomainDALFactory, "findOne">;auditLogService: Pick<TAuditLogServiceFactory, "createAuditLog">;};@@ -138,6 +141,7 @@ export const syncSsoUserProfile = async ({isAuthEnforced,userDAL,userAliasDAL,+ emailDomainDAL,auditLogService}: TSyncSsoUserProfileDTO): Promise<TUsers> => {if (!isAuthEnforced || !userAlias.isEmailVerified) return user;@@ -182,6 +186,24 @@ export const syncSsoUserProfile = async ({let isEmailApplied = isEmailChanged;if (isEmailChanged) {+ const isOrgOwnedRename = await Promise.all([+ verifyEmailDomainOwnership({ email: user.username, orgId, emailDomainDAL }),+ verifyEmailDomainOwnership({ email: assertedUsername, orgId, emailDomainDAL })+ ])+ .then(() => true)+ .catch(() => false);++ if (!isOrgOwnedRename) {+ isEmailApplied = false;+ logger.warn(+ { userId: user.id, orgId, externalId: userAlias.externalId },+ `Skipped SSO email sync, the organization does not own both addresses [userId=${user.id}] [orgId=${orgId}]`+ );+ if (!isNameChanged) return user;+ }+ }++ if (isEmailApplied) {const conflictingUser = await userDAL.findOne({ username: assertedUsername });if (conflictingUser && conflictingUser.id !== user.id) {isEmailApplied = false;