From 054cb6dd151f843d50da66be69a1637375e96d6f 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:14:07 +0000 Subject: [PATCH 1/4] bug: build JWT req.user from trusted fields instead of raw token claims The JWT API auth handler assigned the verified token payload directly to req.user, so admin/username claims in the token were trusted for authorization. req.user is now a fresh object: admin starts false and is only set by roleMapping, and username/email come from the user database (matched on the token sub via oidcId). Push approve/reject/cancel return 403 when no linked username is present. Fixes code scan finding sfind-072118d306f4438fa97c4da854ce3f0d. Signed-off-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- src/service/passport/jwtAuthHandler.ts | 17 ++- src/service/routes/push.ts | 24 +++- test/testJwtAuthHandler.test.ts | 109 +++++++++++++++++- website/docs/configuration/authentication.mdx | 2 + 4 files changed, 146 insertions(+), 6 deletions(-) diff --git a/src/service/passport/jwtAuthHandler.ts b/src/service/passport/jwtAuthHandler.ts index d03fe5555..985c4a3fb 100644 --- a/src/service/passport/jwtAuthHandler.ts +++ b/src/service/passport/jwtAuthHandler.ts @@ -15,6 +15,7 @@ */ import { assignRoles, validateJwt } from './jwtUtils'; +import * as db from '../../db'; import type { Request, Response, NextFunction } from 'express'; import { getAPIAuthMethods } from '../../config'; import { @@ -92,8 +93,20 @@ 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) 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 ? 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/testJwtAuthHandler.test.ts b/test/testJwtAuthHandler.test.ts index 7d41872e1..1a9ac3297 100644 --- a/test/testJwtAuthHandler.test.ts +++ b/test/testJwtAuthHandler.test.ts @@ -16,13 +16,17 @@ 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 pushRouter from '../src/service/routes/push'; +import { isAdminUser } from '../src/service/routes/utils'; function generateRsaKeyPair() { return crypto.generateKeyPairSync('rsa', { @@ -265,5 +269,108 @@ 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] } }, + ); + }); + + 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 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..7a2f44698 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. 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: From c43778ca5219975ec1dcfd284daa243d692a7cd5 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:16:02 +0000 Subject: [PATCH 2/4] bug: persist oidcId in createUser so OIDC users can be resolved by subject Addresses Devin Review on #33: createUser accepted an oidcId but dropped it from the stored record, so findUserByOIDC (used by OIDC login and now by the JWT handler) never matched OIDC-created users. Signed-off-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- src/db/index.ts | 1 + test/testDb.test.ts | 19 +++++++++++++++++++ 2 files changed, 20 insertions(+) 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/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); From ee86f5b8d8ae31aee4e06d11a378406af76c1730 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:35 +0000 Subject: [PATCH 3/4] bug: only link JWT subjects to OIDC users when issuers match --- src/service/passport/jwtAuthHandler.ts | 27 ++++++++++-- test/testJwtAuthHandler.test.ts | 43 +++++++++++++++++++ website/docs/configuration/authentication.mdx | 2 +- 3 files changed, 67 insertions(+), 5 deletions(-) diff --git a/src/service/passport/jwtAuthHandler.ts b/src/service/passport/jwtAuthHandler.ts index 985c4a3fb..12ceff33c 100644 --- a/src/service/passport/jwtAuthHandler.ts +++ b/src/service/passport/jwtAuthHandler.ts @@ -17,7 +17,7 @@ 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, @@ -27,6 +27,23 @@ import { export const type = 'jwt'; +const normalizeIssuer = (issuer: string) => issuer.replace(/\/+$/, ''); + +// 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 that same issuer. +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 && normalizeIssuer(oidcIssuer) === normalizeIssuer(authorityURL); +}; + export const jwtAuthHandler = (overrideConfig: JwtConfig | null = null) => { return async (req: Request, res: Response, next: NextFunction): Promise => { const apiAuthMethods: AuthenticationElement[] = overrideConfig @@ -94,10 +111,12 @@ export const jwtAuthHandler = (overrideConfig: JwtConfig | null = null) => { } // Build req.user from trusted sources only: identity comes from the user - // database (matched on the token subject) and roles come from roleMapping. - // Raw token claims such as `admin` or `username` are never copied over. + // 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 ? await db.findUserByOIDC(sub) : null; + const dbUser = + sub && sharesIssuerWithOidcLogin(authorityURL) ? await db.findUserByOIDC(sub) : null; const user: Record = { sub, admin: false }; if (dbUser) { diff --git a/test/testJwtAuthHandler.test.ts b/test/testJwtAuthHandler.test.ts index 1a9ac3297..34db46d3d 100644 --- a/test/testJwtAuthHandler.test.ts +++ b/test/testJwtAuthHandler.test.ts @@ -25,6 +25,7 @@ import { assignRoles, getJwks, validateJwt } from '../src/service/passport/jwtUt 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'; @@ -296,6 +297,13 @@ describe('JWT', () => { ? { 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 () => { @@ -330,6 +338,41 @@ describe('JWT', () => { }); }); + 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 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' })}`, diff --git a/website/docs/configuration/authentication.mdx b/website/docs/configuration/authentication.mdx index 7a2f44698..26e3cb195 100644 --- a/website/docs/configuration/authentication.mdx +++ b/website/docs/configuration/authentication.mdx @@ -110,7 +110,7 @@ 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. Tokens whose `sub` is not linked to a GitProxy user can still use admin-mapped endpoints, but cannot approve, reject or cancel pushes. +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 the same issuer 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 From 49ccbf1dca1e4efeacfd39d1d8e087f7c6cb57b5 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:18:50 +0000 Subject: [PATCH 4/4] bug: require exact issuer match before linking JWT subjects to OIDC users --- src/service/passport/jwtAuthHandler.ts | 6 ++---- test/testJwtAuthHandler.test.ts | 19 ++++++++++++++++++- website/docs/configuration/authentication.mdx | 2 +- 3 files changed, 21 insertions(+), 6 deletions(-) diff --git a/src/service/passport/jwtAuthHandler.ts b/src/service/passport/jwtAuthHandler.ts index 12ceff33c..6dbc250ea 100644 --- a/src/service/passport/jwtAuthHandler.ts +++ b/src/service/passport/jwtAuthHandler.ts @@ -27,11 +27,9 @@ import { export const type = 'jwt'; -const normalizeIssuer = (issuer: string) => issuer.replace(/\/+$/, ''); - // 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 that same issuer. +// the JWT authority is exactly that same issuer string. const sharesIssuerWithOidcLogin = (authorityURL: string): boolean => { let authMethods: AuthenticationElement[]; try { @@ -41,7 +39,7 @@ const sharesIssuerWithOidcLogin = (authorityURL: string): boolean => { } const oidcIssuer = authMethods.find((method) => method.type.toLowerCase() === 'openidconnect') ?.oidcConfig?.issuer; - return !!oidcIssuer && normalizeIssuer(oidcIssuer) === normalizeIssuer(authorityURL); + return !!oidcIssuer && oidcIssuer === authorityURL; }; export const jwtAuthHandler = (overrideConfig: JwtConfig | null = null) => { diff --git a/test/testJwtAuthHandler.test.ts b/test/testJwtAuthHandler.test.ts index 34db46d3d..8776072da 100644 --- a/test/testJwtAuthHandler.test.ts +++ b/test/testJwtAuthHandler.test.ts @@ -301,7 +301,7 @@ describe('JWT', () => { { type: 'openidconnect', enabled: true, - oidcConfig: { issuer: `${jwtConfig.authorityURL}/` }, + oidcConfig: { issuer: jwtConfig.authorityURL! }, } as any, ]); }); @@ -360,6 +360,23 @@ describe('JWT', () => { 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, diff --git a/website/docs/configuration/authentication.mdx b/website/docs/configuration/authentication.mdx index 26e3cb195..4045779e9 100644 --- a/website/docs/configuration/authentication.mdx +++ b/website/docs/configuration/authentication.mdx @@ -110,7 +110,7 @@ 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 the same issuer 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. +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