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 } : {}),
Comment thread
devin-ai-integration[bot] marked this conversation as resolved.
Resolved
};

if (isBlank(username)) {
Expand Down
36 changes: 33 additions & 3 deletions src/service/passport/jwtAuthHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,9 @@
*/

import { assignRoles, validateJwt } from './jwtUtils';
import * as db from '../../db';
import type { Request, Response, NextFunction } from 'express';
import { getAPIAuthMethods } from '../../config';
import { getAPIAuthMethods, getAuthMethods } from '../../config';
import {
AuthenticationElement,
JwtConfig,
Expand All @@ -26,6 +27,21 @@ import {

export const type = 'jwt';

// Stored oidcId values are subjects issued by the UI OIDC provider. A subject is
// only unique per issuer, so JWT subjects are matched against them only when
// the JWT authority is exactly that same issuer string.
const sharesIssuerWithOidcLogin = (authorityURL: string): boolean => {
let authMethods: AuthenticationElement[];
try {
authMethods = getAuthMethods();
} catch {
return false;
}
const oidcIssuer = authMethods.find((method) => method.type.toLowerCase() === 'openidconnect')
?.oidcConfig?.issuer;
return !!oidcIssuer && oidcIssuer === authorityURL;
};

export const jwtAuthHandler = (overrideConfig: JwtConfig | null = null) => {
return async (req: Request, res: Response, next: NextFunction): Promise<void> => {
const apiAuthMethods: AuthenticationElement[] = overrideConfig
Expand Down Expand Up @@ -92,8 +108,22 @@ export const jwtAuthHandler = (overrideConfig: JwtConfig | null = null) => {
return;
}

req.user = verifiedPayload;
assignRoles(roleMapping as RoleMapping, verifiedPayload, req.user);
// Build req.user from trusted sources only: identity comes from the user
// database (matched on the token subject, same issuer only) and roles come
// from roleMapping. Raw token claims such as `admin` or `username` are never
// copied over.
const sub = typeof verifiedPayload.sub === 'string' ? verifiedPayload.sub : undefined;
const dbUser =
sub && sharesIssuerWithOidcLogin(authorityURL) ? await db.findUserByOIDC(sub) : null;

const user: Record<string, unknown> = { sub, admin: false };
if (dbUser) {
user.username = dbUser.username;
user.email = dbUser.email;
}
assignRoles(roleMapping as RoleMapping, verifiedPayload, user);

req.user = user as Express.User;

console.log('JWT validation successful\n');
next();
Expand Down
24 changes: 21 additions & 3 deletions src/service/routes/push.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,13 @@ router.post('/:id/reject', async (req: Request<{ id: string }>, res: Response) =
}

const id = req.params.id;
const { username } = req.user as { username: string };
const { username } = req.user as { username?: string };
if (!username) {
res.status(403).send({
message: 'User is not linked to a GitProxy account',
});
return;
}
const { reason } = req.body;

if (!reason || !reason.trim()) {
Expand Down Expand Up @@ -158,7 +164,13 @@ router.post(

const id = req.params.id;

const { username } = req.user as { username: string };
const { username } = req.user as { username?: string };
if (!username) {
res.status(403).send({
message: 'User is not linked to a GitProxy account',
});
return;
}

const push = await db.getPush(id);
if (!push) {
Expand Down Expand Up @@ -230,7 +242,13 @@ router.post('/:id/cancel', async (req: Request<{ id: string }>, res: Response) =
}

const id = req.params.id;
const { username } = req.user as { username: string };
const { username } = req.user as { username?: string };
if (!username) {
res.status(403).send({
message: 'User is not linked to a GitProxy account',
});
return;
}

const isAllowed = await db.canUserCancelPush(id, username);

Expand Down
19 changes: 19 additions & 0 deletions test/testDb.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -444,6 +444,25 @@ describe('Database clients', () => {
expect(cleanUsers).not.toContainEqual(TEST_USER);
});

it('should persist oidcId so the user can be found by OIDC subject', async () => {
await db.deleteUser(TEST_USER.username);

await db.createUser(
TEST_USER.username,
'',
TEST_USER.email,
TEST_USER.gitAccount,
false,
'oidc-subject-123',
);

const user = await db.findUserByOIDC('oidc-subject-123');
expect(user?.username).toBe(TEST_USER.username.toLowerCase());
expect(user?.password).toBeNull();

await db.deleteUser(TEST_USER.username);
});

it('should be able to update a user', async () => {
// Ensure user doesn't exist first
await db.deleteUser(TEST_USER.username);
Expand Down
169 changes: 168 additions & 1 deletion test/testJwtAuthHandler.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,18 @@

import axios from 'axios';
import crypto from 'crypto';
import { NextFunction } from 'express';
import express, { NextFunction } from 'express';
import request from 'supertest';
import jwt, { JwtPayload } from 'jsonwebtoken';
import { describe, it, expect, vi, beforeEach, afterEach, MockInstance } from 'vitest';

import { assignRoles, getJwks, validateJwt } from '../src/service/passport/jwtUtils';
import { jwtAuthHandler } from '../src/service/passport/jwtAuthHandler';
import { JwtConfig, RoleMapping } from '../src/config/generated/config';
import * as db from '../src/db';
import * as config from '../src/config';
import pushRouter from '../src/service/routes/push';
import { isAdminUser } from '../src/service/routes/utils';

function generateRsaKeyPair() {
return crypto.generateKeyPairSync('rsa', {
Expand Down Expand Up @@ -265,5 +270,167 @@
expect(res.status).toHaveBeenCalledWith(401);
expect(res.send).toHaveBeenCalledWith(expect.stringMatching(/Invalid JWT:/));
});

describe('req.user construction', () => {
const { privateKey, publicKey } = generateRsaKeyPair();
const jwk = publicKeyToJwk(publicKey, 'test-kid');

const signToken = (payload: Record<string, unknown>) =>
jwt.sign(payload, privateKey, {
algorithm: 'RS256',
issuer: jwtConfig.authorityURL!,
audience: jwtConfig.expectedAudience!,
keyid: 'test-kid',
});

const forgedPayload = {
azp: 'client-id',
sub: 'mallory-sub',
admin: true,
username: 'approver',
email: 'approver@example.com',
};

beforeEach(() => {
vi.spyOn(axios, 'get').mockImplementation(async (url: string) =>
url.endsWith('/.well-known/openid-configuration')
? { data: { jwks_uri: 'https://mock.com/jwks' } }
: { data: { keys: [jwk] } },
);
vi.spyOn(config, 'getAuthMethods').mockReturnValue([
{
type: 'openidconnect',
enabled: true,
oidcConfig: { issuer: jwtConfig.authorityURL! },
} as any,
]);
});

it('should not trust admin or username claims from the token', async () => {
req.header.mockReturnValue(`Bearer ${signToken(forgedPayload)}`);
vi.spyOn(db, 'findUserByOIDC').mockResolvedValue(null);

await jwtAuthHandler(jwtConfig)(req, res, next);

expect(next).toHaveBeenCalledOnce();
expect(req.user.admin).toBe(false);
expect(req.user.username).toBeUndefined();
expect(req.user.email).toBeUndefined();
expect(isAdminUser(req.user)).toBe(false);
});

it('should resolve username and email from the user database by subject', async () => {
req.header.mockReturnValue(`Bearer ${signToken(forgedPayload)}`);
const findSpy = vi.spyOn(db, 'findUserByOIDC').mockResolvedValue({
username: 'mallory',
email: 'mallory@example.com',
admin: false,
} as any);

await jwtAuthHandler(jwtConfig)(req, res, next);

expect(findSpy).toHaveBeenCalledWith('mallory-sub');
expect(req.user).toEqual({
sub: 'mallory-sub',
admin: false,
username: 'mallory',
email: 'mallory@example.com',
});
});

it('should not link identity when the JWT issuer differs from the OIDC login issuer', async () => {
vi.spyOn(config, 'getAuthMethods').mockReturnValue([
{
type: 'openidconnect',
enabled: true,
oidcConfig: { issuer: 'https://other-idp.example.com' },
} as any,
]);
req.header.mockReturnValue(`Bearer ${signToken(forgedPayload)}`);
const findSpy = vi.spyOn(db, 'findUserByOIDC').mockResolvedValue({
username: 'victim',
email: 'victim@example.com',
admin: false,
} as any);

await jwtAuthHandler(jwtConfig)(req, res, next);

expect(findSpy).not.toHaveBeenCalled();
expect(req.user.username).toBeUndefined();
expect(req.user.email).toBeUndefined();
});

it('should not link identity when issuers differ only by a trailing slash', async () => {
vi.spyOn(config, 'getAuthMethods').mockReturnValue([
{
type: 'openidconnect',
enabled: true,
oidcConfig: { issuer: `${jwtConfig.authorityURL}/` },
} as any,
]);
req.header.mockReturnValue(`Bearer ${signToken(forgedPayload)}`);
const findSpy = vi.spyOn(db, 'findUserByOIDC');

await jwtAuthHandler(jwtConfig)(req, res, next);

expect(findSpy).not.toHaveBeenCalled();
expect(req.user.username).toBeUndefined();
});

it('should not link identity when no OIDC login is configured', async () => {
vi.spyOn(config, 'getAuthMethods').mockReturnValue([
{ type: 'local', enabled: true } as any,
]);
req.header.mockReturnValue(`Bearer ${signToken(forgedPayload)}`);
const findSpy = vi.spyOn(db, 'findUserByOIDC');

await jwtAuthHandler(jwtConfig)(req, res, next);

expect(findSpy).not.toHaveBeenCalled();
expect(req.user.username).toBeUndefined();
});

it('should grant admin only through roleMapping', async () => {
req.header.mockReturnValue(
`Bearer ${signToken({ azp: 'client-id', sub: 'ci-bot', admin: 'admin' })}`,
);
vi.spyOn(db, 'findUserByOIDC').mockResolvedValue(null);

await jwtAuthHandler(jwtConfig)(req, res, next);

expect(req.user.admin).toBe(true);
expect(isAdminUser(req.user)).toBe(true);
});

it('should return 403 when a forged token tries to authorise a push', async () => {
vi.spyOn(db, 'findUserByOIDC').mockResolvedValue(null);
const canApproveSpy = vi.spyOn(db, 'canUserApproveRejectPush').mockResolvedValue(true);
const authoriseSpy = vi.spyOn(db, 'authorise');

const app = express();
app.use(express.json());
app.use(jwtAuthHandler(jwtConfig));
app.use('/api/v1/push', pushRouter);

const response = await request(app)
.post('/api/v1/push/some-push-id/authorise')
.set('Authorization', `Bearer ${signToken(forgedPayload)}`)
.send({
params: {
attestation: [
{
label: 'I am happy for this to be pushed to the upstream repository',
tooltip: { text: 'tooltip', links: [] },
checked: true,
},
],
},
});

expect(response.status).toBe(403);
expect(canApproveSpy).not.toHaveBeenCalled();
expect(authoriseSpy).not.toHaveBeenCalled();
});
});
});
});
2 changes: 2 additions & 0 deletions website/docs/configuration/authentication.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,8 @@ In other words, your JWT token provider can define an arbitrary `claim` that can

Note that if the `expectedAudience` is missing, it will be set to the client ID.

Roles are granted **only** through `roleMapping`: an `admin` (or any other role) claim inside the token is ignored, and the user has `admin: false` unless a mapping matches. Likewise, the GitProxy identity (`username`, `email`) is never read from token claims; it is resolved from the GitProxy user whose `oidcId` matches the token's `sub` claim. This lookup only happens when the JWT `authorityURL` is exactly the same issuer string (including any trailing slash) as the enabled `openidconnect` UI login, because a `sub` is only unique within its issuer; with a different API issuer, tokens are never linked to GitProxy users. Tokens whose `sub` is not linked to a GitProxy user can still use admin-mapped endpoints, but cannot approve, reject or cancel pushes.

### Adding your own methods

You can add new UI auth methods by extending the [passport.js configuration file](https://github.com/finos/git-proxy/blob/main/src/service/passport/local.js) with your desired method. You'll have to define a module and then add it to the `authStrategies` map:
Expand Down
Loading