Skip to content

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

fix(platform-230): use SSO platform identifiers

Tre Dubrava7b5cde3decd4
diff --git a/backend/src/db/migrations/20260309201009_add-oauth-alias-unique-index.ts b/backend/src/db/migrations/20260309201009_add-oauth-alias-unique-index.ts
new file mode 100644
index 0000000000..674f0319d4
--- /dev/null
+++ b/backend/src/db/migrations/20260309201009_add-oauth-alias-unique-index.ts
@@ -0,0 +1,18 @@
+import { Knex } from "knex";
+
+import { TableName } from "../schemas";
+
+const INDEX_NAME = "user_aliases_oauth_externalid_aliastype_unique";
+
+export async function up(knex: Knex): Promise<void> {
+ await knex.raw(
+ `CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS "${INDEX_NAME}" ON "${TableName.UserAliases}" ("externalId", "aliasType") WHERE "aliasType" IN ('google', 'github', 'gitlab')`
+ );
+}
+
+export async function down(knex: Knex): Promise<void> {
+ await knex.raw(`DROP INDEX IF EXISTS "${INDEX_NAME}"`);
+}
+
+const config = { transaction: false };
+export { config };
diff --git a/backend/src/lib/requests/github.ts b/backend/src/lib/requests/github.ts
index f25e46af58..61e609eaf3 100644
--- a/backend/src/lib/requests/github.ts
+++ b/backend/src/lib/requests/github.ts
@@ -18,11 +18,12 @@ export const fetchGithubEmails = async (accessToken: string) => {
};
type TGithubUser = {
+ id: number;
name?: string;
login: string;
};
-export const fetchGithubUser = async (accessToken: string) => {
+export const fetchGithubUser = async (accessToken: string): Promise<TGithubUser> => {
const { data } = await request.get<TGithubUser>(`${INTEGRATION_GITHUB_API_URL}/user`, {
headers: {
Authorization: `Bearer ${accessToken}`
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index da923313a6..97d1f892b9 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -1002,6 +1002,7 @@ export const registerRoutes = async (
const loginService = authLoginServiceFactory({
userDAL,
+ userAliasDAL,
smtpService,
tokenService,
orgDAL,
diff --git a/backend/src/server/routes/v1/sso-router.ts b/backend/src/server/routes/v1/sso-router.ts
index bcc77eb312..e9ffbad269 100644
--- a/backend/src/server/routes/v1/sso-router.ts
+++ b/backend/src/server/routes/v1/sso-router.ts
@@ -73,7 +73,8 @@ export const registerOauthMiddlewares = (server: FastifyZodProvider) => {
lastName: profile?.name?.familyName || "",
authMethod: AuthMethod.GOOGLE,
callbackPort,
- orgSlug
+ orgSlug,
+ providerUserId: profile.id
});
const googleDistinctId = user.username ?? user.email ?? "";
@@ -155,7 +156,8 @@ export const registerOauthMiddlewares = (server: FastifyZodProvider) => {
firstName: githubUser.name || githubUser.login,
lastName: "",
authMethod: AuthMethod.GITHUB,
- callbackPort
+ callbackPort,
+ providerUserId: String(githubUser.id)
});
const githubDistinctId = user.username ?? user.email ?? "";
@@ -229,7 +231,8 @@ export const registerOauthMiddlewares = (server: FastifyZodProvider) => {
firstName: profile.displayName || profile.username || "",
lastName: "",
authMethod: AuthMethod.GITLAB,
- callbackPort
+ callbackPort,
+ providerUserId: String(profile.id)
});
const gitlabDistinctId = user.username ?? user.email ?? "";
diff --git a/backend/src/services/auth/auth-login-service.ts b/backend/src/services/auth/auth-login-service.ts
index e0069349ca..ca5f71fa49 100644
--- a/backend/src/services/auth/auth-login-service.ts
+++ b/backend/src/services/auth/auth-login-service.ts
@@ -42,6 +42,8 @@ import { LoginMethod } from "../super-admin/super-admin-types";
import { TTotpServiceFactory } from "../totp/totp-service";
import { TUserDALFactory } from "../user/user-dal";
import { UserEncryption } from "../user/user-types";
+import { TUserAliasDALFactory } from "../user-alias/user-alias-dal";
+import { UserAliasType } from "../user-alias/user-alias-types";
import { enforceUserLockStatus, getAuthMethodAndOrgId, validateProviderAuthToken, verifyCaptcha } from "./auth-fns";
import {
TLoginClientProofDTO,
@@ -61,6 +63,7 @@ import {
type TAuthLoginServiceFactoryDep = {
userDAL: TUserDALFactory;
+ userAliasDAL: Pick<TUserAliasDALFactory, "findOne" | "create">;
orgDAL: TOrgDALFactory;
tokenService: TAuthTokenServiceFactory;
smtpService: TSmtpService;
@@ -76,6 +79,7 @@ type TAuthLoginServiceFactoryDep = {
export type TAuthLoginFactory = ReturnType<typeof authLoginServiceFactory>;
export const authLoginServiceFactory = ({
userDAL,
+ userAliasDAL,
tokenService,
smtpService,
orgDAL,
@@ -991,10 +995,47 @@ export const authLoginServiceFactory = ({
/*
* OAuth2 login for google,github, and other oauth2 provider
* */
- const oauth2Login = async ({ email, firstName, lastName, authMethod, callbackPort, orgSlug }: TOauthLoginDTO) => {
- // akhilmhdh: case sensitive email resolution
- const usersByUsername = await userDAL.findUserByUsername(email);
- let user = usersByUsername?.length > 1 ? usersByUsername.find((el) => el.username === email) : usersByUsername?.[0];
+ const authMethodToAliasType = (method: AuthMethod): UserAliasType => {
+ switch (method) {
+ case AuthMethod.GOOGLE:
+ return UserAliasType.GOOGLE;
+ case AuthMethod.GITHUB:
+ return UserAliasType.GITHUB;
+ case AuthMethod.GITLAB:
+ return UserAliasType.GITLAB;
+ default:
+ throw new BadRequestError({ message: `Unsupported OAuth auth method: ${method}` });
+ }
+ };
+
+ const oauth2Login = async ({
+ email,
+ firstName,
+ lastName,
+ authMethod,
+ callbackPort,
+ orgSlug,
+ providerUserId
+ }: TOauthLoginDTO) => {
+ const aliasType = authMethodToAliasType(authMethod);
+
+ // Step 1: Look up user by provider alias (stable, immutable ID)
+ let user: TUsers | undefined;
+ let isNewAlias = false;
+ const existingAlias = await userAliasDAL.findOne({ externalId: providerUserId, aliasType });
+ if (existingAlias) {
+ user = await userDAL.findById(existingAlias.userId);
+ }
+
+ // Step 2: Fall back to email lookup for existing users without an alias yet
+ if (!user) {
+ const usersByUsername = await userDAL.findUserByUsername(email);
+ user = usersByUsername?.length > 1 ? usersByUsername.find((el) => el.username === email) : usersByUsername?.[0];
+ if (user) {
+ isNewAlias = true;
+ }
+ }
+
const serverCfg = await getServerCfg();
if (serverCfg.enabledLoginMethods && user) {
@@ -1061,38 +1102,41 @@ export const authLoginServiceFactory = ({
});
}
- user = await userDAL.create({
- username: email.trim().toLowerCase(),
- email: email.trim().toLowerCase(),
- isEmailVerified: true,
- firstName,
- lastName,
- authMethods: [authMethod],
- isGhost: false
- });
+ user = await userDAL.transaction(async (tx) => {
+ const newUser = await userDAL.create(
+ {
+ username: email.trim().toLowerCase(),
+ email: email.trim().toLowerCase(),
+ isEmailVerified: true,
+ firstName,
+ lastName,
+ authMethods: [authMethod],
+ isGhost: false
+ },
+ tx
+ );
- if (authMethod === AuthMethod.GITHUB && serverCfg.defaultAuthOrgId && !appCfg.isCloud) {
- const defaultOrg = await orgDAL.findOrgById(serverCfg.defaultAuthOrgId);
- if (!defaultOrg) {
- throw new BadRequestError({
- message: `Failed to find default organization with ID ${serverCfg.defaultAuthOrgId}`
+ if (authMethod === AuthMethod.GITHUB && serverCfg.defaultAuthOrgId && !appCfg.isCloud) {
+ const defaultOrg = await orgDAL.findOrgById(serverCfg.defaultAuthOrgId);
+ if (!defaultOrg) {
+ throw new BadRequestError({
+ message: `Failed to find default organization with ID ${serverCfg.defaultAuthOrgId}`
+ });
+ }
+ orgId = defaultOrg.id;
+ const existingMembership = await orgDAL.findEffectiveOrgMembership({
+ actorType: ActorType.USER,
+ actorId: newUser.id,
+ orgId,
+ acceptAnyStatus: true
});
- }
- orgId = defaultOrg.id;
- const orgMembership = await orgDAL.findEffectiveOrgMembership({
- actorType: ActorType.USER,
- actorId: user.id,
- orgId,
- acceptAnyStatus: true
- });
- if (!orgMembership) {
- const { role, roleId } = await getDefaultOrgMembershipRole(defaultOrg.defaultMembershipRole);
+ if (!existingMembership) {
+ const { role, roleId } = await getDefaultOrgMembershipRole(defaultOrg.defaultMembershipRole);
- await membershipUserDAL.transaction(async (tx) => {
const membership = await membershipUserDAL.create(
{
- actorUserId: user?.id,
+ actorUserId: newUser.id,
inviteEmail: email,
scopeOrgId: orgId,
scope: AccessScope.Organization,
@@ -1109,9 +1153,22 @@ export const authLoginServiceFactory = ({
},
tx
);
- });
+ }
}
- }
+
+ await userAliasDAL.create(
+ {
+ userId: newUser.id,
+ aliasType,
+ externalId: providerUserId,
+ emails: [email],
+ orgId: orgId || null
+ },
+ tx
+ );
+
+ return newUser;
+ });
} else {
const isLinkingRequired = !user?.authMethods?.includes(authMethod);
if (isLinkingRequired) {
@@ -1144,6 +1201,26 @@ export const authLoginServiceFactory = ({
}
}
+ // Self-healing backfill: create alias for existing users found by email fallback
+ if (isNewAlias) {
+ try {
+ await userAliasDAL.create({
+ userId: user.id,
+ aliasType,
+ externalId: providerUserId,
+ emails: [email],
+ orgId: orgId || null
+ });
+ } catch (err) {
+ // Swallow duplicate key errors from the unique index (race condition: concurrent login already created the alias)
+ if (err instanceof DatabaseError && (err.error as { code: string })?.code === "23505") {
+ logger.warn(`OAuth alias backfill for user ${user.id} skipped: alias already exists`);
+ } else {
+ throw err;
+ }
+ }
+ }
+
const isUserCompleted = user.isAccepted;
const providerAuthToken = crypto.jwt().sign(
{
diff --git a/backend/src/services/auth/auth-login-type.ts b/backend/src/services/auth/auth-login-type.ts
index 9b010a8604..d11d2ddf39 100644
--- a/backend/src/services/auth/auth-login-type.ts
+++ b/backend/src/services/auth/auth-login-type.ts
@@ -34,6 +34,7 @@ export type TOauthLoginDTO = {
authMethod: AuthMethod;
callbackPort?: string;
orgSlug?: string;
+ providerUserId: string;
};
export type TOauthTokenExchangeDTO = {
diff --git a/backend/src/services/user-alias/user-alias-types.ts b/backend/src/services/user-alias/user-alias-types.ts
index 7207e8acf5..3974bf71b4 100644
--- a/backend/src/services/user-alias/user-alias-types.ts
+++ b/backend/src/services/user-alias/user-alias-types.ts
@@ -1,5 +1,8 @@
export enum UserAliasType {
LDAP = "ldap",
SAML = "saml",
- OIDC = "oidc"
+ OIDC = "oidc",
+ GOOGLE = "google",
+ GITHUB = "github",
+ GITLAB = "gitlab"
}