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..89fa4bf34 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'; @@ -69,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) => { + passport.deserializeUser(async (id: SessionRef | string, done) => { try { - const user = await db.findUserByOIDC(id); - done(null, user); + done(null, await deserializeSessionId(id)); } catch (error: unknown) { done(error); } @@ -99,29 +99,74 @@ 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) && 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); + 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); } }; +export type SessionRef = { oidcId: string } | { username: string }; + +// 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: 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. +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..cb25e116b 100644 --- a/test/testOidc.test.ts +++ b/test/testOidc.test.ts @@ -175,3 +175,223 @@ 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', + 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.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', + 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); + }); +});