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
moved the stale-alias check before the state mutations in all three login paths.
Thiago Araujo da Silvafc2430e23052
diff --git a/backend/e2e-test/routes/v3/auth-signup-sso-enforced.spec.ts b/backend/e2e-test/routes/v3/auth-signup-sso-enforced.spec.tsindex 0e01f4cedb..c78ba85c90 100644--- a/backend/e2e-test/routes/v3/auth-signup-sso-enforced.spec.ts+++ b/backend/e2e-test/routes/v3/auth-signup-sso-enforced.spec.ts@@ -126,6 +126,13 @@ describe("Auth SSO Signup V3 (SSO enforced)", () => {const victimAfter = await getDb()(TableName.Users).where({ id: victim.id }).first();expect(victimAfter?.isAccepted).toBe(true);expect(victimAfter?.isEmailVerified).toBe(true);++ // The stale-alias guard must run BEFORE any state mutation: the victim is not enrolled into the+ // org (no membership created) since the IdP never proved control of the victim's account.+ const victimMembership = await getDb()(TableName.Membership)+ .where({ actorUserId: victim.id, scopeOrgId: TEST_ORG_ID })+ .first();+ expect(victimMembership).toBeUndefined();});test("SAML login promotes an unverified alias when the asserted email matches the account", async () => {diff --git a/backend/src/ee/services/ldap-config/ldap-config-service.ts b/backend/src/ee/services/ldap-config/ldap-config-service.tsindex cae04e6f01..c61968d7c9 100644--- a/backend/src/ee/services/ldap-config/ldap-config-service.ts+++ b/backend/src/ee/services/ldap-config/ldap-config-service.ts@@ -38,7 +38,7 @@ import { TTelemetryServiceFactory } from "@app/services/telemetry/telemetry-servimport { 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 } from "@app/services/user-alias/user-alias-fns";+import { ensureSsoAccountVerified, isStaleSsoAlias } 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";@@ -486,6 +486,11 @@ export const ldapConfigServiceFactory = ({// org owns this domain, and password signup is blocked for enforced domains).const skipEmailVerification = Boolean(organization.authEnforced);+ // A stale, still-unverified alias may point at another user's account. Don't mutate that+ // account's org membership / group state until the IdP proves control of it (the+ // email-verification fallback below issues no session). Resolved against the existing alias+ // before any mutation; freshly created aliases are never stale.+ let isStaleAlias = false;if (userAlias) {// Verify the existing user's stored email domain + cross-org checkconst existingUser = await userDAL.findOne({ id: userAlias.userId });@@ -495,41 +500,43 @@ export const ldapConfigServiceFactory = ({orgId,emailDomainDAL});+ isStaleAlias = isStaleSsoAlias({ user: existingUser, userAlias, assertedEmail: sanitizedEmail });}- await userDAL.transaction(async (tx) => {- const [orgMembership] = await orgDAL.findMembership(- {- [`${TableName.Membership}.actorUserId` as "actorUserId"]: userAlias.userId,- [`${TableName.Membership}.scopeOrgId` as "scopeOrgId"]: orgId,- [`${TableName.Membership}.scope` as "scope"]: AccessScope.Organization- },- { tx }- );- if (!orgMembership) {- const { role, roleId } = await getDefaultOrgMembershipRole(organization.defaultMembershipRole);-- const membership = await orgDAL.createMembership(+ if (!isStaleAlias)+ await userDAL.transaction(async (tx) => {+ const [orgMembership] = await orgDAL.findMembership({- actorUserId: userAlias.userId,- scopeOrgId: orgId,- scope: AccessScope.Organization,- status: OrgMembershipStatus.Invited,- isActive: true+ [`${TableName.Membership}.actorUserId` as "actorUserId"]: userAlias.userId,+ [`${TableName.Membership}.scopeOrgId` as "scopeOrgId"]: orgId,+ [`${TableName.Membership}.scope` as "scope"]: AccessScope.Organization},- tx+ { tx });- await membershipRoleDAL.create(- {- membershipId: membership.id,- role,- customRoleId: roleId- },- tx- );- } else if (!orgMembership.isActive) {- throw new ForbiddenRequestError({ message: "User organization membership is inactive" });- }- });+ if (!orgMembership) {+ const { role, roleId } = await getDefaultOrgMembershipRole(organization.defaultMembershipRole);++ const membership = await orgDAL.createMembership(+ {+ actorUserId: userAlias.userId,+ scopeOrgId: orgId,+ scope: AccessScope.Organization,+ status: OrgMembershipStatus.Invited,+ isActive: true+ },+ tx+ );+ await membershipRoleDAL.create(+ {+ membershipId: membership.id,+ role,+ customRoleId: roleId+ },+ tx+ );+ } else if (!orgMembership.isActive) {+ throw new ForbiddenRequestError({ message: "User organization membership is inactive" });+ }+ });} else {let isNewUser = false;userAlias = await userDAL.transaction(async (tx) => {@@ -622,7 +629,7 @@ export const ldapConfigServiceFactory = ({let user = await userDAL.transaction(async (tx) => {const newUser = await userDAL.findOne({ id: userAlias.userId }, tx);- if (groups) {+ if (groups && !isStaleAlias) {const ldapGroupIdsToBePartOf = (await ldapGroupMapDAL.find({ldapConfigId,diff --git a/backend/src/ee/services/oidc/oidc-config-service.ts b/backend/src/ee/services/oidc/oidc-config-service.tsindex ab94d5c93e..3560be0656 100644--- a/backend/src/ee/services/oidc/oidc-config-service.ts+++ b/backend/src/ee/services/oidc/oidc-config-service.ts@@ -46,7 +46,7 @@ import { TTelemetryServiceFactory } from "@app/services/telemetry/telemetry-servimport { 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 } from "@app/services/user-alias/user-alias-fns";+import { ensureSsoAccountVerified, isStaleSsoAlias } 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";@@ -223,6 +223,11 @@ export const oidcConfigServiceFactory = ({const skipEmailVerification = Boolean(organization.authEnforced);let user: TUsers;+ // A stale, still-unverified alias may point at another user's account. Don't mutate that+ // account's org membership / group state until the IdP proves control of it (the+ // email-verification fallback below issues no session). Resolved against the existing alias+ // before any mutation; freshly created aliases are never stale.+ let isStaleAlias = false;if (userAlias) {user = await userDAL.transaction(async (tx) => {const foundUser = await userDAL.findById(userAlias.userId, tx);@@ -232,6 +237,11 @@ export const oidcConfigServiceFactory = ({orgId,emailDomainDAL});+ isStaleAlias = isStaleSsoAlias({ user: foundUser, userAlias, assertedEmail: sanitizedEmail });+ if (isStaleAlias) {+ return foundUser;+ }+const [orgMembership] = await orgDAL.findMembership({[`${TableName.Membership}.actorUserId` as "actorUserId"]: userAlias.userId,@@ -360,7 +370,7 @@ export const oidcConfigServiceFactory = ({}}- if (manageGroupMemberships) {+ if (manageGroupMemberships && !isStaleAlias) {const userGroups = await userGroupMembershipDAL.findGroupMembershipsByUserIdInOrg(user.id, orgId);const orgGroups = await groupDAL.findByOrgId(orgId);diff --git a/backend/src/ee/services/saml-config/saml-config-service.ts b/backend/src/ee/services/saml-config/saml-config-service.tsindex aae12b7312..227572c61d 100644--- a/backend/src/ee/services/saml-config/saml-config-service.ts+++ b/backend/src/ee/services/saml-config/saml-config-service.ts@@ -40,7 +40,7 @@ import { TTelemetryServiceFactory } from "@app/services/telemetry/telemetry-servimport { 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 } from "@app/services/user-alias/user-alias-fns";+import { ensureSsoAccountVerified, isStaleSsoAlias } 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";@@ -566,7 +566,16 @@ export const samlConfigServiceFactory = ({orgId,emailDomainDAL});+ // A stale, still-unverified alias may point at another user's account. Don't mutate that+ // account's org membership / identity metadata / group state until the IdP proves control of+ // it (the email-verification fallback below issues no session). This guard must run before the+ // mutations, not just before ensureSsoAccountVerified at the end.+ const isStaleAlias = isStaleSsoAlias({ user: foundUser, userAlias, assertedEmail: sanitizedEmail });user = await userDAL.transaction(async (tx) => {+ if (isStaleAlias) {+ return foundUser;+ }+const [orgMembership] = await orgDAL.findMembership({[`${TableName.Membership}.actorUserId` as "actorUserId"]: userAlias.userId,diff --git a/backend/src/services/user-alias/user-alias-fns.ts b/backend/src/services/user-alias/user-alias-fns.tsindex 9376f6afac..51f71df4d8 100644--- a/backend/src/services/user-alias/user-alias-fns.ts+++ b/backend/src/services/user-alias/user-alias-fns.ts@@ -11,6 +11,34 @@ type TEnsureSsoAccountVerifiedDTO = {userAliasDAL: Pick<TUserAliasDALFactory, "updateById">;};+type TIsStaleSsoAliasDTO = {+ user: Pick<TUsers, "username" | "email">;+ userAlias: Pick<TUserAliases, "isEmailVerified" | "emails">;+ assertedEmail: string;+};++/**+ * The legacy SSO flow persisted aliases before email verification completed, so an as-yet-unverified+ * alias may point at a different user's account. Such an alias is "stale" when the email asserted by+ * the IdP in this login does not match any of the aliased account's known emails — i.e. the IdP has+ * not proven control of the aliased account. Callers must not provision org membership, identity+ * metadata, or group memberships onto that account (nor issue a session for it) until ownership is+ * proven via the separate email-verification flow. A verified alias is already trusted, so it is+ * never considered stale.+ */+export const isStaleSsoAlias = ({ user, userAlias, assertedEmail }: TIsStaleSsoAliasDTO): boolean => {+ if (userAlias.isEmailVerified) return false;++ const normalizedAssertedEmail = assertedEmail?.toLowerCase().trim();+ const accountEmails = new Set(+ [user.username, user.email, ...(userAlias.emails ?? [])]+ .filter((email): email is string => Boolean(email))+ .map((email) => email.toLowerCase().trim())+ );++ return !normalizedAssertedEmail || !accountEmails.has(normalizedAssertedEmail);+};+/*** When an org enforces SSO, the verified domain + IdP are authoritative, so we skip the separate* email-verification step. This marks the user + alias as verified/accepted before a session is@@ -36,16 +64,10 @@ export const ensureSsoAccountVerified = async ({return { user, userAlias };}- if (!userAlias.isEmailVerified) {- const normalizedAssertedEmail = assertedEmail?.toLowerCase().trim();- const accountEmails = new Set(- [user.username, user.email, ...(userAlias.emails ?? [])]- .filter((email): email is string => Boolean(email))- .map((email) => email.toLowerCase().trim())- );- if (!normalizedAssertedEmail || !accountEmails.has(normalizedAssertedEmail)) {- return { user, userAlias };- }+ // A still-unverified alias whose asserted email doesn't match the aliased account is stale and+ // must not be promoted — the caller falls back to the email-verification flow (no session issued).+ if (isStaleSsoAlias({ user, userAlias, assertedEmail })) {+ return { user, userAlias };}await userDAL.transaction(async (tx) => {