-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathmain.ts
More file actions
307 lines (269 loc) · 10.8 KB
/
Copy pathmain.ts
File metadata and controls
307 lines (269 loc) · 10.8 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
import { getInput, getBooleanInput, info, setFailed } from "@actions/core";
import { exec } from "@actions/exec";
import { context as githubContext } from "@actions/github";
import { downloadTool } from "@actions/tool-cache";
import { readFileSync, chmodSync } from "fs";
const mayhemUrl: string =
getInput("mayhem-url") || "https://app.mayhem.security";
/**
* Operating systems that an mCode CLI is available for, mapped to the URL path it can be
* downloaded from on a recent Mayhem cluster.
*/
enum CliOsPath {
Linux = "Linux/mayhem",
MacOS = "Darwin/mayhem.pkg",
Windows = "Windows/mayhem.exe",
}
type Config = {
githubToken: string;
mayhemToken: string;
packagePath: string;
duration: string;
sarifOutputDir: string;
junitOutputDir: string;
coverageOutputDir: string;
failOnDefects: boolean;
verbosity: string;
owner: string;
project: string;
repo: string;
ciUrl: string;
branchName: string;
revision: string;
mergeBaseBranchName: string;
};
function getConfig(): Config {
const githubToken: string = getInput("github-token", {
required: true,
});
process.env["GITHUB_TOKEN"] = githubToken;
const issueNumber = githubContext.issue.number;
if (issueNumber) {
process.env["GITHUB_ISSUE_ID"] = String(issueNumber);
}
const repo = process.env["GITHUB_REPOSITORY"];
if (repo === undefined) {
throw Error(
"Missing GITHUB_REPOSITORY environment variable. " +
"Are you not running this in a Github Action environment?",
);
}
const ghRepo = `${process.env["GITHUB_SERVER_URL"]}:443/${repo}/`;
const eventPath = process.env["GITHUB_EVENT_PATH"] || "event.json";
const event = JSON.parse(readFileSync(eventPath, "utf-8")) || {};
const eventPullRequest = event.pull_request;
// Optional typed run duration (in seconds). When set it must be a positive
// integer; it takes precedence over any `--duration` passed via `args`.
const rawDuration = getInput("duration");
const duration = rawDuration
? validateDuration(rawDuration, "duration input")
: "";
return {
githubToken,
mayhemToken: getInput("mayhem-token") || githubToken,
packagePath: getInput("package") || ".",
duration,
sarifOutputDir: getInput("sarif-output") || "",
junitOutputDir: getInput("junit-output") || "",
coverageOutputDir: getInput("coverage-output") || "",
failOnDefects: getBooleanInput("fail-on-defects") || false,
verbosity: getInput("verbosity") || "info",
owner: getInput("owner").toLowerCase(),
project: (getInput("project") || repo).toLowerCase(),
repo,
ciUrl: `${ghRepo}/actions/runs/${process.env["GITHUB_RUN_ID"]}`,
branchName: eventPullRequest
? eventPullRequest.head.ref
: process.env["GITHUB_REF_NAME"]?.slice("refs/heads/".length) || "main",
revision: eventPullRequest
? eventPullRequest.head.sha
: process.env["GITHUB_SHA"] || "unknown",
mergeBaseBranchName: eventPullRequest ? eventPullRequest.base.ref : "main",
};
}
/**
* Validates a run duration (in seconds) and returns it in canonical form. A
* duration must be a positive integer; anything else (a decimal like "30.5", a
* suffix like "20m", zero, a missing value) is rejected, since the CLI would
* otherwise treat a malformed duration as an unbounded run. Leading zeros are
* stripped ("000000120" -> "120") so the CLI receives a clean value. Throws
* with a message naming `source` on invalid input.
* @param value the raw duration string to validate.
* @param source human-readable origin of the value, used in the error message.
* @return the duration normalized to its canonical decimal integer string.
*/
function validateDuration(value: string, source: string): string {
if (!/^\d+$/.test(value) || parseInt(value, 10) <= 0) {
throw Error(
`invalid duration '${value}' (${source}): ` +
"it must be a positive integer number of seconds.",
);
}
return String(parseInt(value, 10));
}
/**
* Downloads the mCode CLI from the given Mayhem cluster, marks it as executable, and returns the
* path to the downloaded CLI.
* @param url the base URL of the Mayhem cluster, such as "https://app.mayhem.security".
* @param os the operating system to download the CLI for.
* @return Path to the downloaded mCode CLI; resolves when the CLI download is complete.
*/
async function downloadCli(url: string, os: CliOsPath): Promise<string> {
// Download the CLI and mark it as executable.
const mcodePath = await downloadTool(`${url}/cli/${os}`);
chmodSync(mcodePath, 0o755);
return mcodePath;
}
/** Mapping action arguments to CLI arguments and completing a run */
async function run(): Promise<void> {
try {
// Validate the action inputs and create a Config object from them.
const config = getConfig();
// Download the mCode CLI for Linux.
const cli = await downloadCli(mayhemUrl, CliOsPath.Linux);
const args: string[] = (getInput("args") || "").split(" ");
// Resolve the effective run duration. Precedence:
// 1. the typed `duration` input,
// 2. a `--duration` passed inside `args`,
// 3. the documented default of 60 seconds.
const argsDurationIndex = args.indexOf("--duration");
if (config.duration) {
if (argsDurationIndex !== -1) {
// The typed input wins over a --duration smuggled through args.
args.splice(argsDurationIndex, 2, "--duration", config.duration);
} else {
args.push("--duration", config.duration);
}
info(`Duration: ${config.duration}s (from the 'duration' input).`);
} else if (argsDurationIndex !== -1) {
const argsDuration = validateDuration(
args[argsDurationIndex + 1] ?? "",
"--duration in args",
);
// Write the normalized value back so the CLI gets a clean duration.
args[argsDurationIndex + 1] = argsDuration;
info(`Duration: ${argsDuration}s (from '--duration' in 'args').`);
} else {
args.push("--duration", "60");
info("Duration: 60s (default).");
}
if (!args.includes("--image")) {
args.push("--image", "forallsecure/debian-buster:latest");
}
args.push("--ci-url", config.ciUrl);
args.push("--merge-base-branch-name", config.mergeBaseBranchName);
args.push("--branch-name", config.branchName);
args.push("--revision", config.revision);
const argsString = args.join(" ");
// Generate arguments for wait command
// sarif, junit, coverage
const waitArgs = [];
if (config.sarifOutputDir) {
// $runName is a variable that is set in the bash script
waitArgs.push("--sarif", `${config.sarifOutputDir}/\${runName}.sarif`);
}
if (config.junitOutputDir) {
// $runName is a variable that is set in the bash script
waitArgs.push("--junit", `${config.junitOutputDir}/\${runName}.xml`);
}
if (config.coverageOutputDir) {
waitArgs.push("--coverage");
}
if (config.failOnDefects) {
waitArgs.push("--fail-on-defects");
}
// create wait args string
const waitArgsString = waitArgs.join(" ");
const script = `
set -xe
# create sarif output directory
if [ -n "${config.sarifOutputDir}" ]; then
mkdir -p ${config.sarifOutputDir};
fi
# create junit output directory
if [ -n "${config.junitOutputDir}" ]; then
mkdir -p ${config.junitOutputDir};
fi
# create coverage output directory
if [ -n "${config.coverageOutputDir}" ]; then
mkdir -p ${config.coverageOutputDir};
fi
# Run mayhem
run=$(${cli} --verbosity ${config.verbosity} run ${config.packagePath} \
--project ${config.project} \
--owner ${config.owner} ${argsString});
# Persist the run id to the GitHub output
echo "runId=$run" >> $GITHUB_OUTPUT;
if [ -n "$run" ]; then
echo "Run $run succesfully scheduled.";
else
echo "Could not start run successfully, exiting with non-zero exit code.".
exit 1;
fi
# if the user didn't specify requiring any output, don't wait for the result.
if [ -z "${config.coverageOutputDir}" ] && \
[ -z "${config.junitOutputDir}" ] && \
[ -z "${config.sarifOutputDir}" ] && \
[ "${config.failOnDefects.toString().toLowerCase()}" != "true" ]; then
echo "No coverage, junit or sarif output requested, not waiting for job result.";
exit 0;
fi
# run name is the last part of the run id
runName="$(echo $run | awk -F / '{ print $(NF-1) }')";
# wait for run to finish
if ! ${cli} --verbosity ${config.verbosity} wait $run \
--owner ${config.owner} \
${waitArgsString}; then
exit 3;
fi
# check status, exit with non-zero status if failed or stopped
status=$(${cli} --verbosity ${config.verbosity} show \
--owner ${config.owner} \
--format json $run | jq '.[0].status');
if [[ $status == *"stopped"* || $status == *"failed"* ]]; then
exit 2;
fi
# Strip the run number from the full run path to get the project/target,
# and save the run number separately.
target=$(echo $run | sed 's:/[^/]*$::')
run_number=$(echo $run | sed 's:.*/::')
if [ -n "${config.coverageOutputDir}" ]; then
${cli} --verbosity ${config.verbosity} download --owner ${config.owner} --output ${config.coverageOutputDir} --run_number $run_number $target;
fi
`;
process.env["MAYHEM_TOKEN"] = config.mayhemToken;
process.env["MAYHEM_URL"] = mayhemUrl;
// Match the --owner/--project flags passed to `mayhem run` above, so the
// wait/show/download subcommands (which only get --owner explicitly)
// resolve the same project instead of falling back to the GitHub repo.
// `project` may already be a fully-qualified "owner/project" reference,
// in which case `owner` shouldn't be prepended again.
process.env["MAYHEM_PROJECT"] = config.project.includes("/")
? config.project
: `${config.owner}/${config.project}`;
// Start fuzzing
const cliRunning = exec("bash", ["-c", script], {
ignoreReturnCode: true,
});
const res = await cliRunning;
if (res === 1) {
throw new Error(`The Mayhem for Code scan was unable to execute the Mayhem run for your target.
Check your configuration. For package visibility/permissions issues, see
https://docs.github.com/en/packages/learn-github-packages/configuring-a-packages-access-control-and-visibility
on how to set your package to 'Public'.`);
} else if (res === 2) {
throw new Error(
"The Mayhem for Code scan detected the Mayhem run for your " +
"target was unsuccessful.",
);
} else if (res === 3) {
throw new Error("The Mayhem for Code scan found defects in your target.");
}
} catch (err: unknown) {
if (err instanceof Error) {
info(`mcode action failed with: ${err.message}`);
setFailed(err.message);
}
}
}
run();