-
Notifications
You must be signed in to change notification settings - Fork 226
Expand file tree
/
Copy pathsarif-processing.ts
More file actions
355 lines (306 loc) · 8.95 KB
/
sarif-processing.ts
File metadata and controls
355 lines (306 loc) · 8.95 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
import type {
Log,
PhysicalLocation,
Region,
ReportingDescriptor,
Result,
Run,
} from "sarif";
import type { SarifLink } from "../common/sarif-utils";
import {
parseHighlightedLine,
parseSarifPlainTextMessage,
parseSarifRegion,
} from "../common/sarif-utils";
import type {
AnalysisAlert,
AnalysisMessage,
AnalysisMessageLocationTokenLocation,
AnalysisMessageToken,
CodeFlow,
CodeSnippet,
HighlightedRegion,
ResultSeverity,
ThreadFlow,
} from "./shared/analysis-result";
import { getErrorMessage } from "../common/helpers-pure";
// A line of more than 8k characters is probably generated.
const CODE_SNIPPET_LARGE_LINE_SIZE_LIMIT = 8192;
// If less than 1% of the line is highlighted, we consider it a small snippet.
const CODE_SNIPPET_HIGHLIGHTED_REGION_MINIMUM_RATIO = 0.01;
const defaultSeverity = "Warning";
export function extractAnalysisAlerts(
sarifLog: Log,
fileLinkPrefix: string,
): {
alerts: AnalysisAlert[];
errors: string[];
} {
const alerts: AnalysisAlert[] = [];
const errors: string[] = [];
for (const run of sarifLog.runs ?? []) {
for (const result of run.results ?? []) {
try {
alerts.push(...extractResultAlerts(run, result, fileLinkPrefix));
} catch (e) {
errors.push(
`Error when processing SARIF result: ${getErrorMessage(e)}`,
);
continue;
}
}
}
return { alerts, errors };
}
function extractResultAlerts(
run: Run,
result: Result,
fileLinkPrefix: string,
): AnalysisAlert[] {
const alerts: AnalysisAlert[] = [];
const message = getMessage(result, fileLinkPrefix);
const rule = tryGetRule(run, result);
const severity = tryGetSeverity(run, result, rule) || defaultSeverity;
const codeFlows = getCodeFlows(result, fileLinkPrefix);
const shortDescription = getShortDescription(rule, message);
for (const location of result.locations ?? []) {
const physicalLocation = location.physicalLocation!;
const filePath = physicalLocation.artifactLocation!.uri!;
const codeSnippet = getCodeSnippet(
physicalLocation.contextRegion,
physicalLocation.region,
);
const highlightedRegion = physicalLocation.region
? getHighlightedRegion(physicalLocation.region)
: undefined;
const analysisAlert: AnalysisAlert = {
message,
shortDescription,
fileLink: {
fileLinkPrefix,
filePath,
},
severity,
codeSnippet,
highlightedRegion,
codeFlows,
};
alerts.push(analysisAlert);
}
return alerts;
}
function getShortDescription(
rule: ReportingDescriptor | undefined,
message: AnalysisMessage,
): string {
if (rule?.shortDescription?.text) {
return rule.shortDescription.text;
}
return message.tokens.map((token) => token.text).join("");
}
export function tryGetSeverity(
sarifRun: Run,
result: Result,
rule: ReportingDescriptor | undefined,
): ResultSeverity | undefined {
if (!sarifRun || !result || !rule) {
return undefined;
}
const severity = rule.properties?.["problem.severity"];
if (!severity) {
return undefined;
}
switch (severity.toLowerCase()) {
case "recommendation":
return "Recommendation";
case "warning":
return "Warning";
case "error":
return "Error";
}
return undefined;
}
export function tryGetRule(
sarifRun: Run,
result: Result,
): ReportingDescriptor | undefined {
if (!sarifRun || !result) {
return undefined;
}
const resultRule = result.rule;
if (!resultRule) {
return undefined;
}
// The rule can found in two places:
// - Either in the run's tool driver tool component
// - Or in the run's tool extensions tool component
const ruleId = resultRule.id;
if (ruleId) {
const rule = sarifRun.tool.driver.rules?.find((r) => r.id === ruleId);
if (rule) {
return rule;
}
}
const ruleIndex = resultRule.index;
if (ruleIndex !== undefined) {
const toolComponentIndex = result.rule?.toolComponent?.index;
const toolExtensions = sarifRun.tool.extensions;
if (toolComponentIndex !== undefined && toolExtensions !== undefined) {
const toolComponent = toolExtensions[toolComponentIndex];
if (toolComponent?.rules !== undefined) {
return toolComponent.rules[ruleIndex];
}
}
}
// Couldn't find the rule.
return undefined;
}
export function tryGetFilePath(
physicalLocation: PhysicalLocation,
): string | undefined {
const filePath = physicalLocation.artifactLocation?.uri;
// We expect the location uri value to be a relative file path, with no scheme.
// We only need to support output from CodeQL here, so we can be quite strict,
// even though the SARIF spec supports many more types of URI.
if (
filePath === undefined ||
filePath === "" ||
filePath.startsWith("file:")
) {
return undefined;
}
return filePath;
}
function getCodeSnippet(
contextRegion?: Region,
region?: Region,
): CodeSnippet | undefined {
const actualRegion = contextRegion ?? region;
if (!actualRegion) {
return undefined;
}
const text = actualRegion.snippet?.text || "";
const { startLine, endLine } = parseSarifRegion(actualRegion);
if (
contextRegion &&
region &&
text.length > CODE_SNIPPET_LARGE_LINE_SIZE_LIMIT
) {
const code = text.split("\n");
const highlightedRegion = parseSarifRegion(region);
const highlightedLines = code.map((line, index) => {
return parseHighlightedLine(line, startLine + index, highlightedRegion);
});
const highlightedCharactersCount = highlightedLines.reduce(
(a, line) => a + line.highlightedSection.length,
0,
);
const highlightedRatio = highlightedCharactersCount / text.length;
if (highlightedRatio < CODE_SNIPPET_HIGHLIGHTED_REGION_MINIMUM_RATIO) {
// If not enough is highlighted and the snippet is large, it's probably generated or bundled code and
// we don't want to show it.
return undefined;
}
}
return {
startLine,
endLine,
text,
};
}
function getHighlightedRegion(region: Region): HighlightedRegion {
const { startLine, startColumn, endLine, endColumn } =
parseSarifRegion(region);
return {
startLine,
startColumn,
endLine,
// parseSarifRegion currently shifts the end column by 1 to account
// for the way vscode counts columns so we need to shift it back.
endColumn: endColumn + 1,
};
}
function getCodeFlows(result: Result, fileLinkPrefix: string): CodeFlow[] {
const codeFlows = [];
if (result.codeFlows) {
for (const codeFlow of result.codeFlows) {
const threadFlows: ThreadFlow[] = [];
for (const threadFlow of codeFlow.threadFlows) {
for (const threadFlowLocation of threadFlow.locations) {
const physicalLocation =
threadFlowLocation.location!.physicalLocation!;
const filePath = tryGetFilePath(physicalLocation);
const codeSnippet = getCodeSnippet(
physicalLocation.contextRegion,
physicalLocation.region,
);
const highlightedRegion = physicalLocation.region
? getHighlightedRegion(physicalLocation.region)
: undefined;
if (filePath !== undefined) {
threadFlows.push({
fileLink: {
fileLinkPrefix,
filePath,
},
codeSnippet,
highlightedRegion,
});
}
}
}
codeFlows.push({ threadFlows } as CodeFlow);
}
}
return codeFlows;
}
function getMessage(result: Result, fileLinkPrefix: string): AnalysisMessage {
const tokens: AnalysisMessageToken[] = [];
const messageText = result.message.text!;
const messageParts = parseSarifPlainTextMessage(messageText);
for (const messagePart of messageParts) {
if (typeof messagePart === "string") {
tokens.push({ t: "text", text: messagePart });
} else {
const location = getRelatedLocation(messagePart, result, fileLinkPrefix);
if (location === undefined) {
tokens.push({ t: "text", text: messagePart.text });
} else {
tokens.push({
t: "location",
text: messagePart.text,
location,
});
}
}
}
return { tokens };
}
function getRelatedLocation(
messagePart: SarifLink,
result: Result,
fileLinkPrefix: string,
): AnalysisMessageLocationTokenLocation | undefined {
const relatedLocation = result.relatedLocations!.find(
(rl) => rl.id === messagePart.dest,
);
if (
relatedLocation === undefined ||
relatedLocation.physicalLocation?.artifactLocation?.uri === undefined ||
relatedLocation.physicalLocation?.artifactLocation?.uri?.startsWith(
"file:",
) ||
relatedLocation.physicalLocation?.region === undefined
) {
return undefined;
}
return {
fileLink: {
fileLinkPrefix,
filePath: relatedLocation.physicalLocation.artifactLocation.uri,
},
highlightedRegion: getHighlightedRegion(
relatedLocation.physicalLocation.region,
),
};
}