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: updated check for verified domain in all providers
=7351cfbdb9ef
diff --git a/backend/src/ee/services/email-domain/email-domain-fns.ts b/backend/src/ee/services/email-domain/email-domain-fns.tsnew file mode 100644index 0000000000..b81916404a--- /dev/null+++ b/backend/src/ee/services/email-domain/email-domain-fns.ts@@ -0,0 +1,84 @@+import { getHostname } from "tldts";++import { AccessScope, TableName } from "@app/db/schemas";+import { BadRequestError } from "@app/lib/errors";+import { TOrgDALFactory } from "@app/services/org/org-dal";++import { TEmailDomainDALFactory } from "./email-domain-dal";+import { EmailDomainStatus } from "./email-domain-types";++/**+ * Given an email and orgId, verifies the org is allowed to manage a user with this email.+ *+ * Two-tier check:+ * 1. If the email domain has a verified record → it must belong to this org, else throw.+ * 2. If no verified domain → if a userId is provided, check if that user exists in another org.+ * If so, throw — the org must verify the domain first to manage cross-org users.+ */+export const verifyEmailDomainOwnership = async ({+ email,+ orgId,+ emailDomainDAL,+ orgDAL,+ userId+}: {+ email: string;+ orgId: string;+ emailDomainDAL: Pick<TEmailDomainDALFactory, "findOne">;+ orgDAL: Pick<TOrgDALFactory, "findMembership">;+ userId?: string;+}) => {+ const emailDomain = getHostname(email);+ if (!emailDomain) throw new BadRequestError({ message: "Invalid email address" });++ // Tier 1: Check verified domain ownership+ const verifiedDomain = await emailDomainDAL.findOne({+ domain: emailDomain,+ status: EmailDomainStatus.Verified+ });++ if (verifiedDomain) {+ if (verifiedDomain.orgId !== orgId) {+ throw new BadRequestError({+ message: `The email domain "${emailDomain}" is verified by another organization. This operation is not allowed.`+ });+ }+ return;+ }++ // Tier 2: No verified domain — check if user exists in other orgs+ if (!userId) return;++ const existingMemberships = await orgDAL.findMembership({+ [`${TableName.Membership}.actorUserId` as "actorUserId"]: userId,+ [`${TableName.Membership}.scope` as "scope"]: AccessScope.Organization+ });++ const belongsToOtherOrg = existingMemberships.some((m) => m.scopeOrgId !== orgId);+ if (belongsToOtherOrg) {+ throw new BadRequestError({+ message: `This user belongs to another organization. To manage users with this email domain, please verify "${emailDomain}" in your organization's email domain settings first.`+ });+ }+};++/**+ * Given a domain string, finds the verified email domain record+ * and returns its orgId. Returns undefined if no verified record exists.+ */+export const findOrgIdByVerifiedDomain = async ({+ domain,+ emailDomainDAL+}: {+ domain: string;+ emailDomainDAL: Pick<TEmailDomainDALFactory, "findOne">;+}) => {+ const normalizedDomain = domain.toLowerCase().trim();++ const verifiedDomain = await emailDomainDAL.findOne({+ domain: normalizedDomain,+ status: EmailDomainStatus.Verified+ });++ return verifiedDomain ?? undefined;+};diff --git a/backend/src/ee/services/ldap-config/ldap-config-service.ts b/backend/src/ee/services/ldap-config/ldap-config-service.tsindex 231df210e7..8bf1db098b 100644--- a/backend/src/ee/services/ldap-config/ldap-config-service.ts+++ b/backend/src/ee/services/ldap-config/ldap-config-service.ts@@ -35,6 +35,8 @@ import { normalizeUsername } from "@app/services/user/user-fns";import { TUserAliasDALFactory } from "@app/services/user-alias/user-alias-dal";import { UserAliasType } from "@app/services/user-alias/user-alias-types";+import { TEmailDomainDALFactory } from "../email-domain/email-domain-dal";+import { verifyEmailDomainOwnership } from "../email-domain/email-domain-fns";import { TLicenseServiceFactory } from "../license/license-service";import { OrgPermissionActions, OrgPermissionSubjects } from "../permission/org-permission";import { TPermissionServiceFactory } from "../permission/permission-service-types";@@ -86,6 +88,7 @@ type TLdapConfigServiceFactoryDep = {smtpService: Pick<TSmtpService, "sendMail">;kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;loginService: Pick<TAuthLoginFactory, "processProviderCallback">;+ emailDomainDAL: Pick<TEmailDomainDALFactory, "findOne">;};export type TLdapConfigServiceFactory = ReturnType<typeof ldapConfigServiceFactory>;@@ -108,7 +111,8 @@ export const ldapConfigServiceFactory = ({tokenService,smtpService,kmsService,- loginService+ loginService,+ emailDomainDAL}: TLdapConfigServiceFactoryDep) => {const createLdapCfg = async ({actor,@@ -405,6 +409,9 @@ export const ldapConfigServiceFactory = ({});}+ // Verify that the email domain (if verified on the platform) belongs to this org+ await verifyEmailDomainOwnership({ email, orgId, emailDomainDAL, orgDAL });+let userAlias = await userAliasDAL.findOne({externalId,orgId,@@ -415,6 +422,11 @@ export const ldapConfigServiceFactory = ({if (!organization) throw new NotFoundError({ message: `Organization with ID '${orgId}' not found` });if (userAlias) {+ // Verify the existing user's stored email domain + cross-org check+ const existingUser = await userDAL.findOne({ id: userAlias.userId });+ if (existingUser) {+ await verifyEmailDomainOwnership({ email: existingUser.username, orgId, emailDomainDAL, orgDAL, userId: existingUser.id });+ }await userDAL.transaction(async (tx) => {const [orgMembership] = await orgDAL.findMembership({@@ -459,41 +471,7 @@ export const ldapConfigServiceFactory = ({userAlias = await userDAL.transaction(async (tx) => {let newUser: TUsers | undefined;- const usersWithSameEmail = await userDAL.find(- {- email: email.toLowerCase()- },- {- tx- }- );-- const verifiedEmail = usersWithSameEmail.find((el) => el.isEmailVerified);- const userWithSameUsername = usersWithSameEmail.find((el) => el.username === email.toLowerCase());- if (verifiedEmail) {- newUser = verifiedEmail;- } else if (userWithSameUsername) {- newUser = userWithSameUsername;- }-- // Prevent cross-org account takeover: if an existing user was found by email,- // verify they are already a member of this org before binding the LDAP identity.- if (newUser) {- const [existingMembership] = await orgDAL.findMembership(- {- [`${TableName.Membership}.actorUserId` as "actorUserId"]: newUser.id,- [`${TableName.Membership}.scopeOrgId` as "scopeOrgId"]: orgId,- [`${TableName.Membership}.scope` as "scope"]: AccessScope.Organization- },- { tx }- );- if (!existingMembership) {- throw new ForbiddenRequestError({- message:- "User is not a member of this organization. Please contact your organization admin to receive an invite."- });- }- }+ newUser = await userDAL.findOne({ username: email.toLowerCase() }, tx);if (!newUser) {const uniqueUsername = await normalizeUsername(username, userDAL);diff --git a/backend/src/ee/services/oidc/oidc-config-service.ts b/backend/src/ee/services/oidc/oidc-config-service.tsindex 36684379c4..76a323aa31 100644--- a/backend/src/ee/services/oidc/oidc-config-service.ts+++ b/backend/src/ee/services/oidc/oidc-config-service.ts@@ -39,6 +39,8 @@ import { normalizeUsername } from "@app/services/user/user-fns";import { TUserAliasDALFactory } from "@app/services/user-alias/user-alias-dal";import { UserAliasType } from "@app/services/user-alias/user-alias-types";+import { TEmailDomainDALFactory } from "../email-domain/email-domain-dal";+import { verifyEmailDomainOwnership } from "../email-domain/email-domain-fns";import { TOidcConfigDALFactory } from "./oidc-config-dal";import {OIDCConfigurationType,@@ -88,6 +90,7 @@ type TOidcConfigServiceFactoryDep = {auditLogService: Pick<TAuditLogServiceFactory, "createAuditLog">;kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;loginService: Pick<TAuthLoginFactory, "processProviderCallback">;+ emailDomainDAL: Pick<TEmailDomainDALFactory, "findOne">;};export type TOidcConfigServiceFactory = ReturnType<typeof oidcConfigServiceFactory>;@@ -110,7 +113,8 @@ export const oidcConfigServiceFactory = ({projectBotDAL,auditLogService,kmsService,- loginService+ loginService,+ emailDomainDAL}: TOidcConfigServiceFactoryDep) => {const getOidc = async (dto: TGetOidcCfgDTO) => {const oidcCfg = await oidcConfigDAL.findOne({@@ -188,6 +192,9 @@ export const oidcConfigServiceFactory = ({});}+ // Verify that the email domain (if verified on the platform) belongs to this org+ await verifyEmailDomainOwnership({ email, orgId, emailDomainDAL, orgDAL });+let userAlias = await userAliasDAL.findOne({externalId,orgId,@@ -201,6 +208,8 @@ export const oidcConfigServiceFactory = ({if (userAlias) {user = await userDAL.transaction(async (tx) => {const foundUser = await userDAL.findById(userAlias.userId, tx);+ // Verify the existing user's stored email domain + cross-org check+ await verifyEmailDomainOwnership({ email: foundUser.username, orgId, emailDomainDAL, orgDAL, userId: foundUser.id });const [orgMembership] = await orgDAL.findMembership({[`${TableName.Membership}.actorUserId` as "actorUserId"]: userAlias.userId,@@ -247,59 +256,15 @@ export const oidcConfigServiceFactory = ({user = await userDAL.transaction(async (tx) => {let newUser: TUsers | undefined;// we prioritize getting the most complete user to create the new alias under- const usersWithSameEmail = await userDAL.find(- {- email: email.toLowerCase()- },- {- tx- }- );-- const verifiedEmail = usersWithSameEmail.find((el) => el.isEmailVerified);- const userWithSameUsername = usersWithSameEmail.find((el) => el.username === email.toLowerCase());- if (verifiedEmail) {- newUser = verifiedEmail;- } else if (userWithSameUsername) {- newUser = userWithSameUsername;- }-- if (!newUser) {- // this fetches user entries created via invites- newUser = await userDAL.findOne(- {- username: email- },- tx- );-- if (newUser && !newUser.isEmailVerified) {- // we automatically mark it as email-verified because we've configured trust for OIDC emails- newUser = await userDAL.updateById(newUser.id, {- isEmailVerified: serverCfg.trustOidcEmails- });- }- }+ newUser = await userDAL.findOne({+ username: email.toLowerCase()+ });- // Prevent cross-org account takeover: if an existing user was found by email,- // verify they are already a member of this org before binding the SSO identity.- // Without this check, an attacker could configure OIDC on their own org with a- // victim's email and get a provider token signed for the victim's userId.- if (newUser) {- const [existingMembership] = await orgDAL.findMembership(- {- [`${TableName.Membership}.actorUserId` as "actorUserId"]: newUser.id,- [`${TableName.Membership}.scopeOrgId` as "scopeOrgId"]: orgId,- [`${TableName.Membership}.scope` as "scope"]: AccessScope.Organization- },- { tx }- );- if (!existingMembership) {- throw new ForbiddenRequestError({- message:- "User is not a member of this organization. Please contact your organization admin to receive an invite."- });- }+ if (newUser && !newUser.isEmailVerified && serverCfg.trustOidcEmails) {+ // we automatically mark it as email-verified because we've configured trust for OIDC emails+ newUser = await userDAL.updateById(newUser.id, {+ isEmailVerified: serverCfg.trustOidcEmails+ });}if (!newUser) {diff --git a/backend/src/ee/services/saml-config/saml-config-service.ts b/backend/src/ee/services/saml-config/saml-config-service.tsindex 5291631e57..21fd51e722 100644--- a/backend/src/ee/services/saml-config/saml-config-service.ts+++ b/backend/src/ee/services/saml-config/saml-config-service.ts@@ -38,6 +38,8 @@ import { normalizeUsername } from "@app/services/user/user-fns";import { TUserAliasDALFactory } from "@app/services/user-alias/user-alias-dal";import { UserAliasType } from "@app/services/user-alias/user-alias-types";+import { TEmailDomainDALFactory } from "../email-domain/email-domain-dal";+import { findOrgIdByVerifiedDomain, verifyEmailDomainOwnership } from "../email-domain/email-domain-fns";import { TGroupDALFactory } from "../group/group-dal";import { addUsersToGroupByUserIds, removeUsersFromGroupByUserIds } from "../group/group-fns";import { TUserGroupMembershipDALFactory } from "../group/user-group-membership-dal";@@ -85,6 +87,7 @@ type TSamlConfigServiceFactoryDep = {projectKeyDAL: Pick<TProjectKeyDALFactory, "find" | "delete" | "findLatestProjectKey" | "insertMany">;membershipGroupDAL: Pick<TMembershipGroupDALFactory, "find" | "create">;loginService: Pick<TAuthLoginFactory, "processProviderCallback">;+ emailDomainDAL: Pick<TEmailDomainDALFactory, "findOne">;};export const samlConfigServiceFactory = ({@@ -105,7 +108,8 @@ export const samlConfigServiceFactory = ({kmsService,membershipRoleDAL,membershipGroupDAL,- loginService+ loginService,+ emailDomainDAL}: TSamlConfigServiceFactoryDep): TSamlConfigServiceFactory => {const parseSamlGroups = (groupsValue: string): string[] => {let samlGroups: string[] = [];@@ -423,13 +427,32 @@ export const samlConfigServiceFactory = ({});}} else if (dto.type === "orgSlug") {- const org = await orgDAL.findOne({ slug: dto.orgSlug, rootOrgId: null });- if (!org) {- throw new NotFoundError({- message: `Organization with slug '${dto.orgSlug}' not found`- });+ let resolvedOrgId: string | undefined;++ // If orgSlug starts with @, treat the rest as a domain name and resolve via verified email domains+ if (dto.orgSlug.startsWith("@")) {+ const domain = dto.orgSlug.slice(1);+ const verifiedDomain = await findOrgIdByVerifiedDomain({ domain, emailDomainDAL });+ if (verifiedDomain) {+ resolvedOrgId = verifiedDomain.orgId;+ }+ }++ if (dto.orgSlug.startsWith("@") && !resolvedOrgId) {+ throw new NotFoundError({ message: `No verified domain found for '${dto.orgSlug.slice(1)}'` });+ }++ if (!resolvedOrgId) {+ const org = await orgDAL.findOne({ slug: dto.orgSlug, rootOrgId: null });+ if (!org) {+ throw new NotFoundError({+ message: `Organization with slug '${dto.orgSlug}' not found`+ });+ }+ resolvedOrgId = org.id;}- samlConfig = await samlConfigDAL.findOne({ orgId: org.id });++ samlConfig = await samlConfigDAL.findOne({ orgId: resolvedOrgId });} else if (dto.type === "ssoId") {// TODO:// We made this change because saml config ids were not moved over during the migration@@ -524,6 +547,9 @@ export const samlConfigServiceFactory = ({aliasType: UserAliasType.SAML});+ // Verify that the email domain (if verified on the platform) belongs to this org+ await verifyEmailDomainOwnership({ email, orgId, emailDomainDAL, orgDAL });+const organization = await orgDAL.findOrgById(orgId);if (!organization) throw new NotFoundError({ message: `Organization with ID '${orgId}' not found` });@@ -535,8 +561,16 @@ export const samlConfigServiceFactory = ({let user: TUsers;if (userAlias) {+ const foundUser = await userDAL.findById(userAlias.userId);+ // Verify the existing user's stored email domain + cross-org check+ await verifyEmailDomainOwnership({+ email: foundUser.username,+ orgId,+ emailDomainDAL,+ orgDAL,+ userId: foundUser.id+ });user = await userDAL.transaction(async (tx) => {- const foundUser = await userDAL.findById(userAlias.userId, tx);const [orgMembership] = await orgDAL.findMembership({[`${TableName.Membership}.actorUserId` as "actorUserId"]: userAlias.userId,@@ -611,46 +645,13 @@ export const samlConfigServiceFactory = ({user = await userDAL.transaction(async (tx) => {let newUser: TUsers | undefined;- const usersWithSameEmail = await userDAL.find(- {- email: email.toLowerCase()- },- {- tx- }- );-- const verifiedEmail = usersWithSameEmail.find((el) => el.isEmailVerified);- const userWithSameUsername = usersWithSameEmail.find((el) => el.username === email.toLowerCase());- if (verifiedEmail) {- newUser = verifiedEmail;- } else if (userWithSameUsername) {- newUser = userWithSameUsername;- }-- // Prevent cross-org account takeover: if an existing user was found by email,- // verify they are already a member of this org before binding the SAML identity.- if (newUser) {- const [existingMembership] = await orgDAL.findMembership(- {- [`${TableName.Membership}.actorUserId` as "actorUserId"]: newUser.id,- [`${TableName.Membership}.scopeOrgId` as "scopeOrgId"]: orgId,- [`${TableName.Membership}.scope` as "scope"]: AccessScope.Organization- },- { tx }- );- if (!existingMembership) {- throw new ForbiddenRequestError({- message:- "User is not a member of this organization. Please contact your organization admin to receive an invite."- });- }- }+ newUser = await userDAL.findOne({ username: email.toLowerCase() }, tx);if (!newUser) {const uniqueUsername = await normalizeUsername(`${firstName ?? ""}-${lastName ?? ""}`, userDAL);newUser = await userDAL.create({+ // TODO(auth-revamp): check if trustSamlEmails is neededusername: serverCfg.trustSamlEmails ? email.toLowerCase() : uniqueUsername,email,isEmailVerified: serverCfg.trustSamlEmails,diff --git a/backend/src/ee/services/scim/scim-service.ts b/backend/src/ee/services/scim/scim-service.tsindex 49856a9b4a..f7f41922e3 100644--- a/backend/src/ee/services/scim/scim-service.ts+++ b/backend/src/ee/services/scim/scim-service.ts@@ -42,6 +42,8 @@ import { normalizeUsername } from "@app/services/user/user-fns";import { TUserAliasDALFactory } from "@app/services/user-alias/user-alias-dal";import { UserAliasType } from "@app/services/user-alias/user-alias-types";+import { TEmailDomainDALFactory } from "../email-domain/email-domain-dal";+import { verifyEmailDomainOwnership } from "../email-domain/email-domain-fns";import { TLicenseServiceFactory } from "../license/license-service";import { OrgPermissionActions, OrgPermissionSubjects } from "../permission/org-permission";import { TPermissionServiceFactory } from "../permission/permission-service-types";@@ -55,7 +57,7 @@ type TScimServiceFactoryDep = {TUserDALFactory,"find" | "findOne" | "create" | "transaction" | "findUserEncKeyByUserIdsBatch" | "findById" | "updateById">;- userAliasDAL: Pick<TUserAliasDALFactory, "findOne" | "create" | "delete" | "update">;+ userAliasDAL: Pick<TUserAliasDALFactory, "findOne" | "create" | "delete" | "update" | "find">;orgDAL: Pick<TOrgDALFactory,| "createMembership"@@ -102,6 +104,7 @@ type TScimServiceFactoryDep = {externalGroupOrgRoleMappingDAL: TExternalGroupOrgRoleMappingDALFactory;additionalPrivilegeDAL: TAdditionalPrivilegeDALFactory;scimEventsDAL: Pick<TScimEventsDALFactory, "create" | "findEventsByOrgId">;+ emailDomainDAL: Pick<TEmailDomainDALFactory, "findOne">;};export const scimServiceFactory = ({@@ -122,7 +125,8 @@ export const scimServiceFactory = ({membershipUserDAL,membershipRoleDAL,additionalPrivilegeDAL,- scimEventsDAL+ scimEventsDAL,+ emailDomainDAL}: TScimServiceFactoryDep): TScimServiceFactory => {const createScimToken: TScimServiceFactory["createScimToken"] = async ({actor,@@ -404,18 +408,25 @@ export const scimServiceFactory = ({aliasType});+ // Resolve the user ID: either from the existing alias, or by looking up the email+ const existingUserId = userAlias?.userId ?? (await userDAL.findOne({ username: email.toLowerCase() }))?.id;++ // Verify that the email domain (if verified on the platform) belongs to this org+ await verifyEmailDomainOwnership({ email, orgId, emailDomainDAL, orgDAL, userId: existingUserId });+const { user: createdUser, orgMembership: createdOrgMembership } = await userDAL.transaction(async (tx) => {let user: TUsers | undefined;let orgMembership: TMemberships;if (userAlias) {user = await userDAL.findById(userAlias.userId, tx);- const effectiveMembership = await orgDAL.findEffectiveOrgMembership({- actorType: ActorType.USER,- actorId: user.id,- orgId,- acceptAnyStatus: true,+ const effectiveMembership = await membershipUserDAL.findOne(+ {+ actorUserId: user.id,+ scope: AccessScope.Organization,+ scopeOrgId: orgId+ },tx- });+ );if (!effectiveMembership) {const { role, roleId } = await getDefaultOrgMembershipRole(org.defaultMembershipRole);@@ -439,73 +450,17 @@ export const scimServiceFactory = ({},tx);- } else if (effectiveMembership.actorUserId === user.id) {- orgMembership = effectiveMembership;- if (orgMembership.status === OrgMembershipStatus.Invited && user.isAccepted) {- orgMembership = await membershipUserDAL.updateById(- orgMembership.id,- {- status: OrgMembershipStatus.Accepted- },- tx- );- }} else {- // Effective access via group only; create direct membership so SCIM list/get work- const { role, roleId } = await getDefaultOrgMembershipRole(org.defaultMembershipRole);-- orgMembership = await membershipUserDAL.create(- {- actorUserId: userAlias.userId,- inviteEmail: email.toLowerCase(),- scopeOrgId: orgId,- scope: AccessScope.Organization,- status: OrgMembershipStatus.Accepted,- isActive: true- },- tx- );- await membershipRoleDAL.create(- {- membershipId: orgMembership.id,- role,- customRoleId: roleId- },- tx- );+ orgMembership = effectiveMembership;}} else {- // we fetch all users with this email- const usersWithSameEmail = await userDAL.find(- {- email: email.toLowerCase()- },- {- tx- }- );-- // if there is a verified email user pick that- const verifiedEmail = usersWithSameEmail.find((el) => el.isEmailVerified);- const userWithSameUsername = usersWithSameEmail.find((el) => el.username === email.toLowerCase());- if (verifiedEmail) {- user = verifiedEmail;- // a user who is invited via email not logged in yet- } else if (userWithSameUsername) {- user = userWithSameUsername;- }-+ user = await userDAL.findOne({ username: email.toLowerCase() }, tx);if (!user) {- const uniqueUsername = await normalizeUsername(- // external id is username- `${firstName}-${lastName}`,- userDAL- );user = await userDAL.create({- username: trustScimEmails ? email.toLowerCase() : uniqueUsername,+ username: email.toLowerCase(),email: email.toLowerCase(),- isEmailVerified: trustScimEmails,+ isEmailVerified: false,firstName,lastName,authMethods: [],@@ -530,18 +485,19 @@ export const scimServiceFactory = ({externalId,emails: email ? [email.toLowerCase()] : [],orgId,- isEmailVerified: trustScimEmails+ isEmailVerified: false},tx);- const effectiveMembership = await orgDAL.findEffectiveOrgMembership({- actorType: ActorType.USER,- actorId: user.id,- orgId,- acceptAnyStatus: true,+ const effectiveMembership = await membershipUserDAL.findOne(+ {+ actorUserId: user.id,+ scopeOrgId: orgId,+ scope: AccessScope.Organization+ },tx- });+ );if (!effectiveMembership) {const { role, roleId } = await getDefaultOrgMembershipRole(org.defaultMembershipRole);@@ -565,40 +521,8 @@ export const scimServiceFactory = ({},tx);- } else if (effectiveMembership.actorUserId === user.id) {- orgMembership = effectiveMembership;- if (orgMembership.status === OrgMembershipStatus.Invited && user.isAccepted) {- orgMembership = await orgDAL.updateMembershipById(- orgMembership.id,- {- status: OrgMembershipStatus.Accepted- },- tx- );- }} else {- // Effective access via group only; create direct membership so SCIM list/get work- const { role, roleId } = await getDefaultOrgMembershipRole(org.defaultMembershipRole);-- orgMembership = await membershipUserDAL.create(- {- actorUserId: user.id,- inviteEmail: email.toLowerCase(),- scopeOrgId: orgId,- scope: AccessScope.Organization,- status: OrgMembershipStatus.Accepted,- isActive: true- },- tx- );- await membershipRoleDAL.create(- {- membershipId: orgMembership.id,- role,- customRoleId: roleId- },- tx- );+ orgMembership = effectiveMembership;}}await scimEventsDAL.create(@@ -610,7 +534,7 @@ export const scimServiceFactory = ({email: user.email ?? "",firstName: user.firstName,lastName: user.lastName,- active: orgMembership.isActive+ active: orgMembership?.isActive}},tx@@ -633,7 +557,7 @@ export const scimServiceFactory = ({return buildScimUser({orgMembershipId: createdOrgMembership.id,- username: externalId,+ username: email,firstName: createdUser.firstName,lastName: createdUser.lastName,email: createdUser.email ?? "",@@ -653,8 +577,8 @@ export const scimServiceFactory = ({});}- const [membership] = await orgDAL- .findMembership({+ const membership = await membershipUserDAL+ .findOne({[`${TableName.Membership}.id` as "id"]: orgMembershipId,[`${TableName.Membership}.scopeOrgId` as "scopeOrgId"]: orgId,[`${TableName.Membership}.scope` as "scope"]: AccessScope.Organization@@ -672,27 +596,56 @@ export const scimServiceFactory = ({status: 404});- if (!membership.scimEnabled)+ if (!org.scimEnabled)throw new ScimRequestError({detail: "SCIM is disabled for the organization",status: 403});+ const userAliases = await userAliasDAL.find({+ userId: membership.actorUserId,+ orgId,+ aliasType: org.orgAuthMethod === OrgAuthMethod.OIDC ? UserAliasType.OIDC : UserAliasType.SAML+ });+ const userAliasesIds = userAliases.map((el) => el.id);+ if (!userAliasesIds.length)+ throw new ScimRequestError({+ detail: "User alias not found",+ status: 404+ });++ const user = await userDAL.findOne({ id: membership.actorUserId });+const scimUser = buildScimUser({orgMembershipId: membership.id,- email: membership.email,- lastName: membership.lastName,- firstName: membership.firstName,+ email: user.email,+ lastName: user.lastName,+ firstName: user.firstName,active: membership.isActive,- username: membership.externalId ?? membership.username,+ username: user.username,createdAt: membership.createdAt,updatedAt: membership.updatedAt});scimPatch(scimUser, operations);- const serverCfg = await getServerCfg();- const trustScimEmails =- org.orgAuthMethod === OrgAuthMethod.OIDC ? serverCfg.trustOidcEmails : serverCfg.trustSamlEmails;+ await verifyEmailDomainOwnership({+ email: user.username,+ orgId,+ emailDomainDAL,+ orgDAL,+ userId: membership.actorUserId+ });+ // TODO(auth-revamp): validate username is email+ const hasEmailChanged = scimUser.userName !== user.username;+ if (hasEmailChanged) {+ await verifyEmailDomainOwnership({+ email: scimUser.userName,+ orgId,+ emailDomainDAL,+ orgDAL,+ userId: user.id+ });+ }await userDAL.transaction(async (tx) => {await membershipUserDAL.updateById(@@ -702,25 +655,38 @@ export const scimServiceFactory = ({},tx);- const hasEmailChanged = scimUser.emails[0].value !== membership.email;await userDAL.updateById(membership.actorUserId as string,{firstName: scimUser.name.givenName,- email: scimUser.emails[0].value.toLowerCase(),+ ...(hasEmailChanged ? { username: scimUser.userName, email: scimUser.userName } : {}),lastName: scimUser.name.familyName,- isEmailVerified: hasEmailChanged ? trustScimEmails : undefined+ isEmailVerified: hasEmailChanged ? false : undefined},tx);+ if (hasEmailChanged) {+ // clean up previous alias of same auth type and set the new one+ await userAliasDAL.delete({ $in: { id: userAliasesIds } }, tx);+ await userAliasDAL.create(+ {+ userId: user.id,+ aliasType: org.orgAuthMethod === OrgAuthMethod.OIDC ? UserAliasType.OIDC : UserAliasType.SAML,+ emails: [scimUser.userName],+ orgId,+ externalId: userAliases[0].externalId+ },+ tx+ );+ }await scimEventsDAL.create({orgId,eventType: ScimEvent.UPDATE_USER,event: {firstName: scimUser.name.givenName,- email: scimUser.emails[0].value.toLowerCase(),+ email: scimUser.userName,lastName: scimUser.name.familyName,active: scimUser.active}@@ -774,23 +740,42 @@ export const scimServiceFactory = ({status: 403});- const serverCfg = await getServerCfg();- const hasEmailChanged = email?.toLowerCase() !== membership.email;- const defaultEmailVerified =- org.orgAuthMethod === OrgAuthMethod.OIDC ? serverCfg.trustOidcEmails : serverCfg.trustSamlEmails;- await userDAL.transaction(async (tx) => {- await userAliasDAL.update(- {- orgId,- aliasType: org.orgAuthMethod === OrgAuthMethod.OIDC ? UserAliasType.OIDC : UserAliasType.SAML,- userId: membership.actorUserId as string- },- {- externalId- },- tx- );+ const aliasType = org.orgAuthMethod === OrgAuthMethod.OIDC ? UserAliasType.OIDC : UserAliasType.SAML;++ const userAliases = await userAliasDAL.find({+ userId: membership.actorUserId,+ orgId,+ aliasType+ });+ if (!userAliases.length)+ throw new ScimRequestError({+ detail: "User alias not found",+ status: 404+ });++ const user = await userDAL.findOne({ id: membership.actorUserId });+ const hasEmailChanged = email?.toLowerCase() !== user.username;++ await verifyEmailDomainOwnership({+ email: user.username,+ orgId,+ emailDomainDAL,+ orgDAL,+ userId: membership.actorUserId+ });++ if (hasEmailChanged && email) {+ await verifyEmailDomainOwnership({+ email,+ orgId,+ emailDomainDAL,+ orgDAL,+ userId: membership.actorUserId+ });+ }++ await userDAL.transaction(async (tx) => {await membershipUserDAL.updateById(membership.id,{@@ -802,13 +787,31 @@ export const scimServiceFactory = ({membership.actorUserId!,{firstName,- email: email?.toLowerCase(),+ ...(hasEmailChanged && email ? { username: email.toLowerCase(), email: email.toLowerCase() } : {}),lastName,- isEmailVerified: hasEmailChanged ? defaultEmailVerified : undefined+ isEmailVerified: hasEmailChanged ? false : undefined},tx);+ if (hasEmailChanged && email) {+ const userAliasesIds = userAliases.map((el) => el.id);+ await userAliasDAL.delete({ $in: { id: userAliasesIds } }, tx);+ await userAliasDAL.create(+ {+ userId: user.id,+ aliasType,+ emails: [email.toLowerCase()],+ orgId,+ externalId: externalId || userAliases[0].externalId+ },+ tx+ );+ } else {+ // 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,@@ -827,10 +830,10 @@ export const scimServiceFactory = ({return buildScimUser({orgMembershipId: membership.id,- username: externalId,- email: membership.email,- firstName: membership.firstName,- lastName: membership.lastName,+ username: user.username,+ email: hasEmailChanged && email ? email.toLowerCase() : user.email,+ firstName: firstName || user.firstName,+ lastName: lastName || user.lastName,active,createdAt: membership.createdAt,updatedAt: membership.updatedAtdiff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex 95373f871f..d2b8c8abc8 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -928,7 +928,8 @@ export const registerRoutes = async (membershipGroupDAL,membershipRoleDAL,membershipUserDAL,- additionalPrivilegeDAL+ additionalPrivilegeDAL,+ emailDomainDAL});const githubOrgSyncConfigService = githubOrgSyncServiceFactory({@@ -1021,7 +1022,8 @@ export const registerRoutes = async (kmsService,membershipRoleDAL,membershipGroupDAL,- loginService+ loginService,+ emailDomainDAL});const ldapService = ldapConfigServiceFactory({@@ -1042,7 +1044,8 @@ export const registerRoutes = async (kmsService,membershipGroupDAL,membershipRoleDAL,- loginService+ loginService,+ emailDomainDAL});const passwordService = authPaswordServiceFactory({tokenService,@@ -2219,7 +2222,8 @@ export const registerRoutes = async (auditLogService,membershipGroupDAL,membershipRoleDAL,- loginService+ loginService,+ emailDomainDAL});const userEngagementService = userEngagementServiceFactory({diff --git a/backend/src/services/auth/auth-login-service.ts b/backend/src/services/auth/auth-login-service.tsindex 8edadca742..0f7b927a25 100644--- a/backend/src/services/auth/auth-login-service.ts+++ b/backend/src/services/auth/auth-login-service.ts@@ -149,6 +149,62 @@ export const authLoginServiceFactory = ({});};+ /*+ * Private+ * Determines the required MFA method based on org enforcement vs user preference.+ */+ const getRequiredMfaMethod = (+ org: { enforceMfa?: boolean | null; selectedMfaMethod?: string | null },+ user: { isMfaEnabled?: boolean | null; selectedMfaMethod?: string | null }+ ): { isMfaRequired: boolean; requiredMfaMethod: MfaMethod } => {+ const isOrgMfaEnforced = Boolean(org.enforceMfa);+ const isUserMfaEnabled = Boolean(user.isMfaEnabled);+ const isMfaRequired = isOrgMfaEnforced || isUserMfaEnabled;++ const requiredMfaMethod = isOrgMfaEnforced+ ? ((org.selectedMfaMethod as MfaMethod) ?? MfaMethod.EMAIL)+ : ((user.selectedMfaMethod as MfaMethod) ?? MfaMethod.EMAIL);++ return { isMfaRequired, requiredMfaMethod };+ };++ /*+ * Private+ * Issues an MFA challenge: generates an MFA JWT token and sends the email code if needed.+ */+ const issueMfaChallenge = async ({+ userId,+ email,+ authMethod,+ organizationId,+ requiredMfaMethod+ }: {+ userId: string;+ email?: string | null;+ authMethod: AuthMethod;+ organizationId?: string;+ requiredMfaMethod: MfaMethod;+ }) => {+ const appCfg = getConfig();++ const mfaToken = crypto.jwt().sign(+ {+ authMethod,+ authTokenType: AuthTokenType.MFA_TOKEN,+ userId,+ organizationId+ },+ appCfg.AUTH_SECRET,+ { expiresIn: appCfg.JWT_MFA_LIFETIME }+ );++ if (requiredMfaMethod === MfaMethod.EMAIL && email) {+ await sendUserMfaCode({ userId, email });+ }++ return mfaToken;+ };+/** Generate the auth and refresh token.* Shared by mfa verification, login verification with mfa disabled, and select organization.@@ -290,31 +346,18 @@ export const authLoginServiceFactory = ({if (organizationId) {const org = await orgDAL.findById(organizationId);if (org) {- const isOrgMfaEnforced = org.enforceMfa;- const isUserMfaEnabled = user.isMfaEnabled;- const isMfaRequired = isOrgMfaEnforced || isUserMfaEnabled;+ const { isMfaRequired, requiredMfaMethod } = getRequiredMfaMethod(org, user);if (isMfaRequired) {enforceUserLockStatus(Boolean(user.isLocked), user.temporaryLockDateEnd);- const requiredMfaMethod = isOrgMfaEnforced- ? ((org.selectedMfaMethod as MfaMethod) ?? MfaMethod.EMAIL)- : ((user.selectedMfaMethod as MfaMethod) ?? MfaMethod.EMAIL);-- const mfaToken = crypto.jwt().sign(- {- authMethod,- authTokenType: AuthTokenType.MFA_TOKEN,- userId: user.id,- organizationId- },- appCfg.AUTH_SECRET,- { expiresIn: appCfg.JWT_MFA_LIFETIME }- );-- if (requiredMfaMethod === MfaMethod.EMAIL && user.email) {- await sendUserMfaCode({ userId: user.id, email: user.email });- }+ const mfaToken = await issueMfaChallenge({+ userId: user.id,+ email: user.email,+ authMethod,+ organizationId,+ requiredMfaMethod+ });return { result: ProviderAuthResult.MFA_REQUIRED, mfaToken, mfaMethod: requiredMfaMethod } as const;}@@ -796,8 +839,7 @@ export const authLoginServiceFactory = ({// Step 2: Fall back to email lookup for existing users without an alias yetif (!user) {- const usersByUsername = await userDAL.findUserByUsername(email);- user = usersByUsername?.length > 1 ? usersByUsername.find((el) => el.username === email) : usersByUsername?.[0];+ user = await userDAL.findOne({ username: email });if (user) {isNewAlias = true;}@@ -892,11 +934,10 @@ export const authLoginServiceFactory = ({});}orgId = defaultOrg.id;- const existingMembership = await orgDAL.findEffectiveOrgMembership({- actorType: ActorType.USER,- actorId: newUser.id,- orgId,- acceptAnyStatus: true+ const existingMembership = await orgDAL.findMembership({+ actorUserId: newUser.id,+ scopeOrgId: orgId,+ scope: AccessScope.Organization});if (!existingMembership) {@@ -945,20 +986,15 @@ export const authLoginServiceFactory = ({// if user is signing up with SSO after invitation, their names should be set based on their SSO profileuser = await userDAL.updateById(user.id, {authMethods: [...(user.authMethods || []), authMethod],- firstName: !user.isAccepted ? firstName : undefined,- lastName: !user.isAccepted ? lastName : undefined+ firstName,+ lastName});}// Sync email/username if the provider email has changed (user found by alias)const normalizedProviderEmail = email.trim().toLowerCase();if (existingAlias && user.email !== normalizedProviderEmail) {- const conflictingUsers = await userDAL.findUserByUsername(normalizedProviderEmail);- const conflictingUser =- conflictingUsers?.length > 1- ? conflictingUsers.find((el) => el.username === normalizedProviderEmail)- : conflictingUsers?.[0];-+ const conflictingUser = await userDAL.findOne({ username: normalizedProviderEmail });if (conflictingUser && conflictingUser.id !== user.id) {throw new BadRequestError({message:@@ -972,7 +1008,10 @@ export const authLoginServiceFactory = ({user!.id,{username: normalizedProviderEmail,- email: normalizedProviderEmail+ email: normalizedProviderEmail,+ isGitHubVerified: authMethod !== AuthMethod.GITHUB && user?.isGitHubVerified,+ isGoogleVerified: authMethod !== AuthMethod.GOOGLE && user?.isGoogleVerified,+ isGitLabVerified: authMethod !== AuthMethod.GITLAB && user?.isGitLabVerified},tx);@@ -1027,7 +1066,6 @@ export const authLoginServiceFactory = ({aliasType,externalId: providerUserId,emails: [email],- orgId: orgId || null,isEmailVerified: isAliasVerified});aliasId = newAlias.id;@@ -1199,13 +1237,7 @@ export const authLoginServiceFactory = ({});}- const isOrgMfaEnforced = rootOrg.enforceMfa;- const isUserMfaEnabled = user.isMfaEnabled;- const isMfaRequired = isOrgMfaEnforced || isUserMfaEnabled;- // Determine which MFA method should be used (org takes precedence)- const requiredMfaMethod = isOrgMfaEnforced- ? (rootOrg.selectedMfaMethod ?? MfaMethod.EMAIL)- : (user.selectedMfaMethod ?? MfaMethod.EMAIL);+ const { isMfaRequired, requiredMfaMethod } = getRequiredMfaMethod(rootOrg, user);// Check if organization has changedconst hasOrganizationChanged = decodedToken?.organizationId ? decodedToken.organizationId !== rootOrg.id : false;// Check if MFA method has changed@@ -1217,24 +1249,12 @@ export const authLoginServiceFactory = ({if (shouldTriggerMfa) {enforceUserLockStatus(Boolean(user.isLocked), user.temporaryLockDateEnd);- const mfaToken = crypto.jwt().sign(- {- authMethod: decodedToken.authMethod,- authTokenType: AuthTokenType.MFA_TOKEN,- userId: user.id- },- cfg.AUTH_SECRET,- {- expiresIn: cfg.JWT_MFA_LIFETIME- }- );-- if (requiredMfaMethod === MfaMethod.EMAIL && user.email) {- await sendUserMfaCode({- userId: user.id,- email: user.email- });- }+ const mfaToken = await issueMfaChallenge({+ userId: user.id,+ email: user.email,+ authMethod: decodedToken.authMethod,+ requiredMfaMethod+ });return { isMfaEnabled: true, mfa: mfaToken, mfaMethod: requiredMfaMethod } as const;}@@ -1318,54 +1338,37 @@ export const authLoginServiceFactory = ({}// Create audit log for organization selection- if (isSubOrganization) {- await auditLogService.createAuditLog({- orgId: organizationId,- ipAddress,- userAgent,- userAgentType: getUserAgentType(userAgent),- actor: {- type: ActorType.USER,- metadata: {- email: user.email,- userId: user.id,- username: user.username,- authMethod: decodedToken.authMethod- }- },- event: {- type: EventType.SELECT_SUB_ORGANIZATION,- metadata: {- organizationId,- organizationName: selectedOrg.name,- rootOrganizationId: selectedOrg.rootOrgId || ""- }+ await auditLogService.createAuditLog({+ orgId: organizationId,+ ipAddress,+ userAgent,+ userAgentType: getUserAgentType(userAgent),+ actor: {+ type: ActorType.USER,+ metadata: {+ email: user.email,+ userId: user.id,+ username: user.username,+ authMethod: decodedToken.authMethod}- });- } else {- await auditLogService.createAuditLog({- orgId: organizationId,- ipAddress,- userAgent,- userAgentType: getUserAgentType(userAgent),- actor: {- type: ActorType.USER,- metadata: {- email: user.email,- userId: user.id,- username: user.username,- authMethod: decodedToken.authMethod+ },+ event: isSubOrganization+ ? {+ type: EventType.SELECT_SUB_ORGANIZATION,+ metadata: {+ organizationId,+ organizationName: selectedOrg.name,+ rootOrganizationId: selectedOrg.rootOrgId || ""+ }}- },- event: {- type: EventType.SELECT_ORGANIZATION,- metadata: {- organizationId,- organizationName: selectedOrg.name+ : {+ type: EventType.SELECT_ORGANIZATION,+ metadata: {+ organizationId,+ organizationName: selectedOrg.name+ }}- }- });- }+ });return {...tokens,diff --git a/frontend/src/pages/auth/SignUpSsoPage/components/EmailConfirmationStep/EmailConfirmationStep.tsx b/frontend/src/pages/auth/SignUpSsoPage/components/EmailConfirmationStep/EmailConfirmationStep.tsxdeleted file mode 100644index 2240fe263a..0000000000--- a/frontend/src/pages/auth/SignUpSsoPage/components/EmailConfirmationStep/EmailConfirmationStep.tsx+++ /dev/null@@ -1,185 +0,0 @@-// confirm email-// if same email exists, then trigger fn to merge automatically-import { useState } from "react";-import ReactCodeInput from "react-code-input";-import { useNavigate } from "@tanstack/react-router";--import Error from "@app/components/basic/Error";-import { createNotification } from "@app/components/notifications";-import { Button } from "@app/components/v2";-import { useSendEmailVerificationCode, useVerifyEmailVerificationCode } from "@app/hooks/api";-import { UserAliasType } from "@app/hooks/api/users/types";--type Props = {- authType?: UserAliasType;- username: string;- email: string;- organizationSlug: string;- setStep: (step: number) => void;-};--// The style for the verification code input-const props = {- inputStyle: {- fontFamily: "monospace",- margin: "4px",- MozAppearance: "textfield",- width: "55px",- borderRadius: "5px",- fontSize: "24px",- height: "55px",- paddingLeft: "7",- backgroundColor: "#0d1117",- color: "white",- border: "1px solid #2d2f33",- textAlign: "center",- outlineColor: "#8ca542",- borderColor: "#2d2f33"- }-} as const;-const propsPhone = {- inputStyle: {- fontFamily: "monospace",- margin: "4px",- MozAppearance: "textfield",- width: "40px",- borderRadius: "5px",- fontSize: "24px",- height: "40px",- paddingLeft: "7",- backgroundColor: "#0d1117",- color: "white",- border: "1px solid #2d2f33",- textAlign: "center",- outlineColor: "#8ca542",- borderColor: "#2d2f33"- }-} as const;--export const EmailConfirmationStep = ({- authType,- username,- email,- organizationSlug,- setStep-}: Props) => {- const navigate = useNavigate();- const [code, setCode] = useState("");- const [codeError, setCodeError] = useState(false);- const [isResendingVerificationEmail] = useState(false);- const [isLoading] = useState(false);-- const { mutateAsync: sendEmailVerificationCode } = useSendEmailVerificationCode();- const { mutateAsync: verifyEmailVerificationCode } = useVerifyEmailVerificationCode();-- const checkCode = async () => {- await verifyEmailVerificationCode({ username, code });- setCodeError(false);-- createNotification({- text: "Successfully verified code",- type: "success"- });-- switch (authType) {- case UserAliasType.SAML: {- window.open(`/api/v1/sso/redirect/saml2/organizations/${organizationSlug}`);- window.close();- break;- }- case UserAliasType.LDAP: {- navigate({ to: "/login/ldap", search: { organizationSlug } });- break;- }- case UserAliasType.OIDC: {- window.open(`/api/v1/sso/oidc/login?orgSlug=${organizationSlug}`);- window.close();- break;- }- default: {- setStep(1);- break;- }- }-- setCode("");- };-- const resendCode = async () => {- const queryParams = new URLSearchParams(window.location.search);- const token = queryParams.get("token");- if (!token) {- createNotification({- text: "Failed to resend code, no token found",- type: "error"- });- return;- }- await sendEmailVerificationCode(token);- createNotification({- text: "Successfully resent code",- type: "success"- });- };-- return (- <div className="mx-auto h-full w-full pb-4 md:px-8">- <p className="text-md flex justify-center text-bunker-200">- We've sent a verification code to {email}- </p>- <div className="mx-auto hidden w-max min-w-[20rem] md:block">- <ReactCodeInput- name=""- inputMode="tel"- type="text"- fields={6}- onChange={setCode}- {...props}- className="mt-6 mb-2"- />- </div>- <div className="mx-auto mt-4 block w-max md:hidden">- <ReactCodeInput- name=""- inputMode="tel"- type="text"- fields={6}- onChange={setCode}- {...propsPhone}- className="mt-2 mb-2"- />- </div>- {codeError && <Error text="Oops. Your code is wrong. Please try again." />}- <div className="mx-auto mt-2 flex w-1/4 max-w-xs min-w-[20rem] flex-col items-center justify-center text-center text-sm md:max-w-md md:text-left lg:w-[19%]">- <div className="text-l w-full py-1 text-lg">- <Button- type="submit"- onClick={checkCode}- size="sm"- isFullWidth- className="h-14"- colorSchema="primary"- variant="outline_bg"- isLoading={isLoading}- >- {" "}- Verify- </Button>- </div>- </div>- <div className="mx-auto flex max-h-24 w-full max-w-md flex-col items-center justify-center pt-2">- <div className="flex flex-row items-baseline gap-1 text-sm">- <span className="text-bunker-400">Don't see the code?</span>- <div className="text-md mt-2 flex flex-row text-bunker-400">- <button disabled={isLoading} onClick={resendCode} type="button">- <span className="cursor-pointer duration-200 hover:text-bunker-200 hover:underline hover:decoration-primary-700 hover:underline-offset-4">- {isResendingVerificationEmail ? "Resending..." : "Resend"}- </span>- </button>- </div>- </div>- <p className="pb-2 text-sm text-bunker-400">Make sure to check your spam inbox.</p>- </div>- </div>- );-};diff --git a/frontend/src/pages/auth/SignUpSsoPage/components/EmailConfirmationStep/index.tsx b/frontend/src/pages/auth/SignUpSsoPage/components/EmailConfirmationStep/index.tsxdeleted file mode 100644index 32f3a636e1..0000000000--- a/frontend/src/pages/auth/SignUpSsoPage/components/EmailConfirmationStep/index.tsx+++ /dev/null@@ -1 +0,0 @@-export { EmailConfirmationStep } from "./EmailConfirmationStep";