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/jwtAuthHandler.ts b/src/service/passport/jwtAuthHandler.ts index d03fe5555..6dbc250ea 100644 --- a/src/service/passport/jwtAuthHandler.ts +++ b/src/service/passport/jwtAuthHandler.ts @@ -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, @@ -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 => { const apiAuthMethods: AuthenticationElement[] = overrideConfig @@ -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 = { 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(); diff --git a/src/service/routes/push.ts b/src/service/routes/push.ts index 1e900d6ea..3d3fa1d7a 100644 --- a/src/service/routes/push.ts +++ b/src/service/routes/push.ts @@ -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()) { @@ -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) { @@ -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); diff --git a/test/testDb.test.ts b/test/testDb.test.ts index 91fdb6eca..465104b17 100644 --- a/test/testDb.test.ts +++ b/test/testDb.test.ts @@ -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); diff --git a/test/testJwtAuthHandler.test.ts b/test/testJwtAuthHandler.test.ts index 7d41872e1..8776072da 100644 --- a/test/testJwtAuthHandler.test.ts +++ b/test/testJwtAuthHandler.test.ts @@ -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', { @@ -265,5 +270,167 @@ describe('JWT', () => { 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) => + 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(); + }); + }); }); }); diff --git a/website/docs/configuration/authentication.mdx b/website/docs/configuration/authentication.mdx index 626c4f746..4045779e9 100644 --- a/website/docs/configuration/authentication.mdx +++ b/website/docs/configuration/authentication.mdx @@ -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: