Skip to content

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

refuse email change if SSO enforce and domain aware username

Thiago Araujo da Silva215e217eac1c
diff --git a/backend/CLAUDE.md b/backend/CLAUDE.md
index f1685606ce..cf1fb8e1b0 100644
--- a/backend/CLAUDE.md
+++ b/backend/CLAUDE.md
@@ -461,7 +461,11 @@ rejected every email change outright, which left the data stale *and* put the pr
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.
+(`user-service.ts`) is refused when the next login would overwrite it anyway, which
+`$getManagedEmailReason` narrows to the case that actually would: the account's own address sits on a
+domain one of its SSO-enforced orgs has verified. Membership in an enforced org is not the test, since
+the user row is global and an address outside that org's domains is one `syncSsoUserProfile` will not
+touch. SCIM stays a blanket refusal, because the directory provisions the address either way.
### Permission System (CASL)
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index a3c673da94..4e1d58021a 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -1313,7 +1313,8 @@ export const registerRoutes = async (
webAuthnCredentialDAL,
mfaRecoveryCodeService,
usageMeteringService,
- alertChannelRecipientDAL
+ alertChannelRecipientDAL,
+ emailDomainDAL
});
const totpService = totpServiceFactory({
diff --git a/backend/src/services/user/user-service.test.ts b/backend/src/services/user/user-service.test.ts
new file mode 100644
index 0000000000..db88badb07
--- /dev/null
+++ b/backend/src/services/user/user-service.test.ts
@@ -0,0 +1,142 @@
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
+
+import { EmailDomainStatus } from "@app/ee/services/email-domain/email-domain-types";
+
+import { userServiceFactory } from "./user-service";
+
+vi.mock("@app/lib/config/env", () => ({
+ getConfig: () => ({ SITE_URL: "https://app.infisical.com", isSmtpConfigured: true })
+}));
+
+vi.mock("@app/lib/logger", () => ({
+ logger: { info: vi.fn(), error: vi.fn(), warn: vi.fn(), debug: vi.fn() }
+}));
+
+const USER_ID = "11111111-1111-1111-1111-111111111111";
+const ENFORCED_ORG_ID = "22222222-2222-2222-2222-222222222222";
+
+const user = {
+ id: USER_ID,
+ username: "[email protected]",
+ email: "[email protected]",
+ authMethods: ["email"]
+};
+
+type Overrides = {
+ organizations?: { id: string; scimEnabled?: boolean; authEnforced?: boolean }[];
+ verifiedDomains?: { orgId: string; domain: string; status: string }[];
+};
+
+const buildService = ({ organizations = [], verifiedDomains = [] }: Overrides) => {
+ const emailDomainDAL = {
+ find: vi.fn(async (filter: Record<string, unknown>) => {
+ const orgIds = (filter.$in as { orgId: string[] })?.orgId ?? [];
+ return verifiedDomains.filter(
+ (row) => row.domain === filter.domain && row.status === filter.status && orgIds.includes(row.orgId)
+ );
+ })
+ };
+
+ const tokenService = { createTokenForUser: vi.fn().mockResolvedValue("123456") };
+ const smtpService = { sendMail: vi.fn().mockResolvedValue(undefined) };
+
+ const service = userServiceFactory({
+ userDAL: {
+ findById: vi.fn().mockResolvedValue(user),
+ // The service threads `tx` through every call; the stubs ignore it.
+ transaction: vi.fn(async (cb: (tx: unknown) => Promise<unknown>) => cb({}))
+ },
+ membershipUserDAL: {
+ find: vi.fn().mockResolvedValue(organizations.map((org) => ({ scopeOrgId: org.id })))
+ },
+ orgDAL: { find: vi.fn().mockResolvedValue(organizations) },
+ emailDomainDAL,
+ tokenService,
+ smtpService
+ } as unknown as Parameters<typeof userServiceFactory>[0]);
+
+ return { service, emailDomainDAL, tokenService };
+};
+
+// Settle the call before advancing the clock, so a refusal that rejects while the timers run still
+// has a handler attached. The success path pads its response to a fixed duration to defeat timing
+// enumeration, which is what needs the clock advanced at all.
+const requestChange = async (service: ReturnType<typeof buildService>["service"]) => {
+ const settled = service
+ .requestEmailChangeOTP({ userId: USER_ID, newEmail: "[email protected]" })
+ .then((value) => ({ value, error: undefined }))
+ .catch((error: Error) => ({ value: undefined, error }));
+
+ await vi.runAllTimersAsync();
+
+ const { value, error } = await settled;
+ if (error) throw error;
+ return value;
+};
+
+describe("requestEmailChangeOTP managed-email gate", () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ test("allows the change when the user belongs to no organization", async () => {
+ const { service, tokenService } = buildService({});
+
+ await expect(requestChange(service)).resolves.toMatchObject({ success: true });
+ expect(tokenService.createTokenForUser).toHaveBeenCalledOnce();
+ });
+
+ test("refuses the change when any organization has SCIM enabled", async () => {
+ const { service, emailDomainDAL } = buildService({
+ organizations: [{ id: ENFORCED_ORG_ID, scimEnabled: true }]
+ });
+
+ await expect(requestChange(service)).rejects.toThrow(/SCIM is enabled/);
+ expect(emailDomainDAL.find).not.toHaveBeenCalled();
+ });
+
+ test("refuses the change when the address is on a verified domain of an SSO-enforced org", async () => {
+ const { service } = buildService({
+ organizations: [{ id: ENFORCED_ORG_ID, authEnforced: true }],
+ verifiedDomains: [{ orgId: ENFORCED_ORG_ID, domain: "corp.com", status: EmailDomainStatus.Verified }]
+ });
+
+ await expect(requestChange(service)).rejects.toThrow(/enforces SSO/);
+ });
+
+ test("allows the change when the enforced org has not verified the address's domain", async () => {
+ const { service, tokenService } = buildService({
+ organizations: [{ id: ENFORCED_ORG_ID, authEnforced: true }],
+ verifiedDomains: [{ orgId: ENFORCED_ORG_ID, domain: "other.com", status: EmailDomainStatus.Verified }]
+ });
+
+ await expect(requestChange(service)).resolves.toMatchObject({ success: true });
+ expect(tokenService.createTokenForUser).toHaveBeenCalledOnce();
+ });
+
+ test("allows the change when the domain is verified only by an org that does not enforce SSO", async () => {
+ const { service, tokenService } = buildService({
+ organizations: [{ id: ENFORCED_ORG_ID, authEnforced: true }, { id: "33333333-3333-3333-3333-333333333333" }],
+ verifiedDomains: [
+ { orgId: "33333333-3333-3333-3333-333333333333", domain: "corp.com", status: EmailDomainStatus.Verified }
+ ]
+ });
+
+ await expect(requestChange(service)).resolves.toMatchObject({ success: true });
+ expect(tokenService.createTokenForUser).toHaveBeenCalledOnce();
+ });
+
+ test("allows the change when the domain is only pending verification", async () => {
+ const { service, tokenService } = buildService({
+ organizations: [{ id: ENFORCED_ORG_ID, authEnforced: true }],
+ verifiedDomains: [{ orgId: ENFORCED_ORG_ID, domain: "corp.com", status: EmailDomainStatus.Pending }]
+ });
+
+ await expect(requestChange(service)).resolves.toMatchObject({ success: true });
+ expect(tokenService.createTokenForUser).toHaveBeenCalledOnce();
+ });
+});
diff --git a/backend/src/services/user/user-service.ts b/backend/src/services/user/user-service.ts
index 3cf8638492..efb0a9c231 100644
--- a/backend/src/services/user/user-service.ts
+++ b/backend/src/services/user/user-service.ts
@@ -1,7 +1,9 @@
import { ForbiddenError } from "@casl/ability";
import { Knex } from "knex";
-import { AccessScope, OrganizationActionScope } from "@app/db/schemas";
+import { AccessScope, OrganizationActionScope, TUsers } from "@app/db/schemas";
+import { TEmailDomainDALFactory } from "@app/ee/services/email-domain/email-domain-dal";
+import { EmailDomainStatus } from "@app/ee/services/email-domain/email-domain-types";
import { OrgPermissionActions, OrgPermissionSubjects } from "@app/ee/services/permission/org-permission";
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
import { getConfig } from "@app/lib/config/env";
@@ -75,6 +77,7 @@ type TUserServiceFactoryDep = {
mfaRecoveryCodeService: Pick<TMfaRecoveryCodeServiceFactory, "rotateRecoveryCodes" | "deleteRecoveryCodes">;
usageMeteringService: Pick<TUsageMeteringServiceFactory, "emit">;
alertChannelRecipientDAL: Pick<TAlertChannelRecipientDALFactory, "deleteByPrincipals">;
+ emailDomainDAL: Pick<TEmailDomainDALFactory, "find">;
};
export type TUserServiceFactory = ReturnType<typeof userServiceFactory>;
@@ -92,7 +95,8 @@ export const userServiceFactory = ({
webAuthnCredentialDAL,
mfaRecoveryCodeService,
usageMeteringService,
- alertChannelRecipientDAL
+ alertChannelRecipientDAL,
+ emailDomainDAL
}: TUserServiceFactoryDep) => {
const sendEmailVerificationCode = async (token: string) => {
const config = getConfig();
@@ -272,11 +276,16 @@ export const userServiceFactory = ({
* 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.
+ *
+ * Enforcement only reaches an address on a domain the enforcing org has verified, since
+ * syncSsoUserProfile refuses to rename anything else. The user row is global, so membership in an
+ * enforced org is not on its own a claim over the address: someone whose mailbox sits outside that
+ * org's domains still owns it and keeps the change.
*/
- const $getManagedEmailReason = async (userId: string, tx?: Knex) => {
+ const $getManagedEmailReason = async (user: Pick<TUsers, "id" | "username">, tx?: Knex) => {
const userOrgs = await membershipUserDAL.find(
{
- actorUserId: userId,
+ actorUserId: user.id,
scope: AccessScope.Organization
},
{ tx }
@@ -293,8 +302,27 @@ export const userServiceFactory = ({
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.";
+ const authEnforcedOrgIds = organizations.filter((org) => org.authEnforced).map((org) => org.id);
+ if (!authEnforcedOrgIds.length) {
+ return null;
+ }
+
+ const emailDomain = user.username.split("@")[1]?.toLowerCase().trim();
+ if (!emailDomain) {
+ return null;
+ }
+
+ const [managedDomain] = await emailDomainDAL.find(
+ {
+ domain: emailDomain,
+ status: EmailDomainStatus.Verified,
+ $in: { orgId: authEnforcedOrgIds }
+ },
+ { tx, limit: 1 }
+ );
+
+ if (managedDomain) {
+ return "Email changes are disabled because your address is on a domain belonging to an organization that enforces SSO. Your email address is managed by your identity provider.";
}
return null;
@@ -327,7 +355,7 @@ export const userServiceFactory = ({
});
}
- const managedEmailReason = await $getManagedEmailReason(userId, tx);
+ const managedEmailReason = await $getManagedEmailReason(user, tx);
if (managedEmailReason) {
throw new BadRequestError({ message: managedEmailReason, name: "RequestEmailChangeOTP" });
}
@@ -373,7 +401,7 @@ export const userServiceFactory = ({
throw new BadRequestError({ message: "Cannot update email for LDAP users", name: "VerifyCurrentEmailOTP" });
}
- const managedEmailReason = await $getManagedEmailReason(userId, tx);
+ const managedEmailReason = await $getManagedEmailReason(user, tx);
if (managedEmailReason) {
throw new BadRequestError({ message: managedEmailReason, name: "VerifyCurrentEmailOTP" });
}
@@ -450,7 +478,7 @@ export const userServiceFactory = ({
throw new BadRequestError({ message: "Cannot update email for LDAP users", name: "UpdateUserEmail" });
}
- const managedEmailReason = await $getManagedEmailReason(userId, tx);
+ const managedEmailReason = await $getManagedEmailReason(user, tx);
if (managedEmailReason) {
throw new BadRequestError({ message: managedEmailReason, name: "UpdateUserEmail" });
}
diff --git a/docs/documentation/platform/sso/overview.mdx b/docs/documentation/platform/sso/overview.mdx
index 5d41dcc76d..9daef01b65 100644
--- a/docs/documentation/platform/sso/overview.mdx
+++ b/docs/documentation/platform/sso/overview.mdx
@@ -50,7 +50,7 @@ When you enforce SAML or OIDC SSO for your organization, members can only access
- **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.
+- **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 on one of your verified domains 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.