-
Notifications
You must be signed in to change notification settings - Fork 158
Expand file tree
/
Copy pathgitleaks.ts
More file actions
201 lines (176 loc) · 6.02 KB
/
gitleaks.ts
File metadata and controls
201 lines (176 loc) · 6.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
/**
* 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 { spawn } from 'node:child_process';
import { PathLike } from 'node:fs';
import fs from 'node:fs/promises';
import { Request } from 'express';
import { Action, Step } from '../../actions';
import { getAPIs } from '../../../config';
import { handleErrorAndLogInStep } from '../../../utils/errors';
const EXIT_CODE = 99;
function runCommand(
cwd: string,
command: string,
args: readonly string[] = [],
): Promise<{
exitCode: number | null;
stdout: string;
stderr: string;
}> {
return new Promise((resolve, reject) => {
const child = spawn(command, args, { cwd, shell: true });
let stdout = '';
let stderr = '';
child.stdout.on('data', (data) => {
stdout += data?.toString() ?? '';
});
child.stderr.on('data', (data) => {
stderr += data?.toString() ?? '';
});
child.on('close', (exitCode) => {
resolve({ exitCode, stdout, stderr });
});
child.on('error', (err) => {
reject(err);
});
});
}
type ConfigOptions = {
enabled: boolean;
ignoreGitleaksAllow: boolean;
noColor: boolean;
configPath: string | undefined;
};
const DEFAULT_CONFIG: ConfigOptions = {
// adding gitleaks into main git-proxy for now as default off
// in the future will likely be moved to a plugin where it'll be default on
enabled: false,
ignoreGitleaksAllow: true,
noColor: false,
configPath: undefined,
};
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null;
}
async function fileIsReadable(path: PathLike): Promise<boolean> {
try {
if (!(await fs.stat(path)).isFile()) {
return false;
}
await fs.access(path, fs.constants.R_OK);
return true;
} catch (error: unknown) {
return false;
}
}
const getPluginConfig = async (): Promise<ConfigOptions> => {
const userConfig = getAPIs();
if (typeof userConfig !== 'object') {
return DEFAULT_CONFIG;
}
if (!Object.hasOwn(userConfig, 'gitleaks')) {
return DEFAULT_CONFIG;
}
const gitleaksConfig = userConfig.gitleaks;
if (!isRecord(gitleaksConfig)) {
return DEFAULT_CONFIG;
}
let configPath: string | undefined = undefined;
if (typeof gitleaksConfig.configPath === 'string') {
const userConfigPath = gitleaksConfig.configPath.trim();
if (userConfigPath.length > 0 && (await fileIsReadable(userConfigPath))) {
configPath = userConfigPath;
} else {
throw new Error(`Unable to read file at the provided config path: ${userConfigPath}`);
}
}
// TODO: integrate zod
return {
enabled:
typeof gitleaksConfig.enabled === 'boolean' ? gitleaksConfig.enabled : DEFAULT_CONFIG.enabled,
ignoreGitleaksAllow:
typeof gitleaksConfig.ignoreGitleaksAllow === 'boolean'
? gitleaksConfig.ignoreGitleaksAllow
: DEFAULT_CONFIG.ignoreGitleaksAllow,
noColor:
typeof gitleaksConfig.noColor === 'boolean' ? gitleaksConfig.noColor : DEFAULT_CONFIG.noColor,
configPath,
};
};
const exec = async (_req: Request, action: Action): Promise<Action> => {
const step = new Step('gitleaks');
let config: ConfigOptions | undefined = undefined;
try {
config = await getPluginConfig();
} catch (error: unknown) {
handleErrorAndLogInStep(step, error, 'Failed to get gitleaks config');
action.addStep(step);
return action;
}
if (!config.enabled) {
step.log('Gitleaks is disabled, skipping.');
action.addStep(step);
return action;
}
const { commitFrom, commitTo } = action;
const workingDir = `${action.proxyGitPath}/${action.repoName}`;
step.log(`Scanning range with gitleaks: ${commitFrom}:${commitTo} in ${workingDir}`);
try {
const gitRootCommit = await runCommand(workingDir, 'git', [
'rev-list',
'--max-parents=0',
'HEAD',
]);
if (gitRootCommit.exitCode !== 0) {
throw new Error('failed to run git');
}
const rootCommit = gitRootCommit.stdout.trim();
const gitleaksArgs = [
`--exit-code=${EXIT_CODE}`,
'--platform=none',
config.configPath ? `--config=${config.configPath}` : undefined, // allow for custom config
config.ignoreGitleaksAllow ? '--ignore-gitleaks-allow' : undefined, // force scanning for security
'--no-banner', // reduce git-proxy error output
config.noColor ? '--no-color' : undefined, // colour output should appear properly in the console
'--redact', // avoid printing the contents
'--verbose',
'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}'`,
].filter((v) => typeof v === 'string');
const gitleaks = await runCommand(workingDir, 'gitleaks', gitleaksArgs);
if (gitleaks.exitCode !== 0) {
// any failure
if (gitleaks.exitCode !== EXIT_CODE) {
step.setError('Failed to run gitleaks, please contact an administrator.');
} else {
// exit code matched our gitleaks findings exit code
// newline prefix to avoid tab indent at the start
step.setError('\n' + gitleaks.stdout + gitleaks.stderr);
}
} else {
step.log('Succeeded.');
step.log(`Gitleaks output: ${gitleaks.stderr}`);
}
} catch (error: unknown) {
handleErrorAndLogInStep(step, error, 'Failed to spawn gitleaks');
}
action.addStep(step);
return action;
};
exec.displayName = 'gitleaks.exec';
export { exec };