-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathpolicy-results-services.ts
More file actions
206 lines (191 loc) · 7.63 KB
/
Copy pathpolicy-results-services.ts
File metadata and controls
206 lines (191 loc) · 7.63 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
202
203
204
205
206
import * as core from '@actions/core';
import { Octokit } from '@octokit/rest';
import * as fs from 'fs/promises';
import { Inputs, vaildateScanResultsActionInput } from '../inputs';
import * as VeracodePolicyResult from '../namespaces/VeracodePolicyResult';
import * as Checks from '../namespaces/Checks';
import { updateChecks } from './check-service';
import appConfig from '../app-config';
import * as VeracodeApplication from '../namespaces/VeracodeApplication';
import * as http from '../api/http-request';
export async function preparePolicyResults(inputs: Inputs): Promise<void> {
const baseUrl = process.env.GITHUB_API_URL || 'https://api.github.com';
const octokit = new Octokit({
auth: inputs.token,
baseUrl: baseUrl
});
const repo = inputs.source_repository.split('/');
const ownership = {
owner: repo[0],
repo: repo[1],
};
const checkStatic: Checks.ChecksStatic = {
owner: ownership.owner,
repo: ownership.repo,
check_run_id: inputs.check_run_id,
status: Checks.Status.Completed,
};
// When the action is preparePolicyResults, need to make sure token,
// check_run_id and source_repository are provided
if (!vaildateScanResultsActionInput(inputs)) {
core.setFailed('token, check_run_id and source_repository are required.');
// TODO: Based on the veracode.yml, update the checks status to failure or pass
await updateChecks(
octokit,
checkStatic,
inputs.fail_checks_on_error ? Checks.Conclusion.Failure : Checks.Conclusion.Success,
[],
'Token, check_run_id and source_repository are required.',
);
return;
}
let findingsArray: VeracodePolicyResult.Finding[] = [];
let resultsUrl: string = '';
try {
const data = await fs.readFile('policy_flaws.json', 'utf-8');
const parsedData: VeracodePolicyResult.ResultsData = JSON.parse(data);
findingsArray = parsedData._embedded.findings;
resultsUrl = await fs.readFile('results_url.txt', 'utf-8');
await postScanReport(inputs, findingsArray);
} catch (error) {
core.debug(`Error reading or parsing filtered_results.json:${error}`);
core.setFailed('Error reading or parsing pipeline scan results.');
// TODO: Based on the veracode.yml, update the checks status to failure or pass
await updateChecks(
octokit,
checkStatic,
inputs.fail_checks_on_error ? Checks.Conclusion.Failure : Checks.Conclusion.Success,
[],
'Error reading or parsing pipeline scan results.',
);
return;
}
core.info(`Policy findings: ${findingsArray.length}`);
core.info(`Results URL: ${resultsUrl}`);
if (findingsArray.length === 0) {
core.info('No findings violates the policy, exiting and update the github check status to success');
// update inputs.check_run_id status to success
await updateChecks(
octokit,
checkStatic,
Checks.Conclusion.Success,
[],
`No policy violated findings, the full report can be found [here](${resultsUrl}).`,
);
return;
} else {
core.info('Findings violate the policy, exiting and update the github check status to failure');
// use octokit to check the language of the source repository. If it is a java project, then
// use octokit to check if the source repository is using java maven or java gradle
// if so, filePathPrefix = 'src/main/java/'
const repoResponse = await octokit.repos.get(ownership);
const language = repoResponse.data.language;
core.info(`Source repository language: ${language}`);
let javaMaven = false;
if (language === 'Java') {
let pomFileExists = false;
let gradleFileExists = false;
try {
await octokit.repos.getContent({ ...ownership, path: 'pom.xml' });
pomFileExists = true;
} catch (error) {
core.debug(`Error reading or parsing source repository:${error}`);
}
try {
await octokit.repos.getContent({ ...ownership, path: 'build.gradle' });
gradleFileExists = true;
} catch (error) {
core.debug(`Error reading or parsing source repository:${error}`);
}
if (pomFileExists || gradleFileExists) javaMaven = true;
}
// update inputs.check_run_id status to failure
const annotations = getAnnotations(findingsArray, javaMaven);
const maxNumberOfAnnotations = 50;
for (let index = 0; index < annotations.length / maxNumberOfAnnotations; index++) {
const annotationBatch = annotations.slice(index * maxNumberOfAnnotations, (index + 1) * maxNumberOfAnnotations);
if (annotationBatch.length > 0) {
await updateChecks(
octokit,
checkStatic,
inputs.fail_checks_on_policy ? Checks.Conclusion.Failure : Checks.Conclusion.Success,
annotationBatch,
`Here's the summary of the check result, the full report can be found [here](${resultsUrl}).`,
);
}
}
return;
}
}
function getAnnotations(policyFindings: VeracodePolicyResult.Finding[], javaMaven: boolean): Checks.Annotation[] {
const annotations: Checks.Annotation[] = [];
policyFindings.forEach(function (element) {
if (javaMaven) {
element.finding_details.file_path = `src/main/java/${element.finding_details.file_path}`;
if (element.finding_details.file_path.includes('WEB-INF'))
element.finding_details.file_path = element.finding_details.file_path.replace(
/src\/main\/java\//, // Use regular expression for precise replacement
'src/main/webapp/',
);
}
const displayMessage = element.description
.replace(/<span>/g, '')
.replace(/<\/span> /g, '\n')
.replace(/<\/span>/g, '');
let filePath = element.finding_details.file_path;
if (filePath.startsWith('/')) filePath = filePath.substring(1);
const message = `Filename: ${filePath}\nLine: ${element.finding_details.file_line_number}\nCWE: ${element.finding_details.cwe.id} (${element.finding_details.cwe.name})\n\n${displayMessage}`;
annotations.push({
path: `${filePath}`,
start_line: element.finding_details.file_line_number,
end_line: element.finding_details.file_line_number,
annotation_level: 'warning',
title: element.finding_details.cwe.name,
message: message,
});
});
return annotations;
}
export async function postScanReport(inputs: Inputs, policyFindings: VeracodePolicyResult.Finding[]): Promise<void> {
try {
if (inputs.vid.startsWith('vera01ei-')) {
return;
}
const getSelfUserDetailsResource = {
resourceUri: appConfig.api.veracode.selfUserUri,
queryAttribute: '',
queryValue: '',
};
const applicationResponse: VeracodeApplication.OrganizationData =
await http.getResourceByAttribute<VeracodeApplication.OrganizationData>(
inputs.vid,
inputs.vkey,
getSelfUserDetailsResource,
);
const commit_sha = inputs.head_sha;
const org_id = applicationResponse.organization.org_id;
let scan_id;
const source_repository = inputs.source_repository;
const repository_Url = inputs.gitRepositoryUrl;
for (let i = 0; i < policyFindings.length; i++) {
const element = policyFindings[i];
if (typeof element.build_id !== 'undefined') {
scan_id = '' + element.build_id;
break;
}
}
if (typeof scan_id !== 'undefined') {
const scanReport = JSON.stringify({
scm: 'GITHUB',
commitSha: commit_sha,
organizationId: org_id,
scanId: scan_id,
repositoryName: source_repository,
repositoryUrl: repository_Url,
});
await http.postResourceByAttribute(inputs.vid, inputs.vkey, scanReport);
}
} catch (error) {
core.debug(`Error posting scan report: ${error}`);
}
}