Skip to content

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

update email and name when SSO enforced

Thiago Araujo da Silva8d2dfdeb8d3a
diff --git a/backend/CLAUDE.md b/backend/CLAUDE.md
index 28bde0525d..4459b5fde6 100644
--- a/backend/CLAUDE.md
+++ b/backend/CLAUDE.md
@@ -421,6 +421,41 @@ audit-log entitlement, so on those deployments only the `logger.info` line survi
Do not special-case this event past the retention gate; treat the application log as the floor and
the audit event as the addition for licensed instances.
+### Profile Sync From The IdP (SSO-enforced orgs)
+
+An IdP keyed on a stable identifier lets someone change mailbox and display name without changing
+who they are, so our copy of both goes stale: notification mail goes to an address that no longer
+exists, and every audit entry written from then on records it. `syncSsoUserProfile`
+(`src/services/user-alias/user-alias-fns.ts`) carries the asserted email and name onto the account,
+and is called from all three login services right after `ensureSsoAccountVerified`, outside the
+caller's transaction, with its result flowing into the session.
+
+The gate is `organization.authEnforced` **and** a verified alias, and both halves matter. Enforcement
+is the org saying the IdP is authoritative for identity, which is the same claim that already skips
+email verification at signup. The verified alias is the proof that the IdP controls *this* account:
+an unverified alias asserting an unrecognized email is exactly what `isStaleSsoAlias` exists to
+catch, and reading that as a rename would let a stale alias rewrite somebody else's account. One
+consequence to know: a legacy unverified alias whose email changed before its next login is stale,
+so it gets the email-verification fallback (a code sent to the dead mailbox) rather than a sync.
+
+Two invariants:
+
+- **It never fails a login.** A rename that could not be applied leaves stale data, which is what we
+ already had; a throw locks the person out of an org that has no other way in. Every failure path
+ returns the unchanged user.
+- **It never renames onto an occupied address.** `users.username` is globally unique and the row is
+ global rather than org-scoped, so the asserted address may already be a personal signup or an
+ unmerged duplicate. The conflict is recorded (`SSO_USER_PROFILE_SYNC_CONFLICT`) and the email is
+ left alone; the name still syncs. The preceding read is not a lock, so a unique violation lands on
+ the same path.
+
+SCIM is the other half of the same story and moves with it. `updateScimUser` / `replaceScimUser`
+rejected every email change outright, which left the data stale *and* put the provisioning job in a
+permanent error state (Entra quarantines after repeated failures). Both now accept the change under
+the same `authEnforced` gate via `$resolveScimEmailChange`, and answer an occupied address with
+`409 uniqueness` rather than a constraint-shaped 500. Self-service email change
+(`user-service.ts`) is refused for the same orgs, since the next login would overwrite it anyway.
+
### Permission System (CASL)
Uses CASL (`@casl/ability`) with MongoDB-style rules. Permission logic lives in `src/ee/services/permission/`:
diff --git a/backend/e2e-test/routes/v1/scim.spec.ts b/backend/e2e-test/routes/v1/scim.spec.ts
index 61a5c1b8c9..dba6bc89b3 100644
--- a/backend/e2e-test/routes/v1/scim.spec.ts
+++ b/backend/e2e-test/routes/v1/scim.spec.ts
@@ -668,4 +668,145 @@ describe("SCIM v1 Router", () => {
}
);
});
+
+ describe("Provisioned email changes", () => {
+ const seedUser = async (db: Knex, label: string) => {
+ const [user] = await db(TableName.Users)
+ .insert({
+ email: `scim-email-${label}@${TEST_DOMAIN}`,
+ username: `scim-email-${label}@${TEST_DOMAIN}`,
+ isGhost: false,
+ isEmailVerified: true,
+ authMethods: ["email"]
+ })
+ .returning("*");
+ createdUserIds.push(user.id);
+
+ const [membership] = await db(TableName.Membership)
+ .insert({
+ actorUserId: user.id,
+ scopeOrgId: ORG_ID,
+ scope: AccessScope.Organization,
+ isActive: true
+ })
+ .returning("*");
+ createdMembershipIds.push(membership.id);
+
+ await db(TableName.MembershipRole).insert({ membershipId: membership.id, role: "member" });
+
+ const [alias] = await db(TableName.UserAliases)
+ .insert({
+ userId: user.id,
+ orgId: ORG_ID,
+ aliasType: "saml",
+ externalId: `scim-email-ext-${label}`,
+ emails: [user.username]
+ })
+ .returning("*");
+
+ return { user, membership, alias };
+ };
+
+ // Entra addresses the mailbox through a filter path rather than an index.
+ const patchEmail = (membershipId: string, newEmail: string) =>
+ testServer.inject({
+ method: "PATCH",
+ url: `/api/v1/scim/Users/${membershipId}`,
+ headers: { authorization: `Bearer ${scimToken}`, "content-type": "application/scim+json" },
+ payload: JSON.stringify({
+ schemas: ["urn:ietf:params:scim:api:messages:2.0:PatchOp"],
+ Operations: [{ op: "replace", path: 'emails[type eq "work"].value', value: newEmail }]
+ })
+ });
+
+ const putUser = (membershipId: string, externalId: string, newEmail: string) =>
+ testServer.inject({
+ method: "PUT",
+ url: `/api/v1/scim/Users/${membershipId}`,
+ headers: { authorization: `Bearer ${scimToken}`, "content-type": "application/scim+json" },
+ payload: JSON.stringify({
+ schemas: ["urn:ietf:params:scim:schemas:core:2.0:User"],
+ userName: externalId,
+ name: { givenName: "Robert", familyName: "Smith" },
+ emails: [{ primary: true, value: newEmail }],
+ active: true
+ })
+ });
+
+ afterEach(async () => {
+ await getDb()(TableName.Organization).where({ id: ORG_ID }).update({ authEnforced: false });
+ });
+
+ test("should reject an email change when the org does not enforce SSO", async () => {
+ const db = getDb();
+ const label = `norename-${crypto.randomUUID().slice(0, 8)}`;
+ const { user, membership } = await seedUser(db, label);
+
+ const res = await patchEmail(membership.id, `renamed-${label}@${TEST_DOMAIN}`);
+
+ expect(res.statusCode).toBe(400);
+ expect(JSON.parse(res.payload).mutability).toBe("immutable");
+
+ const [row] = await db(TableName.Users).where({ id: user.id }).select("username");
+ expect(row.username).toBe(user.username);
+ });
+
+ test("should apply a PATCH email change when the org enforces SSO", async () => {
+ const db = getDb();
+ const label = `patch-${crypto.randomUUID().slice(0, 8)}`;
+ const { user, membership, alias } = await seedUser(db, label);
+ const newEmail = `renamed-${label}@${TEST_DOMAIN}`;
+
+ await db(TableName.Organization).where({ id: ORG_ID }).update({ authEnforced: true });
+
+ const res = await patchEmail(membership.id, newEmail);
+
+ expect(res.statusCode).toBe(200);
+ expect(JSON.parse(res.payload).emails[0].value).toBe(newEmail);
+
+ const [row] = await db(TableName.Users).where({ id: user.id }).select("username", "email");
+ expect(row.username).toBe(newEmail);
+ expect(row.email).toBe(newEmail);
+
+ // The old address stays on the alias so a login in flight from before the rename still resolves.
+ const [aliasRow] = await db(TableName.UserAliases).where({ id: alias.id }).select("emails");
+ expect(aliasRow.emails).toEqual([user.username, newEmail]);
+ });
+
+ test("should apply a PUT email change when the org enforces SSO", async () => {
+ const db = getDb();
+ const label = `put-${crypto.randomUUID().slice(0, 8)}`;
+ const { user, membership } = await seedUser(db, label);
+ const newEmail = `renamed-${label}@${TEST_DOMAIN}`;
+
+ await db(TableName.Organization).where({ id: ORG_ID }).update({ authEnforced: true });
+
+ const res = await putUser(membership.id, `scim-email-ext-${label}`, newEmail);
+
+ expect(res.statusCode).toBe(200);
+ expect(JSON.parse(res.payload).emails[0].value).toBe(newEmail);
+
+ const [row] = await db(TableName.Users).where({ id: user.id }).select("username", "email");
+ expect(row.username).toBe(newEmail);
+ expect(row.email).toBe(newEmail);
+ });
+
+ test("should report a conflict when the new address is already another account", async () => {
+ const db = getDb();
+ const label = `conflict-${crypto.randomUUID().slice(0, 8)}`;
+ const { user, membership } = await seedUser(db, label);
+ const { user: occupant } = await seedUser(db, `occupant-${label}`);
+
+ await db(TableName.Organization).where({ id: ORG_ID }).update({ authEnforced: true });
+
+ const res = await patchEmail(membership.id, occupant.username);
+
+ expect(res.statusCode).toBe(409);
+ expect(JSON.parse(res.payload).scimType).toBe("uniqueness");
+
+ const [row] = await db(TableName.Users).where({ id: user.id }).select("username");
+ expect(row.username).toBe(user.username);
+ });
+ });
+
});
diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.ts
index 5301ca3c1a..01ab022621 100644
--- a/backend/src/ee/services/audit-log/audit-log-types.ts
+++ b/backend/src/ee/services/audit-log/audit-log-types.ts
@@ -591,6 +591,8 @@ export enum EventType {
OIDC_GROUP_MEMBERSHIP_MAPPING_ASSIGN_USER = "oidc-group-membership-mapping-assign-user",
OIDC_GROUP_MEMBERSHIP_MAPPING_REMOVE_USER = "oidc-group-membership-mapping-remove-user",
OIDC_PROVISIONED_PLACEHOLDER_ADOPTED = "oidc-provisioned-placeholder-adopted",
+ SSO_USER_PROFILE_SYNCED = "sso-user-profile-synced",
+ SSO_USER_PROFILE_SYNC_CONFLICT = "sso-user-profile-sync-conflict",
CREATE_KMIP_CLIENT = "create-kmip-client",
UPDATE_KMIP_CLIENT = "update-kmip-client",
DELETE_KMIP_CLIENT = "delete-kmip-client",
@@ -4953,6 +4955,33 @@ interface OidcProvisionedPlaceholderAdoptedEvent {
};
}
+interface SsoUserProfileSyncedEvent {
+ type: EventType.SSO_USER_PROFILE_SYNCED;
+ metadata: {
+ userId: string;
+ aliasType: string;
+ externalId: string;
+ previousEmail?: string;
+ newEmail?: string;
+ previousFirstName?: string | null;
+ newFirstName?: string;
+ previousLastName?: string | null;
+ newLastName?: string;
+ };
+}
+
+interface SsoUserProfileSyncConflictEvent {
+ type: EventType.SSO_USER_PROFILE_SYNC_CONFLICT;
+ metadata: {
+ userId: string;
+ aliasType: string;
+ externalId: string;
+ currentEmail: string;
+ assertedEmail: string;
+ conflictingUserId?: string;
+ };
+}
+
interface CreateKmipClientEvent {
type: EventType.CREATE_KMIP_CLIENT;
metadata: {
@@ -7630,6 +7659,8 @@ export type Event =
| OidcGroupMembershipMappingAssignUserEvent
| OidcGroupMembershipMappingRemoveUserEvent
| OidcProvisionedPlaceholderAdoptedEvent
+ | SsoUserProfileSyncedEvent
+ | SsoUserProfileSyncConflictEvent
| CreateKmipClientEvent
| UpdateKmipClientEvent
| DeleteKmipClientEvent
diff --git a/backend/src/ee/services/ldap-config/ldap-config-service.ts b/backend/src/ee/services/ldap-config/ldap-config-service.ts
index a06e1a3dcb..e08d06de5b 100644
--- a/backend/src/ee/services/ldap-config/ldap-config-service.ts
+++ b/backend/src/ee/services/ldap-config/ldap-config-service.ts
@@ -9,6 +9,7 @@ import {
TLdapConfigsUpdate,
TUsers
} from "@app/db/schemas";
+import { TAuditLogServiceFactory } from "@app/ee/services/audit-log/audit-log-types";
import { TGroupDALFactory } from "@app/ee/services/group/group-dal";
import { addUsersToGroupByUserIds, removeUsersFromGroupByUserIds } from "@app/ee/services/group/group-fns";
import { TUserGroupMembershipDALFactory } from "@app/ee/services/group/user-group-membership-dal";
@@ -51,7 +52,7 @@ import { TTelemetryServiceFactory } from "@app/services/telemetry/telemetry-serv
import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";
import { TUserDALFactory } from "@app/services/user/user-dal";
import { TUserAliasDALFactory } from "@app/services/user-alias/user-alias-dal";
-import { ensureSsoAccountVerified, isStaleSsoAlias } from "@app/services/user-alias/user-alias-fns";
+import { ensureSsoAccountVerified, isStaleSsoAlias, syncSsoUserProfile } from "@app/services/user-alias/user-alias-fns";
import { UserAliasType } from "@app/services/user-alias/user-alias-types";
import { TEmailDomainDALFactory } from "../email-domain/email-domain-dal";
@@ -75,6 +76,7 @@ import { TLdapGroupMapDALFactory } from "./ldap-group-map-dal";
type TLdapConfigServiceFactoryDep = {
ldapConfigDAL: Pick<TLdapConfigDALFactory, "create" | "update" | "findOne" | "transaction">;
+ auditLogService: Pick<TAuditLogServiceFactory, "createAuditLog">;
ldapGroupMapDAL: Pick<TLdapGroupMapDALFactory, "find" | "create" | "delete" | "findLdapGroupMapsByLdapConfigId">;
orgDAL: Pick<
TOrgDALFactory,
@@ -118,6 +120,7 @@ export type TLdapConfigServiceFactory = ReturnType<typeof ldapConfigServiceFacto
export const ldapConfigServiceFactory = ({
ldapConfigDAL,
+ auditLogService,
ldapGroupMapDAL,
orgDAL,
groupDAL,
@@ -747,6 +750,19 @@ export const ldapConfigServiceFactory = ({
}));
}
+ user = await syncSsoUserProfile({
+ user,
+ userAlias,
+ assertedEmail: sanitizedEmail,
+ assertedFirstName: firstName,
+ assertedLastName: lastName,
+ orgId,
+ isAuthEnforced: Boolean(organization.authEnforced),
+ userDAL,
+ userAliasDAL,
+ auditLogService
+ });
+
if (user.email && (!userAlias.isEmailVerified || !user.isAccepted)) {
const token = await tokenService.createTokenForUser({
type: TokenType.TOKEN_EMAIL_VERIFICATION,
diff --git a/backend/src/ee/services/oidc/oidc-config-service.ts b/backend/src/ee/services/oidc/oidc-config-service.ts
index 05cd8f2a10..d75e80169e 100644
--- a/backend/src/ee/services/oidc/oidc-config-service.ts
+++ b/backend/src/ee/services/oidc/oidc-config-service.ts
@@ -61,7 +61,8 @@ import { TUserAliasDALFactory } from "@app/services/user-alias/user-alias-dal";
import {
adoptProvisionedShadowUser,
ensureSsoAccountVerified,
- isStaleSsoAlias
+ isStaleSsoAlias,
+ syncSsoUserProfile
} from "@app/services/user-alias/user-alias-fns";
import { UserAliasType } from "@app/services/user-alias/user-alias-types";
@@ -541,6 +542,21 @@ export const oidcConfigServiceFactory = ({
}));
}
+ // The IdP is authoritative for identity in an org that enforces SSO, so a mailbox or name
+ // changed there is carried onto the account rather than left to go stale.
+ user = await syncSsoUserProfile({
+ user,
+ userAlias,
+ assertedEmail: sanitizedEmail,
+ assertedFirstName: firstName,
+ assertedLastName: lastName,
+ orgId,
+ isAuthEnforced: Boolean(organization.authEnforced),
+ userDAL,
+ userAliasDAL,
+ auditLogService
+ });
+
if (user.email && (!userAlias.isEmailVerified || !user.isAccepted)) {
const token = await tokenService.createTokenForUser({
type: TokenType.TOKEN_EMAIL_VERIFICATION,
diff --git a/backend/src/ee/services/saml-config/saml-config-service.ts b/backend/src/ee/services/saml-config/saml-config-service.ts
index 308cfb07fd..30a8aa5150 100644
--- a/backend/src/ee/services/saml-config/saml-config-service.ts
+++ b/backend/src/ee/services/saml-config/saml-config-service.ts
@@ -14,6 +14,7 @@ import {
TSamlConfigsUpdate,
TUsers
} from "@app/db/schemas";
+import { TAuditLogServiceFactory } from "@app/ee/services/audit-log/audit-log-types";
import { getEnforcedIdentityLimit, throwOnPlanSeatLimitReached } from "@app/ee/services/license/license-fns";
import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
import { requestMemoKeys } from "@app/lib/request-context/memo-keys";
@@ -44,7 +45,7 @@ import { TTelemetryServiceFactory } from "@app/services/telemetry/telemetry-serv
import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";
import { TUserDALFactory } from "@app/services/user/user-dal";
import { TUserAliasDALFactory } from "@app/services/user-alias/user-alias-dal";
-import { ensureSsoAccountVerified, isStaleSsoAlias } from "@app/services/user-alias/user-alias-fns";
+import { ensureSsoAccountVerified, isStaleSsoAlias, syncSsoUserProfile } from "@app/services/user-alias/user-alias-fns";
import { UserAliasType } from "@app/services/user-alias/user-alias-types";
import { TEmailDomainDALFactory } from "../email-domain/email-domain-dal";
@@ -63,6 +64,7 @@ const GROUP_SYNC_SUPPORTED_PROVIDERS = [SamlProviders.GOOGLE_SAML] as SamlProvid
type TSamlConfigServiceFactoryDep = {
samlConfigDAL: Pick<TSamlConfigDALFactory, "create" | "findOne" | "update" | "findById">;
+ auditLogService: Pick<TAuditLogServiceFactory, "createAuditLog">;
userDAL: Pick<
TUserDALFactory,
| "create"
@@ -105,6 +107,7 @@ type TSamlConfigServiceFactoryDep = {
export const samlConfigServiceFactory = ({
samlConfigDAL,
+ auditLogService,
orgDAL,
userDAL,
userAliasDAL,
@@ -794,6 +797,21 @@ export const samlConfigServiceFactory = ({
}));
}
+ // The IdP is authoritative for identity in an org that enforces SSO, so a mailbox or name
+ // changed there is carried onto the account rather than left to go stale.
+ user = await syncSsoUserProfile({
+ user,
+ userAlias,
+ assertedEmail: sanitizedEmail,
+ assertedFirstName: firstName,
+ assertedLastName: lastName,
+ orgId,
+ isAuthEnforced: Boolean(organization.authEnforced),
+ userDAL,
+ userAliasDAL,
+ auditLogService
+ });
+
if (user.email && (!userAlias.isEmailVerified || !user.isAccepted)) {
const token = await tokenService.createTokenForUser({
type: TokenType.TOKEN_EMAIL_VERIFICATION,
diff --git a/backend/src/ee/services/scim/scim-service.ts b/backend/src/ee/services/scim/scim-service.ts
index 2311fa4f65..5e9a5390a7 100644
--- a/backend/src/ee/services/scim/scim-service.ts
+++ b/backend/src/ee/services/scim/scim-service.ts
@@ -11,6 +11,7 @@ import {
TableName,
TGroups,
TMemberships,
+ TOrganizations,
TUsers
} from "@app/db/schemas";
import { TGroupDALFactory } from "@app/ee/services/group/group-dal";
@@ -22,7 +23,9 @@ import { TScimDALFactory } from "@app/ee/services/scim/scim-dal";
import { PgSqlLock } from "@app/keystore/keystore";
import { getConfig } from "@app/lib/config/env";
import { crypto } from "@app/lib/crypto";
-import { BadRequestError, NotFoundError, ScimRequestError, UnauthorizedError } from "@app/lib/errors";
+import { DatabaseErrorCode } from "@app/lib/error-codes";
+import { BadRequestError, DatabaseError, NotFoundError, ScimRequestError, UnauthorizedError } from "@app/lib/errors";
+import { unique } from "@app/lib/fn";
import { logger } from "@app/lib/logger";
import { ms } from "@app/lib/ms";
import { alphaNumericNanoId } from "@app/lib/nanoid";
@@ -88,7 +91,7 @@ type TScimServiceFactoryDep = {
TUserDALFactory,
"find" | "findOne" | "create" | "transaction" | "findUserEncKeyByUserIdsBatch" | "findById" | "updateById"
>;
- userAliasDAL: Pick<TUserAliasDALFactory, "findOne" | "create" | "delete" | "update" | "find">;
+ userAliasDAL: Pick<TUserAliasDALFactory, "findOne" | "create" | "delete" | "update" | "updateById" | "find">;
orgDAL: Pick<
TOrgDALFactory,
| "createMembership"
@@ -621,6 +624,79 @@ export const scimServiceFactory = ({
});
};
+ /**
+ * SCIM addresses people by the identifier the IdP asserts, but ours is users.username, which is
+ * the mailbox, so someone renamed at the IdP arrives here as a write to a field we treat as
+ * immutable. Refusing it leaves our copy stale and puts the provisioning job into a permanent
+ * error state. Where the org enforces SSO it has already made the IdP authoritative for identity,
+ * so the new address is taken; otherwise the mailbox is still ours and the refusal stands.
+ *
+ * Returns the address to write, or null when there is nothing to change.
+ */
+ const $resolveScimEmailChange = async ({
+ org,
+ user,
+ assertedEmail
+ }: {
+ org: Pick<TOrganizations, "id" | "authEnforced">;
+ user: Pick<TUsers, "id" | "email" | "username">;
+ assertedEmail?: string | null;
+ }): Promise<string | null> => {
+ if (!assertedEmail) return null;
+
+ const newEmail = sanitizeEmail(assertedEmail);
+ if (newEmail === user.email && newEmail === user.username) return null;
+
+ if (!org.authEnforced) {
+ throw new ScimRequestError({
+ detail:
+ "Email cannot be changed. Enable SSO enforcement for this organization to let your identity provider manage member email addresses.",
+ status: 400,
+ mutability: "immutable"
+ });
+ }
+
+ try {
+ validateEmail(newEmail);
+ } catch (err) {
+ throw new ScimRequestError({
+ detail: `'${assertedEmail}' is not a valid email address`,
+ status: 400,
+ scimType: "invalidValue",
+ error: err
+ });
+ }
+
+ await verifyEmailDomainOwnership({ email: newEmail, orgId: org.id, emailDomainDAL });
+
+ const conflictingUser = await userDAL.findOne({ username: newEmail });
+ if (conflictingUser && conflictingUser.id !== user.id) {
+ throw new ScimRequestError({
+ detail: `An Infisical account already exists for '${newEmail}'. Remove or merge that account before changing this user's email.`,
+ status: 409,
+ scimType: "uniqueness"
+ });
+ }
+
+ return newEmail;
+ };
+
+ /**
+ * The conflict check above is a read, not a lock, so a concurrent login or invite can take the
+ * address first. Report that as the conflict it is instead of a 500 carrying a constraint name.
+ */
+ const $toScimEmailConflictError = (err: unknown, newEmail: string) => {
+ if (err instanceof DatabaseError && (err.error as { code?: string })?.code === DatabaseErrorCode.UniqueViolation) {
+ return new ScimRequestError({
+ detail: `An Infisical account already exists for '${newEmail}'. Remove or merge that account before changing this user's email.`,
+ status: 409,
+ scimType: "uniqueness",
+ error: err
+ });
+ }
+ return err;
+ };
+
// partial
const updateScimUser: TScimServiceFactory["updateScimUser"] = async ({ orgMembershipId, orgId, operations }) => {
const org = await requestMemoize(requestMemoKeys.orgFindOrgById(orgId), () => orgDAL.findOrgById(orgId));
@@ -687,51 +763,65 @@ export const scimServiceFactory = ({
});
scimPatch(scimUser, operations);
- // email is our identifier - changing that user must delete this user and provision a new one
- if (scimUser.emails?.[0]?.value !== user?.email) {
- throw new ScimRequestError({
- detail: "Email cannot be changed",
- status: 400,
- mutability: "immutable"
- });
- }
+ const newEmail = await $resolveScimEmailChange({
+ org,
+ user,
+ assertedEmail: scimUser.emails?.[0]?.value
+ });
await verifyEmailDomainOwnership({
email: user.username,
orgId,
emailDomainDAL
});
- await userDAL.transaction(async (tx) => {
- await membershipUserDAL.updateById(
- membership.id,
- {
- isActive: scimUser.active
- },
- tx
- );
- await userDAL.updateById(
- membership.actorUserId as string,
- {
- firstName: scimUser.name.givenName,
- lastName: scimUser.name.familyName
- },
- tx
- );
- await scimEventsDAL.create(
- {
- orgId,
- eventType: ScimEvent.UPDATE_USER,
- event: {
+ try {
+ await userDAL.transaction(async (tx) => {
+ await membershipUserDAL.updateById(
+ membership.id,
+ {
+ isActive: scimUser.active
+ },
+ tx
+ );
+ await userDAL.updateById(
+ membership.actorUserId as string,
+ {
firstName: scimUser.name.givenName,
- email: scimUser.userName,
lastName: scimUser.name.familyName,
- active: scimUser.active
- }
- },
- tx
- );
- });
+ ...(newEmail ? { email: newEmail, username: newEmail } : {})
+ },
+ tx
+ );
+
+ // The old address stays on the alias: it is what past assertions carried, and dropping it
+ // would make a login in flight from before the rename look stale.
+ if (newEmail) {
+ await Promise.all(
+ userAliases.map((alias) =>
+ userAliasDAL.updateById(alias.id, { emails: unique([...(alias.emails ?? []), newEmail]) }, tx)
+ )
+ );
+ }
+
+ await scimEventsDAL.create(
+ {
+ orgId,
+ eventType: ScimEvent.UPDATE_USER,
+ event: {
+ firstName: scimUser.name.givenName,
+ email: scimUser.userName,
+ lastName: scimUser.name.familyName,
+ active: scimUser.active,
+ ...(newEmail ? { previousEmail: user.username, newEmail } : {})
+ }
+ },
+ tx
+ );
+ });
+ } catch (err) {
+ throw $toScimEmailConflictError(err, newEmail ?? "");
+ }
return scimUser;
};
@@ -794,14 +884,7 @@ export const scimServiceFactory = ({
const user = await userDAL.findOne({ id: membership.actorUserId });
- // email is our identifier - changing that user must delete this user and provision a new one
- if (email && (user.email !== email || user.username !== email)) {
- throw new ScimRequestError({
- detail: "Email cannot be changed",
- status: 400,
- mutability: "immutable"
- });
- }
+ const newEmail = await $resolveScimEmailChange({ org, user, assertedEmail: email });
await verifyEmailDomainOwnership({
email: user.username,
@@ -809,46 +892,65 @@ export const scimServiceFactory = ({
emailDomainDAL
});
- await userDAL.transaction(async (tx) => {
- await membershipUserDAL.updateById(
- membership.id,
- {
- isActive: active
- },
- tx
- );
- await userDAL.updateById(
- membership.actorUserId!,
- {
- firstName,
- lastName
- },
- tx
- );
-
- // Update externalId on existing alias if provided and changed
- await userAliasDAL.update({ orgId, aliasType, userId: membership.actorUserId as string }, { externalId }, tx);
-
- await scimEventsDAL.create(
- {
- orgId,
- eventType: ScimEvent.REPLACE_USER,
- event: {
- username: externalId,
+ try {
+ await userDAL.transaction(async (tx) => {
+ await membershipUserDAL.updateById(
+ membership.id,
+ {
+ isActive: active
+ },
+ tx
+ );
+ await userDAL.updateById(
+ membership.actorUserId!,
+ {
firstName,
- email: email?.toLowerCase(),
lastName,
- active
- }
- },
- tx
- );
- });
+ ...(newEmail ? { email: newEmail, username: newEmail } : {})
+ },
+ tx
+ );
+
+ // Update externalId on existing alias if provided and changed. The old address stays on the
+ // alias: it is what past assertions carried, and dropping it would make a login in flight
+ // from before the rename look stale.
+ await Promise.all(
+ userAliases.map((alias) =>
+ userAliasDAL.updateById(
+ alias.id,
+ {
+ externalId,
+ ...(newEmail ? { emails: unique([...(alias.emails ?? []), newEmail]) } : {})
+ },
+ tx
+ )
+ )
+ );
+
+ await scimEventsDAL.create(
+ {
+ orgId,
+ eventType: ScimEvent.REPLACE_USER,
+ event: {
+ username: externalId,
+ firstName,
+ email: email?.toLowerCase(),
+ lastName,
+ active,
+ ...(newEmail ? { previousEmail: user.username, newEmail } : {})
+ }
+ },
+ tx
+ );
+ });
+ } catch (err) {
+ throw $toScimEmailConflictError(err, newEmail ?? "");
+ }
return buildScimUser({
orgMembershipId: membership.id,
username: externalId || user.username,
- email: user.email,
+ email: newEmail ?? user.email,
firstName: firstName || user.firstName,
lastName: lastName || user.lastName,
active,
diff --git a/backend/src/lib/errors/index.ts b/backend/src/lib/errors/index.ts
index 77b8077ca2..6f8c001a65 100644
--- a/backend/src/lib/errors/index.ts
+++ b/backend/src/lib/errors/index.ts
@@ -190,16 +190,20 @@ export class ScimRequestError extends Error {
mutability?: string;
+ scimType?: string;
+
constructor({
name,
error,
detail,
status,
- mutability
+ mutability,
+ scimType
}: {
message?: string;
name?: string;
mutability?: string;
+ scimType?: string;
error?: unknown;
detail: string;
status: number;
@@ -211,6 +215,7 @@ export class ScimRequestError extends Error {
this.detail = detail;
this.status = status;
this.mutability = mutability;
+ this.scimType = scimType;
}
}
diff --git a/backend/src/server/plugins/error-handler.ts b/backend/src/server/plugins/error-handler.ts
index 428cd9b5eb..c2d6dad22c 100644
--- a/backend/src/server/plugins/error-handler.ts
+++ b/backend/src/server/plugins/error-handler.ts
@@ -309,7 +309,8 @@ export const fastifyErrHandler = fastifyPlugin(async (server: FastifyZodProvider
schemas: error.schemas,
status: error.status,
detail: error.detail,
- mutability: error.mutability
+ mutability: error.mutability,
+ scimType: error.scimType
});
} else if (error instanceof OidcAuthError) {
void res.status(HttpStatusCodes.InternalServerError).send({
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index e230d1efb5..a3c673da94 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -1362,6 +1362,7 @@ export const registerRoutes = async (
});
const samlService = samlConfigServiceFactory({
+ auditLogService,
identityMetadataDAL,
additionalPrivilegeDAL,
permissionService,
@@ -1388,6 +1389,7 @@ export const registerRoutes = async (
});
const ldapService = ldapConfigServiceFactory({
+ auditLogService,
additionalPrivilegeDAL,
ldapConfigDAL,
ldapGroupMapDAL,
diff --git a/backend/src/services/user-alias/user-alias-fns.test.ts b/backend/src/services/user-alias/user-alias-fns.test.ts
index 10b38b7d77..e6ee989506 100644
--- a/backend/src/services/user-alias/user-alias-fns.test.ts
+++ b/backend/src/services/user-alias/user-alias-fns.test.ts
@@ -1,11 +1,16 @@
import { Knex } from "knex";
import { describe, expect, test, vi } from "vitest";
-import { TUsers } from "@app/db/schemas";
+import { TUserAliases, TUsers } from "@app/db/schemas";
import { DatabaseErrorCode } from "@app/lib/error-codes";
import { DatabaseError, ForbiddenRequestError } from "@app/lib/errors";
-import { adoptProvisionedShadowUser, resolveAliasUserIds } from "./user-alias-fns";
+import { adoptProvisionedShadowUser, resolveAliasUserIds, syncSsoUserProfile } from "./user-alias-fns";
+import { UserAliasType } from "./user-alias-types";
+
+vi.mock("@app/lib/logger", () => ({
+ logger: { warn: vi.fn(), error: vi.fn(), info: vi.fn() }
+}));
const alias = (externalId: string, userId: string) => ({ externalId, userId });
@@ -296,3 +301,161 @@ describe("adoptProvisionedShadowUser", () => {
await expect(adopt(deps)).rejects.toThrow(DatabaseError);
});
});
+
+const makeUser = (overrides: Partial<TUsers> = {}) =>
+ ({
+ id: "user-1",
+ username: "[email protected]",
+ email: "[email protected]",
+ firstName: "Robert",
+ lastName: "Smith",
+ ...overrides
+ }) as TUsers;
+
+const makeAlias = (overrides: Partial<TUserAliases> = {}) =>
+ ({
+ id: "alias-1",
+ userId: "user-1",
+ orgId: "org-1",
+ aliasType: UserAliasType.OIDC,
+ externalId: "[email protected]",
+ emails: ["[email protected]"],
+ isEmailVerified: true,
+ ...overrides
+ }) as 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 updatedRows: Record<string, unknown>[] = [];
+ const userDAL = {
+ findOne: vi.fn().mockResolvedValue(conflictingUser),
+ updateById: vi.fn().mockImplementation((id: string, update: Record<string, unknown>) => {
+ if (updateError) throw updateError;
+ updatedRows.push(update);
+ return { ...makeUser(), ...update };
+ }),
+ transaction: vi.fn().mockImplementation((cb: (tx: unknown) => unknown) => cb({}))
+ };
+ const userAliasDAL = { updateById: vi.fn().mockResolvedValue(undefined) };
+ const auditLogService = {
+ createAuditLog: vi.fn<(arg: TAuditLogArg) => Promise<void>>().mockResolvedValue(undefined)
+ };
+
+ return { userDAL, userAliasDAL, auditLogService, updatedRows };
+};
+
+const sync = (args: Record<string, unknown>, deps: ReturnType<typeof makeDeps>) =>
+ syncSsoUserProfile({
+ user: makeUser(),
+ userAlias: makeAlias(),
+ assertedEmail: "[email protected]",
+ orgId: "org-1",
+ isAuthEnforced: true,
+ userDAL: deps.userDAL,
+ userAliasDAL: deps.userAliasDAL,
+ auditLogService: deps.auditLogService,
+ ...args
+ } as Parameters<typeof syncSsoUserProfile>[0]);
+
+describe("syncSsoUserProfile", () => {
+ test("does nothing when the org does not enforce SSO", async () => {
+ const deps = makeDeps();
+ const user = await sync({ assertedEmail: "[email protected]", isAuthEnforced: false }, deps);
+
+ expect(user.username).toBe("[email protected]");
+ expect(deps.userDAL.updateById).not.toHaveBeenCalled();
+ expect(deps.auditLogService.createAuditLog).not.toHaveBeenCalled();
+ });
+
+ test("does nothing when the alias is not yet verified", async () => {
+ const deps = makeDeps();
+ const user = await sync(
+ { assertedEmail: "[email protected]", userAlias: makeAlias({ isEmailVerified: false }) },
+ deps
+ );
+
+ expect(user.username).toBe("[email protected]");
+ expect(deps.userDAL.updateById).not.toHaveBeenCalled();
+ });
+
+ test("does not write when nothing differs", async () => {
+ const deps = makeDeps();
+ await sync({ assertedFirstName: "Robert", assertedLastName: "Smith" }, deps);
+
+ expect(deps.userDAL.findOne).not.toHaveBeenCalled();
+ expect(deps.userDAL.updateById).not.toHaveBeenCalled();
+ });
+
+ test("carries a renamed mailbox onto the account and the alias", async () => {
+ const deps = makeDeps();
+ const user = await sync({ assertedEmail: "[email protected]" }, deps);
+
+ expect(user.username).toBe("[email protected]");
+ expect(user.email).toBe("[email protected]");
+ expect(deps.userAliasDAL.updateById).toHaveBeenCalledWith(
+ "alias-1",
+ expect.anything()
+ );
+ const [audited] = deps.auditLogService.createAuditLog.mock.calls[0];
+ expect(audited.event.type).toBe("sso-user-profile-synced");
+ expect(audited.event.metadata.previousEmail).toBe("[email protected]");
+ expect(audited.event.metadata.newEmail).toBe("[email protected]");
+ });
+
+ test("syncs a changed name without touching the email", async () => {
+ const deps = makeDeps();
+ const user = await sync({ assertedFirstName: "Bob", assertedLastName: "Smith" }, deps);
+
+ expect(user.firstName).toBe("Bob");
+ expect(deps.updatedRows[0]).toEqual({ firstName: "Bob" });
+ expect(deps.userAliasDAL.updateById).not.toHaveBeenCalled();
+ });
+
+ test("does not blank out a name the assertion omits", async () => {
+ const deps = makeDeps();
+ await sync({ assertedFirstName: "", assertedLastName: undefined }, deps);
+
+ expect(deps.userDAL.updateById).not.toHaveBeenCalled();
+ });
+
+ test("skips the email but keeps the name when the address belongs to another account", async () => {
+ const deps = makeDeps({ conflictingUser: { ...makeUser(), id: "user-2" } as TUsers });
+ 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" });
+ const [audited] = deps.auditLogService.createAuditLog.mock.calls[0];
+ expect(audited.event.type).toBe("sso-user-profile-sync-conflict");
+ expect(audited.event.metadata.conflictingUserId).toBe("user-2");
+ });
+
+ test("leaves the account untouched when the conflicting account is the only change", async () => {
+ const deps = makeDeps({ conflictingUser: { ...makeUser(), id: "user-2" } as TUsers });
+ const user = await sync({ assertedEmail: "[email protected]" }, deps);
+
+ expect(user.username).toBe("[email protected]");
+ expect(deps.userDAL.updateById).not.toHaveBeenCalled();
+ });
+
+ test("never fails the login when the address is taken between the check and the write", async () => {
+ const deps = makeDeps({
+ updateError: new DatabaseError({ error: { code: DatabaseErrorCode.UniqueViolation } })
+ });
+ const user = await sync({ assertedEmail: "[email protected]" }, deps);
+
+ expect(user.username).toBe("[email protected]");
+ const [audited] = deps.auditLogService.createAuditLog.mock.calls[0];
+ expect(audited.event.type).toBe("sso-user-profile-sync-conflict");
+ });
+
+ test("never fails the login on an unexpected database error", async () => {
+ const deps = makeDeps({ updateError: new Error("connection reset") });
+ const user = await sync({ assertedEmail: "[email protected]" }, deps);
+
+ expect(user.username).toBe("[email protected]");
+ expect(deps.auditLogService.createAuditLog).not.toHaveBeenCalled();
+ });
+});
diff --git a/backend/src/services/user-alias/user-alias-fns.ts b/backend/src/services/user-alias/user-alias-fns.ts
index b16598455b..ee3f0b6763 100644
--- a/backend/src/services/user-alias/user-alias-fns.ts
+++ b/backend/src/services/user-alias/user-alias-fns.ts
@@ -1,11 +1,14 @@
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 { DatabaseErrorCode } from "@app/lib/error-codes";
import { DatabaseError, ForbiddenRequestError } from "@app/lib/errors";
import { unique } from "@app/lib/fn";
+import { logger } from "@app/lib/logger";
import { sanitizeEmail } from "@app/lib/validator/validate-email";
+import { ActorType } from "../auth/auth-type";
import { TOrgDALFactory } from "../org/org-dal";
import { TUserDALFactory } from "../user/user-dal";
import { TUserAliasDALFactory } from "./user-alias-dal";
@@ -93,6 +96,161 @@ export const ensureSsoAccountVerified = async ({
};
};
+type TSyncSsoUserProfileDTO = {
+ user: TUsers;
+ userAlias: TUserAliases;
+ // Caller has already sanitized this and verified its domain against the org.
+ assertedEmail: string;
+ assertedFirstName?: string | null;
+ assertedLastName?: string | null;
+ orgId: string;
+ isAuthEnforced: boolean;
+ userDAL: Pick<TUserDALFactory, "findOne" | "updateById" | "transaction">;
+ userAliasDAL: Pick<TUserAliasDALFactory, "updateById">;
+ auditLogService: Pick<TAuditLogServiceFactory, "createAuditLog">;
+};
+
+/**
+ * An IdP that keys people on a stable identifier (a UPN, say) lets them change mailbox and display
+ * name without changing who they are, so our copy of both goes stale: notification mail is sent to
+ * an address that no longer exists, and every audit entry written from then on records it. Where
+ * the org enforces SSO it has already made the IdP authoritative for identity, so the assertion is
+ * the better source and we take it.
+ *
+ * Requires a verified alias, which is our proof that the IdP controls this account. An unverified
+ * alias asserting an unrecognized email is what isStaleSsoAlias exists to catch, and reading that
+ * as a rename would let a stale alias rewrite somebody else's account.
+ *
+ * Runs on every login, so it writes only on a real difference. Call it outside the caller's
+ * transaction: it owns its own, and the audit entry must not describe a change that later rolls
+ * back.
+ *
+ * Never fails the login. An unsynced profile is stale data, which is what we already had, whereas a
+ * throw here locks someone out of an org that has no other way in.
+ */
+export const syncSsoUserProfile = async ({
+ user,
+ userAlias,
+ assertedEmail,
+ assertedFirstName,
+ assertedLastName,
+ orgId,
+ isAuthEnforced,
+ userDAL,
+ userAliasDAL,
+ auditLogService
+}: TSyncSsoUserProfileDTO): Promise<TUsers> => {
+ if (!isAuthEnforced || !userAlias.isEmailVerified) return user;
+
+ const assertedUsername = sanitizeEmail(assertedEmail);
+ const isEmailChanged = Boolean(assertedUsername) && assertedUsername !== user.username;
+
+ const firstName = assertedFirstName?.trim();
+ const lastName = assertedLastName?.trim();
+ const nameChanges: { firstName?: string; lastName?: string } = {};
+ if (firstName && firstName !== user.firstName) nameChanges.firstName = firstName;
+ if (lastName && lastName !== user.lastName) nameChanges.lastName = lastName;
+ const isNameChanged = Object.keys(nameChanges).length > 0;
+
+ if (!isEmailChanged && !isNameChanged) return user;
+
+ const logConflict = async (conflictingUserId?: string) => {
+ logger.warn(
+ { userId: user.id, orgId, externalId: userAlias.externalId, assertedEmail: assertedUsername, conflictingUserId },
+ `Skipped SSO email sync, the asserted address belongs to another account [userId=${user.id}] [orgId=${orgId}]`
+ );
+ await auditLogService
+ .createAuditLog({
+ actor: { type: ActorType.PLATFORM, metadata: {} },
+ orgId,
+ event: {
+ type: EventType.SSO_USER_PROFILE_SYNC_CONFLICT,
+ metadata: {
+ userId: user.id,
+ aliasType: userAlias.aliasType,
+ externalId: userAlias.externalId,
+ currentEmail: user.username,
+ assertedEmail: assertedUsername,
+ conflictingUserId
+ }
+ }
+ })
+ .catch((err) => {
+ logger.error(err, `Failed to audit SSO profile sync conflict for user ${user.id} in org ${orgId}`);
+ });
+ };
+
+ let isEmailApplied = isEmailChanged;
+ if (isEmailChanged) {
+ const conflictingUser = await userDAL.findOne({ username: assertedUsername });
+ if (conflictingUser && conflictingUser.id !== user.id) {
+ isEmailApplied = false;
+ await logConflict(conflictingUser.id);
+ if (!isNameChanged) return user;
+ }
+ }
+
+ try {
+ const updatedUser = await userDAL.transaction(async (tx) => {
+ const nextUser = await userDAL.updateById(
+ user.id,
+ {
+ ...nameChanges,
+ ...(isEmailApplied ? { email: assertedUsername, username: assertedUsername } : {})
+ },
+ tx
+ );
+
+ if (isEmailApplied) {
+ await userAliasDAL.updateById(
+ userAlias.id,
+ { emails: unique([...(userAlias.emails ?? []), assertedUsername]) },
+ tx
+ );
+ }
+
+ return nextUser;
+ });
+
+ logger.info(
+ { userId: user.id, orgId, externalId: userAlias.externalId, isEmailApplied },
+ `Synced SSO profile from the identity provider [userId=${user.id}] [orgId=${orgId}]`
+ );
+
+ await auditLogService
+ .createAuditLog({
+ actor: { type: ActorType.PLATFORM, metadata: {} },
+ orgId,
+ event: {
+ type: EventType.SSO_USER_PROFILE_SYNCED,
+ metadata: {
+ userId: user.id,
+ aliasType: userAlias.aliasType,
+ externalId: userAlias.externalId,
+ ...(isEmailApplied ? { previousEmail: user.username, newEmail: assertedUsername } : {}),
+ ...(nameChanges.firstName
+ ? { previousFirstName: user.firstName, newFirstName: nameChanges.firstName }
+ : {}),
+ ...(nameChanges.lastName ? { previousLastName: user.lastName, newLastName: nameChanges.lastName } : {})
+ }
+ }
+ })
+ .catch((err) => {
+ logger.error(err, `Failed to audit SSO profile sync for user ${user.id} in org ${orgId}`);
+ });
+
+ return updatedUser;
+ } catch (err) {
+ if (err instanceof DatabaseError && (err.error as { code?: string })?.code === DatabaseErrorCode.UniqueViolation) {
+ await logConflict();
+ return user;
+ }
+
+ logger.error(err, `Failed to sync SSO profile for user ${user.id} in org ${orgId}`);
+ return user;
+ }
+};
+
type TResolveAliasUserIdsDTO = {
identifiers: string[];
aliases: Pick<TUserAliases, "externalId" | "userId">[];
diff --git a/backend/src/services/user/user-service.ts b/backend/src/services/user/user-service.ts
index fee62d8e50..3cf8638492 100644
--- a/backend/src/services/user/user-service.ts
+++ b/backend/src/services/user/user-service.ts
@@ -268,7 +268,12 @@ export const userServiceFactory = ({
return updatedUser;
};
- const checkUserScimRestriction = async (userId: string, tx?: Knex) => {
+ /**
+ * Returns why this account's email is managed elsewhere, or null when the user owns it. SCIM
+ * provisions the address from the directory; SSO enforcement makes the IdP authoritative for it
+ * and overwrites whatever is set here on the next login, so offering the change would be a lie.
+ */
+ const $getManagedEmailReason = async (userId: string, tx?: Knex) => {
const userOrgs = await membershipUserDAL.find(
{
actorUserId: userId,
@@ -278,13 +283,21 @@ export const userServiceFactory = ({
);
if (userOrgs.length === 0) {
- return false;
+ return null;
}
const orgIds = userOrgs.map((membership) => membership.scopeOrgId);
const organizations = await orgDAL.find({ $in: { id: orgIds } }, { tx });
- return organizations.some((org) => org.scimEnabled);
+ if (organizations.some((org) => org.scimEnabled)) {
+ return "Email changes are disabled because SCIM is enabled for one or more of your organizations";
+ }
+
+ if (organizations.some((org) => org.authEnforced)) {
+ return "Email changes are disabled because one or more of your organizations enforce SSO. Your email address is managed by your identity provider.";
+ }
+
+ return null;
};
const requestEmailChangeOTP = async ({ userId, newEmail }: TUpdateUserEmailDTO) => {
@@ -314,12 +327,9 @@ export const userServiceFactory = ({
});
}
- const hasScimRestriction = await checkUserScimRestriction(userId, tx);
- if (hasScimRestriction) {
- throw new BadRequestError({
- message: "Email changes are disabled because SCIM is enabled for one or more of your organizations",
- name: "RequestEmailChangeOTP"
- });
+ const managedEmailReason = await $getManagedEmailReason(userId, tx);
+ if (managedEmailReason) {
+ throw new BadRequestError({ message: managedEmailReason, name: "RequestEmailChangeOTP" });
}
// Availability of the requested address is deliberately NOT checked here: step 1
@@ -363,12 +373,9 @@ export const userServiceFactory = ({
throw new BadRequestError({ message: "Cannot update email for LDAP users", name: "VerifyCurrentEmailOTP" });
}
- const hasScimRestriction = await checkUserScimRestriction(userId, tx);
- if (hasScimRestriction) {
- throw new BadRequestError({
- message: "Email changes are disabled because SCIM is enabled for one or more of your organizations",
- name: "VerifyCurrentEmailOTP"
- });
+ const managedEmailReason = await $getManagedEmailReason(userId, tx);
+ if (managedEmailReason) {
+ throw new BadRequestError({ message: managedEmailReason, name: "VerifyCurrentEmailOTP" });
}
let tokenData;
@@ -443,12 +450,9 @@ export const userServiceFactory = ({
throw new BadRequestError({ message: "Cannot update email for LDAP users", name: "UpdateUserEmail" });
}
- const hasScimRestriction = await checkUserScimRestriction(userId, tx);
- if (hasScimRestriction) {
- throw new BadRequestError({
- message: "You are part of an organization that has SCIM enabled, and email changes are not allowed",
- name: "UpdateUserEmail"
- });
+ const managedEmailReason = await $getManagedEmailReason(userId, tx);
+ if (managedEmailReason) {
+ throw new BadRequestError({ message: managedEmailReason, name: "UpdateUserEmail" });
}
// Validate OTP and get the new email from token aliasId field
diff --git a/docs/documentation/platform/scim/overview.mdx b/docs/documentation/platform/scim/overview.mdx
index 23e559442c..0bcf40076e 100644
--- a/docs/documentation/platform/scim/overview.mdx
+++ b/docs/documentation/platform/scim/overview.mdx
@@ -24,6 +24,12 @@ You can configure your organization in Infisical to have users and user groups b
- Provisioning: The SCIM provider pushes user information to Infisical. If the user exists in Infisical, Infisical sends an email invitation to add them to the relevant organization in Infisical; if not, Infisical initializes a new user and sends them an email invitation to finish setting up their account in the organization.
- Deprovisioning: The SCIM provider instructs Infisical to remove user(s) from an organization in Infisical.
+## Email address changes
+
+Infisical identifies a member by their email address, so an update that changes the address is rejected unless your organization [enforces SSO](/documentation/platform/sso/overview#sso-enforcement). With enforcement on, the address comes from your identity provider: the update renames the existing Infisical account, and the member keeps their memberships and project access.
+
+The update is rejected with `409 Conflict` when another Infisical account already uses the new address. Remove or merge that account, then retry the provisioning job.
+
SCIM providers:
- [Okta SCIM](/documentation/platform/scim/okta)
diff --git a/docs/documentation/platform/sso/overview.mdx b/docs/documentation/platform/sso/overview.mdx
index 2b59f344b8..5d41dcc76d 100644
--- a/docs/documentation/platform/sso/overview.mdx
+++ b/docs/documentation/platform/sso/overview.mdx
@@ -46,10 +46,11 @@ If your required identity provider is not shown in the list above, please reach
## SSO enforcement
-When you enforce SAML or OIDC SSO for your organization, members can only access Infisical by logging in through your identity provider. Enforcement has two additional effects tied to your [verified email domain(s)](/documentation/platform/email-domain):
+When you enforce SAML or OIDC SSO for your organization, members can only access Infisical by logging in through your identity provider. Enforcement has three additional effects tied to your [verified email domain(s)](/documentation/platform/email-domain):
- **Email & password signup is blocked for your verified domain(s).** Once SSO is enforced, new email/password accounts can no longer be created for addresses on your verified domain(s). The verified domain and IdP are authoritative, so allowing a competing password account would reopen an account-takeover vector.
- **Email verification is skipped for SSO sign-ins.** Because the verified domain and IdP already prove ownership of the email, Infisical skips the additional email-verification step that normally applies to SSO logins (see the FAQ below).
+- **Email addresses and names come from your identity provider.** Each SSO login updates the member's email address and name to match the assertion. Someone renamed in your identity provider keeps their Infisical account and their access, and later notifications and audit log entries carry the new address. Members can't change their own email address while enforcement is on.
<Warning>
Before enforcing SSO, make sure a break-glass organization admin already has a password and SSO bypass access. After enforcement is enabled, the signup block prevents creating new password accounts for the domain.
@@ -77,6 +78,13 @@ This portal is accessible at `/login/admin` (e.g., https://app.infisical.com/log
To skip this step, [enforce SSO](#sso-enforcement) for your organization. Enforcement requires a [verified email domain](/documentation/platform/email-domain), so the domain and your identity provider are already authoritative for that email.
</Accordion>
+ <Accordion title="What happens when a member's email address changes in my identity provider?">
+ With SSO enforcement on, the next login updates that member's Infisical email address and name to match the assertion. The account, its memberships, and its access are unchanged, and audit log entries written from then on carry the new address. Entries written earlier keep the address that was current when they were recorded.
+
+ If your organization provisions through [SCIM](/documentation/platform/scim/overview), the change arrives on the provisioning job instead, without waiting for the member to log in.
+
+ When another Infisical account already uses the new address, Infisical leaves the email address as it is and records the conflict in the audit log. Remove or merge the other account, and the change applies on the next login.
+ </Accordion>
<Accordion title="Why do I get redirected to SSO when trying to use the Admin Login Portal?">
You are likely being redirected because you do not have email authentication mode enabled, or you're not an **Organization Admin**. This portal requires **Organization Admin** status and direct credential login (email and password). **Server Admin** status alone is insufficient.
</Accordion>
diff --git a/frontend/src/hooks/api/auditLogs/constants.tsx b/frontend/src/hooks/api/auditLogs/constants.tsx
index c873899893..d29a7d0fc4 100644
--- a/frontend/src/hooks/api/auditLogs/constants.tsx
+++ b/frontend/src/hooks/api/auditLogs/constants.tsx
@@ -199,6 +199,9 @@ export const eventToNameMap: { [K in EventType]: string } = {
"OIDC group membership mapping removed user from groups",
[EventType.OIDC_PROVISIONED_PLACEHOLDER_ADOPTED]:
"OIDC login adopted provisioned placeholder account",
+ [EventType.SSO_USER_PROFILE_SYNCED]: "Synced user profile from identity provider",
+ [EventType.SSO_USER_PROFILE_SYNC_CONFLICT]:
+ "Skipped user email sync from identity provider due to conflict",
[EventType.SECRET_APPROVAL_REQUEST_REVIEW]: "Review Secret Approval Request",
[EventType.CREATE_KMIP_CLIENT]: "Create KMIP client",
[EventType.UPDATE_KMIP_CLIENT]: "Update KMIP client",
diff --git a/frontend/src/hooks/api/auditLogs/enums.tsx b/frontend/src/hooks/api/auditLogs/enums.tsx
index 2abe4658a1..93bdf31aa1 100644
--- a/frontend/src/hooks/api/auditLogs/enums.tsx
+++ b/frontend/src/hooks/api/auditLogs/enums.tsx
@@ -206,6 +206,8 @@ export enum EventType {
OIDC_GROUP_MEMBERSHIP_MAPPING_ASSIGN_USER = "oidc-group-membership-mapping-assign-user",
OIDC_GROUP_MEMBERSHIP_MAPPING_REMOVE_USER = "oidc-group-membership-mapping-remove-user",
OIDC_PROVISIONED_PLACEHOLDER_ADOPTED = "oidc-provisioned-placeholder-adopted",
+ SSO_USER_PROFILE_SYNCED = "sso-user-profile-synced",
+ SSO_USER_PROFILE_SYNC_CONFLICT = "sso-user-profile-sync-conflict",
CREATE_KMIP_CLIENT = "create-kmip-client",
UPDATE_KMIP_CLIENT = "update-kmip-client",
DELETE_KMIP_CLIENT = "delete-kmip-client",