Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/db/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ export const createUser = async (
gitAccount: gitAccount,
email: email,
admin: admin,
...(oidcId ? { oidcId } : {}),
};

if (isBlank(username)) {
Expand Down
77 changes: 61 additions & 16 deletions src/service/passport/oidc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand Down Expand Up @@ -69,13 +70,12 @@ export const configure = async (passport: PassportStatic): Promise<PassportStati
passport.use(type, strategy);

passport.serializeUser((user: Partial<db.User>, 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);
}
Expand All @@ -99,29 +99,74 @@ export const handleUserAuthentication = async (
done: (err: unknown, user?: Partial<db.User>) => void,
): Promise<void> => {
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'));
}
Comment thread
devin-ai-integration[bot] marked this conversation as resolved.
Resolved

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<db.User>): SessionRef =>
user.oidcId ? { oidcId: user.oidcId } : { username: user.username ?? '' };

export const deserializeSessionId = async (id: SessionRef | string): Promise<db.User | null> => {
// 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<string>} - An unused username
*/
export const getAvailableUsername = async (email: string, sub: string): Promise<string> => {
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.
Expand Down
21 changes: 21 additions & 0 deletions test/testDb.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();

Expand Down
220 changes: 220 additions & 0 deletions test/testOidc.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, unknown>) => {
const done = vi.fn();
await oidc.handleUserAuthentication(userInfo as any, done);
return done.mock.calls[0] as [unknown, Partial<StoredUser> | 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);
});
});
Loading