From ad15d711568de05805067d355b873edf76295070 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:19:37 +0000 Subject: [PATCH 1/5] fix: authenticate pusher from credentials instead of commit metadata (security bug) --- docs/Architecture.md | 2 +- docs/Processors.md | 17 +- .../push-action/checkUserPushPermission.ts | 43 ++++-- src/proxy/processors/push-action/parsePush.ts | 9 +- src/proxy/processors/pusherIdentity.ts | 104 +++++++++++++ src/service/routes/push.ts | 16 +- .../checkUserPushPermission.test.ts | 136 ++++++++++++---- test/processors/pusherIdentity.test.ts | 145 ++++++++++++++++++ test/testCheckUserPushPermission.test.ts | 49 ++++-- test/testParsePush.test.ts | 13 +- test/testPush.test.ts | 4 +- 11 files changed, 455 insertions(+), 83 deletions(-) create mode 100644 src/proxy/processors/pusherIdentity.ts create mode 100644 test/processors/pusherIdentity.test.ts diff --git a/docs/Architecture.md b/docs/Architecture.md index 7f49ebe62..7c6d3e9c7 100644 --- a/docs/Architecture.md +++ b/docs/Architecture.md @@ -53,7 +53,7 @@ Don't forget to save and update the attached .drawio (XML)! --> Three types of policies can be applied to incoming pushes: - Default policies: These are already present in the GitProxy pull/push chain and require modifying source code to change their behaviour. - - For example, [`checkUserPushPermission`](./Processors.md#checkuserpushpermission) which simply checks if the pusher's email exists in the GitProxy database, and if their user is marked in the "Contributors" list (`canPush`) for the repository they're trying to push to. + - For example, [`checkUserPushPermission`](./Processors.md#checkuserpushpermission) which authenticates the pusher from their git credentials, checks that they map to a GitProxy user (via `gitAccount`), and if their user is marked in the "Contributors" list (`canPush`) for the repository they're trying to push to. - Configurable policies: These are policies that can be easily configured through the GitProxy config (`proxy.config.json` or a custom file). - For example, [`checkCommitMessages`](./Processors.md#checkcommitmessages) which reads the configuration and matches the string patterns provided with the commit messages in the push in order to block it. - Custom policies: diff --git a/docs/Processors.md b/docs/Processors.md index de5bcb696..8cfccaea6 100644 --- a/docs/Processors.md +++ b/docs/Processors.md @@ -80,13 +80,22 @@ Source: [/src/proxy/processors/push-action/checkAuthorEmails.ts](/src/proxy/proc #### `checkUserPushPermission` -Checks if the push has a valid user email associated to it (the email of the user making the push, **not the individual commit authors**), and if that user is allowed to push to that specific repo. +Authenticates the pusher from the credentials presented to the proxy (the HTTP Basic `Authorization` header sent by the git client) and checks that the matching GitProxy user is allowed to push to that specific repo. Commit metadata in the pack (e.g. the committer email) is **never** used to identify the pusher, since it is fully controlled by the client. + +The pusher's SCM account is resolved as follows: + +- `github.com`: the token owner's `login` from `GET https://api.github.com/user` +- GitLab hosts (hostname contains `gitlab`): the token owner's `username` from `GET /api/v4/user` +- Any other git server: the Basic auth username, which the server authenticates together with the password + +The SCM account is then matched (case-insensitively) against the `gitAccount` of GitProxy users. On success, `action.user` and `action.userEmail` are set to that GitProxy user's username and email; these are what the dashboard uses to prevent a reviewer from approving or rejecting their own push. This step will fail on various scenarios such as: -- Push has no email associated to it (potentially a push parsing error) -- The email associated to the push matches multiple GitProxy users -- The user with the given email isn't in the repo's contributor list (`canPush`) +- The push has no valid Basic credentials, or the SCM provider cannot resolve the token owner +- The SCM account matches multiple GitProxy users +- No GitProxy user has that SCM account as their `gitAccount` +- The user isn't in the repo's contributor (`canPush`) or approver (`canAuthorise`) list Note: The _pusher_ can potentially be a different user from the _commit author(s)_. In order to filter the commit authors, you must use the `commitConfig.author` config entry. See [`checkAuthorEmails`](#checkauthoremails) for more details. diff --git a/src/proxy/processors/push-action/checkUserPushPermission.ts b/src/proxy/processors/push-action/checkUserPushPermission.ts index 934176586..85af71c99 100644 --- a/src/proxy/processors/push-action/checkUserPushPermission.ts +++ b/src/proxy/processors/push-action/checkUserPushPermission.ts @@ -18,60 +18,71 @@ import { Request } from 'express'; import { Action, Step } from '../../actions'; import { getUsers, isUserPushAllowed } from '../../../db'; +import { getAuthenticatedGitAccount } from '../pusherIdentity'; // Execute if the repo is approved -const exec = async (_req: Request, action: Action): Promise => { +const exec = async (req: Request, action: Action): Promise => { const step = new Step('checkUserPushPermission'); - const userEmail = action.userEmail; - if (!userEmail) { - step.setError('Push blocked: User not found. Please contact an administrator for support.'); + // The pusher is identified from the credentials presented to the proxy, never from + // commit metadata in the pack, which the client fully controls. + const gitAccount = await getAuthenticatedGitAccount(action.url, req.headers?.authorization, step); + + if (!gitAccount) { + step.setError( + 'Push blocked: Unable to authenticate the pusher. Please make sure your git credentials are valid.', + ); action.addStep(step); step.error = true; return action; } - return await validateUser(userEmail, action, step); + return await validateUser(gitAccount, action, step); }; /** * Helper that validates the user's push permission. * This can be used by other actions that need it. - * @param {string} userEmail The user to validate + * @param {string} gitAccount The authenticated SCM account of the pusher * @param {Action} action The action object * @param {Step} step The step object * @return {Promise} The action object */ -const validateUser = async (userEmail: string, action: Action, step: Step): Promise => { +const validateUser = async (gitAccount: string, action: Action, step: Step): Promise => { let isUserAllowed = false; - // Find the user associated with this email address - const list = await getUsers({ email: userEmail }); + // Find the GitProxy user linked to this SCM account + const list = (await getUsers()).filter( + (user) => user.gitAccount?.toLowerCase() === gitAccount.toLowerCase(), + ); if (list.length > 1) { step.error = true; step.log( - `Multiple Users have email <${userEmail}> so we cannot uniquely identify the user, ending`, + `Multiple Users have git account ${gitAccount} so we cannot uniquely identify the user, ending`, ); step.setError( - `Your push has been blocked (there are multiple users with email ${action.userEmail})`, + `Your push has been blocked (there are multiple users with git account ${gitAccount})`, ); action.addStep(step); return action; } else if (list.length == 0) { - step.log(`No user with email address ${userEmail} found`); + step.log(`No user with git account ${gitAccount} found`); } else { + action.user = list[0].username; + action.userEmail = list[0].email; + step.log(`Push authenticated as user ${list[0].username} (git account ${gitAccount})`); isUserAllowed = await isUserPushAllowed(action.url, list[0].username); } - step.log(`User ${userEmail} permission on Repo ${action.url}: ${isUserAllowed}`); + step.log(`User ${gitAccount} permission on Repo ${action.url}: ${isUserAllowed}`); if (!isUserAllowed) { step.error = true; - step.log(`User ${userEmail} is not allowed to push on repo ${action.url}, ending`); + step.log(`User ${gitAccount} is not allowed to push on repo ${action.url}, ending`); step.setError( - `Your push has been blocked (${action.userEmail} ` + + `Your push has been blocked (${gitAccount} ` + `is not allowed to push on repo ` + `${action.url})`, ); @@ -79,7 +90,7 @@ const validateUser = async (userEmail: string, action: Action, step: Step): Prom return action; } - step.log(`User ${userEmail} is allowed to push on repo ${action.url}`); + step.log(`User ${gitAccount} is allowed to push on repo ${action.url}`); action.addStep(step); return action; }; diff --git a/src/proxy/processors/push-action/parsePush.ts b/src/proxy/processors/push-action/parsePush.ts index 2a324c055..aabbde925 100644 --- a/src/proxy/processors/push-action/parsePush.ts +++ b/src/proxy/processors/push-action/parsePush.ts @@ -109,12 +109,11 @@ async function exec(req: Request, action: Action): Promise { action.commitFrom = action.commitData[action.commitData.length - 1].parent; } - const { committer, committerEmail } = action.commitData[action.commitData.length - 1]; - // Note: This is not always the pusher's email, it's the last committer's email. + // The committer is self-asserted by the client and must not be used as the pusher's + // identity; checkUserPushPermission sets action.user from the push credentials. // See https://github.com/finos/git-proxy/issues/1400 - step.log(`Push request received from user ${committer} with email ${committerEmail}`); - action.user = committer; - action.userEmail = committerEmail; + const { committer, committerEmail } = action.commitData[action.commitData.length - 1]; + step.log(`Push contains commits last committed by ${committer} <${committerEmail}>`); } step.content = { diff --git a/src/proxy/processors/pusherIdentity.ts b/src/proxy/processors/pusherIdentity.ts new file mode 100644 index 000000000..0758ac119 --- /dev/null +++ b/src/proxy/processors/pusherIdentity.ts @@ -0,0 +1,104 @@ +/** + * Copyright 2026 GitProxy Contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import axios from 'axios'; +import { Step } from '../actions'; +import { getErrorMessage } from '../../utils/errors'; + +const IDENTITY_LOOKUP_TIMEOUT_MS = 10000; + +export type BasicCredentials = { username: string; password: string }; + +/** + * Parses an HTTP Basic `Authorization` header as sent by git clients. + * @param {string | undefined} header The raw Authorization header + * @return {BasicCredentials | null} The credentials, or null if missing or malformed + */ +export const parseBasicAuth = (header?: string): BasicCredentials | null => { + if (!header) return null; + const [scheme, encoded] = header.trim().split(/\s+/); + if (!scheme || scheme.toLowerCase() !== 'basic' || !encoded) return null; + + const decoded = Buffer.from(encoded, 'base64').toString('utf8'); + const separator = decoded.indexOf(':'); + if (separator < 0) return null; + + const username = decoded.slice(0, separator); + const password = decoded.slice(separator + 1); + if (!password) return null; + return { username, password }; +}; + +/** + * Resolves the SCM account that owns the credentials presented to the proxy. + * + * GitHub and GitLab accept any username alongside a token, so the account is + * resolved by asking the provider who the token belongs to. Other git servers + * authenticate the username and password together, so the username is used. + * @param {string} url The upstream repository URL + * @param {string | undefined} authHeader The Authorization header sent by the git client + * @param {Step} step The step used for logging + * @return {Promise} The authenticated SCM account, or null if it cannot be established + */ +export const getAuthenticatedGitAccount = async ( + url: string, + authHeader: string | undefined, + step: Step, +): Promise => { + const credentials = parseBasicAuth(authHeader); + if (!credentials) { + step.log('No valid Basic Authorization header was provided with the push'); + return null; + } + + let upstream: URL; + try { + upstream = new URL(url); + } catch { + step.log(`Unable to parse upstream URL ${url}`); + return null; + } + + const hostname = upstream.hostname.toLowerCase(); + const headers = { + Authorization: `Bearer ${credentials.password}`, + Accept: 'application/json', + 'User-Agent': 'git-proxy', + }; + + try { + if (hostname === 'github.com') { + const { data } = await axios.get<{ login?: string }>('https://api.github.com/user', { + headers, + timeout: IDENTITY_LOOKUP_TIMEOUT_MS, + }); + return data?.login || null; + } + + if (hostname.includes('gitlab')) { + const { data } = await axios.get<{ username?: string }>( + `${upstream.protocol}//${upstream.host}/api/v4/user`, + { headers, timeout: IDENTITY_LOOKUP_TIMEOUT_MS }, + ); + return data?.username || null; + } + } catch (error: unknown) { + step.log(`Unable to resolve the account for the push credentials: ${getErrorMessage(error)}`); + return null; + } + + return credentials.username || null; +}; diff --git a/src/service/routes/push.ts b/src/service/routes/push.ts index 1e900d6ea..3b2a3bf3c 100644 --- a/src/service/routes/push.ts +++ b/src/service/routes/push.ts @@ -83,13 +83,13 @@ router.post('/:id/reject', async (req: Request<{ id: string }>, res: Response) = const push = await getValidPushOrRespond(id, res); if (!push) return; - // Get the committer of the push via their email - const committerEmail = push.userEmail; - const list = await db.getUsers({ email: committerEmail }); + // Get the pusher (authenticated by checkUserPushPermission) via their email + const pusherEmail = push.userEmail; + const list = await db.getUsers({ email: pusherEmail }); if (list.length === 0) { res.status(404).send({ - message: `No user found with the committer's email address: ${committerEmail}`, + message: `No user found with the pusher's email address: ${pusherEmail}`, }); return; } @@ -168,14 +168,14 @@ router.post( return; } - // Get the committer of the push via their email address - const committerEmail = push.userEmail; + // Get the pusher (authenticated by checkUserPushPermission) via their email address + const pusherEmail = push.userEmail; - const list = await db.getUsers({ email: committerEmail }); + const list = await db.getUsers({ email: pusherEmail }); if (list.length === 0) { res.status(404).send({ - message: `No user found with the committer's email address: ${committerEmail}`, + message: `No user found with the pusher's email address: ${pusherEmail}`, }); return; } diff --git a/test/processors/checkUserPushPermission.test.ts b/test/processors/checkUserPushPermission.test.ts index 0bc5c2356..a3853c0d7 100644 --- a/test/processors/checkUserPushPermission.test.ts +++ b/test/processors/checkUserPushPermission.test.ts @@ -25,17 +25,30 @@ vi.mock('../../src/db', () => ({ isUserPushAllowed: vi.fn(), })); +vi.mock('axios', () => ({ + default: { get: vi.fn() }, +})); + // import after mocking +import axios from 'axios'; import { getUsers, isUserPushAllowed } from '../../src/db'; import { exec } from '../../src/proxy/processors/push-action/checkUserPushPermission'; +const basicAuth = (username: string, password: string) => + `Basic ${Buffer.from(`${username}:${password}`).toString('base64')}`; + +const GITHUB_URL = 'https://github.com/finos/git-proxy.git'; +const GENERIC_URL = 'https://git.example.com/finos/git-proxy.git'; + describe('checkUserPushPermission', () => { let getUsersMock: Mock; let isUserPushAllowedMock: Mock; + let axiosGetMock: Mock; beforeEach(() => { getUsersMock = vi.mocked(getUsers); isUserPushAllowedMock = vi.mocked(isUserPushAllowed); + axiosGetMock = vi.mocked(axios.get); }); afterEach(() => { @@ -49,20 +62,13 @@ describe('checkUserPushPermission', () => { let stepLogSpy: ReturnType; beforeEach(() => { - req = {} as Request; - action = new Action( - '1234567890', - 'push', - 'POST', - 1234567890, - 'https://github.com/finos/git-proxy.git', - ); - action.user = 'git-user'; - action.userEmail = 'db-user@test.com'; + req = { headers: { authorization: basicAuth('anything', 'ghp_token') } } as Request; + action = new Action('1234567890', 'push', 'POST', 1234567890, GITHUB_URL); stepLogSpy = vi.spyOn(Step.prototype, 'log'); + axiosGetMock.mockResolvedValue({ data: { login: 'git-user' } }); }); - it('should allow push when user has permission', async () => { + it('should allow push when the authenticated user has permission', async () => { getUsersMock.mockResolvedValue([ { username: 'db-user', email: 'db-user@test.com', gitAccount: 'git-user' }, ]); @@ -70,46 +76,87 @@ describe('checkUserPushPermission', () => { const result = await exec(req, action); + expect(axiosGetMock).toHaveBeenCalledWith( + 'https://api.github.com/user', + expect.objectContaining({ + headers: expect.objectContaining({ Authorization: 'Bearer ghp_token' }), + }), + ); + expect(isUserPushAllowedMock).toHaveBeenCalledWith(GITHUB_URL, 'db-user'); expect(result.steps).toHaveLength(1); expect(result.steps[0].error).toBe(false); + expect(result.user).toBe('db-user'); + expect(result.userEmail).toBe('db-user@test.com'); expect(stepLogSpy).toHaveBeenLastCalledWith( - 'User db-user@test.com is allowed to push on repo https://github.com/finos/git-proxy.git', + `User git-user is allowed to push on repo ${GITHUB_URL}`, ); }); - it('should reject push when user has no permission', async () => { + it('should identify the pusher from credentials, ignoring commit committer metadata', async () => { + // Mallory authenticates as herself but forges Bob's email on the committer line + axiosGetMock.mockResolvedValue({ data: { login: 'mallory-gh' } }); + action.commitData = [ + { + tree: 't', + parent: 'p', + author: 'Bob', + committer: 'Bob', + authorEmail: 'bob@acme.com', + committerEmail: 'bob@acme.com', + commitTimestamp: '0', + message: 'm', + }, + ]; getUsersMock.mockResolvedValue([ - { username: 'db-user', email: 'db-user@test.com', gitAccount: 'git-user' }, + { username: 'bob', email: 'bob@acme.com', gitAccount: 'bob-gh' }, + { username: 'mallory', email: 'mallory@acme.com', gitAccount: 'Mallory-GH' }, ]); - isUserPushAllowedMock.mockResolvedValue(false); + isUserPushAllowedMock.mockResolvedValue(true); const result = await exec(req, action); - expect(result.steps).toHaveLength(1); + expect(isUserPushAllowedMock).toHaveBeenCalledWith(GITHUB_URL, 'mallory'); + expect(result.user).toBe('mallory'); + expect(result.userEmail).toBe('mallory@acme.com'); + }); + + it('should block a pusher whose account is not linked to a GitProxy user even if the committer email is', async () => { + // Eve has upstream credentials but no GitProxy account + axiosGetMock.mockResolvedValue({ data: { login: 'eve-gh' } }); + getUsersMock.mockResolvedValue([ + { username: 'bob', email: 'bob@acme.com', gitAccount: 'bob-gh' }, + ]); + + const result = await exec(req, action); + + expect(isUserPushAllowedMock).not.toHaveBeenCalled(); expect(result.steps[0].error).toBe(true); - expect(stepLogSpy).toHaveBeenLastCalledWith( - `Your push has been blocked (db-user@test.com is not allowed to push on repo https://github.com/finos/git-proxy.git)`, + expect(result.steps[0].errorMessage).toContain( + `Your push has been blocked (eve-gh is not allowed to push on repo ${GITHUB_URL})`, ); - expect(result.steps[0].errorMessage).toContain('Your push has been blocked'); + expect(result.userEmail).toBeUndefined(); }); - it('should reject push when no user found for git account', async () => { - getUsersMock.mockResolvedValue([]); + it('should reject push when user has no permission', async () => { + getUsersMock.mockResolvedValue([ + { username: 'db-user', email: 'db-user@test.com', gitAccount: 'git-user' }, + ]); + isUserPushAllowedMock.mockResolvedValue(false); const result = await exec(req, action); expect(result.steps).toHaveLength(1); expect(result.steps[0].error).toBe(true); expect(stepLogSpy).toHaveBeenLastCalledWith( - `Your push has been blocked (db-user@test.com is not allowed to push on repo https://github.com/finos/git-proxy.git)`, + `Your push has been blocked (git-user is not allowed to push on repo ${GITHUB_URL})`, ); expect(result.steps[0].errorMessage).toContain('Your push has been blocked'); }); it('should handle multiple users for git account by rejecting the push', async () => { getUsersMock.mockResolvedValue([ - { username: 'user1', email: 'db-user@test.com', gitAccount: 'git-user' }, - { username: 'user2', email: 'db-user@test.com', gitAccount: 'git-user' }, + { username: 'user1', email: 'user1@test.com', gitAccount: 'git-user' }, + { username: 'user2', email: 'user2@test.com', gitAccount: 'GIT-USER' }, ]); const result = await exec(req, action); @@ -117,24 +164,52 @@ describe('checkUserPushPermission', () => { expect(result.steps).toHaveLength(1); expect(result.steps[0].error).toBe(true); expect(stepLogSpy).toHaveBeenLastCalledWith( - 'Your push has been blocked (there are multiple users with email db-user@test.com)', + 'Your push has been blocked (there are multiple users with git account git-user)', ); }); - it('should return error when no user is set in the action', async () => { - action.user = undefined; - action.userEmail = undefined; - getUsersMock.mockResolvedValue([]); + it('should block the push when no Authorization header is provided', async () => { + req = { headers: {} } as Request; const result = await exec(req, action); + expect(axiosGetMock).not.toHaveBeenCalled(); + expect(getUsersMock).not.toHaveBeenCalled(); expect(result.steps).toHaveLength(1); expect(result.steps[0].error).toBe(true); expect(result.steps[0].errorMessage).toContain( - 'Push blocked: User not found. Please contact an administrator for support.', + 'Push blocked: Unable to authenticate the pusher', ); }); + it('should block the push when the provider rejects the token', async () => { + axiosGetMock.mockRejectedValue(new Error('Request failed with status code 401')); + + const result = await exec(req, action); + + expect(getUsersMock).not.toHaveBeenCalled(); + expect(result.steps[0].error).toBe(true); + expect(result.steps[0].errorMessage).toContain( + 'Push blocked: Unable to authenticate the pusher', + ); + }); + + it('should use the Basic username for git servers that authenticate it', async () => { + action = new Action('1', 'push', 'POST', 1, GENERIC_URL); + req = { headers: { authorization: basicAuth('testuser', 'user123') } } as Request; + getUsersMock.mockResolvedValue([ + { username: 'tester', email: 'tester@test.com', gitAccount: 'testuser' }, + ]); + isUserPushAllowedMock.mockResolvedValue(true); + + const result = await exec(req, action); + + expect(axiosGetMock).not.toHaveBeenCalled(); + expect(isUserPushAllowedMock).toHaveBeenCalledWith(GENERIC_URL, 'tester'); + expect(result.steps[0].error).toBe(false); + expect(result.userEmail).toBe('tester@test.com'); + }); + describe('fuzzing', () => { it('should not crash on arbitrary getUsers return values (fuzzing)', async () => { const userList = fc.sample( @@ -148,6 +223,7 @@ describe('checkUserPushPermission', () => { 1, )[0]; getUsersMock.mockResolvedValue(userList); + isUserPushAllowedMock.mockResolvedValue(false); const result = await exec(req, action); diff --git a/test/processors/pusherIdentity.test.ts b/test/processors/pusherIdentity.test.ts new file mode 100644 index 000000000..2d97f0f2d --- /dev/null +++ b/test/processors/pusherIdentity.test.ts @@ -0,0 +1,145 @@ +/** + * Copyright 2026 GitProxy Contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; +import type { Mock } from 'vitest'; +import { Step } from '../../src/proxy/actions'; + +vi.mock('axios', () => ({ + default: { get: vi.fn() }, +})); + +import axios from 'axios'; +import { + getAuthenticatedGitAccount, + parseBasicAuth, +} from '../../src/proxy/processors/pusherIdentity'; + +const basicAuth = (credentials: string) => `Basic ${Buffer.from(credentials).toString('base64')}`; + +describe('pusherIdentity', () => { + let axiosGetMock: Mock; + let step: Step; + + beforeEach(() => { + axiosGetMock = vi.mocked(axios.get); + step = new Step('test'); + }); + + afterEach(() => { + vi.clearAllMocks(); + }); + + describe('parseBasicAuth', () => { + it('parses username and password, keeping colons in the password', () => { + expect(parseBasicAuth(basicAuth('user:pa:ss'))).toEqual({ + username: 'user', + password: 'pa:ss', + }); + }); + + it.each([undefined, '', 'Bearer abc', 'Basic', basicAuth('no-separator'), basicAuth('user:')])( + 'returns null for %s', + (header) => { + expect(parseBasicAuth(header)).toBeNull(); + }, + ); + }); + + describe('getAuthenticatedGitAccount', () => { + it('resolves the GitHub token owner and ignores the Basic username', async () => { + axiosGetMock.mockResolvedValue({ data: { login: 'real-owner' } }); + + const account = await getAuthenticatedGitAccount( + 'https://github.com/org/repo.git', + basicAuth('claimed-user:ghp_abc'), + step, + ); + + expect(account).toBe('real-owner'); + expect(axiosGetMock).toHaveBeenCalledWith( + 'https://api.github.com/user', + expect.objectContaining({ + headers: expect.objectContaining({ Authorization: 'Bearer ghp_abc' }), + }), + ); + }); + + it('resolves the GitLab token owner from the same host', async () => { + axiosGetMock.mockResolvedValue({ data: { username: 'gl-owner' } }); + + const account = await getAuthenticatedGitAccount( + 'https://gitlab.example.com:8443/group/repo.git', + basicAuth('oauth2:glpat-abc'), + step, + ); + + expect(account).toBe('gl-owner'); + expect(axiosGetMock).toHaveBeenCalledWith( + 'https://gitlab.example.com:8443/api/v4/user', + expect.objectContaining({ + headers: expect.objectContaining({ Authorization: 'Bearer glpat-abc' }), + }), + ); + }); + + it('returns null when the provider lookup fails', async () => { + axiosGetMock.mockRejectedValue(new Error('401')); + + const account = await getAuthenticatedGitAccount( + 'https://github.com/org/repo.git', + basicAuth('user:bad'), + step, + ); + + expect(account).toBeNull(); + }); + + it('returns null when the provider returns no account', async () => { + axiosGetMock.mockResolvedValue({ data: {} }); + + const account = await getAuthenticatedGitAccount( + 'https://github.com/org/repo.git', + basicAuth('user:token'), + step, + ); + + expect(account).toBeNull(); + }); + + it('uses the Basic username for other git servers', async () => { + const account = await getAuthenticatedGitAccount( + 'https://git-server:8443/test-owner/test-repo.git', + basicAuth('testuser:user123'), + step, + ); + + expect(account).toBe('testuser'); + expect(axiosGetMock).not.toHaveBeenCalled(); + }); + + it('returns null without credentials', async () => { + const account = await getAuthenticatedGitAccount( + 'https://github.com/org/repo.git', + undefined, + step, + ); + + expect(account).toBeNull(); + expect(axiosGetMock).not.toHaveBeenCalled(); + }); + }); +}); diff --git a/test/testCheckUserPushPermission.test.ts b/test/testCheckUserPushPermission.test.ts index 704a63f25..794f2abae 100644 --- a/test/testCheckUserPushPermission.test.ts +++ b/test/testCheckUserPushPermission.test.ts @@ -14,8 +14,16 @@ * limitations under the License. */ -import { describe, it, beforeAll, afterAll, expect } from 'vitest'; +import { describe, it, beforeAll, afterAll, expect, vi } from 'vitest'; import { Request } from 'express'; + +vi.mock('axios', () => ({ + default: { + get: vi.fn(async (_url: string, config: { headers: { Authorization: string } }) => ({ + data: { login: config.headers.Authorization.replace('Bearer token-for-', '') }, + })), + }, +})); import * as processor from '../src/proxy/processors/push-action/checkUserPushPermission'; import { Action } from '../src/proxy/actions/Action'; import * as db from '../src/db'; @@ -27,10 +35,15 @@ const TEST_USERNAME_1 = 'push-perms-test'; const TEST_EMAIL_1 = 'push-perms-test@test.com'; const TEST_USERNAME_2 = 'push-perms-test-2'; const TEST_EMAIL_2 = 'push-perms-test-2@test.com'; -const TEST_EMAIL_3 = 'push-perms-test-3@test.com'; + +const reqAs = (gitAccount: string) => + ({ + headers: { + authorization: `Basic ${Buffer.from(`ignored:token-for-${gitAccount}`).toString('base64')}`, + }, + }) as Request; describe('checkUserPushPermission', () => { - const req = {} as Request; let testRepo: Required | null = null; beforeAll(async () => { @@ -51,26 +64,38 @@ describe('checkUserPushPermission', () => { await db.deleteUser(TEST_USERNAME_2); }); - it('allows pushes from an approved committer', async () => { + it('allows pushes from an approved pusher', async () => { const action = new Action('1', 'type', 'method', 1, TEST_URL); - action.userEmail = TEST_EMAIL_1; - const { error } = await processor.exec(req, action); + const { error, user, userEmail } = await processor.exec(reqAs(TEST_USERNAME_1), action); expect(error).toBe(false); + expect(user).toBe(TEST_USERNAME_1); + expect(userEmail).toBe(TEST_EMAIL_1); }); - it('blocks pushes from an unapproved committer', async () => { + it('blocks pushes from an unapproved pusher', async () => { const action = new Action('1', 'type', 'method', 1, TEST_URL); - action.userEmail = TEST_EMAIL_2; - const { error, errorMessage } = await processor.exec(req, action); + const { error, errorMessage } = await processor.exec(reqAs(TEST_USERNAME_2), action); expect(error).toBe(true); expect(errorMessage).toContain('Your push has been blocked'); }); - it('blocks pushes from an unknown committer', async () => { + it('blocks pushes from an unknown pusher', async () => { const action = new Action('1', 'type', 'method', 1, TEST_URL); - action.userEmail = TEST_EMAIL_3; - const { error, errorMessage } = await processor.exec(req, action); + const { error, errorMessage } = await processor.exec(reqAs('unknown-account'), action); expect(error).toBe(true); expect(errorMessage).toContain('Your push has been blocked'); }); + + it('blocks an unapproved pusher who forges an approved committer email', async () => { + const action = new Action('1', 'type', 'method', 1, TEST_URL); + action.userEmail = TEST_EMAIL_1; + const { error, errorMessage, user, userEmail } = await processor.exec( + reqAs(TEST_USERNAME_2), + action, + ); + expect(error).toBe(true); + expect(errorMessage).toContain(`${TEST_USERNAME_2} is not allowed to push`); + expect(user).toBe(TEST_USERNAME_2); + expect(userEmail).toBe(TEST_EMAIL_2); + }); }); diff --git a/test/testParsePush.test.ts b/test/testParsePush.test.ts index 62fda38c7..e0949f136 100644 --- a/test/testParsePush.test.ts +++ b/test/testParsePush.test.ts @@ -512,7 +512,8 @@ describe('parsePackFile', () => { expect(action.setCommit).toHaveBeenCalledWith(oldCommit, newCommit); expect(action.commitFrom).toBe(oldCommit); expect(action.commitTo).toBe(newCommit); - expect(action.user).toBe('Test Committer'); + expect(action.user).toBeNull(); + expect(action.userEmail).toBeUndefined(); // Check parsed commit data expect(action.commitData).toHaveLength(1); @@ -565,7 +566,7 @@ describe('parsePackFile', () => { expect(action.setCommit).toHaveBeenCalledWith(oldCommit, newCommit); expect(action.commitFrom).toBe(oldCommit); expect(action.commitTo).toBe(newCommit); - expect(action.user).toBe(author); + expect(action.user).toBeNull(); // Check parsed commit data expect(action.commitData).toHaveLength(1); @@ -608,7 +609,7 @@ describe('parsePackFile', () => { expect(action.setCommit).toHaveBeenCalledWith(oldCommit, newCommit); expect(action.commitFrom).toBe(oldCommit); expect(action.commitTo).toBe(newCommit); - expect(action.user).toBe('CCCCCCCCCCC'); + expect(action.user).toBeNull(); // Check parsed commit messages only const expectedCommits = TEST_MULTI_OBJ_COMMIT_CONTENT.filter((v) => v.type === 1); @@ -664,7 +665,8 @@ describe('parsePackFile', () => { // commitFrom should still be the zero hash expect(action.commitFrom).toBe(oldCommit); expect(action.commitTo).toBe(newCommit); - expect(action.user).toBe('Test Committer'); + expect(action.user).toBeNull(); + expect(action.userEmail).toBeUndefined(); // Check parsed commit data reflects no parent (zero hash) expect(action.commitData[0].parent).toBe(oldCommit); @@ -883,7 +885,8 @@ describe('parsePackFile', () => { expect(action.commitData).toHaveLength(1); expect(action.commitData[0].message).toBe('Test commit message with PACK inside'); expect(action.commitData[0].committer).toBe('Test Committer'); - expect(action.user).toBe('Test Committer'); + expect(action.user).toBeNull(); + expect(action.userEmail).toBeUndefined(); }); it('should handle PACK data starting immediately after flush packet', async () => { diff --git a/test/testPush.test.ts b/test/testPush.test.ts index 8bf85788d..99afb697f 100644 --- a/test/testPush.test.ts +++ b/test/testPush.test.ts @@ -230,7 +230,7 @@ describe('Push API', () => { }); expect(res.status).toBe(404); expect(res.body.message).toBe( - "No user found with the committer's email address: push-test-3@test.com", + "No user found with the pusher's email address: push-test-3@test.com", ); }); }); @@ -368,7 +368,7 @@ describe('Push API', () => { .send({ reason: 'Testing rejection' }); expect(res.status).toBe(404); expect(res.body.message).toBe( - "No user found with the committer's email address: non-existent-email@test.com", + "No user found with the pusher's email address: non-existent-email@test.com", ); }); From 278e106c5f3e483c6d963db999ed2731779b2b26 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:22:15 +0000 Subject: [PATCH 2/5] fix: resolve pusher before plugins and fail closed on unverifiable hosts (security bug) --- docs/Architecture.md | 1 + docs/Processors.md | 10 ++- src/proxy/chain.ts | 5 +- .../push-action/checkUserPushPermission.ts | 15 +++- src/proxy/processors/push-action/index.ts | 2 + .../processors/push-action/resolvePusher.ts | 46 ++++++++++ src/proxy/processors/pusherIdentity.ts | 7 +- test/chain.test.ts | 2 + .../checkUserPushPermission.test.ts | 10 +-- test/processors/pusherIdentity.test.ts | 4 +- test/processors/resolvePusher.test.ts | 89 +++++++++++++++++++ 11 files changed, 173 insertions(+), 18 deletions(-) create mode 100644 src/proxy/processors/push-action/resolvePusher.ts create mode 100644 test/processors/resolvePusher.test.ts diff --git a/docs/Architecture.md b/docs/Architecture.md index 7c6d3e9c7..689178812 100644 --- a/docs/Architecture.md +++ b/docs/Architecture.md @@ -75,6 +75,7 @@ Action chains are a list of processors that a Git operation goes through before Executed when a user makes a `git push` to GitProxy. These are the actions in `pushActionChain`, by order of execution: - [`parsePush`](./Processors.md#parsepush) +- [`resolvePusher`](./Processors.md#resolvepusher) - [`checkEmptyBranch`](./Processors.md#checkemptybranch) - [`checkRepoInAuthorisedList`](./Processors.md#checkrepoinauthorisedlist) - [`checkCommitMessages`](./Processors.md#checkcommitmessages) diff --git a/docs/Processors.md b/docs/Processors.md index 8cfccaea6..bd83142fc 100644 --- a/docs/Processors.md +++ b/docs/Processors.md @@ -78,6 +78,12 @@ Note that invalid regex patterns will throw an error during proxy startup. These Source: [/src/proxy/processors/push-action/checkAuthorEmails.ts](/src/proxy/processors/push-action/checkAuthorEmails.ts) +#### `resolvePusher` + +Runs right after `parsePush` (and before any push plugins). Resolves the authenticated pusher in the same way as [`checkUserPushPermission`](#checkuserpushpermission) and, if exactly one GitProxy user matches, sets `action.user` and `action.userEmail` so that plugins see a trusted identity. It never blocks the push; enforcement happens in `checkUserPushPermission`. + +Source: [/src/proxy/processors/push-action/resolvePusher.ts](/src/proxy/processors/push-action/resolvePusher.ts) + #### `checkUserPushPermission` Authenticates the pusher from the credentials presented to the proxy (the HTTP Basic `Authorization` header sent by the git client) and checks that the matching GitProxy user is allowed to push to that specific repo. Commit metadata in the pack (e.g. the committer email) is **never** used to identify the pusher, since it is fully controlled by the client. @@ -86,13 +92,13 @@ The pusher's SCM account is resolved as follows: - `github.com`: the token owner's `login` from `GET https://api.github.com/user` - GitLab hosts (hostname contains `gitlab`): the token owner's `username` from `GET /api/v4/user` -- Any other git server: the Basic auth username, which the server authenticates together with the password +- Any other git server: the push is blocked, since the Basic auth username alone does not prove who owns the credentials The SCM account is then matched (case-insensitively) against the `gitAccount` of GitProxy users. On success, `action.user` and `action.userEmail` are set to that GitProxy user's username and email; these are what the dashboard uses to prevent a reviewer from approving or rejecting their own push. This step will fail on various scenarios such as: -- The push has no valid Basic credentials, or the SCM provider cannot resolve the token owner +- The push has no valid Basic credentials, the SCM provider cannot resolve the token owner, or the host is not GitHub/GitLab - The SCM account matches multiple GitProxy users - No GitProxy user has that SCM account as their `gitAccount` - The user isn't in the repo's contributor (`canPush`) or approver (`canAuthorise`) list diff --git a/src/proxy/chain.ts b/src/proxy/chain.ts index ab63f1f8d..8abe7dff9 100644 --- a/src/proxy/chain.ts +++ b/src/proxy/chain.ts @@ -24,6 +24,7 @@ import { handleErrorAndLog } from '../utils/errors'; const pushActionChain: ((req: Request, action: Action) => Promise)[] = [ proc.push.parsePush, + proc.push.resolvePusher, proc.push.checkEmptyBranch, proc.push.checkRepoInAuthorisedList, proc.push.checkCommitMessages, @@ -111,8 +112,8 @@ export const getChain = async ( ); for (const pluginObj of chainPluginLoader.pushPlugins) { console.log(`Inserting push plugin ${pluginObj.constructor.name} into chain`); - // insert custom functions after parsePush but before other actions - pushActionChain.splice(1, 0, pluginObj.exec); + // insert custom functions after parsePush and resolvePusher but before other actions + pushActionChain.splice(2, 0, pluginObj.exec); } for (const pluginObj of chainPluginLoader.pullPlugins) { console.log(`Inserting pull plugin ${pluginObj.constructor.name} into chain`); diff --git a/src/proxy/processors/push-action/checkUserPushPermission.ts b/src/proxy/processors/push-action/checkUserPushPermission.ts index 85af71c99..fde1da419 100644 --- a/src/proxy/processors/push-action/checkUserPushPermission.ts +++ b/src/proxy/processors/push-action/checkUserPushPermission.ts @@ -18,6 +18,7 @@ import { Request } from 'express'; import { Action, Step } from '../../actions'; import { getUsers, isUserPushAllowed } from '../../../db'; +import { User } from '../../../db/types'; import { getAuthenticatedGitAccount } from '../pusherIdentity'; // Execute if the repo is approved @@ -40,6 +41,14 @@ const exec = async (req: Request, action: Action): Promise => { return await validateUser(gitAccount, action, step); }; +/** + * Finds the GitProxy users linked to an SCM account. + * @param {string} gitAccount The authenticated SCM account + * @return {Promise} The matching users + */ +const findUsersByGitAccount = async (gitAccount: string): Promise => + (await getUsers()).filter((user) => user.gitAccount?.toLowerCase() === gitAccount.toLowerCase()); + /** * Helper that validates the user's push permission. * This can be used by other actions that need it. @@ -52,9 +61,7 @@ const validateUser = async (gitAccount: string, action: Action, step: Step): Pro let isUserAllowed = false; // Find the GitProxy user linked to this SCM account - const list = (await getUsers()).filter( - (user) => user.gitAccount?.toLowerCase() === gitAccount.toLowerCase(), - ); + const list = await findUsersByGitAccount(gitAccount); if (list.length > 1) { step.error = true; @@ -97,4 +104,4 @@ const validateUser = async (gitAccount: string, action: Action, step: Step): Pro exec.displayName = 'checkUserPushPermission.exec'; -export { exec, validateUser }; +export { exec, validateUser, findUsersByGitAccount }; diff --git a/src/proxy/processors/push-action/index.ts b/src/proxy/processors/push-action/index.ts index 5bcb0d0f3..2e887a5f4 100644 --- a/src/proxy/processors/push-action/index.ts +++ b/src/proxy/processors/push-action/index.ts @@ -29,6 +29,7 @@ import { exec as checkIfWaitingAuth } from './checkIfWaitingAuth'; import { exec as checkCommitMessages } from './checkCommitMessages'; import { exec as checkAuthorEmails } from './checkAuthorEmails'; import { exec as checkUserPushPermission } from './checkUserPushPermission'; +import { exec as resolvePusher } from './resolvePusher'; import { exec as checkEmptyBranch } from './checkEmptyBranch'; @@ -47,5 +48,6 @@ export { checkCommitMessages, checkAuthorEmails, checkUserPushPermission, + resolvePusher, checkEmptyBranch, }; diff --git a/src/proxy/processors/push-action/resolvePusher.ts b/src/proxy/processors/push-action/resolvePusher.ts new file mode 100644 index 000000000..621f8279b --- /dev/null +++ b/src/proxy/processors/push-action/resolvePusher.ts @@ -0,0 +1,46 @@ +/** + * Copyright 2026 GitProxy Contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Request } from 'express'; + +import { Action, Step } from '../../actions'; +import { getAuthenticatedGitAccount } from '../pusherIdentity'; +import { findUsersByGitAccount } from './checkUserPushPermission'; + +// Records the authenticated pusher on the action so that push plugins, which run right +// after this step, see a trusted identity. Never blocks: checkUserPushPermission enforces. +const exec = async (req: Request, action: Action): Promise => { + const step = new Step('resolvePusher'); + + const gitAccount = await getAuthenticatedGitAccount(action.url, req.headers?.authorization, step); + if (gitAccount) { + const list = await findUsersByGitAccount(gitAccount); + if (list.length === 1) { + action.user = list[0].username; + action.userEmail = list[0].email; + step.log(`Push authenticated as user ${list[0].username} (git account ${gitAccount})`); + } else { + step.log(`Found ${list.length} users with git account ${gitAccount}`); + } + } + + action.addStep(step); + return action; +}; + +exec.displayName = 'resolvePusher.exec'; + +export { exec }; diff --git a/src/proxy/processors/pusherIdentity.ts b/src/proxy/processors/pusherIdentity.ts index 0758ac119..9076704d1 100644 --- a/src/proxy/processors/pusherIdentity.ts +++ b/src/proxy/processors/pusherIdentity.ts @@ -46,8 +46,8 @@ export const parseBasicAuth = (header?: string): BasicCredentials | null => { * Resolves the SCM account that owns the credentials presented to the proxy. * * GitHub and GitLab accept any username alongside a token, so the account is - * resolved by asking the provider who the token belongs to. Other git servers - * authenticate the username and password together, so the username is used. + * resolved by asking the provider who the token belongs to. The Basic username is + * never trusted on its own, so pushes to other git servers cannot be authenticated. * @param {string} url The upstream repository URL * @param {string | undefined} authHeader The Authorization header sent by the git client * @param {Step} step The step used for logging @@ -100,5 +100,6 @@ export const getAuthenticatedGitAccount = async ( return null; } - return credentials.username || null; + step.log(`Unable to verify the owner of the push credentials for host ${hostname}`); + return null; }; diff --git a/test/chain.test.ts b/test/chain.test.ts index 44eb6750f..a26685616 100644 --- a/test/chain.test.ts +++ b/test/chain.test.ts @@ -30,6 +30,7 @@ const mockLoader = { const initMockPushProcessors = () => { return { parsePush: vi.fn(), + resolvePusher: vi.fn(), checkEmptyBranch: vi.fn(), checkRepoInAuthorisedList: vi.fn(), checkCommitMessages: vi.fn(), @@ -154,6 +155,7 @@ describe('proxy chain', function () { //all processors upto checkIfWaitingAuth should have run + clearBareClone & audit expect(mockPreProcessors.parseAction).toHaveBeenCalled(); expect(mockPushProcessors.parsePush).toHaveBeenCalled(); + expect(mockPushProcessors.resolvePusher).toHaveBeenCalled(); expect(mockPushProcessors.checkEmptyBranch).toHaveBeenCalled(); expect(mockPushProcessors.checkRepoInAuthorisedList).toHaveBeenCalled(); expect(mockPushProcessors.checkCommitMessages).toHaveBeenCalled(); diff --git a/test/processors/checkUserPushPermission.test.ts b/test/processors/checkUserPushPermission.test.ts index a3853c0d7..d8796cae8 100644 --- a/test/processors/checkUserPushPermission.test.ts +++ b/test/processors/checkUserPushPermission.test.ts @@ -194,9 +194,9 @@ describe('checkUserPushPermission', () => { ); }); - it('should use the Basic username for git servers that authenticate it', async () => { + it('should block pushes to git servers whose token owner cannot be verified', async () => { action = new Action('1', 'push', 'POST', 1, GENERIC_URL); - req = { headers: { authorization: basicAuth('testuser', 'user123') } } as Request; + req = { headers: { authorization: basicAuth('testuser', 'attacker-token') } } as Request; getUsersMock.mockResolvedValue([ { username: 'tester', email: 'tester@test.com', gitAccount: 'testuser' }, ]); @@ -205,9 +205,9 @@ describe('checkUserPushPermission', () => { const result = await exec(req, action); expect(axiosGetMock).not.toHaveBeenCalled(); - expect(isUserPushAllowedMock).toHaveBeenCalledWith(GENERIC_URL, 'tester'); - expect(result.steps[0].error).toBe(false); - expect(result.userEmail).toBe('tester@test.com'); + expect(isUserPushAllowedMock).not.toHaveBeenCalled(); + expect(result.steps[0].error).toBe(true); + expect(result.userEmail).toBeUndefined(); }); describe('fuzzing', () => { diff --git a/test/processors/pusherIdentity.test.ts b/test/processors/pusherIdentity.test.ts index 2d97f0f2d..760ca2554 100644 --- a/test/processors/pusherIdentity.test.ts +++ b/test/processors/pusherIdentity.test.ts @@ -120,14 +120,14 @@ describe('pusherIdentity', () => { expect(account).toBeNull(); }); - it('uses the Basic username for other git servers', async () => { + it('does not trust the Basic username for other git servers', async () => { const account = await getAuthenticatedGitAccount( 'https://git-server:8443/test-owner/test-repo.git', basicAuth('testuser:user123'), step, ); - expect(account).toBe('testuser'); + expect(account).toBeNull(); expect(axiosGetMock).not.toHaveBeenCalled(); }); diff --git a/test/processors/resolvePusher.test.ts b/test/processors/resolvePusher.test.ts new file mode 100644 index 000000000..af87a1192 --- /dev/null +++ b/test/processors/resolvePusher.test.ts @@ -0,0 +1,89 @@ +/** + * Copyright 2026 GitProxy Contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; +import { Request } from 'express'; +import { Action } from '../../src/proxy/actions'; + +vi.mock('../../src/db', () => ({ + getUsers: vi.fn(), + isUserPushAllowed: vi.fn(), +})); + +vi.mock('axios', () => ({ + default: { get: vi.fn() }, +})); + +// import after mocking +import axios from 'axios'; +import { getUsers } from '../../src/db'; +import { exec } from '../../src/proxy/processors/push-action/resolvePusher'; + +const GITHUB_URL = 'https://github.com/finos/git-proxy.git'; + +const basicAuth = (username: string, password: string) => + `Basic ${Buffer.from(`${username}:${password}`).toString('base64')}`; + +describe('resolvePusher', () => { + let action: Action; + let req: Request; + + beforeEach(() => { + action = new Action('1', 'push', 'POST', 1, GITHUB_URL); + req = { headers: { authorization: basicAuth('anything', 'ghp_token') } } as Request; + vi.mocked(axios.get).mockResolvedValue({ data: { login: 'alice-gh' } }); + vi.mocked(getUsers).mockResolvedValue([ + { username: 'alice', email: 'alice@test.com', gitAccount: 'Alice-GH' }, + { username: 'bob', email: 'bob@test.com', gitAccount: 'bob-gh' }, + ] as any); + }); + + afterEach(() => { + vi.clearAllMocks(); + }); + + it('sets the authenticated pusher on the action for push plugins', async () => { + action.user = 'bob'; + action.userEmail = 'bob@test.com'; + + const result = await exec(req, action); + + expect(result.user).toBe('alice'); + expect(result.userEmail).toBe('alice@test.com'); + expect(result.steps[0].stepName).toBe('resolvePusher'); + expect(result.steps[0].error).toBe(false); + }); + + it('leaves the identity unset without blocking when no single user matches', async () => { + vi.mocked(axios.get).mockResolvedValue({ data: { login: 'mallory-gh' } }); + + const result = await exec(req, action); + + expect(result.user).toBeUndefined(); + expect(result.userEmail).toBeUndefined(); + expect(result.steps[0].error).toBe(false); + }); + + it('leaves the identity unset without blocking when credentials are missing', async () => { + req = { headers: {} } as Request; + + const result = await exec(req, action); + + expect(getUsers).not.toHaveBeenCalled(); + expect(result.user).toBeUndefined(); + expect(result.steps[0].error).toBe(false); + }); +}); From efaa43e2fa396f5fee5b98d7b3fb2164311edd43 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:24:05 +0000 Subject: [PATCH 3/5] fix: verify push credentials once per action (bug) --- .../push-action/checkUserPushPermission.ts | 4 +-- .../processors/push-action/resolvePusher.ts | 4 +-- src/proxy/processors/pusherIdentity.ts | 25 ++++++++++++++++++- test/processors/resolvePusher.test.ts | 14 +++++++++++ 4 files changed, 42 insertions(+), 5 deletions(-) diff --git a/src/proxy/processors/push-action/checkUserPushPermission.ts b/src/proxy/processors/push-action/checkUserPushPermission.ts index fde1da419..2be024861 100644 --- a/src/proxy/processors/push-action/checkUserPushPermission.ts +++ b/src/proxy/processors/push-action/checkUserPushPermission.ts @@ -19,7 +19,7 @@ import { Request } from 'express'; import { Action, Step } from '../../actions'; import { getUsers, isUserPushAllowed } from '../../../db'; import { User } from '../../../db/types'; -import { getAuthenticatedGitAccount } from '../pusherIdentity'; +import { getVerifiedGitAccount } from '../pusherIdentity'; // Execute if the repo is approved const exec = async (req: Request, action: Action): Promise => { @@ -27,7 +27,7 @@ const exec = async (req: Request, action: Action): Promise => { // The pusher is identified from the credentials presented to the proxy, never from // commit metadata in the pack, which the client fully controls. - const gitAccount = await getAuthenticatedGitAccount(action.url, req.headers?.authorization, step); + const gitAccount = await getVerifiedGitAccount(action, req.headers?.authorization, step); if (!gitAccount) { step.setError( diff --git a/src/proxy/processors/push-action/resolvePusher.ts b/src/proxy/processors/push-action/resolvePusher.ts index 621f8279b..c365791a8 100644 --- a/src/proxy/processors/push-action/resolvePusher.ts +++ b/src/proxy/processors/push-action/resolvePusher.ts @@ -17,7 +17,7 @@ import { Request } from 'express'; import { Action, Step } from '../../actions'; -import { getAuthenticatedGitAccount } from '../pusherIdentity'; +import { getVerifiedGitAccount } from '../pusherIdentity'; import { findUsersByGitAccount } from './checkUserPushPermission'; // Records the authenticated pusher on the action so that push plugins, which run right @@ -25,7 +25,7 @@ import { findUsersByGitAccount } from './checkUserPushPermission'; const exec = async (req: Request, action: Action): Promise => { const step = new Step('resolvePusher'); - const gitAccount = await getAuthenticatedGitAccount(action.url, req.headers?.authorization, step); + const gitAccount = await getVerifiedGitAccount(action, req.headers?.authorization, step); if (gitAccount) { const list = await findUsersByGitAccount(gitAccount); if (list.length === 1) { diff --git a/src/proxy/processors/pusherIdentity.ts b/src/proxy/processors/pusherIdentity.ts index 9076704d1..bb5e726ff 100644 --- a/src/proxy/processors/pusherIdentity.ts +++ b/src/proxy/processors/pusherIdentity.ts @@ -15,7 +15,7 @@ */ import axios from 'axios'; -import { Step } from '../actions'; +import { Action, Step } from '../actions'; import { getErrorMessage } from '../../utils/errors'; const IDENTITY_LOOKUP_TIMEOUT_MS = 10000; @@ -103,3 +103,26 @@ export const getAuthenticatedGitAccount = async ( step.log(`Unable to verify the owner of the push credentials for host ${hostname}`); return null; }; + +const verifiedAccounts = new WeakMap(); + +/** + * Resolves the authenticated SCM account for a push, verifying the credentials with the + * provider at most once per action so that every step in the chain agrees on the pusher. + * @param {Action} action The push action + * @param {string | undefined} authHeader The Authorization header sent by the git client + * @param {Step} step The step used for logging + * @return {Promise} The authenticated SCM account, or null if it cannot be established + */ +export const getVerifiedGitAccount = async ( + action: Action, + authHeader: string | undefined, + step: Step, +): Promise => { + const cached = verifiedAccounts.get(action); + if (cached) return cached; + + const gitAccount = await getAuthenticatedGitAccount(action.url, authHeader, step); + if (gitAccount) verifiedAccounts.set(action, gitAccount); + return gitAccount; +}; diff --git a/test/processors/resolvePusher.test.ts b/test/processors/resolvePusher.test.ts index af87a1192..11d8539b1 100644 --- a/test/processors/resolvePusher.test.ts +++ b/test/processors/resolvePusher.test.ts @@ -31,6 +31,8 @@ vi.mock('axios', () => ({ import axios from 'axios'; import { getUsers } from '../../src/db'; import { exec } from '../../src/proxy/processors/push-action/resolvePusher'; +import { exec as checkUserPushPermission } from '../../src/proxy/processors/push-action/checkUserPushPermission'; +import { isUserPushAllowed } from '../../src/db'; const GITHUB_URL = 'https://github.com/finos/git-proxy.git'; @@ -67,6 +69,18 @@ describe('resolvePusher', () => { expect(result.steps[0].error).toBe(false); }); + it('verifies the credentials once for both resolvePusher and checkUserPushPermission', async () => { + vi.mocked(isUserPushAllowed).mockResolvedValue(true); + + await exec(req, action); + vi.mocked(axios.get).mockRejectedValue(new Error('provider unavailable')); + const result = await checkUserPushPermission(req, action); + + expect(axios.get).toHaveBeenCalledTimes(1); + expect(isUserPushAllowed).toHaveBeenCalledWith(GITHUB_URL, 'alice'); + expect(result.steps[1].error).toBe(false); + }); + it('leaves the identity unset without blocking when no single user matches', async () => { vi.mocked(axios.get).mockResolvedValue({ data: { login: 'mallory-gh' } }); From 2d9d44a6acfe8d959313612999e1e15b9890aad7 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:45:52 +0000 Subject: [PATCH 4/5] feature: allow self-hosted Basic auth git servers via basicAuthHosts --- config.schema.json | 7 ++++ docs/Architecture.md | 8 ++++ docs/Processors.md | 3 +- src/config/generated/config.ts | 8 ++++ src/config/index.ts | 5 +++ src/proxy/processors/pusherIdentity.ts | 24 +++++++++++- test-e2e.proxy.config.json | 1 + test/processors/pusherIdentity.test.ts | 53 ++++++++++++++++++++++++++ 8 files changed, 106 insertions(+), 3 deletions(-) diff --git a/config.schema.json b/config.schema.json index c72543037..099653675 100644 --- a/config.schema.json +++ b/config.schema.json @@ -277,6 +277,13 @@ "description": "Flag to enable CSRF protections for UI", "type": "boolean" }, + "basicAuthHosts": { + "description": "Hostnames of self-hosted git servers that verify the Basic auth username and password themselves (e.g. via htpasswd or LDAP). For these hosts, GitProxy identifies the pusher by the Basic auth username once the server accepts the credentials. Do not list servers that accept any username alongside a token.", + "type": "array", + "items": { + "type": "string" + } + }, "plugins": { "type": "array", "description": "List of plugins to integrate on GitProxy's push or pull actions. Each value is either a file path or a module name.", diff --git a/docs/Architecture.md b/docs/Architecture.md index 689178812..eee46ebc6 100644 --- a/docs/Architecture.md +++ b/docs/Architecture.md @@ -345,6 +345,14 @@ This will limit the number of **requests made to the API** to 150 per minute. Optionally, a `statusCode` and a `message` can be specified to override the default responses. +#### `basicAuthHosts` + +Hostnames (optionally with port) of self-hosted git servers that verify the Basic auth username and password themselves, such as servers backed by htpasswd or LDAP. For pushes to these hosts, GitProxy confirms the credentials are accepted by the server and then identifies the pusher by the Basic auth username, which must match a GitProxy user's `gitAccount`. Pushes to hosts that are neither GitHub, GitLab nor listed here are blocked. Never list a server that accepts any username alongside a token. + +```json +"basicAuthHosts": ["git.internal.example.com"] +``` + #### `privateOrganizations` (deprecated) Formerly used to block organizations, replaced by `commitConfig.diff.block.providers`. diff --git a/docs/Processors.md b/docs/Processors.md index bd83142fc..1d3d41bdf 100644 --- a/docs/Processors.md +++ b/docs/Processors.md @@ -92,13 +92,14 @@ The pusher's SCM account is resolved as follows: - `github.com`: the token owner's `login` from `GET https://api.github.com/user` - GitLab hosts (hostname contains `gitlab`): the token owner's `username` from `GET /api/v4/user` +- Hosts listed in the `basicAuthHosts` configuration (self-hosted servers that verify the Basic auth username and password themselves): the Basic auth username, once the server accepts the credentials for `git-receive-pack` on the repository - Any other git server: the push is blocked, since the Basic auth username alone does not prove who owns the credentials The SCM account is then matched (case-insensitively) against the `gitAccount` of GitProxy users. On success, `action.user` and `action.userEmail` are set to that GitProxy user's username and email; these are what the dashboard uses to prevent a reviewer from approving or rejecting their own push. This step will fail on various scenarios such as: -- The push has no valid Basic credentials, the SCM provider cannot resolve the token owner, or the host is not GitHub/GitLab +- The push has no valid Basic credentials, the SCM provider cannot resolve the token owner, or the host is not GitHub/GitLab or listed in `basicAuthHosts` - The SCM account matches multiple GitProxy users - No GitProxy user has that SCM account as their `gitAccount` - The user isn't in the repo's contributor (`canPush`) or approver (`canAuthorise`) list diff --git a/src/config/generated/config.ts b/src/config/generated/config.ts index 0a85e8e70..afb797e66 100644 --- a/src/config/generated/config.ts +++ b/src/config/generated/config.ts @@ -36,6 +36,13 @@ export interface GitProxyConfig { * List of repositories that are authorised to be pushed to through the proxy. */ authorisedList?: AuthorisedRepo[]; + /** + * Hostnames of self-hosted git servers that verify the Basic auth username and password + * themselves (e.g. via htpasswd or LDAP). For these hosts, GitProxy identifies the pusher + * by the Basic auth username once the server accepts the credentials. Do not list servers + * that accept any username alongside a token. + */ + basicAuthHosts?: string[]; /** * Block commits based on rules defined over author/committer e-mail addresses, commit * message content and diff content @@ -763,6 +770,7 @@ const typeMap: any = { typ: u(undefined, a(r('AuthenticationElement'))), }, { json: 'authorisedList', js: 'authorisedList', typ: u(undefined, a(r('AuthorisedRepo'))) }, + { json: 'basicAuthHosts', js: 'basicAuthHosts', typ: u(undefined, a('')) }, { json: 'commitConfig', js: 'commitConfig', typ: u(undefined, r('CommitConfig')) }, { json: 'configurationSources', js: 'configurationSources', typ: u(undefined, 'any') }, { json: 'contactEmail', js: 'contactEmail', typ: u(undefined, '') }, diff --git a/src/config/index.ts b/src/config/index.ts index 0d4591300..fb61c99b5 100644 --- a/src/config/index.ts +++ b/src/config/index.ts @@ -307,6 +307,11 @@ export const getDomains = () => { return config.domains || {}; }; +export const getBasicAuthHosts = (): string[] => { + const config = loadFullConfiguration(); + return config.basicAuthHosts || []; +}; + export const getUIRouteAuth = () => { const config = loadFullConfiguration(); return config.uiRouteAuth || {}; diff --git a/src/proxy/processors/pusherIdentity.ts b/src/proxy/processors/pusherIdentity.ts index bb5e726ff..ebcdc7f98 100644 --- a/src/proxy/processors/pusherIdentity.ts +++ b/src/proxy/processors/pusherIdentity.ts @@ -17,6 +17,7 @@ import axios from 'axios'; import { Action, Step } from '../actions'; import { getErrorMessage } from '../../utils/errors'; +import { getBasicAuthHosts } from '../../config'; const IDENTITY_LOOKUP_TIMEOUT_MS = 10000; @@ -42,12 +43,21 @@ export const parseBasicAuth = (header?: string): BasicCredentials | null => { return { username, password }; }; +const isBasicAuthHost = (upstream: URL): boolean => + getBasicAuthHosts().some((host) => { + const configured = host.toLowerCase(); + return ( + configured === upstream.host.toLowerCase() || configured === upstream.hostname.toLowerCase() + ); + }); + /** * Resolves the SCM account that owns the credentials presented to the proxy. * * GitHub and GitLab accept any username alongside a token, so the account is - * resolved by asking the provider who the token belongs to. The Basic username is - * never trusted on its own, so pushes to other git servers cannot be authenticated. + * resolved by asking the provider who the token belongs to. For servers listed in + * basicAuthHosts, which verify the Basic username themselves, the username is trusted + * once the server accepts the credentials. Pushes to any other host cannot be authenticated. * @param {string} url The upstream repository URL * @param {string | undefined} authHeader The Authorization header sent by the git client * @param {Step} step The step used for logging @@ -95,6 +105,16 @@ export const getAuthenticatedGitAccount = async ( ); return data?.username || null; } + + if (isBasicAuthHost(upstream)) { + await axios.get(`${upstream.origin}${upstream.pathname}/info/refs`, { + params: { service: 'git-receive-pack' }, + headers: { Authorization: authHeader!, 'User-Agent': 'git-proxy' }, + timeout: IDENTITY_LOOKUP_TIMEOUT_MS, + validateStatus: (status) => status === 200, + }); + return credentials.username || null; + } } catch (error: unknown) { step.log(`Unable to resolve the account for the push credentials: ${getErrorMessage(error)}`); return null; diff --git a/test-e2e.proxy.config.json b/test-e2e.proxy.config.json index f8fb9a32b..7c5ff38a3 100644 --- a/test-e2e.proxy.config.json +++ b/test-e2e.proxy.config.json @@ -10,6 +10,7 @@ "sendEmail": false, "emailConfig": {} }, + "basicAuthHosts": ["git-server"], "authorisedList": [ { "project": "test-owner", diff --git a/test/processors/pusherIdentity.test.ts b/test/processors/pusherIdentity.test.ts index 760ca2554..fda1398f6 100644 --- a/test/processors/pusherIdentity.test.ts +++ b/test/processors/pusherIdentity.test.ts @@ -22,7 +22,12 @@ vi.mock('axios', () => ({ default: { get: vi.fn() }, })); +vi.mock('../../src/config', () => ({ + getBasicAuthHosts: vi.fn(() => []), +})); + import axios from 'axios'; +import { getBasicAuthHosts } from '../../src/config'; import { getAuthenticatedGitAccount, parseBasicAuth, @@ -41,6 +46,7 @@ describe('pusherIdentity', () => { afterEach(() => { vi.clearAllMocks(); + vi.mocked(getBasicAuthHosts).mockReturnValue([]); }); describe('parseBasicAuth', () => { @@ -131,6 +137,53 @@ describe('pusherIdentity', () => { expect(axiosGetMock).not.toHaveBeenCalled(); }); + it('trusts the Basic username for basicAuthHosts once the server accepts the credentials', async () => { + vi.mocked(getBasicAuthHosts).mockReturnValue(['git-server']); + axiosGetMock.mockResolvedValue({ status: 200, data: '' }); + const authHeader = basicAuth('testuser:user123'); + + const account = await getAuthenticatedGitAccount( + 'https://git-server:8443/test-owner/test-repo.git', + authHeader, + step, + ); + + expect(account).toBe('testuser'); + expect(axiosGetMock).toHaveBeenCalledWith( + 'https://git-server:8443/test-owner/test-repo.git/info/refs', + expect.objectContaining({ + params: { service: 'git-receive-pack' }, + headers: expect.objectContaining({ Authorization: authHeader }), + }), + ); + }); + + it('matches basicAuthHosts entries that include a port', async () => { + vi.mocked(getBasicAuthHosts).mockReturnValue(['git-server:8443']); + axiosGetMock.mockResolvedValue({ status: 200, data: '' }); + + const account = await getAuthenticatedGitAccount( + 'https://git-server:8443/test-owner/test-repo.git', + basicAuth('testuser:user123'), + step, + ); + + expect(account).toBe('testuser'); + }); + + it('returns null when a basicAuthHosts server rejects the credentials', async () => { + vi.mocked(getBasicAuthHosts).mockReturnValue(['git-server']); + axiosGetMock.mockRejectedValue(new Error('Request failed with status code 401')); + + const account = await getAuthenticatedGitAccount( + 'https://git-server:8443/test-owner/test-repo.git', + basicAuth('testuser:wrong-password'), + step, + ); + + expect(account).toBeNull(); + }); + it('returns null without credentials', async () => { const account = await getAuthenticatedGitAccount( 'https://github.com/org/repo.git', From 25c3136addc366318d470d9295a0eeaf9620bc98 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:49:06 +0000 Subject: [PATCH 5/5] fix: require auth on basicAuthHosts and prefer them over GitLab API (bug) --- config.schema.json | 14 +++--- docs/Architecture.md | 2 +- docs/Processors.md | 2 +- src/proxy/processors/pusherIdentity.ts | 51 +++++++++++++++---- test/processors/pusherIdentity.test.ts | 64 ++++++++++++++++++++++-- website/docs/configuration/reference.mdx | 27 ++++++++++ 6 files changed, 138 insertions(+), 22 deletions(-) diff --git a/config.schema.json b/config.schema.json index 099653675..0fa2727e2 100644 --- a/config.schema.json +++ b/config.schema.json @@ -277,13 +277,6 @@ "description": "Flag to enable CSRF protections for UI", "type": "boolean" }, - "basicAuthHosts": { - "description": "Hostnames of self-hosted git servers that verify the Basic auth username and password themselves (e.g. via htpasswd or LDAP). For these hosts, GitProxy identifies the pusher by the Basic auth username once the server accepts the credentials. Do not list servers that accept any username alongside a token.", - "type": "array", - "items": { - "type": "string" - } - }, "plugins": { "type": "array", "description": "List of plugins to integrate on GitProxy's push or pull actions. Each value is either a file path or a module name.", @@ -374,6 +367,13 @@ } } } + }, + "basicAuthHosts": { + "description": "Hostnames of self-hosted git servers that verify the Basic auth username and password themselves (e.g. via htpasswd or LDAP). For these hosts, GitProxy identifies the pusher by the Basic auth username once the server accepts the credentials. Do not list servers that accept any username alongside a token.", + "type": "array", + "items": { + "type": "string" + } } }, "definitions": { diff --git a/docs/Architecture.md b/docs/Architecture.md index eee46ebc6..2c216296f 100644 --- a/docs/Architecture.md +++ b/docs/Architecture.md @@ -347,7 +347,7 @@ Optionally, a `statusCode` and a `message` can be specified to override the defa #### `basicAuthHosts` -Hostnames (optionally with port) of self-hosted git servers that verify the Basic auth username and password themselves, such as servers backed by htpasswd or LDAP. For pushes to these hosts, GitProxy confirms the credentials are accepted by the server and then identifies the pusher by the Basic auth username, which must match a GitProxy user's `gitAccount`. Pushes to hosts that are neither GitHub, GitLab nor listed here are blocked. Never list a server that accepts any username alongside a token. +Hostnames (optionally with port) of self-hosted git servers that verify the Basic auth username and password themselves, such as servers backed by htpasswd or LDAP. For pushes to these hosts, GitProxy checks that the server rejects anonymous `git-receive-pack` discovery and accepts it with the push credentials, and then identifies the pusher by the Basic auth username, which must match a GitProxy user's `gitAccount`. This setting takes precedence over the GitHub/GitLab API lookup for the listed hosts. Pushes to hosts that are neither GitHub, GitLab nor listed here are blocked. Never list a server that accepts any username alongside a token. ```json "basicAuthHosts": ["git.internal.example.com"] diff --git a/docs/Processors.md b/docs/Processors.md index 1d3d41bdf..4ea174550 100644 --- a/docs/Processors.md +++ b/docs/Processors.md @@ -92,7 +92,7 @@ The pusher's SCM account is resolved as follows: - `github.com`: the token owner's `login` from `GET https://api.github.com/user` - GitLab hosts (hostname contains `gitlab`): the token owner's `username` from `GET /api/v4/user` -- Hosts listed in the `basicAuthHosts` configuration (self-hosted servers that verify the Basic auth username and password themselves): the Basic auth username, once the server accepts the credentials for `git-receive-pack` on the repository +- Hosts listed in the `basicAuthHosts` configuration (self-hosted servers that verify the Basic auth username and password themselves): the Basic auth username, once the server rejects anonymous `git-receive-pack` discovery on the repository and accepts it with the push credentials (checked before the GitHub/GitLab rules) - Any other git server: the push is blocked, since the Basic auth username alone does not prove who owns the credentials The SCM account is then matched (case-insensitively) against the `gitAccount` of GitProxy users. On success, `action.user` and `action.userEmail` are set to that GitProxy user's username and email; these are what the dashboard uses to prevent a reviewer from approving or rejecting their own push. diff --git a/src/proxy/processors/pusherIdentity.ts b/src/proxy/processors/pusherIdentity.ts index ebcdc7f98..548a72914 100644 --- a/src/proxy/processors/pusherIdentity.ts +++ b/src/proxy/processors/pusherIdentity.ts @@ -51,6 +51,43 @@ const isBasicAuthHost = (upstream: URL): boolean => ); }); +/** + * The Basic username is only trusted if the server rejects anonymous receive-pack + * discovery but accepts it with the presented credentials. + */ +const verifyBasicAuthCredentials = async ( + upstream: URL, + authHeader: string, + username: string, + step: Step, +): Promise => { + const url = `${upstream.origin}${upstream.pathname}/info/refs`; + const options = { + params: { service: 'git-receive-pack' }, + timeout: IDENTITY_LOOKUP_TIMEOUT_MS, + validateStatus: () => true, + }; + + const anonymous = await axios.get(url, { ...options, headers: { 'User-Agent': 'git-proxy' } }); + if (anonymous.status !== 401 && anonymous.status !== 403) { + step.log( + `${upstream.host} does not require authentication for pushes, cannot verify the pusher`, + ); + return null; + } + + const authenticated = await axios.get(url, { + ...options, + headers: { Authorization: authHeader, 'User-Agent': 'git-proxy' }, + }); + if (authenticated.status !== 200) { + step.log(`${upstream.host} rejected the push credentials (status ${authenticated.status})`); + return null; + } + + return username || null; +}; + /** * Resolves the SCM account that owns the credentials presented to the proxy. * @@ -98,6 +135,10 @@ export const getAuthenticatedGitAccount = async ( return data?.login || null; } + if (isBasicAuthHost(upstream)) { + return await verifyBasicAuthCredentials(upstream, authHeader!, credentials.username, step); + } + if (hostname.includes('gitlab')) { const { data } = await axios.get<{ username?: string }>( `${upstream.protocol}//${upstream.host}/api/v4/user`, @@ -105,16 +146,6 @@ export const getAuthenticatedGitAccount = async ( ); return data?.username || null; } - - if (isBasicAuthHost(upstream)) { - await axios.get(`${upstream.origin}${upstream.pathname}/info/refs`, { - params: { service: 'git-receive-pack' }, - headers: { Authorization: authHeader!, 'User-Agent': 'git-proxy' }, - timeout: IDENTITY_LOOKUP_TIMEOUT_MS, - validateStatus: (status) => status === 200, - }); - return credentials.username || null; - } } catch (error: unknown) { step.log(`Unable to resolve the account for the push credentials: ${getErrorMessage(error)}`); return null; diff --git a/test/processors/pusherIdentity.test.ts b/test/processors/pusherIdentity.test.ts index fda1398f6..690deb363 100644 --- a/test/processors/pusherIdentity.test.ts +++ b/test/processors/pusherIdentity.test.ts @@ -137,9 +137,15 @@ describe('pusherIdentity', () => { expect(axiosGetMock).not.toHaveBeenCalled(); }); + const mockGitServer = (anonymousStatus: number, authenticatedStatus: number) => + axiosGetMock.mockImplementation(async (_url: string, options: any) => ({ + status: options?.headers?.Authorization ? authenticatedStatus : anonymousStatus, + data: '', + })); + it('trusts the Basic username for basicAuthHosts once the server accepts the credentials', async () => { vi.mocked(getBasicAuthHosts).mockReturnValue(['git-server']); - axiosGetMock.mockResolvedValue({ status: 200, data: '' }); + mockGitServer(401, 200); const authHeader = basicAuth('testuser:user123'); const account = await getAuthenticatedGitAccount( @@ -149,6 +155,14 @@ describe('pusherIdentity', () => { ); expect(account).toBe('testuser'); + expect(axiosGetMock).toHaveBeenCalledTimes(2); + expect(axiosGetMock).toHaveBeenCalledWith( + 'https://git-server:8443/test-owner/test-repo.git/info/refs', + expect.objectContaining({ + params: { service: 'git-receive-pack' }, + headers: expect.not.objectContaining({ Authorization: expect.anything() }), + }), + ); expect(axiosGetMock).toHaveBeenCalledWith( 'https://git-server:8443/test-owner/test-repo.git/info/refs', expect.objectContaining({ @@ -160,7 +174,7 @@ describe('pusherIdentity', () => { it('matches basicAuthHosts entries that include a port', async () => { vi.mocked(getBasicAuthHosts).mockReturnValue(['git-server:8443']); - axiosGetMock.mockResolvedValue({ status: 200, data: '' }); + mockGitServer(401, 200); const account = await getAuthenticatedGitAccount( 'https://git-server:8443/test-owner/test-repo.git', @@ -171,9 +185,26 @@ describe('pusherIdentity', () => { expect(account).toBe('testuser'); }); + it('prefers basicAuthHosts over the GitLab API for configured hosts', async () => { + vi.mocked(getBasicAuthHosts).mockReturnValue(['gitlab-mirror.example.com']); + mockGitServer(401, 200); + + const account = await getAuthenticatedGitAccount( + 'https://gitlab-mirror.example.com/team/repo.git', + basicAuth('testuser:user123'), + step, + ); + + expect(account).toBe('testuser'); + expect(axiosGetMock).not.toHaveBeenCalledWith( + expect.stringContaining('/api/v4/user'), + expect.anything(), + ); + }); + it('returns null when a basicAuthHosts server rejects the credentials', async () => { vi.mocked(getBasicAuthHosts).mockReturnValue(['git-server']); - axiosGetMock.mockRejectedValue(new Error('Request failed with status code 401')); + mockGitServer(401, 401); const account = await getAuthenticatedGitAccount( 'https://git-server:8443/test-owner/test-repo.git', @@ -184,6 +215,33 @@ describe('pusherIdentity', () => { expect(account).toBeNull(); }); + it('returns null when a basicAuthHosts server allows anonymous pushes', async () => { + vi.mocked(getBasicAuthHosts).mockReturnValue(['git-server']); + mockGitServer(200, 200); + + const account = await getAuthenticatedGitAccount( + 'https://git-server:8443/test-owner/test-repo.git', + basicAuth('victim:wrong-password'), + step, + ); + + expect(account).toBeNull(); + expect(axiosGetMock).toHaveBeenCalledTimes(1); + }); + + it('returns null when a basicAuthHosts server is unreachable', async () => { + vi.mocked(getBasicAuthHosts).mockReturnValue(['git-server']); + axiosGetMock.mockRejectedValue(new Error('connect ECONNREFUSED')); + + const account = await getAuthenticatedGitAccount( + 'https://git-server:8443/test-owner/test-repo.git', + basicAuth('testuser:user123'), + step, + ); + + expect(account).toBeNull(); + }); + it('returns null without credentials', async () => { const account = await getAuthenticatedGitAccount( 'https://github.com/org/repo.git', diff --git a/website/docs/configuration/reference.mdx b/website/docs/configuration/reference.mdx index 361415bbf..bfbeccb7c 100644 --- a/website/docs/configuration/reference.mdx +++ b/website/docs/configuration/reference.mdx @@ -2028,5 +2028,32 @@ Specific value: `"jwt"` +
+ + 24. [Optional] Property GitProxy configuration file > basicAuthHosts + +
+ +| | | +| ------------ | ----------------- | +| **Type** | `array of string` | +| **Required** | No | + +**Description:** Hostnames of self-hosted git servers that verify the Basic auth username and password themselves (e.g. via htpasswd or LDAP). For these hosts, GitProxy identifies the pusher by the Basic auth username once the server accepts the credentials. Do not list servers that accept any username alongside a token. + +| Each item of this array must be | Description | +| --------------------------------------------- | ----------- | +| [basicAuthHosts items](#basicAuthHosts_items) | - | + +### 24.1. GitProxy configuration file > basicAuthHosts > basicAuthHosts items + +| | | +| ------------ | -------- | +| **Type** | `string` | +| **Required** | No | + +
+
+ ---------------------------------------------------------------------------------------------------------------------------- Generated using [json-schema-for-humans](https://github.com/coveooss/json-schema-for-humans) on 2026-01-21 at 14:25:25 +0100