/
common.ts
201 lines (186 loc) · 6.3 KB
/
common.ts
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
import { GitHubAdvisoryId } from "audit-types";
import { SpawnOptionsWithoutStdio } from "child_process";
import { spawn } from "cross-spawn";
import escapeStringRegexp from "escape-string-regexp";
import * as eventStream from "event-stream";
import * as JSONStream from "JSONStream";
import ReadlineTransform from "readline-transform";
import { blue, yellow } from "./colors";
import { AuditCiConfig } from "./config";
import { Summary } from "./model";
export function partition<T>(a: T[], fun: (parameter: T) => boolean) {
const returnValue: { truthy: T[]; falsy: T[] } = { truthy: [], falsy: [] };
for (const item of a) {
if (fun(item)) {
returnValue.truthy.push(item);
} else {
returnValue.falsy.push(item);
}
}
return returnValue;
}
export function reportAudit(summary: Summary, config: AuditCiConfig) {
const {
allowlist,
"show-not-found": showNotFound,
"show-found": showFound,
"output-format": outputFormat,
} = config;
const {
allowlistedModulesFound,
allowlistedAdvisoriesFound,
allowlistedModulesNotFound,
allowlistedAdvisoriesNotFound,
allowlistedPathsNotFound,
failedLevelsFound,
advisoriesFound,
advisoryPathsFound,
} = summary;
if (outputFormat === "text") {
if (allowlist.modules.length > 0) {
console.log(
blue,
`Modules to allowlist: ${allowlist.modules.join(", ")}.`
);
}
if (showFound) {
if (allowlistedModulesFound.length > 0) {
const found = allowlistedModulesFound.join(", ");
console.warn(yellow, `Found vulnerable allowlisted modules: ${found}.`);
}
if (allowlistedAdvisoriesFound.length > 0) {
const found = allowlistedAdvisoriesFound.join(", ");
console.warn(
yellow,
`Found vulnerable allowlisted advisories: ${found}.`
);
}
}
if (showNotFound) {
if (allowlistedModulesNotFound.length > 0) {
const found = allowlistedModulesNotFound
.sort((a, b) => a.localeCompare(b))
.join(", ");
const allowlistMessage =
allowlistedModulesNotFound.length === 1
? `Consider not allowlisting module: ${found}.`
: `Consider not allowlisting modules: ${found}.`;
console.warn(yellow, allowlistMessage);
}
if (allowlistedAdvisoriesNotFound.length > 0) {
const found = allowlistedAdvisoriesNotFound
.sort((a, b) => a.localeCompare(b))
.join(", ");
const allowlistMessage =
allowlistedAdvisoriesNotFound.length === 1
? `Consider not allowlisting advisory: ${found}.`
: `Consider not allowlisting advisories: ${found}.`;
console.warn(yellow, allowlistMessage);
}
if (allowlistedPathsNotFound.length > 0) {
const found = allowlistedPathsNotFound
.sort((a, b) => a.localeCompare(b))
.join(", ");
const allowlistMessage =
allowlistedPathsNotFound.length === 1
? `Consider not allowlisting path: ${found}.`
: `Consider not allowlisting paths: ${found}.`;
console.warn(yellow, allowlistMessage);
}
}
if (advisoryPathsFound.length > 0) {
const found = advisoryPathsFound.join("\n");
console.warn(yellow, `Found vulnerable advisory paths:`);
console.log(found);
}
}
if (failedLevelsFound.length > 0) {
// Get the levels that have failed by filtering the keys with true values
throw new Error(
`Failed security audit due to ${failedLevelsFound.join(
", "
)} vulnerabilities.\nVulnerable advisories are:\n${advisoriesFound
.map((element) => gitHubAdvisoryIdToUrl(element))
.join("\n")}`
);
}
return summary;
}
function hasMessage(value: unknown): value is { message: unknown } {
return typeof value === "object" && value != undefined && "message" in value;
}
function hasStatusCode(
value: unknown
): value is { statusCode: unknown; message: unknown } {
return (
typeof value === "object" && value != undefined && "statusCode" in value
);
}
export function runProgram(
command: string,
arguments_: readonly string[],
options: SpawnOptionsWithoutStdio,
stdoutListener,
stderrListener
) {
const transform = new ReadlineTransform({ skipEmpty: true });
const proc = spawn(command, arguments_, options);
proc.stdout.setEncoding("utf8");
proc.stdout
.pipe(transform)
// TODO: Review this JSONStream.parse()
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
.pipe(JSONStream.parse())
.pipe(
eventStream.mapSync((data: unknown) => {
if (!data) return;
try {
// due to response without error
if (
hasMessage(data) &&
typeof data.message === "string" &&
data.message.includes("ENOTFOUND")
) {
stderrListener(data.message);
return;
}
// TODO: There are no tests that cover this case, not sure when this happens.
if (hasStatusCode(data) && data.statusCode === 404) {
stderrListener(data.message);
return;
}
stdoutListener(data);
} catch (error) {
stderrListener(error);
}
})
);
return new Promise<void>((resolve, reject) => {
proc.on("close", () => resolve());
proc.on("error", (error) => reject(error));
});
}
function wildcardToRegex(stringWithWildcard: string) {
const regexString = stringWithWildcard
.split(/\*+/) // split at every wildcard (*) character
.map((s) => escapeStringRegexp(s)) // escape the substrings to make sure that they aren't evaluated
.join(".*"); // construct a regex matching anything at each wildcard location
return new RegExp(`^${regexString}$`);
}
export function matchString(template: string, string_: string) {
return template.includes("*")
? wildcardToRegex(template).test(string_)
: template === string_;
}
export function isGitHubAdvisoryId(id: string): id is GitHubAdvisoryId {
return id.startsWith("GHSA");
}
export function gitHubAdvisoryUrlToAdvisoryId(url: string): GitHubAdvisoryId {
return url.split("/")[4] as GitHubAdvisoryId;
}
export function gitHubAdvisoryIdToUrl<T extends string>(
id: T
): `https://github.com/advisories/${T}` {
return `https://github.com/advisories/${id}`;
}