-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathmain.ts
More file actions
246 lines (203 loc) · 9.23 KB
/
main.ts
File metadata and controls
246 lines (203 loc) · 9.23 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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
import * as core from '@actions/core';
import * as github from '@actions/github';
import { getScanStatus, startScan, getScanFindings } from './api';
import { getCurrentUnixTime, sleep } from './time';
import { postScanStatusMessage } from './postMessage';
import { postFindingsAsReviewComments } from './postReviewComment';
import { transformPostScanStatusAsComment } from './transformers/transformPostScanStatusAsComment';
import { transformPostFindingsAsReviewComment } from './transformers/transformPostFindingsAsReviewComment';
const STATUS_FAILED = 'FAILED';
const STATUS_SUCCEEDED = 'SUCCEEDED';
const STATUS_TIMED_OUT = 'TIMED_OUT';
const ALLOWED_POST_SCAN_STATUS_OPTIONS = ['on', 'off', 'only_if_new_findings'];
const ALLOWED_POST_REVIEW_COMMENTS_OPTIONS = ['on', 'off'];
async function run(): Promise<void> {
try {
const secretKey: string = core.getInput('secret-key');
const fromSeverity: string = core.getInput('minimum-severity');
const failOnTimeout: string = core.getInput('fail-on-timeout');
const failOnDependencyScan: string = core.getInput('fail-on-dependency-scan');
const failOnSastScan: string = core.getInput('fail-on-sast-scan');
const failOnIacScan: string = core.getInput('fail-on-iac-scan');
const timeoutInSeconds = parseTimeoutDuration(core.getInput('timeout-seconds'));
let postScanStatusAsComment = core.getInput('post-scan-status-comment');
let postReviewComments = core.getInput('post-sast-review-comments');
if (!['LOW', 'MEDIUM', 'HIGH', 'CRITICAL'].includes(fromSeverity.toUpperCase())) {
core.setOutput('output', STATUS_FAILED);
core.setFailed(`Invalid property value for minimum-severity. Allowed values are: LOW, MEDIUM, HIGH, CRITICAL`);
return;
}
postScanStatusAsComment = transformPostScanStatusAsComment(postScanStatusAsComment);
if (!ALLOWED_POST_SCAN_STATUS_OPTIONS.includes(postScanStatusAsComment)) {
core.setOutput('ouput', STATUS_FAILED);
core.setFailed(`Invalid property value for post-scan-status-comment. Allowed values are: ${ALLOWED_POST_SCAN_STATUS_OPTIONS.join(', ')}`);
return;
}
postReviewComments = transformPostFindingsAsReviewComment(postReviewComments);
if (!ALLOWED_POST_REVIEW_COMMENTS_OPTIONS.includes(postReviewComments)) {
core.setOutput('ouput', STATUS_FAILED);
core.setFailed(`Invalid property value for post-sast-review-comments. Allowed values are: ${ALLOWED_POST_SCAN_STATUS_OPTIONS.join(', ')}`);
return;
}
const isMergeGroupAction = !!github.context.payload?.merge_group;
const startScanPayload = {
version: '1.0.5',
branch_name: github.context.payload?.pull_request?.head?.ref || github.context.payload?.ref || (isMergeGroupAction && 'merge_group'),
repository_id: github.context.payload.repository?.node_id,
base_commit_id: github.context.payload?.pull_request?.base?.sha || github.context.payload?.before || github.context.payload?.merge_group?.base_sha,
head_commit_id: github.context.payload?.pull_request?.head?.sha || github.context.payload?.after || github.context.payload?.merge_group?.head_sha,
author:
github.context.payload?.pull_request?.user?.login ||
github.context.payload?.head_commit?.author?.username ||
github.context.payload?.merge_group?.head_commit?.author?.name,
pull_request_metadata: {
title: github.context.payload?.pull_request?.title,
url: github.context.payload?.pull_request?.html_url,
},
// user config
fail_on_dependency_scan: failOnDependencyScan,
fail_on_sast_scan: failOnSastScan,
fail_on_iac_scan: failOnIacScan,
minimum_severity: fromSeverity,
};
if (secretKey) {
const redactedToken = '********************' + secretKey.slice(-4);
core.info(`starting a scan with secret key: "${redactedToken}"`);
} else {
const isLikelyDependabotPr = (startScanPayload.branch_name ?? '').starts_with('dependabot/')
if (isLikelyDependabotPr) {
core.info(`it looks like the action is running on a dependabot PR, this means that secret variables are not available in this context and thus we can not start a scan. Please see: https://github.blog/changelog/2021-02-19-github-actions-workflows-triggered-by-dependabot-prs-will-run-with-read-only-permissions/`);
core.setOutput('outcome', STATUS_SUCCEEDED);
return;
}
core.info(`secret key not set.`);
}
if (failOnDependencyScan === 'false' && failOnIacScan === 'false' && failOnSastScan === 'false') {
core.setOutput('output', STATUS_FAILED);
core.setFailed(`You must enable at least one of the scans.`);
return;
}
const scanId = await startScan(secretKey, startScanPayload);
core.info(`successfully started a scan with id: "${scanId}"`);
const getScanCompletionStatus = getScanStatus(secretKey, scanId);
const expirationTimestamp = getCurrentUnixTime() + timeoutInSeconds * 1000;
let scanIsCompleted = false;
core.info('==== check if scan is completed ====');
do {
const result = await getScanCompletionStatus();
if (!result.all_scans_completed) {
core.info('==== scan is not yet completed, wait a few seconds ====');
await sleep(5000);
const dependencyScanTimeoutReached = getCurrentUnixTime() > expirationTimestamp;
if (dependencyScanTimeoutReached) {
if (failOnTimeout === 'true') {
core.setOutput('output', STATUS_FAILED);
core.setFailed(
`dependency scan reached time out: the scan did not complete within the set timeout`
);
return;
}
core.setOutput('output', STATUS_TIMED_OUT);
core.info(`dependency scan reached time out: the scan did not complete within the set timeout.`);
return;
}
continue;
}
scanIsCompleted = true;
let moreDetailsText = '';
if (result.diff_url) {
moreDetailsText = ` More details at ${result.diff_url}`;
}
let shouldPostComment = (postScanStatusAsComment === 'on' || postScanStatusAsComment === 'only_if_new_findings');
if (isMergeGroupAction) {
shouldPostComment = false; // no review comments in merge queue
}
if (shouldPostComment && !!result.outcome?.human_readable_message) {
try {
const options = { onlyIfNewFindings: postScanStatusAsComment === 'only_if_new_findings', hasNewFindings: !!result.gate_passed };
await postScanStatusMessage(result.outcome?.human_readable_message, options);
} catch (error) {
if (error instanceof Error) {
core.info(`unable to post scan status comment due to error: ${error.message}`);
} else {
core.info(`unable to post scan status comment due to unknown error`);
}
}
}
let shouldPostReviewComments = (postReviewComments === 'on');
if (isMergeGroupAction) {
shouldPostReviewComments = false; // no review comments in merge queue
}
if (shouldPostReviewComments) {
await createReviewComments(secretKey, scanId)
}
core.setOutput('scanResultUrl', result.diff_url);
const {
gate_passed = false,
new_issues_found = 0,
issue_links = [],
new_dependency_issues_found = 0,
new_iac_issues_found = 0,
new_sast_issues_found = 0,
} = result;
if (!gate_passed) {
for (const linkToIssue of issue_links) {
core.error(`New issue detected with severity >=${fromSeverity}. Check it out at: ${linkToIssue}`);
}
throw new Error(
`dependency scan completed: found ${new_issues_found} new issues with severity >=${fromSeverity}.${moreDetailsText}`
);
}
if (new_dependency_issues_found > 0) {
throw new Error(`${new_dependency_issues_found} new dependency issue(s) detected.${moreDetailsText}`);
}
if (new_iac_issues_found > 0) {
throw new Error(`${new_iac_issues_found} new IaC issue(s) detected.${moreDetailsText}`);
}
if (new_sast_issues_found > 0) {
throw new Error(`${new_sast_issues_found} new SAST issue(s) detected.${moreDetailsText}`);
}
core.info(
`==== scan is completed, no new issues with severity >=${fromSeverity} found.${moreDetailsText} ====`
);
} while (!scanIsCompleted);
core.setOutput('outcome', STATUS_SUCCEEDED);
} catch (error) {
core.setOutput('outcome', STATUS_FAILED);
if (error instanceof Error) core.setFailed(error.message);
}
}
async function createReviewComments(secretKey: string, scanId: number): Promise<void> {
try {
const findingResponse = await getScanFindings(secretKey, scanId)
const findings = findingResponse.introduced_sast_issues.map(finding => (
{
commit_id: findingResponse.end_commit_id,
path: finding.file,
line: finding.end_line,
start_line: finding.start_line,
body: `**${finding.title}**\n${finding.description}\n**Remediation:** ${finding.remediation}\n<sup>[View details in Aikido Security](https://app.aikido.dev/featurebranch/scan/${scanId}?groupId=${findingResponse.group_id})</sub>`
}
))
if (findings.length > 0) {
await postFindingsAsReviewComments(findings);
}
} catch (error) {
if (error instanceof Error) {
core.info(`unable to post review comments due to error: ${error.message}`);
} else {
core.info(`unable to post review comments due to unknown error`);
}
}
}
function parseTimeoutDuration(rawTimeoutInSeconds: string): number {
if (rawTimeoutInSeconds === '') return 120;
try {
return parseInt(rawTimeoutInSeconds, 10);
} catch (error) {
throw new Error(
`Invalid timeout provided. The provided timeout should be a valid number, but got: "${rawTimeoutInSeconds}"`
);
}
}
void run();