Skip to content

Commit cca6713

Browse files
committed
reafactor: gitleaks rules update and general code clean up
1 parent 518234f commit cca6713

File tree

14 files changed

+3062
-144
lines changed

14 files changed

+3062
-144
lines changed

gitleaks.toml

Lines changed: 2978 additions & 84 deletions
Large diffs are not rendered by default.

proxy.config.json

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,12 @@
1111
"project": "finos",
1212
"name": "git-proxy",
1313
"url": "https://github.com/finos/git-proxy.git"
14+
},
15+
{
16+
"project": "project name",
17+
"name": "repo name",
18+
"url": "repo url",
19+
"LocalRepoRoot": "specify you local repository path"
1420
}
1521
],
1622
"sink": [

src/proxy/chain.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ const pushActionChain = [
1212
proc.push.getDiff,
1313
proc.push.checkSensitiveData, // checkSensitiveData added
1414
proc.push.checkExifJpeg,
15-
proc.push.checkForAiMlUsage,
15+
proc.push.checkForAiMlusage,
1616
proc.push.clearBareClone,
1717
proc.push.checkCryptoImplementation,
1818
proc.push.scanDiff,

src/proxy/processors/push-action/checkCommitMessages.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
const Step = require('../../actions').Step;
22
const config = require('../../../config');
3-
const { exec: eexec } = require('./checkForSecrets');
3+
const { exec: eexec } = require('./checkForSecrets.js');
44
console.log(eexec);
55
const commitConfig = config.getCommitConfig();
66

src/proxy/processors/push-action/checkCryptoImplementation.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,6 @@ const exec = async (req, action) => {
135135
}
136136
};
137137

138-
// exec.displayName = 'checkCryptoImplementation.exec';
138+
exec.displayName = 'checkCryptoImplementation.exec';
139139
exports.exec = exec;
140140
exports.analyzeCodeForCrypto = analyzeCodeForCrypto;

src/proxy/processors/push-action/checkExifJpeg.js

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@ const { Step } = require('../../actions');
33
const config = require('../../../config');
44

55
const commitConfig = config.getCommitConfig();
6+
const authorizedlist = config.getAuthorisedList();
7+
68
const validExtensions = ['.jpeg', '.png', '.jpg', '.tiff'];
79
// Make sure you have modified the proxy.config.json;
810
// Function to check sensitive EXIF data
@@ -27,8 +29,9 @@ const checkSensitiveExifData = (metadata) => {
2729
};
2830

2931
// Function to retrieve EXIF data using ExifTool
30-
const getExifData = async (filePath) => {
32+
const getExifData = async (relativePath,repoRoot) => {
3133
const exifTool = new ExifTool();
34+
const filePath = path.join(repoRoot, relativePath);
3235
try {
3336
const metadata = await exifTool.read(filePath);
3437
return metadata ? checkSensitiveExifData(metadata) : true;
@@ -67,7 +70,14 @@ const exec = async (req, action, log = console.log) => {
6770
const filteredPaths = filePaths.filter(path => validExtensions.some(ext => path.endsWith(ext) && allowedFileType.includes(ext)));
6871

6972
if (filteredPaths.length > 0) {
70-
const exifResults = await Promise.all(filteredPaths.map(filePath => getExifData(filePath)));
73+
74+
const exifResults = await Promise.all(
75+
filteredPaths.map((Path) => {
76+
const repo = action.url;
77+
const repoRoot = authorizedlist.find((item) => item.url === repo).LocalRepoRoot;
78+
getExifData(Path, repoRoot);
79+
}),
80+
);
7181
const isBlocked = exifResults.some(result => !result);
7282

7383
if (isBlocked) {

src/proxy/processors/push-action/checkForAiMlUsage.js

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
const { Step } = require('../../actions');
22
const config = require('../../../config');
33
const commitConfig = config.getCommitConfig();
4+
const authorizedlist = config.getAuthorisedList();
45

56
const fs = require('fs');
67

@@ -58,21 +59,23 @@ const isAiMlFileByContent = (fileContent) => {
5859

5960

6061
// Main function to detect AI/ML usage in an array of file paths
61-
const detectAiMlUsageFiles = async (filePaths) => {
62+
const detectAiMlUsageFiles = async (filePaths,repoRoot) => {
6263
const results = [];
6364
// console.log("filePaths!", filePaths);
64-
for (const filePath of filePaths) {
65+
for (let filePath of filePaths) {
6566
try {
6667
const fileName = filePath.split('/').pop();
6768
// console.log(fileName, "!!!");
6869
// Check if the file name itself indicates AI/ML usage
6970
if (isAiMlFileByExtension(fileName)) {
70-
// console.log("FOUND EXTENSION for ", fileName);
71+
console.log("FOUND EXTENSION for ", fileName);
7172
results.push(false); continue;
7273
// Skip content check if the file name is a match
7374
}
7475
// Check for AI/ML indicators within the file content
7576
// console.log("testing content for ", fileName);
77+
filePath = path.join(repoRoot, filePath);
78+
7679
const content = await fs.promises.readFile(filePath, 'utf8');
7780
if (isAiMlFileByContent(content)) {
7881
results.push(false); continue;
@@ -118,7 +121,9 @@ const exec = async (req, action, log = console.log) => {
118121
// console.log(filePaths);
119122

120123
if (filePaths.length) {
121-
const aiMlDetected = await detectAiMlUsageFiles(filePaths);
124+
const repoRoot = authorizedlist.find((item) => item.url === action.url).LocalRepoRoot;
125+
126+
const aiMlDetected = await detectAiMlUsageFiles(filePaths,repoRoot);
122127
// console.log(aiMlDetected);
123128
const isBlocked = aiMlDetected.some(found => !found);
124129
// const isBlocked = false;
@@ -139,5 +144,5 @@ const exec = async (req, action, log = console.log) => {
139144
return action;
140145
};
141146

142-
exec.displayName = 'logFileChanges.exec';
147+
exec.displayName = 'checkForAiMlUsage.exec';
143148
module.exports = { exec };

src/proxy/processors/push-action/checkForSecrets renamed to src/proxy/processors/push-action/checkForSecrets.js

Lines changed: 25 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@ const { exec: cexec } = require('child_process');
44
const path = require('path');
55
const config = require('../../../config');
66
const commitConfig = config.getCommitConfig();
7+
const authorizedlist = config.getAuthorisedList();
8+
79

810
// Function to extract relevant file paths from Git diff content
911
// go to proxyconfig.json and enable the feature
@@ -37,53 +39,39 @@ function extractRelevantDirectories(diffContent) {
3739
}
3840

3941
// Function to run Gitleaks with directory paths
40-
function runGitleaks(filePaths) {
42+
function runGitleaks(filePaths,repoRoot) {
4143
return new Promise((resolve, reject) => {
4244
const filesToCheck = filePaths
43-
.map((filePath) => `"${path.resolve(filePath).replace(/\\/g, '/')}"`)
45+
.map((filePath) => `"${path.resolve(repoRoot,filePath).replace(/\\/g, '/')}"`)
4446
.join(' ');
47+
console.log("filesToCheck:", filesToCheck);
4548

4649
const configPath = path.resolve(__dirname, '../../../../gitleaks.toml').replace(/\\/g, '/');
47-
const reportPath = path
48-
.resolve(__dirname, '../../../../gitleaks_report.json')
49-
.replace(/\\/g, '/');
50+
const reportPath = repoRoot + '/gitleaks_report.json';
5051

51-
const command = `gitleaks dir ${filesToCheck} --config="${configPath}" --report-format json --log-level error --report-path="${reportPath}"`;
52+
const command = `gitleaks dir ${filesToCheck} --config="${configPath}" --report-format json --log-level debug --report-path="${reportPath}"`;
5253
console.log(`Executing Gitleaks Command: ${command}`);
5354

5455
cexec(command, (error, stdout, stderr) => {
5556
if (error) {
56-
console.error(`Error executing gitleaks: ${error.message}`);
57-
reject(new Error(`Error executing gitleaks: ${error.message}`));
58-
} else if (stderr) {
59-
console.error(`stderr: ${stderr}`);
60-
reject(new Error(`stderr: ${stderr}`));
57+
// If leaks are found, handle the warning gracefully
58+
console.log("stderrrrr:",stderr);
59+
if (stderr.includes("leaks found")) {
60+
console.warn("Leaks were found, but execution succeeded.");
61+
resolve(true); // Consider this a successful run
62+
} else {
63+
console.error(`Error executing gitleaks: ${error.message}`);
64+
reject(new Error(`Error executing gitleaks: ${error.message}`));
65+
}
6166
} else {
62-
resolve(stdout);
67+
resolve(false);
6368
}
6469
});
6570
});
6671
}
6772

68-
// Function to check for sensitive secrets in the Gitleaks output
69-
function checkForSensitiveSecrets(output) {
70-
try {
71-
const findings = JSON.parse(output);
72-
73-
if (findings.length > 0) {
74-
findings.forEach((finding) => {
75-
console.log(`Secret found in file: ${finding.file}`);
76-
console.log(` Rule: ${finding.rule_id}`);
77-
console.log(` Secret: ${finding.secret}`);
78-
});
79-
return true;
80-
}
81-
return false;
82-
} catch (error) {
83-
console.error('Error parsing Gitleaks output:', error);
84-
return false;
85-
}
86-
}
73+
74+
8775

8876
// Example usage in exec function
8977
const exec = async (req, action) => {
@@ -98,13 +86,14 @@ const exec = async (req, action) => {
9886

9987
if (diffStep && diffStep.content) {
10088
const dirPaths = extractRelevantDirectories(diffStep.content);
101-
89+
const repoRoot = authorizedlist.find((item) => item.url === action.url).LocalRepoRoot;
90+
10291
if (dirPaths.length > 0) {
10392
try {
104-
const result = await runGitleaks(dirPaths);
105-
const hasSensitiveSecrets = checkForSensitiveSecrets(result);
93+
const res = await runGitleaks(dirPaths,repoRoot);
94+
10695

107-
if (hasSensitiveSecrets) {
96+
if (res) {
10897
step.blocked = true;
10998
step.blockedMessage = 'Sensitive secrets detected in the diff.';
11099
console.log('Sensitive secrets detected! Push blocked.');
@@ -126,7 +115,7 @@ const exec = async (req, action) => {
126115
};
127116

128117
exec.displayName = 'checkforSecrets.exec';
129-
118+
module.exports = { exec };
130119

131120

132121

src/proxy/processors/push-action/checkSensitiveData.js

Lines changed: 26 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@ const config = require('../../../config');
88
// const { exec: getDiffExec } = require('./getDiff');
99
// Function to check for sensitive data patterns
1010
const commitConfig = config.getCommitConfig();
11+
const authorizedlist = config.getAuthorisedList();
12+
1113
const checkForSensitiveData = (cell) => {
1214
const sensitivePatterns = [
1315
/\d{3}-\d{2}-\d{4}/, // Social Security Number (SSN)
@@ -94,8 +96,9 @@ const checkLogJsonFiles = async (filePath) => {
9496
});
9597
};
9698
// Function to parse the file based on its extension
97-
const parseFile = async (filePath) => {
98-
99+
const parseFile = async (repoRoot, relativePath) => {
100+
const filePath = path.join(repoRoot, relativePath);
101+
99102
const ext = path.extname(filePath).toLowerCase();
100103
const FilestoCheck = commitConfig.diff.block.proxyFileTypes;
101104
if(!FilestoCheck.includes(ext)){
@@ -145,16 +148,27 @@ const exec = async (req, action) => {
145148
const filePaths = extractFilePathsFromDiff(diffStep.content);
146149

147150
if (filePaths.length > 0) {
148-
// Check for sensitive data in all files
149-
const sensitiveDataFound = await Promise.all(filePaths.map(parseFile));
150-
const anySensitiveDataDetected = sensitiveDataFound.some(found => found);
151-
152-
if (anySensitiveDataDetected) {
153-
step.blocked= true;
154-
step.error = true;
155-
step.errorMessage = 'Your push has been blocked due to sensitive data detection.';
156-
console.log(step.errorMessage);
157-
}
151+
try {
152+
const repoUrl = action.url;
153+
const repo = authorizedlist.find((item) => item.url === repoUrl);
154+
// console.log(repo);
155+
const repoRoot = repo.LocalRepoRoot;
156+
// console.log('my reporoot is ' + repoRoot);
157+
158+
const sensitiveDataFound = await Promise.all(
159+
filePaths.map((filePath) => parseFile(repoRoot, filePath)),
160+
);
161+
const anySensitiveDataDetected = sensitiveDataFound.some((found) => found);
162+
163+
if (anySensitiveDataDetected) {
164+
step.blocked = true;
165+
step.error = true;
166+
step.errorMessage = 'Your push has been blocked due to sensitive data detection.';
167+
console.log(step.errorMessage);
168+
}
169+
} catch (error) {
170+
console.error(`Error processing files: ${error.message}`);
171+
}
158172
} else {
159173
console.log('No file paths provided in the diff step.');
160174
}

src/proxy/processors/push-action/index.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,11 @@ exports.scanDiff = require('./scanDiff').exec;
88
exports.blockForAuth = require('./blockForAuth').exec;
99
exports.checkIfWaitingAuth = require('./checkIfWaitingAuth').exec;
1010
exports.checkCommitMessages = require('./checkCommitMessages').exec;
11-
console.log(__dirname);
1211
exports.checkAuthorEmails = require('./checkAuthorEmails').exec;
1312
exports.checkUserPushPermission = require('./checkUserPushPermission').exec;
1413
exports.clearBareClone = require('./clearBareClone').exec;
1514
exports.checkSensitiveData = require('./checkSensitiveData').exec;
1615
exports.checkExifJpeg = require('./checkExifJpeg').exec;
1716
exports.checkForAiMlusage = require('./checkForAiMlUsage').exec;
17+
exports.checkForSecrets = require('./checkForSecrets').exec;
1818
exports.checkCryptoImplementation = require('./checkCryptoImplementation').exec;

0 commit comments

Comments
 (0)