Skip to content

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

fix consistence and resolve by sso external id on provisioning as well

Thiago Araujo da Silva28b07cf3d534
diff --git a/backend/CLAUDE.md b/backend/CLAUDE.md
index 637f5deb5c..1fb6704a57 100644
--- a/backend/CLAUDE.md
+++ b/backend/CLAUDE.md
@@ -335,6 +335,53 @@ never becomes a synchronous dependency of the middleware's own request path. The
(rejections evicted, in-flight promise shared, expiry rebuilding the SSRF-pinned agent) are documented in
`oauth-token-exchange-fns.ts`.
+### Resolving Users From Provisioning Identifiers
+
+Every invite / removal path resolves a person by `users.username` (which always equals their email),
+never by `users.email` and never by a join. An external provisioning system, though, often knows
+people only by the identifier its IdP asserts, a UPN like `[email protected]` rather than the
+mailbox `[email protected]`. SSO login already records that identifier as
+`user_aliases.externalId`, so the two are reconcilable without making `username` diverge from
+`email`.
+
+`resolveUsersBySsoExternalId` in `src/services/user-alias/user-alias-fns.ts` is the one place that
+does it, backed by `userAliasDAL.findBySsoExternalIds`. Callers run it **only after an exact
+`username` lookup has missed**, so an alias can never shadow a real account. It is wired into
+`$getUsers` (`membership-user-service.ts`, the single funnel for org, project, and cert-manager
+invites), `project-membership-service.ts` (removal and membership read-back), and PAM's
+`addProductUserMembers`.
+
+Four invariants, each load-bearing:
+
+- **Scope by `orgId` *and* `aliasType`.** `user_aliases.orgId` is NULL for the global
+ google/github/gitlab aliases, so `whereIn("orgId", ...)` excludes them outright and the
+ `ORG_SCOPED_USER_ALIAS_TYPES` filter is the second lock. Without both, an org admin could name a
+ user in another tenant.
+- **Match `externalId` exactly, never folded.** It is a case-sensitive identifier (OIDC Core defines
+ `sub` that way, as does SAML for nameID) and is stored verbatim, so folding case could collapse two
+ distinct IdP subjects onto one identifier. The known consequence: because both invite routes
+ lowercase their input (`sanitizeEmail`, and the `.refine` on `usernames`), an IdP that asserts
+ mixed-case identifiers cannot be provisioned against at all. Supporting those means relaxing that
+ input validation so the exact identifier survives to the query, not loosening the comparison.
+ Note the one deliberate exception: `adoptProvisionedShadowUser` *does* lowercase, because it looks
+ the identifier up in the `users.username` namespace, where lowercase is canonical.
+- **Ambiguity is an error.** Nothing constrains `(externalId, aliasType)` to be unique for the
+ org-scoped types (only the social ones have a partial unique index), so an identifier can reach two
+ users. Picking one would be a guess about which human it names, and the cost of guessing wrong is
+ granting access to the wrong person. Several aliases on the *same* user are not a conflict.
+- **Dedupe resolved users by `id`.** An identifier now reaches a user by either their username or
+ their alias, so one request can name the same person twice. Undeduped, that violates
+ `membership_unique_user_org` and surfaces as a 500.
+
+A related case sits on the login side: provisioning can name someone before they have ever logged
+in, leaving a placeholder account keyed on the identifier instead of the mailbox.
+`adoptProvisionedShadowUser` (same file, wired into `oidcLogin`'s no-alias branch) adopts that row
+and rewrites it to the asserted mailbox rather than creating a second account. It refuses anything a
+human has claimed (accepted, email-verified, holding a password), anything already bound to an IdP
+(any alias, any org), ghosts, and anything without a membership in the org doing the login. It also
+recovers from a unique violation on `users.username`, because the caller's preceding read is not a
+lock. SAML and LDAP have structurally identical branches and are deliberately not wired up.
+
### 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/invite-org-sso-alias.spec.ts b/backend/e2e-test/routes/v1/invite-org-sso-alias.spec.ts
new file mode 100644
index 0000000000..f5f3a642ca
--- /dev/null
+++ b/backend/e2e-test/routes/v1/invite-org-sso-alias.spec.ts
@@ -0,0 +1,225 @@
+import crypto from "node:crypto";
+
+import { AccessScope, TableName } from "@app/db/schemas";
+import { seedData1 } from "@app/db/seed-data";
+import { UserAliasType } from "@app/services/user-alias/user-alias-types";
+
+const ORG_ID = seedData1.organization.id;
+
+const createdUserIds: string[] = [];
+
+const seedUser = async (username: string) => {
+ const [user] = await testDb(TableName.Users)
+ .insert({ username, email: username, isAccepted: false, isGhost: false, authMethods: ["email"] })
+ .returning("*");
+ createdUserIds.push(user.id);
+ return user;
+};
+
+const seedAlias = async ({
+ userId,
+ externalId,
+ orgId = ORG_ID,
+ aliasType = UserAliasType.OIDC
+}: {
+ userId: string;
+ externalId: string;
+ orgId?: string | null;
+ aliasType?: UserAliasType;
+}) => {
+ await testDb(TableName.UserAliases).insert({ userId, externalId, orgId, aliasType });
+};
+
+const findUserByUsername = (username: string) =>
+ testDb(TableName.Users).where({ username }).select("id", "username", "email").first();
+
+const findOrgMemberships = (userId: string) =>
+ testDb(TableName.Membership)
+ .where({ actorUserId: userId, scopeOrgId: ORG_ID, scope: AccessScope.Organization })
+ .select("id");
+
+const PROJECT_ID = seedData1.project.id;
+
+// Seeded directly instead of through the invite endpoint, since what's under test is identifier
+// resolution on the removal path.
+const seedProjectMembership = async (userId: string) => {
+ const [membership] = await testDb(TableName.Membership)
+ .insert({
+ scope: AccessScope.Project,
+ actorUserId: userId,
+ scopeOrgId: ORG_ID,
+ scopeProjectId: PROJECT_ID,
+ isActive: true
+ })
+ .returning("*");
+ await testDb(TableName.MembershipRole).insert({ membershipId: membership.id, role: "member" });
+ return membership;
+};
+
+const removeFromProject = (usernames: string[]) =>
+ testServer.inject({
+ method: "DELETE",
+ url: `/api/v1/projects/${PROJECT_ID}/memberships`,
+ headers: { authorization: `Bearer ${jwtAuthToken}` },
+ body: { usernames, emails: [] }
+ });
+
+const findProjectMemberships = (userId: string) =>
+ testDb(TableName.Membership)
+ .where({ actorUserId: userId, scopeProjectId: PROJECT_ID, scope: AccessScope.Project })
+ .select("id");
+
+const inviteToOrg = (inviteeEmails: string[]) =>
+ testServer.inject({
+ method: "POST",
+ url: "/api/v1/invite-org/signup",
+ headers: { authorization: `Bearer ${jwtAuthToken}` },
+ body: { inviteeEmails, organizationId: ORG_ID }
+ });
+
+// A UPN is email-shaped, so it clears the route's validation and is indistinguishable from an email
+// until we look it up. That's the case this suite covers.
+const upn = () => `m${crypto.randomInt(100000, 999999)}@one.example.local`;
+const mailbox = () => `person-${crypto.randomUUID()}@example.local`;
+
+describe("Org invite by SSO alias identifier", () => {
+ afterEach(async () => {
+ if (!createdUserIds.length) return;
+ const memberships = await testDb(TableName.Membership)
+ .whereIn("actorUserId", createdUserIds)
+ .select("id")
+ .then((rows) => rows.map((row) => row.id));
+ if (memberships.length) await testDb(TableName.MembershipRole).whereIn("membershipId", memberships).del();
+ await testDb(TableName.Membership).whereIn("actorUserId", createdUserIds).del();
+ await testDb(TableName.UserAliases).whereIn("userId", createdUserIds).del();
+ await testDb(TableName.Users).whereIn("id", createdUserIds).del();
+ createdUserIds.length = 0;
+ });
+
+ test("an identifier recorded on an org SSO alias resolves to that user instead of creating a second account", async () => {
+ const email = mailbox();
+ const identifier = upn();
+ const user = await seedUser(email);
+ await seedAlias({ userId: user.id, externalId: identifier });
+
+ const res = await inviteToOrg([identifier]);
+ expect(res.statusCode).toBe(200);
+
+ await expect(findUserByUsername(identifier)).resolves.toBeUndefined();
+ await expect(findOrgMemberships(user.id)).resolves.toHaveLength(1);
+ });
+
+ test("naming the same person by both their email and their alias identifier yields one membership", async () => {
+ const email = mailbox();
+ const identifier = upn();
+ const user = await seedUser(email);
+ await seedAlias({ userId: user.id, externalId: identifier });
+
+ const res = await inviteToOrg([email, identifier]);
+ expect(res.statusCode).toBe(200);
+
+ await expect(findOrgMemberships(user.id)).resolves.toHaveLength(1);
+ await expect(findUserByUsername(identifier)).resolves.toBeUndefined();
+ });
+
+ test("an externalId stored with different case does not resolve", async () => {
+ const identifier = upn();
+ const user = await seedUser(mailbox());
+ await seedAlias({ userId: user.id, externalId: identifier.toUpperCase() });
+
+ const res = await inviteToOrg([identifier]);
+ expect(res.statusCode).toBe(200);
+
+ // externalId is case-sensitive, so a differently-cased identifier is a different subject. Since
+ // the invite routes lowercase their input, an IdP asserting mixed-case identifiers can't be
+ // provisioned against at all. Fixing that means relaxing those routes.
+ await expect(findUserByUsername(identifier)).resolves.toMatchObject({ username: identifier });
+ await expect(findOrgMemberships(user.id)).resolves.toHaveLength(0);
+
+ const shadow = await findUserByUsername(identifier);
+ if (shadow) createdUserIds.push(shadow.id);
+ });
+
+ test("an alias belonging to another organization does not resolve", async () => {
+ const identifier = upn();
+ const user = await seedUser(mailbox());
+ const [otherOrg] = await testDb(TableName.Organization)
+ .insert({ name: "other org", slug: `other-org-${crypto.randomUUID()}`, customerId: null })
+ .returning("*");
+
+ try {
+ await seedAlias({ userId: user.id, externalId: identifier, orgId: otherOrg.id });
+
+ const res = await inviteToOrg([identifier]);
+ expect(res.statusCode).toBe(200);
+
+ // Nothing in this org vouches for the identifier, so it's treated as a new person.
+ await expect(findUserByUsername(identifier)).resolves.toMatchObject({ username: identifier });
+ await expect(findOrgMemberships(user.id)).resolves.toHaveLength(0);
+
+ const shadow = await findUserByUsername(identifier);
+ if (shadow) createdUserIds.push(shadow.id);
+ } finally {
+ await testDb(TableName.Organization).where({ id: otherOrg.id }).del();
+ }
+ });
+
+ test("a global social alias does not resolve, even when its externalId matches the identifier", async () => {
+ const identifier = upn();
+ const user = await seedUser(mailbox());
+ // Social aliases are not org-scoped (orgId is NULL), so they must never vouch for an identifier.
+ await seedAlias({ userId: user.id, externalId: identifier, orgId: null, aliasType: UserAliasType.GOOGLE });
+
+ const res = await inviteToOrg([identifier]);
+ expect(res.statusCode).toBe(200);
+
+ await expect(findUserByUsername(identifier)).resolves.toMatchObject({ username: identifier });
+ await expect(findOrgMemberships(user.id)).resolves.toHaveLength(0);
+
+ const shadow = await findUserByUsername(identifier);
+ if (shadow) createdUserIds.push(shadow.id);
+ });
+
+ test("a project membership can be removed by the alias identifier", async () => {
+ const identifier = upn();
+ const user = await seedUser(mailbox());
+ await seedAlias({ userId: user.id, externalId: identifier });
+ await seedProjectMembership(user.id);
+
+ // Removal has to take the same identifier the caller provisioned with, or an entitlement system
+ // can grant access it can never revoke.
+ const res = await removeFromProject([identifier]);
+
+ expect(res.statusCode).toBe(200);
+ await expect(findProjectMemberships(user.id)).resolves.toHaveLength(0);
+ });
+
+ test("naming one person by both email and alias identifier does not break project removal", async () => {
+ const email = mailbox();
+ const identifier = upn();
+ const user = await seedUser(email);
+ await seedAlias({ userId: user.id, externalId: identifier });
+ await seedProjectMembership(user.id);
+
+ // Both forms collapse onto one membership, so the "some users are not part of project" count
+ // check has to compare against the resolved set rather than the raw input.
+ const res = await removeFromProject([email, identifier]);
+
+ expect(res.statusCode).toBe(200);
+ await expect(findProjectMemberships(user.id)).resolves.toHaveLength(0);
+ });
+
+ test("an identifier reaching two distinct accounts is rejected rather than guessed at", async () => {
+ const identifier = upn();
+ const first = await seedUser(mailbox());
+ const second = await seedUser(mailbox());
+ await seedAlias({ userId: first.id, externalId: identifier });
+ await seedAlias({ userId: second.id, externalId: identifier });
+
+ const res = await inviteToOrg([identifier]);
+
+ expect(res.statusCode).toBe(400);
+ expect(res.json().message).toContain(identifier);
+ await expect(findUserByUsername(identifier)).resolves.toBeUndefined();
+ });
+});
diff --git a/backend/src/db/migrations/20260826120000_add-user-alias-lookup-indexes.ts b/backend/src/db/migrations/20260826120000_add-user-alias-lookup-indexes.ts
new file mode 100644
index 0000000000..f4bb1ce9a6
--- /dev/null
+++ b/backend/src/db/migrations/20260826120000_add-user-alias-lookup-indexes.ts
@@ -0,0 +1,48 @@
+import { Knex } from "knex";
+
+import { TableName } from "../schemas";
+
+// user_aliases only had its primary key and the partial unique index on the social alias types, so
+// both FKs were unindexed and every org-scoped SSO login lookup was a seq scan. Between them these
+// two cover every query shape against the table. Column order matters: leading with orgId and
+// userId is what covers the two FKs, which Postgres doesn't index for you.
+const INDEXES = [
+ { name: "idx_user_aliases_org_alias_type_external_id", columns: ['"orgId"', '"aliasType"', '"externalId"'] },
+ { name: "idx_user_aliases_user_org_alias_type", columns: ['"userId"', '"orgId"', '"aliasType"'] }
+];
+
+const MIGRATION_TIMEOUT = 60 * 60 * 1000; // 60 minutes
+const MIGRATION_LOCK_TIMEOUT = 30 * 1000; // 30 seconds
+
+export async function up(knex: Knex): Promise<void> {
+ const stmtResult = await knex.raw("SHOW statement_timeout");
+ const originalStatementTimeout = stmtResult.rows[0].statement_timeout;
+ const lockResult = await knex.raw("SHOW lock_timeout");
+ const originalLockTimeout = lockResult.rows[0].lock_timeout;
+
+ try {
+ await knex.raw(`SET statement_timeout = ${MIGRATION_TIMEOUT}`);
+ await knex.raw(`SET lock_timeout = ${MIGRATION_LOCK_TIMEOUT}`);
+
+ if (await knex.schema.hasTable(TableName.UserAliases)) {
+ for await (const { name, columns } of INDEXES) {
+ await knex.raw(`
+ CREATE INDEX CONCURRENTLY IF NOT EXISTS "${name}"
+ ON ${TableName.UserAliases} (${columns.join(", ")})
+ `);
+ }
+ }
+ } finally {
+ await knex.raw(`SET statement_timeout = '${originalStatementTimeout}'`);
+ await knex.raw(`SET lock_timeout = '${originalLockTimeout}'`);
+ }
+}
+
+export async function down(knex: Knex): Promise<void> {
+ for await (const { name } of INDEXES) {
+ await knex.raw(`DROP INDEX CONCURRENTLY IF EXISTS "${name}"`);
+ }
+}
+
+const config = { transaction: false };
+export { config };
diff --git a/backend/src/ee/services/oidc/oidc-config-service.ts b/backend/src/ee/services/oidc/oidc-config-service.ts
index 9a10038db9..75995112db 100644
--- a/backend/src/ee/services/oidc/oidc-config-service.ts
+++ b/backend/src/ee/services/oidc/oidc-config-service.ts
@@ -15,6 +15,7 @@ import { OrgPermissionSsoActions, OrgPermissionSubjects } from "@app/ee/services
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
import { getConfig } from "@app/lib/config/env";
import { BadRequestError, ForbiddenRequestError, NotFoundError, OidcAuthError } from "@app/lib/errors";
+import { logger } from "@app/lib/logger";
import { requestMemoKeys } from "@app/lib/request-context/memo-keys";
import { RequestContextKey } from "@app/lib/request-context/request-context-keys";
import { requestMemoize } from "@app/lib/request-context/request-memoizer";
@@ -56,7 +57,11 @@ 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 {
+ adoptProvisionedShadowUser,
+ 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";
@@ -305,6 +310,29 @@ export const oidcConfigServiceFactory = ({
tx
);
+ // Provisioning may have already made a placeholder for this person keyed on their IdP
+ // identifier instead of their mailbox. Adopt it rather than creating a second account and
+ // stranding whatever it was granted on one nobody can log into.
+ if (!newUser) {
+ newUser =
+ (await adoptProvisionedShadowUser({
+ externalId,
+ assertedEmail: sanitizedEmail,
+ orgId,
+ userDAL,
+ userAliasDAL,
+ orgDAL,
+ tx
+ })) ?? undefined;
+
+ if (newUser) {
+ logger.info(
+ { userId: newUser.id, orgId, externalId },
+ `Adopted provisioned placeholder account on first OIDC login [userId=${newUser.id}] [orgId=${orgId}] [externalId=${externalId}] [username=${sanitizedEmail}]`
+ );
+ }
+ }
+
if (!newUser) {
newUser = await userDAL.create(
{
diff --git a/backend/src/ee/services/pam-membership/pam-membership-service.ts b/backend/src/ee/services/pam-membership/pam-membership-service.ts
index 6dd15001b2..2300d503a5 100644
--- a/backend/src/ee/services/pam-membership/pam-membership-service.ts
+++ b/backend/src/ee/services/pam-membership/pam-membership-service.ts
@@ -21,8 +21,11 @@ import { PamIdentities } from "@app/services/license-client";
import { TUsageMeteringServiceFactory } from "@app/services/license-client/usage";
import { TMembershipDALFactory } from "@app/services/membership/membership-dal";
import { TMembershipRoleDALFactory } from "@app/services/membership/membership-role-dal";
+import { TOrgDALFactory } from "@app/services/org/org-dal";
import { TProjectAccessRequestDALFactory } from "@app/services/project/project-access-request-dal";
import { TUserDALFactory } from "@app/services/user/user-dal";
+import { TUserAliasDALFactory } from "@app/services/user-alias/user-alias-dal";
+import { resolveUsersBySsoExternalId } from "@app/services/user-alias/user-alias-fns";
import { PamMemberKind, PamProductRole, PamResourceRole } from "../pam/pam-enums";
import { getResourceIdsWithActions, TActorContext } from "../pam/pam-permission";
@@ -65,6 +68,8 @@ type TPamMembershipServiceFactoryDep = {
pamAccountDAL: Pick<TPamAccountDALFactory, "findById" | "find">;
pamSessionDAL: Pick<TPamSessionDALFactory, "find" | "update">;
userDAL: Pick<TUserDALFactory, "findById" | "find">;
+ userAliasDAL: Pick<TUserAliasDALFactory, "findBySsoExternalIds">;
+ orgDAL: Pick<TOrgDALFactory, "findById">;
groupDAL: Pick<TGroupDALFactory, "findById">;
identityDAL: Pick<TIdentityDALFactory, "findById" | "find">;
userGroupMembershipDAL: Pick<TUserGroupMembershipDALFactory, "find">;
@@ -108,6 +113,8 @@ export const pamMembershipServiceFactory = ({
pamAccountDAL,
pamSessionDAL,
userDAL,
+ userAliasDAL,
+ orgDAL,
groupDAL,
userGroupMembershipDAL,
identityGroupMembershipDAL,
@@ -441,6 +448,34 @@ export const pamMembershipServiceFactory = ({
const usersByEmail = emails.length ? await userDAL.find({ $in: { username: emails } }) : [];
const userByEmail = new Map(usersByEmail.map((u) => [u.username, u]));
+
+ // The invite this request accompanies resolves IdP identifiers through SSO aliases, so this
+ // half has to as well, or it rejects a user the other half just added. Keyed by the caller's
+ // identifier so the unresolved list still echoes back what they sent.
+ const unmatched = emails.filter((e) => !userByEmail.has(e));
+ if (unmatched.length) {
+ const org = await orgDAL.findById(ctx.actorOrgId);
+ const { resolved, ambiguousIdentifiers } = await resolveUsersBySsoExternalId({
+ identifiers: unmatched,
+ orgId: ctx.actorOrgId,
+ rootOrgId: org?.rootOrgId,
+ userAliasDAL,
+ userDAL
+ });
+
+ if (ambiguousIdentifiers.length) {
+ throw new BadRequestError({
+ message: `Identifier(s) ${ambiguousIdentifiers
+ .map((el) => `'${el}'`)
+ .join(
+ ", "
+ )} match more than one SSO account in this organization. Use the user's email address instead, or contact support to resolve the duplicate.`
+ });
+ }
+
+ resolved.forEach((user, identifier) => userByEmail.set(identifier, user));
+ }
+
const unresolved = emails.filter((e) => !userByEmail.has(e));
const candidates: { userId: string; label: string }[] = [];
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 389dc24ade..d5bb98f8b1 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -1536,6 +1536,7 @@ export const registerRoutes = async (
projectDAL,
permissionService,
userDAL,
+ userAliasDAL,
userGroupMembershipDAL,
smtpService,
projectKeyDAL,
@@ -1885,6 +1886,8 @@ export const registerRoutes = async (
pamAccountDAL,
pamSessionDAL,
userDAL,
+ userAliasDAL,
+ orgDAL,
groupDAL,
userGroupMembershipDAL,
identityGroupMembershipDAL,
diff --git a/backend/src/services/membership-user/membership-user-service.ts b/backend/src/services/membership-user/membership-user-service.ts
index 5795afd00d..fc5b8356cd 100644
--- a/backend/src/services/membership-user/membership-user-service.ts
+++ b/backend/src/services/membership-user/membership-user-service.ts
@@ -15,7 +15,7 @@ import { TOidcConfigDALFactory } from "@app/ee/services/oidc/oidc-config-dal";
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
import { TSamlConfigDALFactory } from "@app/ee/services/saml-config/saml-config-dal";
import { BadRequestError, NotFoundError } from "@app/lib/errors";
-import { groupBy } from "@app/lib/fn";
+import { groupBy, unique } from "@app/lib/fn";
import { ms } from "@app/lib/ms";
import { requestMemoKeys } from "@app/lib/request-context/memo-keys";
import { requestMemoize } from "@app/lib/request-context/request-memoizer";
@@ -45,6 +45,7 @@ import { getServerCfg } from "../super-admin/super-admin-service";
import { LoginMethod } from "../super-admin/super-admin-types";
import { TUserDALFactory } from "../user/user-dal";
import { TUserAliasDALFactory } from "../user-alias/user-alias-dal";
+import { resolveUsersBySsoExternalId } from "../user-alias/user-alias-fns";
import { TMembershipUserDALFactory } from "./membership-user-dal";
import { assertWillRetainOrgAdmin } from "./membership-user-fns";
import {
@@ -143,12 +144,43 @@ export const membershipUserServiceFactory = ({
})
};
- const $getUsers = async (usernames: string[]) => {
+ const $getUsers = async (usernames: string[], orgId: string, rootOrgId?: string | null) => {
const existingUsers = await userDAL.find({ $in: { username: usernames } });
- if (existingUsers.length !== usernames.length) {
- const newUserEmails = usernames
- .filter((inviteeEmail) => !existingUsers.find((el) => el.username === inviteeEmail))
- .map((el) => el.toLowerCase());
+ const unmatched = usernames.filter((username) => !existingUsers.some((el) => el.username === username));
+
+ // Something that isn't a username may still be an IdP identifier we already recorded on the
+ // member's SSO alias (a UPN, say). This is what lets a provisioning system that only knows IdP
+ // identifiers name existing users. Has to run before the email validation below, since an
+ // externalId needn't look like an email and "Invalid emails" would be a misleading failure.
+ let aliasResolvedIdentifiers: string[] = [];
+ if (unmatched.length) {
+ const { resolved, ambiguousIdentifiers } = await resolveUsersBySsoExternalId({
+ identifiers: unmatched,
+ orgId,
+ rootOrgId,
+ userAliasDAL,
+ userDAL
+ });
+
+ if (ambiguousIdentifiers.length) {
+ throw new BadRequestError({
+ message: `Identifier(s) ${ambiguousIdentifiers
+ .map((el) => `'${el}'`)
+ .join(
+ ", "
+ )} match more than one SSO account in this organization. Invite the user by their email address instead, or contact support to resolve the duplicate.`
+ });
+ }
+
+ // Track identifiers, not resolved usernames: an alias-resolved user's username is their
+ // email, which is never the identifier that found them.
+ aliasResolvedIdentifiers = [...resolved.keys()];
+ existingUsers.push(...resolved.values());
+ }
+
+ const stillUnmatched = unmatched.filter((username) => !aliasResolvedIdentifiers.includes(username));
+ if (stillUnmatched.length) {
+ const newUserEmails = stillUnmatched.map((el) => el.toLowerCase());
const invalidEmails = newUserEmails.filter((el) => {
try {
@@ -199,7 +231,11 @@ export const membershipUserServiceFactory = ({
}
});
}
- return existingUsers;
+
+ // A person can now arrive twice in one request, once by username and once by alias. Callers
+ // count this list against memberships and insert from it, so a dupe trips
+ // membership_unique_user_org.
+ return unique(existingUsers, (user) => user.id);
};
const createMembership = async (dto: TCreateMembershipUserDTO) => {
@@ -271,7 +307,7 @@ export const membershipUserServiceFactory = ({
}
const scopeDatabaseFields = factory.getScopeDatabaseFields(dto.scopeData);
const sanitizedEmails = dto.data.usernames.map((el) => sanitizeEmail(el));
- const users = await $getUsers(sanitizedEmails);
+ const users = await $getUsers(sanitizedEmails, dto.permission.orgId, orgDetails.rootOrgId);
const existingMemberships = await membershipUserDAL.find({
scope: scopeData.scope,
...scopeDatabaseFields,
diff --git a/backend/src/services/project-membership/project-membership-service.ts b/backend/src/services/project-membership/project-membership-service.ts
index 2cdcfa4c17..9bf4084146 100644
--- a/backend/src/services/project-membership/project-membership-service.ts
+++ b/backend/src/services/project-membership/project-membership-service.ts
@@ -8,7 +8,7 @@ import { TPermissionServiceFactory } from "@app/ee/services/permission/permissio
import { ProjectPermissionMemberActions, ProjectPermissionSub } from "@app/ee/services/permission/project-permission";
import { getConfig } from "@app/lib/config/env";
import { BadRequestError, NotFoundError } from "@app/lib/errors";
-import { groupBy } from "@app/lib/fn";
+import { groupBy, unique } from "@app/lib/fn";
import { requestMemoKeys } from "@app/lib/request-context/memo-keys";
import { requestMemoize } from "@app/lib/request-context/request-memoizer";
import { PamIdentities, SecretIdentities } from "@app/services/license-client";
@@ -34,6 +34,8 @@ import { TProjectKeyDALFactory } from "../project-key/project-key-dal";
import { TSecretReminderRecipientsDALFactory } from "../secret-reminder-recipients/secret-reminder-recipients-dal";
import { SmtpTemplates, TSmtpService } from "../smtp/smtp-service";
import { TUserDALFactory } from "../user/user-dal";
+import { TUserAliasDALFactory } from "../user-alias/user-alias-dal";
+import { resolveUsersBySsoExternalId } from "../user-alias/user-alias-fns";
import { TProjectMembershipDALFactory } from "./project-membership-dal";
import {
TAddUsersToWorkspaceDTO,
@@ -50,6 +52,7 @@ type TProjectMembershipServiceFactoryDep = {
membershipUserDAL: TMembershipUserDALFactory;
membershipRoleDAL: Pick<TMembershipRoleDALFactory, "insertMany" | "find" | "delete">;
userDAL: Pick<TUserDALFactory, "find">;
+ userAliasDAL: Pick<TUserAliasDALFactory, "findBySsoExternalIds">;
userGroupMembershipDAL: TUserGroupMembershipDALFactory;
projectDAL: Pick<TProjectDALFactory, "findById" | "findProjectGhostUser" | "transaction" | "findProjectById">;
projectKeyDAL: Pick<TProjectKeyDALFactory, "findLatestProjectKey" | "delete" | "insertMany">;
@@ -89,6 +92,7 @@ export const projectMembershipServiceFactory = ({
secretApprovalPolicyDAL,
membershipUserDAL,
userDAL,
+ userAliasDAL,
membershipRoleDAL,
applicationMembershipCleanupService,
usageMeteringService,
@@ -180,6 +184,41 @@ export const projectMembershipServiceFactory = ({
return projectMembers.map((m) => ({ ...m, isGroupMember: false }));
};
+ /**
+ * A provisioning system may name a member by its IdP identifier (a UPN, say) instead of their
+ * username. Map those to usernames up front so everything downstream keys on the same value,
+ * including the group-membership lookup that decides whose project key survives. Usernames win,
+ * so an alias can never shadow a real account.
+ */
+ const $toCanonicalUsernames = async (identifiers: string[], projectId: string) => {
+ const deduped = unique(identifiers);
+ const existingUsers = await userDAL.find({ $in: { username: deduped } });
+ const unmatched = deduped.filter((identifier) => !existingUsers.some((el) => el.username === identifier));
+ if (!unmatched.length) return deduped;
+
+ const project = await projectDAL.findById(projectId);
+ if (!project) throw new NotFoundError({ message: `Project with ID '${projectId}' not found` });
+
+ const { resolved, ambiguousIdentifiers } = await resolveUsersBySsoExternalId({
+ identifiers: unmatched,
+ orgId: project.orgId,
+ userAliasDAL,
+ userDAL
+ });
+
+ if (ambiguousIdentifiers.length) {
+ throw new BadRequestError({
+ message: `Identifier(s) ${ambiguousIdentifiers
+ .map((el) => `'${el}'`)
+ .join(
+ ", "
+ )} match more than one SSO account in this organization. Use the user's email address instead, or contact support to resolve the duplicate.`
+ });
+ }
+
+ return unique(deduped.map((identifier) => resolved.get(identifier)?.username ?? identifier));
+ };
+
const getProjectMembershipByUsername = async ({
actorId,
actor,
@@ -198,7 +237,10 @@ export const projectMembershipServiceFactory = ({
});
ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionMemberActions.Read, ProjectPermissionSub.Member);
- const [membership] = await projectMembershipDAL.findAllProjectMembers(projectId, { username });
+ const [canonicalUsername] = await $toCanonicalUsernames([username], projectId);
+ const [membership] = await projectMembershipDAL.findAllProjectMembers(projectId, {
+ username: canonicalUsername
+ });
if (!membership) throw new NotFoundError({ message: `Project membership not found for user '${username}'` });
return membership;
};
@@ -323,11 +365,9 @@ export const projectMembershipServiceFactory = ({
});
ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionMemberActions.Delete, ProjectPermissionSub.Member);
- const usernamesAndEmails = [...emails, ...usernames];
+ const usernamesAndEmails = await $toCanonicalUsernames([...emails, ...usernames], projectId);
- const projectMembers = await projectMembershipDAL.findMembershipsByUsername(projectId, [
- ...new Set(usernamesAndEmails.map((element) => element))
- ]);
+ const projectMembers = await projectMembershipDAL.findMembershipsByUsername(projectId, usernamesAndEmails);
if (projectMembers.length !== usernamesAndEmails.length) {
throw new BadRequestError({
diff --git a/backend/src/services/user-alias/user-alias-dal.ts b/backend/src/services/user-alias/user-alias-dal.ts
index 366eadce0e..622d134aa1 100644
--- a/backend/src/services/user-alias/user-alias-dal.ts
+++ b/backend/src/services/user-alias/user-alias-dal.ts
@@ -1,5 +1,8 @@
+import { Knex } from "knex";
+
import { TDbClient } from "@app/db";
import { TableName } from "@app/db/schemas";
+import { DatabaseError } from "@app/lib/errors";
import { ormify } from "@app/lib/knex";
export type TUserAliasDALFactory = ReturnType<typeof userAliasDALFactory>;
@@ -7,7 +10,33 @@ export type TUserAliasDALFactory = ReturnType<typeof userAliasDALFactory>;
export const userAliasDALFactory = (db: TDbClient) => {
const userAliasOrm = ormify(db, TableName.UserAliases);
+ /**
+ * Exact comparison on externalId, deliberately not folded: it's a case-sensitive identifier (OIDC
+ * Core says so for `sub`, SAML likewise for nameID) stored verbatim, so folding could match two
+ * different IdP subjects. Trade-off is that an IdP asserting mixed-case identifiers can't be
+ * provisioned against, since both invite routes lowercase their input. Fixing that means relaxing
+ * those routes, not loosening this.
+ *
+ * orgIds and aliasTypes are the security boundary: orgIds drops the NULL-org social aliases,
+ * aliasTypes is the second lock.
+ */
+ const findBySsoExternalIds = async (
+ { externalIds, orgIds, aliasTypes }: { externalIds: string[]; orgIds: string[]; aliasTypes: string[] },
+ tx?: Knex
+ ) => {
+ try {
+ return await (tx || db.replicaNode())(TableName.UserAliases)
+ .whereIn("orgId", orgIds)
+ .whereIn("aliasType", aliasTypes)
+ .whereIn("externalId", externalIds)
+ .select("externalId", "userId");
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Find user aliases by SSO external id" });
+ }
+ };
+
return {
- ...userAliasOrm
+ ...userAliasOrm,
+ findBySsoExternalIds
};
};
diff --git a/backend/src/services/user-alias/user-alias-fns.test.ts b/backend/src/services/user-alias/user-alias-fns.test.ts
new file mode 100644
index 0000000000..7932d93f8a
--- /dev/null
+++ b/backend/src/services/user-alias/user-alias-fns.test.ts
@@ -0,0 +1,213 @@
+import { Knex } from "knex";
+import { describe, expect, test, vi } from "vitest";
+
+import { TUsers } from "@app/db/schemas";
+import { DatabaseErrorCode } from "@app/lib/error-codes";
+import { DatabaseError } from "@app/lib/errors";
+
+import { adoptProvisionedShadowUser, resolveAliasUserIds } from "./user-alias-fns";
+
+const alias = (externalId: string, userId: string) => ({ externalId, userId });
+
+describe("resolveAliasUserIds", () => {
+ test("resolves an identifier to the user its alias points at", () => {
+ const { userIdByIdentifier, ambiguousIdentifiers } = resolveAliasUserIds({
+ identifiers: ["[email protected]"],
+ aliases: [alias("[email protected]", "user-1")]
+ });
+
+ expect(userIdByIdentifier.get("[email protected]")).toBe("user-1");
+ expect(ambiguousIdentifiers).toEqual([]);
+ });
+
+ // externalId is case-sensitive (OIDC Core says so for `sub`), so a differently-cased identifier
+ // is a different subject and must not resolve.
+ test("does not match an identifier whose case differs from the stored externalId", () => {
+ const { userIdByIdentifier, ambiguousIdentifiers } = resolveAliasUserIds({
+ identifiers: ["[email protected]"],
+ aliases: [alias("[email protected]", "user-1")]
+ });
+
+ expect(userIdByIdentifier.size).toBe(0);
+ expect(ambiguousIdentifiers).toEqual([]);
+ });
+
+ test("treats one user holding several aliases under the same externalId as one account", () => {
+ const { userIdByIdentifier, ambiguousIdentifiers } = resolveAliasUserIds({
+ identifiers: ["[email protected]"],
+ aliases: [alias("[email protected]", "user-1"), alias("[email protected]", "user-1")]
+ });
+
+ expect(userIdByIdentifier.get("[email protected]")).toBe("user-1");
+ expect(ambiguousIdentifiers).toEqual([]);
+ });
+
+ test("reports an identifier that reaches two distinct users as ambiguous and resolves it to nobody", () => {
+ const { userIdByIdentifier, ambiguousIdentifiers } = resolveAliasUserIds({
+ identifiers: ["[email protected]"],
+ aliases: [alias("[email protected]", "user-1"), alias("[email protected]", "user-2")]
+ });
+
+ expect(userIdByIdentifier.has("[email protected]")).toBe(false);
+ expect(ambiguousIdentifiers).toEqual(["[email protected]"]);
+ });
+
+ // Counterpart to the test above: matching is exact, so case-variant aliases on two different
+ // people are two different subjects, not an ambiguity.
+ test("keeps case-variant aliases on different accounts distinct rather than ambiguous", () => {
+ const { userIdByIdentifier, ambiguousIdentifiers } = resolveAliasUserIds({
+ identifiers: ["[email protected]"],
+ aliases: [alias("[email protected]", "user-1"), alias("[email protected]", "user-2")]
+ });
+
+ expect(userIdByIdentifier.get("[email protected]")).toBe("user-2");
+ expect(ambiguousIdentifiers).toEqual([]);
+ });
+
+ test("leaves an identifier with no alias unresolved", () => {
+ const { userIdByIdentifier, ambiguousIdentifiers } = resolveAliasUserIds({
+ identifiers: ["[email protected]"],
+ aliases: [alias("[email protected]", "user-1")]
+ });
+
+ expect(userIdByIdentifier.size).toBe(0);
+ expect(ambiguousIdentifiers).toEqual([]);
+ });
+
+ test("handles empty inputs", () => {
+ expect(resolveAliasUserIds({ identifiers: [], aliases: [] })).toEqual({
+ userIdByIdentifier: new Map(),
+ ambiguousIdentifiers: []
+ });
+ });
+});
+
+const ORG_ID = "org-1";
+const EXTERNAL_ID = "[email protected]";
+const ASSERTED_EMAIL = "[email protected]";
+
+const shadowUser = (overrides: Partial<TUsers> = {}) =>
+ ({
+ id: "shadow-1",
+ username: EXTERNAL_ID,
+ email: EXTERNAL_ID,
+ isGhost: false,
+ isAccepted: false,
+ isEmailVerified: false,
+ hashedPassword: null,
+ ...overrides
+ }) as TUsers;
+
+const buildDeps = ({
+ candidate = shadowUser(),
+ existingAlias = null,
+ membership = [{ id: "membership-1" }]
+}: {
+ candidate?: TUsers | null;
+ existingAlias?: object | null;
+ membership?: object[];
+} = {}) => {
+ const userDAL = {
+ findOne: vi.fn().mockResolvedValue(candidate),
+ updateById: vi
+ .fn()
+ .mockImplementation((id: string, update: Partial<TUsers>) => ({ ...shadowUser(), ...update, id }))
+ };
+ const userAliasDAL = { findOne: vi.fn().mockResolvedValue(existingAlias) };
+ const orgDAL = { findMembership: vi.fn().mockResolvedValue(membership) };
+
+ return { userDAL, userAliasDAL, orgDAL };
+};
+
+const adopt = (deps: ReturnType<typeof buildDeps>, externalId = EXTERNAL_ID) =>
+ adoptProvisionedShadowUser({
+ externalId,
+ assertedEmail: ASSERTED_EMAIL,
+ orgId: ORG_ID,
+ tx: {} as Knex,
+ ...deps
+ });
+
+describe("adoptProvisionedShadowUser", () => {
+ test("rewrites the placeholder's identity to the asserted mailbox", async () => {
+ const deps = buildDeps();
+
+ const adopted = await adopt(deps);
+
+ expect(adopted?.id).toBe("shadow-1");
+ expect(deps.userDAL.updateById).toHaveBeenCalledWith(
+ "shadow-1",
+ { username: ASSERTED_EMAIL, email: ASSERTED_EMAIL },
+ {}
+ );
+ });
+
+ test("looks the placeholder up by the sanitized identifier, so a mixed-case claim still matches", async () => {
+ const deps = buildDeps();
+
+ await adopt(deps, "[email protected]");
+
+ expect(deps.userDAL.findOne).toHaveBeenCalledWith({ username: EXTERNAL_ID }, {});
+ });
+
+ test("declines when the identifier is already the asserted email", async () => {
+ const deps = buildDeps();
+
+ expect(await adopt(deps, ASSERTED_EMAIL)).toBeNull();
+ expect(deps.userDAL.findOne).not.toHaveBeenCalled();
+ });
+
+ test("declines when no placeholder exists", async () => {
+ const deps = buildDeps({ candidate: null });
+
+ expect(await adopt(deps)).toBeNull();
+ expect(deps.userDAL.updateById).not.toHaveBeenCalled();
+ });
+
+ test.each([
+ ["a ghost user", { isGhost: true }],
+ ["an accepted account", { isAccepted: true }],
+ ["an email-verified account", { isEmailVerified: true }],
+ ["an account holding a password", { hashedPassword: "hash" }]
+ ])("declines to adopt %s", async (_label, overrides) => {
+ const deps = buildDeps({ candidate: shadowUser(overrides) });
+
+ expect(await adopt(deps)).toBeNull();
+ expect(deps.userDAL.updateById).not.toHaveBeenCalled();
+ });
+
+ test("declines when any IdP has already bound the account", async () => {
+ const deps = buildDeps({ existingAlias: { id: "alias-1" } });
+
+ expect(await adopt(deps)).toBeNull();
+ expect(deps.userDAL.updateById).not.toHaveBeenCalled();
+ });
+
+ test("declines when the placeholder holds no membership in this org", async () => {
+ const deps = buildDeps({ membership: [] });
+
+ expect(await adopt(deps)).toBeNull();
+ expect(deps.userDAL.updateById).not.toHaveBeenCalled();
+ });
+
+ test("yields to the winner when a concurrent write takes the asserted email first", async () => {
+ const deps = buildDeps();
+ const winner = { ...shadowUser(), id: "winner-1", username: ASSERTED_EMAIL } as TUsers;
+ deps.userDAL.updateById.mockRejectedValueOnce(
+ new DatabaseError({ error: { code: DatabaseErrorCode.UniqueViolation } })
+ );
+ deps.userDAL.findOne.mockResolvedValueOnce(shadowUser()).mockResolvedValueOnce(winner);
+
+ expect(await adopt(deps)).toBe(winner);
+ });
+
+ test("rethrows a unique violation that no concurrent write explains", async () => {
+ const deps = buildDeps();
+ deps.userDAL.updateById.mockRejectedValueOnce(
+ new DatabaseError({ error: { code: DatabaseErrorCode.UniqueViolation } })
+ );
+ deps.userDAL.findOne.mockResolvedValueOnce(shadowUser()).mockResolvedValueOnce(null);
+
+ await expect(adopt(deps)).rejects.toThrow(DatabaseError);
+ });
+});
diff --git a/backend/src/services/user-alias/user-alias-fns.ts b/backend/src/services/user-alias/user-alias-fns.ts
index 51f71df4d8..c4b29bace4 100644
--- a/backend/src/services/user-alias/user-alias-fns.ts
+++ b/backend/src/services/user-alias/user-alias-fns.ts
@@ -1,7 +1,15 @@
-import { TUserAliases, TUsers } from "@app/db/schemas";
+import { Knex } from "knex";
+import { AccessScope, TableName, TUserAliases, TUsers } from "@app/db/schemas";
+import { DatabaseErrorCode } from "@app/lib/error-codes";
+import { DatabaseError } from "@app/lib/errors";
+import { unique } from "@app/lib/fn";
+import { sanitizeEmail } from "@app/lib/validator/validate-email";
+
+import { TOrgDALFactory } from "../org/org-dal";
import { TUserDALFactory } from "../user/user-dal";
import { TUserAliasDALFactory } from "./user-alias-dal";
+import { UserAliasType } from "./user-alias-types";
type TEnsureSsoAccountVerifiedDTO = {
user: TUsers;
@@ -84,3 +92,175 @@ export const ensureSsoAccountVerified = async ({
userAlias: { ...userAlias, isEmailVerified: true }
};
};
+
+type TResolveAliasUserIdsDTO = {
+ identifiers: string[];
+ aliases: Pick<TUserAliases, "externalId" | "userId">[];
+};
+
+/**
+ * Alias types scoped to one org. Social aliases carry a NULL orgId and are global, so letting them
+ * resolve a provisioning identifier would let an org admin name a user in another tenant.
+ */
+export const ORG_SCOPED_USER_ALIAS_TYPES = [UserAliasType.OIDC, UserAliasType.SAML, UserAliasType.LDAP];
+
+export const resolveAliasUserIds = ({ identifiers, aliases }: TResolveAliasUserIdsDTO) => {
+ // externalId is case-sensitive, so don't fold it. Folding could collapse two different IdP
+ // subjects onto one identifier.
+ const userIdsByExternalId = new Map<string, Set<string>>();
+ aliases.forEach((alias) => {
+ const userIds = userIdsByExternalId.get(alias.externalId);
+ if (userIds) {
+ userIds.add(alias.userId);
+ } else {
+ userIdsByExternalId.set(alias.externalId, new Set([alias.userId]));
+ }
+ });
+
+ const userIdByIdentifier = new Map<string, string>();
+ const ambiguousIdentifiers: string[] = [];
+
+ identifiers.forEach((identifier) => {
+ const matchedUserIds = userIdsByExternalId.get(identifier);
+ if (!matchedUserIds?.size) return;
+
+ // Several aliases on the same user (an OIDC row plus a SAML row) is one account, not a
+ // conflict. Two different users is a real conflict, and guessing wrong grants access to the
+ // wrong person, so bail.
+ if (matchedUserIds.size > 1) {
+ ambiguousIdentifiers.push(identifier);
+ return;
+ }
+
+ const [userId] = [...matchedUserIds];
+ userIdByIdentifier.set(identifier, userId);
+ });
+
+ return { userIdByIdentifier, ambiguousIdentifiers };
+};
+
+type TResolveUsersBySsoExternalIdDTO = {
+ identifiers: string[];
+ orgId: string;
+ // Sub-orgs usually have no IdP of their own, so a member's alias lives on the root org.
+ rootOrgId?: string | null;
+ userAliasDAL: Pick<TUserAliasDALFactory, "findBySsoExternalIds">;
+ userDAL: Pick<TUserDALFactory, "find">;
+ tx?: Knex;
+};
+
+/**
+ * Maps an IdP identifier (a UPN, say) to the user its SSO alias points at. Only call this once an
+ * exact username lookup has missed, so an alias can never shadow a real account.
+ */
+export const resolveUsersBySsoExternalId = async ({
+ identifiers,
+ orgId,
+ rootOrgId,
+ userAliasDAL,
+ userDAL,
+ tx
+}: TResolveUsersBySsoExternalIdDTO): Promise<{ resolved: Map<string, TUsers>; ambiguousIdentifiers: string[] }> => {
+ const empty = { resolved: new Map<string, TUsers>(), ambiguousIdentifiers: [] };
+
+ const candidates = unique(identifiers.filter(Boolean));
+ if (!candidates.length) return empty;
+
+ const aliases = await userAliasDAL.findBySsoExternalIds(
+ {
+ externalIds: candidates,
+ aliasTypes: ORG_SCOPED_USER_ALIAS_TYPES,
+ orgIds: rootOrgId ? [orgId, rootOrgId] : [orgId]
+ },
+ tx
+ );
+ if (!aliases.length) return empty;
+
+ const { userIdByIdentifier, ambiguousIdentifiers } = resolveAliasUserIds({ identifiers, aliases });
+ const userIds = unique([...userIdByIdentifier.values()]);
+ if (!userIds.length) return { resolved: new Map<string, TUsers>(), ambiguousIdentifiers };
+
+ // Ghosts hold project key material, so they must never be reachable by a provisioning identifier.
+ const users = await userDAL.find({ $in: { id: userIds }, isGhost: false }, { tx });
+ const userById = new Map(users.map((user) => [user.id, user]));
+
+ const resolved = new Map<string, TUsers>();
+ userIdByIdentifier.forEach((userId, identifier) => {
+ const user = userById.get(userId);
+ if (user) resolved.set(identifier, user);
+ });
+
+ return { resolved, ambiguousIdentifiers };
+};
+
+type TAdoptProvisionedShadowUserDTO = {
+ externalId: string;
+ // Caller has already sanitized this and verified its domain against the org.
+ assertedEmail: string;
+ orgId: string;
+ userDAL: Pick<TUserDALFactory, "findOne" | "updateById">;
+ userAliasDAL: Pick<TUserAliasDALFactory, "findOne">;
+ orgDAL: Pick<TOrgDALFactory, "findMembership">;
+ tx: Knex;
+};
+
+/**
+ * Provisioning can name someone by their IdP identifier before they have ever logged in, which
+ * leaves a placeholder account keyed on that identifier instead of their mailbox. On first login we
+ * adopt the placeholder and rewrite it to the asserted mailbox, rather than creating a second
+ * account and stranding whatever the placeholder was granted.
+ *
+ * Returns null if there is nothing safe to adopt. Only call this once a lookup on the asserted
+ * email has missed.
+ */
+export const adoptProvisionedShadowUser = async ({
+ externalId,
+ assertedEmail,
+ orgId,
+ userDAL,
+ userAliasDAL,
+ orgDAL,
+ tx
+}: TAdoptProvisionedShadowUserDTO): Promise<TUsers | null> => {
+ // We fold case here even though resolveUsersBySsoExternalId doesn't, because this is a username
+ // lookup and usernames are canonically lowercase (validateEmail rejects uppercase ones). The
+ // placeholder's username came from lowercasing the provisioner's input, so match that form.
+ const shadowUsername = sanitizeEmail(externalId);
+ if (!shadowUsername || shadowUsername === assertedEmail) return null;
+
+ const candidate = await userDAL.findOne({ username: shadowUsername }, tx);
+ if (!candidate) return null;
+
+ // Ghosts hold project key material. The rest prove nobody ever claimed this account: accepted,
+ // email-verified, or has a password all mean it belongs to someone.
+ if (candidate.isGhost || candidate.isAccepted || candidate.isEmailVerified || candidate.hashedPassword) return null;
+
+ // Any alias, in any org, means some IdP already owns this account. Without this check one org's
+ // IdP could steal an account bound to another's.
+ const existingAlias = await userAliasDAL.findOne({ userId: candidate.id }, tx);
+ if (existingAlias) return null;
+
+ // Keeps this to placeholders the org itself created through an authorized invite.
+ const [orgMembership] = await orgDAL.findMembership(
+ {
+ [`${TableName.Membership}.actorUserId` as "actorUserId"]: candidate.id,
+ [`${TableName.Membership}.scopeOrgId` as "scopeOrgId"]: orgId,
+ [`${TableName.Membership}.scope` as "scope"]: AccessScope.Organization
+ },
+ { tx }
+ );
+ if (!orgMembership) return null;
+
+ try {
+ return await userDAL.updateById(candidate.id, { username: assertedEmail, email: assertedEmail }, tx);
+ } catch (err) {
+ // The caller's read showed nobody held the asserted email, but a read isn't a lock, so a
+ // concurrent login or invite can grab it first (users.username is globally unique). Yield to
+ // whoever won: same end state as the uncontended path, placeholder left alone.
+ if (err instanceof DatabaseError && (err.error as { code?: string })?.code === DatabaseErrorCode.UniqueViolation) {
+ const winner = await userDAL.findOne({ username: assertedEmail }, tx);
+ if (winner) return winner;
+ }
+ throw err;
+ }
+};