-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.ts
More file actions
569 lines (507 loc) · 17.5 KB
/
main.ts
File metadata and controls
569 lines (507 loc) · 17.5 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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
import core = require("@actions/core");
const fetch = require("node-fetch");
const glob = require("glob");
import FormData = require("form-data");
import fs = require("fs");
// Global constants
const maxUploadFiles: number = 3; // no more than 3 files can be uploaded at a time
const maxRetries: number = 3; // max number of uploads to retry
async function upload_step_init(dt_upload_api_key: string): Promise<Response> {
return await fetch("https://api.securetheorem.com/uploadapi/v1/upload_init", {
headers: {
Accept: "application/json",
Authorization: "APIKey " + dt_upload_api_key,
"Content-Type": "application/json",
},
method: "POST",
});
}
async function check_scan_status(
dt_results_api_key: string,
mobile_app_id: string,
scan_id: string,
): Promise<Response> {
return await fetch(
`https://api.securetheorem.com/apis/mobile_security/results/v2/mobile_apps/${mobile_app_id}/scans/${scan_id}`,
{
headers: {
Accept: "application/json",
Authorization: "APIKey " + dt_results_api_key,
},
method: "GET",
},
);
}
async function get_security_findings(
dt_results_api_key: string,
mobile_app_id: string,
results_since: string | null,
severity?: string,
): Promise<Response> {
const baseUrl =
"https://api.securetheorem.com/apis/mobile_security/results/v2/security_findings";
const params = new URLSearchParams({
mobile_app_id,
status_group: "OPEN",
});
if (results_since) {
params.append("results_since", results_since);
}
if (severity) {
params.append("severity", severity);
}
const url = `${baseUrl}?${params.toString()}`;
return await fetch(url, {
headers: {
Accept: "application/json",
Authorization: "APIKey " + dt_results_api_key,
},
method: "GET",
});
}
async function check_severity_findings(
dt_results_api_key: string,
mobile_app_id: string,
results_since: string,
severity_level: string,
check_scope: string,
): Promise<{ has_findings: boolean; total_count: number }> {
const severity_checks = {
HIGH: ["HIGH"],
MEDIUM: ["HIGH", "MEDIUM"],
LOW: ["HIGH", "MEDIUM", "LOW"],
};
const severities_to_check = severity_checks[severity_level.toUpperCase()];
if (!severities_to_check) {
throw new Error(`Invalid severity level: ${severity_level}`);
}
let total_findings = 0;
// Determine which results_since to use based on scope
const effective_results_since =
check_scope.toUpperCase() === "ALL_ISSUES" ? null : results_since;
for (const severity of severities_to_check) {
const findings_response = await get_security_findings(
dt_results_api_key,
mobile_app_id,
effective_results_since,
severity,
);
if (findings_response.status !== 200) {
throw new Error(
`Error fetching security findings for ${severity} severity: HTTP ${findings_response.status}`,
);
}
const findings_data = await findings_response.json();
const count =
parseInt(findings_data.pagination_information?.total_count, 10) || 0;
if (count === 0) {
console.log(
`Found ${count} ${severity} severity findings (results_since: ${effective_results_since})`,
);
}
total_findings += count;
}
if (total_findings > 0) {
return { has_findings: true, total_count: total_findings };
}
return { has_findings: false, total_count: 0 };
}
async function run() {
// Get inputs
// Mandatory
const dt_upload_api_key = core.getInput("DT_UPLOAD_API_KEY");
const input_binary_path = core.getInput("UPLOAD_BINARY_PATH");
const dt_results_api_key = core.getInput("DT_RESULTS_API_KEY");
// Optional
const sourcemap_file_path = core.getInput("SOURCEMAP_FILE_PATH");
const username = core.getInput("USERNAME");
const password = core.getInput("PASSWORD");
const comments = core.getInput("COMMENTS");
const release_id = core.getInput("RELEASE_ID");
const platform_variant = core.getInput("PLATFORM_VARIANT");
const external_id = core.getInput("EXTERNAL_ID");
const block_on_severity = core.getInput("BLOCK_ON_SEVERITY");
const warn_on_severity = core.getInput("WARN_ON_SEVERITY");
const polling_timeout = core.getInput("POLLING_TIMEOUT");
const wait_for_static_scan_only = core.getInput("WAIT_FOR_STATIC_SCAN_ONLY");
const severity_check_scope =
core.getInput("SEVERITY_CHECK_SCOPE") || "CURRENT_SCAN";
var parsed_polling_timeout;
if (polling_timeout) {
parsed_polling_timeout = parseInt(polling_timeout, 10);
if (isNaN(parsed_polling_timeout)) {
throw new Error("POLLING_TIMEOUT must be a number");
}
if (parsed_polling_timeout <= 0) {
throw new Error("POLLING_TIMEOUT must be greater than 0");
}
}
// Validate severity levels
if (
block_on_severity &&
!["HIGH", "MEDIUM", "LOW"].includes(block_on_severity.toUpperCase())
) {
throw new Error("BLOCK_ON_SEVERITY must be one of: HIGH, MEDIUM, LOW");
}
if (
warn_on_severity &&
!["HIGH", "MEDIUM", "LOW"].includes(warn_on_severity.toUpperCase())
) {
throw new Error("WARN_ON_SEVERITY must be one of: HIGH, MEDIUM, LOW");
}
if (
!["CURRENT_SCAN", "ALL_ISSUES"].includes(severity_check_scope.toUpperCase())
) {
throw new Error(
"SEVERITY_CHECK_SCOPE must be one of: CURRENT_SCAN, ALL_ISSUES",
);
}
// Mask the sensitive fields
core.setSecret(dt_upload_api_key);
core.setSecret(dt_results_api_key);
core.setSecret(password);
// Check that the inputs are set
if (!dt_upload_api_key) {
throw new Error("DT_UPLOAD_API_KEY must be set!");
}
if (!input_binary_path) {
throw new Error("UPLOAD_BINARY_PATH must be set!");
}
if (block_on_severity && !dt_results_api_key) {
throw new Error(
"DT_RESULTS_API_KEY must be set when BLOCK_ON_SEVERITY is enabled!",
);
}
if (warn_on_severity && !dt_results_api_key) {
throw new Error(
"DT_RESULTS_API_KEY must be set when WARN_ON_SEVERITY is enabled!",
);
}
const files = glob.sync(input_binary_path);
if (!files.length) {
throw new Error(
`Did not find any files that match path: ${input_binary_path}`,
);
}
if (files.length > maxUploadFiles) {
throw new Error(
`Too many files (${files.length}) match the provided glob pattern; please write a more restrictive pattern to match no more than ${maxUploadFiles} files.`,
);
}
console.log(`Found ${files.length} files to upload.`);
// Upload all the files that matched the file path
let file_idx: number = 1;
let output: Array<any> = [];
let upload_ids: Array<string> = [];
let scan_info: Array<{ mobile_app_id: string; scan_id: string }> = [];
for (const file_path of files) {
if (!fs.existsSync(file_path)) {
throw new Error(`Could not access file: ${file_path}`);
}
console.log(
`Processing file ${file_path} (${file_idx} of ${files.length}).`,
);
const form = new FormData();
form.append("file", fs.createReadStream(file_path));
if (sourcemap_file_path) {
if (!fs.existsSync(sourcemap_file_path)) {
throw new Error(`Could not access file: ${sourcemap_file_path}`);
}
try {
form.append("sourcemap", fs.createReadStream(sourcemap_file_path));
} catch (err) {
core.setFailed(err);
return;
}
}
// only append optional fields if explicitly set
if (username) {
form.append("username", username);
console.log(`DAST username set to: ${username}`);
}
if (password) {
form.append("password", password);
console.log("DAST password is set to: (hidden)");
}
if (comments) {
form.append("comments", comments);
console.log(`Comments are set to: ${comments}`);
}
if (release_id) {
form.append("release_Id", release_id);
console.log(`Release ID is set to: ${release_id}`);
}
if (platform_variant) {
form.append("platform_variant", platform_variant);
console.log(`Platform variant is set to: ${platform_variant}`);
}
if (external_id) {
form.append("external_id", external_id);
console.log(`External ID is set to: ${external_id}`);
}
// retry upload maxRetries times
for (let loop_idx = 0; loop_idx < maxRetries; loop_idx++) {
// Send the auth request to get the upload URL
const auth_response = await upload_step_init(dt_upload_api_key);
let auth_json;
try {
auth_json = await auth_response.json();
} catch (err) {
core.setFailed(err);
}
if (auth_response.status !== 200) {
// handles auth failure
core.setFailed(auth_json);
break;
}
// Send the scan request with file
console.log("Starting upload...");
const response = await fetch(auth_json.upload_url, {
method: "POST",
body: form,
});
console.log("Finished upload.");
let jsonformat;
try {
jsonformat = await response.json();
} catch (err) {
core.setFailed(err);
}
output.push(jsonformat);
console.log(`Response: HTTP/${response.status}`);
console.log(jsonformat);
// Check the response
// If we receive 409 (ownership conflict) or if this is the last try, bail out
if (response.status === 200) {
if (jsonformat.upload_id) {
upload_ids.push(jsonformat.upload_id);
}
if (jsonformat.mobile_app_id && jsonformat.scan_id) {
scan_info.push({
mobile_app_id: jsonformat.mobile_app_id,
scan_id: jsonformat.scan_id,
});
}
break;
}
if (response.status === 409) {
core.setFailed(jsonformat);
break;
}
if (loop_idx == maxRetries - 1) {
core.setFailed(jsonformat);
}
}
file_idx++;
}
// Check for vulnerabilities if BLOCK_ON_SEVERITY or WARN_ON_SEVERITY is set
if ((!block_on_severity && !warn_on_severity) || scan_info.length === 0) {
core.setOutput("responses", output);
core.setOutput("response", output[0]); // keep the `response` output as the response of the first file upload to maintain compatibility
return;
}
if (block_on_severity) {
console.log(
`Checking for vulnerabilities with minimum severity: ${block_on_severity}`,
);
}
if (warn_on_severity) {
console.log(
`Warning on vulnerabilities with minimum severity: ${warn_on_severity}`,
);
}
if (wait_for_static_scan_only === "true") {
console.log(
"WAIT_FOR_STATIC_SCAN_ONLY is enabled: will wait for static_scan completion",
);
}
if (severity_check_scope.toUpperCase() === "ALL_ISSUES") {
console.log(
"SEVERITY_CHECK_SCOPE is set to ALL_ISSUES: checking all open issues in the mobile app",
);
} else {
console.log(
"SEVERITY_CHECK_SCOPE is set to CURRENT_SCAN: checking only issues from the current scan",
);
}
for (const scan of scan_info) {
const { mobile_app_id, scan_id } = scan;
var maxWaitTime = 300000; // 5 minutes
if (parsed_polling_timeout) {
maxWaitTime = parsed_polling_timeout * 1000;
}
// Poll for scan completion with 23-second intervals
const pollInterval = 23000; // 23 seconds
const startTime = Date.now();
let status_data: any = null;
let scan_completed = false;
let scan_failed = false;
while (Date.now() - startTime < maxWaitTime) {
try {
const status_response = await check_scan_status(
dt_results_api_key,
mobile_app_id,
scan_id,
);
if (status_response.status === 401 || status_response.status === 403) {
console.log(
`Authentication error checking scan status for ${scan_id}: HTTP ${status_response.status}. Please check your DT_RESULTS_API_KEY credentials.`,
);
process.exit(1);
}
if (status_response.status !== 200) {
console.log(
`Error checking scan status for ${scan_id}: HTTP ${status_response.status}`,
);
await new Promise((resolve) => setTimeout(resolve, pollInterval));
continue;
}
status_data = await status_response.json();
// Check status based on WAIT_FOR_STATIC_SCAN_ONLY parameter
let scan_status;
if (wait_for_static_scan_only === "true") {
if (status_data.static_scan?.status) {
scan_status = status_data.static_scan.status;
} else {
console.log(
`static_scan field not available for scan ${scan_id}, falling back to overall scan status`,
);
scan_status = status_data.status;
}
} else {
scan_status = status_data.status;
}
if (
scan_status &&
["FAILED", "SCAN_ATTEMPT_ERROR", "CANCELLED"].includes(scan_status)
) {
console.log(`Scan ${scan_id} failed, skipping vulnerability check`);
break;
}
if (scan_status !== "COMPLETED") {
console.log(
`Scan ${scan_id} still in progress (current status: ${scan_status}), waiting...`,
);
await new Promise((resolve) => setTimeout(resolve, pollInterval));
continue;
}
console.log(`Scan ${scan_id} completed`);
scan_completed = true;
break;
} catch (error) {
console.log(
`Error checking scan status for ${scan_id}: ${error.message}`,
);
await new Promise((resolve) => setTimeout(resolve, pollInterval));
}
}
if (Date.now() - startTime >= maxWaitTime) {
console.log(`Timeout waiting for scan results for scan ${scan_id}`);
}
// Check for security findings with retry logic (max 3 attempts)
const maxAttempts = 3;
const retryInterval = 5000; // 5 seconds
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
if (
scan_failed &&
severity_check_scope.toUpperCase() === "CURRENT_SCAN"
) {
// Skip findings check if scan failed in CURRENT_SCAN mode
break;
}
try {
let results_since: string;
if (severity_check_scope.toUpperCase() === "ALL_ISSUES") {
results_since = "";
} else {
if (!status_data || !status_data.start_date) {
console.log(`No start_date found in scan data for ${scan_id}`);
break;
}
results_since = status_data.start_date;
}
// Check for blocking vulnerabilities first
if (block_on_severity) {
const { has_findings, total_count } = await check_severity_findings(
dt_results_api_key,
mobile_app_id,
results_since,
block_on_severity,
severity_check_scope,
);
if (has_findings) {
const scope_description =
severity_check_scope.toUpperCase() === "ALL_ISSUES"
? "in the mobile app"
: "in this scan";
console.log(
`Found ${total_count} security findings ${scope_description} at or above ${block_on_severity} severity level`,
);
core.setFailed(
`Build blocked due to ${total_count} security findings ${scope_description} at or above ${block_on_severity} severity level`,
);
return;
}
const scope_description =
severity_check_scope.toUpperCase() === "ALL_ISSUES"
? "in the mobile app"
: `for scan ${scan_id}`;
console.log(
`No security findings found at or above ${block_on_severity} severity level ${scope_description}`,
);
}
// Check for warning vulnerabilities
if (warn_on_severity) {
const { has_findings, total_count } = await check_severity_findings(
dt_results_api_key,
mobile_app_id,
results_since,
warn_on_severity,
severity_check_scope,
);
if (has_findings) {
const scope_description =
severity_check_scope.toUpperCase() === "ALL_ISSUES"
? "in the mobile app"
: `for scan ${scan_id}`;
console.log(
`⚠️ WARNING: Found ${total_count} security findings ${scope_description} at or above ${warn_on_severity} severity level`,
);
console.log(
`⚠️ These findings do not block the build, but should be reviewed and addressed.`,
);
} else {
const scope_description =
severity_check_scope.toUpperCase() === "ALL_ISSUES"
? "in the mobile app"
: `for scan ${scan_id}`;
console.log(
`No security findings found at or above ${warn_on_severity} severity level ${scope_description}`,
);
}
}
// Successfully checked findings, exit retry loop
break;
} catch (error) {
console.log(
`Error checking security findings for ${scan_id} (attempt ${attempt}/${maxAttempts}): ${error.message}`,
);
if (attempt < maxAttempts) {
console.log(`Retrying in ${retryInterval / 1000} seconds...`);
await new Promise((resolve) => setTimeout(resolve, retryInterval));
} else {
console.log(
`Failed to check security findings after ${maxAttempts} attempts`,
);
}
}
}
}
core.setOutput("responses", output);
core.setOutput("response", output[0]); // keep the `response` output as the response of the first file upload to maintain compatibility
}
try {
run();
} catch (err) {
core.setFailed(err.message);
}