forked from finos/git-proxy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgitleaks.ts
More file actions
190 lines (166 loc) · 5.55 KB
/
gitleaks.ts
File metadata and controls
190 lines (166 loc) · 5.55 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
import { Action, Step } from '../../actions';
import { getAPIs } from '../../../config';
import { spawn } from 'node:child_process';
import fs from 'node:fs/promises';
import { PathLike } from 'node:fs';
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 (e) {
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 {
console.error('could not read file at the config path provided, will not be fed to gitleaks');
throw new Error("could not check user's config path");
}
}
// 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: any, action: Action): Promise<Action> => {
const step = new Step('gitleaks');
let config: ConfigOptions | undefined = undefined;
try {
config = await getPluginConfig();
} catch (e) {
step.log(`failed to get gitleaks config, please fix the error: ${String(e)}`);
action.error = true;
step.setError('failed setup gitleaks, please contact an administrator\n');
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}, ${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
step.error = true;
if (gitleaks.exitCode !== EXIT_CODE) {
step.setError('failed to run gitleaks, please contact an administrator\n');
} 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.stderr);
}
} catch (e) {
action.error = true;
step.setError('failed to spawn gitleaks, please contact an administrator\n');
action.addStep(step);
return action;
}
action.addStep(step);
return action;
};
exec.displayName = 'gitleaks.exec';
export { exec };