From 0ef3d73412b0f9d35bc4daba3a83d0f48572d28d Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Thu, 5 Nov 2026 05:15:41 +0000 Subject: [PATCH 1/3] fix(oidc): persist OIDC subject and avoid email local-part username collisions (bug) createUser dropped the oidcId it was given, so findUserByOIDC never matched: repeat OIDC logins failed with 'user X already exists' and any identity with a matching email local part could claim a username first and lock the rightful owner out. - db.createUser stores oidcId for OIDC accounts - handleUserAuthentication resolves by subject first, rejects email_verified=false, refuses to bind to existing non-OIDC accounts by email, binds legacy OIDC accounts (password null, no oidcId) on exact email match, and suffixes the username with a hash of the subject when the local part is taken - deserializeUser falls back to a username lookup for non-OIDC sessions Refs: sfind-b275e4805c77462cbcb7852798cac2fb --- src/db/index.ts | 1 + src/service/passport/oidc.ts | 58 ++++++++++--- test/testDb.test.ts | 21 +++++ test/testOidc.test.ts | 152 +++++++++++++++++++++++++++++++++++ 4 files changed, 219 insertions(+), 13 deletions(-) diff --git a/src/db/index.ts b/src/db/index.ts index f9048fb3b..dde32c12d 100644 --- a/src/db/index.ts +++ b/src/db/index.ts @@ -76,6 +76,7 @@ export const createUser = async ( gitAccount: gitAccount, email: email, admin: admin, + ...(oidcId ? { oidcId } : {}), }; if (isBlank(username)) { diff --git a/src/service/passport/oidc.ts b/src/service/passport/oidc.ts index c4c868d5b..c15b22847 100644 --- a/src/service/passport/oidc.ts +++ b/src/service/passport/oidc.ts @@ -19,6 +19,7 @@ import { PassportStatic } from 'passport'; import { getAuthMethods } from '../../config'; import { type UserInfoResponse } from 'openid-client'; import { handleErrorAndLog } from '../../utils/errors'; +import { createHash } from 'crypto'; export const type = 'openidconnect'; @@ -74,7 +75,7 @@ export const configure = async (passport: PassportStatic): Promise { try { - const user = await db.findUserByOIDC(id); + const user = (await db.findUserByOIDC(id)) ?? (await db.findUser(id)); done(null, user); } catch (error: unknown) { done(error); @@ -99,29 +100,60 @@ export const handleUserAuthentication = async ( done: (err: unknown, user?: Partial) => void, ): Promise => { try { - const user = await db.findUserByOIDC(userInfo.sub); + if (!userInfo.sub) return done(new Error('No subject found in OIDC profile')); - if (!user) { - const email = safelyExtractEmail(userInfo); - if (!email) return done(new Error('No email found in OIDC profile')); + const user = await db.findUserByOIDC(userInfo.sub); + if (user) return done(null, user); - const newUser = { - username: getUsername(email), - email, - oidcId: userInfo.sub, - }; + const email = safelyExtractEmail(userInfo); + if (!email) return done(new Error('No email found in OIDC profile')); + if (userInfo.email_verified === false) { + return done(new Error('OIDC email address is not verified')); + } - await db.createUser(newUser.username, '', newUser.email, 'Edit me', false, newUser.oidcId); - return done(null, newUser); + const existingWithEmail = await db.findUserByEmail(email); + if (existingWithEmail) { + if (isUnboundOIDCUser(existingWithEmail)) { + // Accounts created before the OIDC subject was persisted: bind on exact email match. + existingWithEmail.oidcId = userInfo.sub; + await db.updateUser(existingWithEmail); + return done(null, existingWithEmail); + } + return done(new Error(`A user with email ${email} already exists`)); } - return done(null, user); + const username = await getAvailableUsername(email, userInfo.sub); + await db.createUser(username, '', email, 'Edit me', false, userInfo.sub); + + const created = await db.findUserByOIDC(userInfo.sub); + return done(null, created ?? { username, email, oidcId: userInfo.sub }); } catch (error: unknown) { const msg = handleErrorAndLog(error, 'Error during OIDC user authentication'); return done(msg); } }; +// createUser stores an explicit null password only for OIDC accounts; AD upserts omit the field. +const isUnboundOIDCUser = (user: db.User): boolean => !user.oidcId && user.password === null; + +/** + * Picks a username for a new OIDC user. Uses the email local part when free, otherwise + * appends a suffix derived from the OIDC subject so a different identity sharing the + * same local part never collides with (or squats) an existing account. + * @param {string} email - The email address from the OIDC profile + * @param {string} sub - The OIDC subject identifier + * @return {Promise} - An unused username + */ +export const getAvailableUsername = async (email: string, sub: string): Promise => { + const base = getUsername(email); + if (!(await db.findUser(base))) return base; + + const suffixed = `${base}-${createHash('sha256').update(sub).digest('hex').slice(0, 8)}`; + if (!(await db.findUser(suffixed))) return suffixed; + + throw new Error(`Unable to allocate a unique username for ${email}`); +}; + /** * Extracts email from OIDC profile. * Different providers use different fields to store the email. diff --git a/test/testDb.test.ts b/test/testDb.test.ts index 91fdb6eca..6ef4472ef 100644 --- a/test/testDb.test.ts +++ b/test/testDb.test.ts @@ -413,6 +413,27 @@ describe('Database clients', () => { ).rejects.toThrow(`A user with email ${TEST_USER.email} already exists`); }); + it('should persist the OIDC subject when creating an OIDC user', async () => { + const oidcUsername = 'db-oidc-u1'; + await db.deleteUser(oidcUsername); + + await db.createUser(oidcUsername, '', 'db-oidc@test.com', 'Edit me', false, 'oidc-sub-123'); + + const user = await db.findUserByOIDC('oidc-sub-123'); + expect(user?.username).toBe(oidcUsername); + expect(user?.oidcId).toBe('oidc-sub-123'); + expect(user?.password).toBeNull(); + + await db.deleteUser(oidcUsername); + }); + + it('should store a null OIDC subject for local users', async () => { + await ensureUserExists(); + + const user = await db.findUser(TEST_USER.username); + expect(user?.oidcId ?? null).toBeNull(); + }); + it('should be able to find a user', async () => { await ensureUserExists(); diff --git a/test/testOidc.test.ts b/test/testOidc.test.ts index 36275a5e8..653dc5c25 100644 --- a/test/testOidc.test.ts +++ b/test/testOidc.test.ts @@ -175,3 +175,155 @@ describe('OIDC auth method', () => { }); }); }); + +describe('OIDC user identity binding', () => { + type StoredUser = { + username: string; + email: string; + password: string | null; + gitAccount: string; + admin: boolean; + oidcId?: string; + }; + let users: StoredUser[]; + let oidc: typeof import('../src/service/passport/oidc'); + + const login = async (userInfo: Record) => { + const done = vi.fn(); + await oidc.handleUserAuthentication(userInfo as any, done); + return done.mock.calls[0] as [unknown, Partial | undefined]; + }; + + beforeEach(async () => { + users = []; + const fakeDb = { + findUser: vi.fn( + async (u: string) => users.find((x) => x.username === u.toLowerCase()) ?? null, + ), + findUserByEmail: vi.fn( + async (e: string) => users.find((x) => x.email === e.toLowerCase()) ?? null, + ), + findUserByOIDC: vi.fn(async (id: string) => users.find((x) => x.oidcId === id) ?? null), + createUser: vi.fn( + async ( + username: string, + _password: string, + email: string, + gitAccount: string, + admin: boolean, + oidcId: string, + ) => { + if (users.some((x) => x.username === username.toLowerCase())) { + throw new Error(`user ${username} already exists`); + } + if (users.some((x) => x.email === email.toLowerCase())) { + throw new Error(`A user with email ${email} already exists`); + } + users.push({ + username: username.toLowerCase(), + email: email.toLowerCase(), + password: oidcId ? null : 'hashed', + gitAccount, + admin, + ...(oidcId ? { oidcId } : {}), + }); + }, + ), + updateUser: vi.fn(async (user: StoredUser) => { + const existing = users.find((x) => x.username === user.username); + if (existing) Object.assign(existing, user); + }), + }; + + vi.resetModules(); + vi.doMock('../src/db', () => fakeDb); + oidc = await import('../src/service/passport/oidc'); + }); + + afterEach(() => { + vi.doUnmock('../src/db'); + }); + + it('persists the subject and resolves the same account on a repeat login', async () => { + const [err1, first] = await login({ sub: 'sub-alice', email: 'alice@acme.example' }); + expect(err1).toBeNull(); + expect(first).toMatchObject({ username: 'alice', oidcId: 'sub-alice' }); + + const [err2, second] = await login({ sub: 'sub-alice', email: 'alice@acme.example' }); + expect(err2).toBeNull(); + expect(second).toMatchObject({ username: 'alice', oidcId: 'sub-alice' }); + expect(users).toHaveLength(1); + }); + + it('gives a different identity with the same email local part a distinct username', async () => { + await login({ sub: 'sub-alice', email: 'alice@acme.example' }); + + const [err, other] = await login({ sub: 'sub-mallory', email: 'alice@partner.example' }); + expect(err).toBeNull(); + expect(other?.username).toMatch(/^alice-[0-9a-f]{8}$/); + expect(other?.oidcId).toBe('sub-mallory'); + expect(users.find((u) => u.username === 'alice')?.oidcId).toBe('sub-alice'); + }); + + it('does not let an OIDC identity take over a local account username', async () => { + users.push({ + username: 'bob', + email: 'bob@acme.example', + password: 'hashed', + gitAccount: 'bob', + admin: true, + }); + + const [err, user] = await login({ sub: 'sub-bob2', email: 'bob@other.example' }); + expect(err).toBeNull(); + expect(user?.username).not.toBe('bob'); + expect(users.find((u) => u.username === 'bob')?.oidcId).toBeUndefined(); + }); + + it('does not bind an OIDC identity to an existing local account by email', async () => { + users.push({ + username: 'carol', + email: 'carol@acme.example', + password: 'hashed', + gitAccount: 'carol', + admin: false, + }); + + const [err, user] = await login({ sub: 'sub-carol', email: 'carol@acme.example' }); + expect((err as Error).message).toMatch(/already exists/); + expect(user).toBeUndefined(); + expect(users.find((u) => u.username === 'carol')?.oidcId).toBeUndefined(); + }); + + it('binds a legacy OIDC account (no stored subject) on exact email match', async () => { + users.push({ + username: 'dave', + email: 'dave@acme.example', + password: null, + gitAccount: 'Edit me', + admin: false, + }); + + const [err, user] = await login({ sub: 'sub-dave', email: 'dave@acme.example' }); + expect(err).toBeNull(); + expect(user).toMatchObject({ username: 'dave', oidcId: 'sub-dave' }); + expect(users).toHaveLength(1); + }); + + it('rejects a new account when the provider marks the email unverified', async () => { + const [err, user] = await login({ + sub: 'sub-eve', + email: 'eve@acme.example', + email_verified: false, + }); + expect((err as Error).message).toMatch(/not verified/); + expect(user).toBeUndefined(); + expect(users).toHaveLength(0); + }); + + it('rejects a profile without a subject', async () => { + const [err] = await login({ email: 'nosub@acme.example' }); + expect((err as Error).message).toMatch(/No subject/); + expect(users).toHaveLength(0); + }); +}); From 6123293fc160198f0baee3d3f965ac91c9b35e05 Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Thu, 5 Nov 2026 05:17:47 +0000 Subject: [PATCH 2/3] fix(oidc): namespace session ids and require verified email for legacy binding (bug) --- src/service/passport/oidc.ts | 26 +++++++++++++++++--- test/testOidc.test.ts | 47 +++++++++++++++++++++++++++++++++++- 2 files changed, 68 insertions(+), 5 deletions(-) diff --git a/src/service/passport/oidc.ts b/src/service/passport/oidc.ts index c15b22847..db96c1060 100644 --- a/src/service/passport/oidc.ts +++ b/src/service/passport/oidc.ts @@ -70,13 +70,12 @@ export const configure = async (passport: PassportStatic): Promise, done) => { - done(null, user.oidcId || user.username); + done(null, serializeSessionId(user)); }); passport.deserializeUser(async (id: string, done) => { try { - const user = (await db.findUserByOIDC(id)) ?? (await db.findUser(id)); - done(null, user); + done(null, await deserializeSessionId(id)); } catch (error: unknown) { done(error); } @@ -113,7 +112,7 @@ export const handleUserAuthentication = async ( const existingWithEmail = await db.findUserByEmail(email); if (existingWithEmail) { - if (isUnboundOIDCUser(existingWithEmail)) { + if (isUnboundOIDCUser(existingWithEmail) && userInfo.email_verified === true) { // Accounts created before the OIDC subject was persisted: bind on exact email match. existingWithEmail.oidcId = userInfo.sub; await db.updateUser(existingWithEmail); @@ -133,6 +132,25 @@ export const handleUserAuthentication = async ( } }; +const OIDC_SESSION_PREFIX = 'oidc:'; +const USERNAME_SESSION_PREFIX = 'user:'; + +// Session ids are namespaced so a username can never be resolved as another user's OIDC subject. +export const serializeSessionId = (user: Partial): string => + user.oidcId + ? `${OIDC_SESSION_PREFIX}${user.oidcId}` + : `${USERNAME_SESSION_PREFIX}${user.username}`; + +export const deserializeSessionId = async (id: string): Promise => { + if (id.startsWith(OIDC_SESSION_PREFIX)) { + return db.findUserByOIDC(id.slice(OIDC_SESSION_PREFIX.length)); + } + if (id.startsWith(USERNAME_SESSION_PREFIX)) { + return db.findUser(id.slice(USERNAME_SESSION_PREFIX.length)); + } + return db.findUserByOIDC(id); +}; + // createUser stores an explicit null password only for OIDC accounts; AD upserts omit the field. const isUnboundOIDCUser = (user: db.User): boolean => !user.oidcId && user.password === null; diff --git a/test/testOidc.test.ts b/test/testOidc.test.ts index 653dc5c25..aa1cc364e 100644 --- a/test/testOidc.test.ts +++ b/test/testOidc.test.ts @@ -304,12 +304,57 @@ describe('OIDC user identity binding', () => { admin: false, }); - const [err, user] = await login({ sub: 'sub-dave', email: 'dave@acme.example' }); + const [err, user] = await login({ + sub: 'sub-dave', + email: 'dave@acme.example', + email_verified: true, + }); expect(err).toBeNull(); expect(user).toMatchObject({ username: 'dave', oidcId: 'sub-dave' }); expect(users).toHaveLength(1); }); + it('does not bind a legacy OIDC account unless the provider verified the email', async () => { + users.push({ + username: 'dave', + email: 'dave@acme.example', + password: null, + gitAccount: 'Edit me', + admin: false, + }); + + const [err, user] = await login({ sub: 'sub-dave2', email: 'dave@acme.example' }); + expect((err as Error).message).toMatch(/already exists/); + expect(user).toBeUndefined(); + expect(users.find((u) => u.username === 'dave')?.oidcId).toBeUndefined(); + }); + + it("never resolves a username session as another user's OIDC subject", async () => { + users.push( + { + username: 'sub-victim', + email: 'l@acme.example', + password: 'hashed', + gitAccount: 'l', + admin: false, + }, + { + username: 'victim', + email: 'v@acme.example', + password: null, + gitAccount: 'v', + admin: true, + oidcId: 'sub-victim', + }, + ); + + const localId = oidc.serializeSessionId(users[0]); + const oidcId = oidc.serializeSessionId(users[1]); + expect(localId).not.toBe(oidcId); + expect((await oidc.deserializeSessionId(localId))?.username).toBe('sub-victim'); + expect((await oidc.deserializeSessionId(oidcId))?.username).toBe('victim'); + }); + it('rejects a new account when the provider marks the email unverified', async () => { const [err, user] = await login({ sub: 'sub-eve', From 404ff08cb576a47e10e2026880a288fe77b066f9 Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Thu, 5 Nov 2026 05:19:32 +0000 Subject: [PATCH 3/3] fix(oidc): store typed session references instead of prefixed strings (bug) --- src/service/passport/oidc.ts | 27 +++++++++++---------------- test/testOidc.test.ts | 25 ++++++++++++++++++++++++- 2 files changed, 35 insertions(+), 17 deletions(-) diff --git a/src/service/passport/oidc.ts b/src/service/passport/oidc.ts index db96c1060..89fa4bf34 100644 --- a/src/service/passport/oidc.ts +++ b/src/service/passport/oidc.ts @@ -73,7 +73,7 @@ export const configure = async (passport: PassportStatic): Promise { + passport.deserializeUser(async (id: SessionRef | string, done) => { try { done(null, await deserializeSessionId(id)); } catch (error: unknown) { @@ -132,23 +132,18 @@ export const handleUserAuthentication = async ( } }; -const OIDC_SESSION_PREFIX = 'oidc:'; -const USERNAME_SESSION_PREFIX = 'user:'; +export type SessionRef = { oidcId: string } | { username: string }; -// Session ids are namespaced so a username can never be resolved as another user's OIDC subject. -export const serializeSessionId = (user: Partial): string => - user.oidcId - ? `${OIDC_SESSION_PREFIX}${user.oidcId}` - : `${USERNAME_SESSION_PREFIX}${user.username}`; +// Sessions store a typed reference so a username can never be resolved as an OIDC subject (or vice versa). +export const serializeSessionId = (user: Partial): SessionRef => + user.oidcId ? { oidcId: user.oidcId } : { username: user.username ?? '' }; -export const deserializeSessionId = async (id: string): Promise => { - if (id.startsWith(OIDC_SESSION_PREFIX)) { - return db.findUserByOIDC(id.slice(OIDC_SESSION_PREFIX.length)); - } - if (id.startsWith(USERNAME_SESSION_PREFIX)) { - return db.findUser(id.slice(USERNAME_SESSION_PREFIX.length)); - } - return db.findUserByOIDC(id); +export const deserializeSessionId = async (id: SessionRef | string): Promise => { + // Sessions created before typed references stored the raw OIDC subject. + if (typeof id === 'string') return db.findUserByOIDC(id); + if ('oidcId' in id && typeof id.oidcId === 'string') return db.findUserByOIDC(id.oidcId); + if ('username' in id && typeof id.username === 'string') return db.findUser(id.username); + return null; }; // createUser stores an explicit null password only for OIDC accounts; AD upserts omit the field. diff --git a/test/testOidc.test.ts b/test/testOidc.test.ts index aa1cc364e..cb25e116b 100644 --- a/test/testOidc.test.ts +++ b/test/testOidc.test.ts @@ -350,11 +350,34 @@ describe('OIDC user identity binding', () => { const localId = oidc.serializeSessionId(users[0]); const oidcId = oidc.serializeSessionId(users[1]); - expect(localId).not.toBe(oidcId); + expect(localId).not.toEqual(oidcId); expect((await oidc.deserializeSessionId(localId))?.username).toBe('sub-victim'); expect((await oidc.deserializeSessionId(oidcId))?.username).toBe('victim'); }); + it('resolves legacy string session ids only as OIDC subjects', async () => { + users.push( + { + username: 'admin', + email: 'a@acme.example', + password: 'hashed', + gitAccount: 'a', + admin: true, + }, + { + username: 'oddsub', + email: 'o@acme.example', + password: null, + gitAccount: 'o', + admin: false, + oidcId: 'user:admin', + }, + ); + + expect((await oidc.deserializeSessionId('user:admin'))?.username).toBe('oddsub'); + expect(await oidc.deserializeSessionId('admin')).toBeNull(); + }); + it('rejects a new account when the provider marks the email unverified', async () => { const [err, user] = await login({ sub: 'sub-eve',