-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.tsx
More file actions
383 lines (327 loc) · 12.2 KB
/
Copy pathutils.tsx
File metadata and controls
383 lines (327 loc) · 12.2 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
import {CoveredEndpoint, FoundFault, WebFuzzingCommonsReport} from "@/types/GeneratedTypes.tsx";
import {ClassValue, clsx} from "clsx";
import {twMerge} from "tailwind-merge";
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
export const getColor = (code: string | number | null | undefined, isBackground: boolean, isFault: boolean) => {
if (isFault) {
return isBackground ? "bg-red-500" : "text-red-500";
}
if(code === null || code === undefined || code === "") {
return isBackground ? "bg-gray-500" : "text-gray-500";
}
if (typeof code === "number") {
return getColorNumber(code, isBackground);
}
return isBackground ? "bg-red-500" : "text-red-500";
}
const getColorNumber = (code: number, isBackground: boolean) => {
if (code >= 200 && code < 300) return isBackground ? "bg-green-500" : "text-green-500";
if (code >= 300 && code < 400) return isBackground ? "bg-blue-500" : "text-blue-500";
if (code >= 400 && code < 500) return isBackground ? "bg-orange-500" : "text-orange-500";
if (code >= 500) return isBackground ? "bg-red-500" : "text-red-500";
};
export const getHoverColor = (code: string | number | null | undefined, isFault: boolean): string => {
if (isFault) return "hover:bg-red-400";
if (code === null || code === undefined || code === "") return "hover:bg-gray-400";
const num = Number(code);
if (isNaN(num)) return "hover:bg-red-400";
if (num >= 200 && num < 300) return "hover:bg-green-600";
if (num >= 300 && num < 400) return "hover:bg-blue-600";
if (num >= 400 && num < 500) return "hover:bg-orange-600";
if (num >= 500) return "hover:bg-red-600";
return "hover:bg-gray-400";
};
export const fetchFileContent = async (filePath: string): Promise<string | object> => {
try {
const response = await fetch(filePath);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
if (filePath.endsWith('.json')) {
return await response.json() as object;
} else {
return await response.text();
}
} catch (error) {
console.error('Error fetching file:', error);
throw error;
}
}
export const extractCodeLines = (
fileContent: string,
startLine: number | undefined,
endLine: number | undefined
): string => {
const lines: string[] = fileContent.split('\n');
if(!startLine || !endLine){
return "";
}
const startIndex: number = Math.max(0, startLine);
const endIndex: number = Math.min(lines.length - 1, endLine - 1);
if (startIndex > endIndex) {
throw new Error('Start line cannot be greater than end line');
}
if (startIndex >= lines.length || endIndex >= lines.length) {
throw new Error('Line numbers are out of range');
}
return lines.slice(startIndex, endIndex + 2).join('\n');
};
export const extractComments = (code: string): string => {
const lines = code.split("\n");
const groups: string[] = [];
let current: string[] = [];
let inBlock = false;
const flush = () => {
if (current.length === 0) return;
const text = current.join("\n").trim();
if (text.length > 0) groups.push(text);
current = [];
};
for (const raw of lines) {
const trimmed = raw.trim();
if (inBlock) {
const endIdx = trimmed.indexOf("*/");
const body = (endIdx >= 0 ? trimmed.slice(0, endIdx) : trimmed).replace(/^\*+\s?/, "");
if (body.length > 0) current.push(body);
if (endIdx >= 0) {
inBlock = false;
flush();
}
continue;
}
if (trimmed.startsWith("/*")) {
const afterOpen = trimmed.replace(/^\/\*+\s?/, "");
const endIdx = afterOpen.indexOf("*/");
if (endIdx >= 0) {
const body = afterOpen.slice(0, endIdx).trim();
if (body) current.push(body);
flush();
} else {
inBlock = true;
if (afterOpen.length > 0) current.push(afterOpen);
}
continue;
}
const lineMatch = trimmed.match(/^(?:#|\/\/)\s?(.*)$/);
if (lineMatch) {
current.push(lineMatch[1]);
continue;
}
flush();
}
flush();
return groups.join("\n\n");
};
export const calculateAllStatusCounts = (coveredHttpStatus: CoveredEndpoint[], endpointIds:string[]) => {
const allStatusCounts ={
"NO_RESPONSE": 0,
"2XX": 0,
"3XX": 0,
"4XX": 0,
"5XX": 0
}
endpointIds.map(
(endpoint) => {
const allStatusCodes = coveredHttpStatus.filter(status => status.endpointId === endpoint)
.map(
(status) => status.httpStatus
).flat()
const uniqueStatusCodes = [...new Set(allStatusCodes)];
const isContainStatusCode = {
"NO_RESPONSE": false,
"2XX": false,
"3XX": false,
"4XX": false,
"5XX": false
}
uniqueStatusCodes.map(
(status) => {
if(status == null) {
isContainStatusCode["NO_RESPONSE"] = true;
}
else if (status >= 200 && status < 300) {
isContainStatusCode["2XX"] = true;
} else if (status >= 300 && status < 400) {
isContainStatusCode["3XX"] = true;
} else if (status >= 400 && status < 500) {
isContainStatusCode["4XX"] = true;
} else if (status >= 500 && status < 600) {
isContainStatusCode["5XX"] = true;
}
}
)
if(isContainStatusCode["NO_RESPONSE"]){
allStatusCounts["NO_RESPONSE"]++;
}
if (isContainStatusCode["2XX"]) {
allStatusCounts["2XX"]++;
}
if (isContainStatusCode["3XX"]) {
allStatusCounts["3XX"]++;
}
if (isContainStatusCode["4XX"]) {
allStatusCounts["4XX"]++;
}
if (isContainStatusCode["5XX"]) {
allStatusCounts["5XX"]++;
}
}
)
return allStatusCounts;
}
export const getFaultCounts = (foundFaults: FoundFault[], endpointIds?: string[]) => {
const faultCounts = new Map();
// A fault defines a unique operationId, code, and context. To define a unique fault, we can use a combination of these three properties.
foundFaults.forEach(fault => {
fault.faultCategories.forEach(category => {
faultCounts.set(`${fault.operationId}|${category.code}|${category.context}`, (faultCounts.get(category.code) || 0) + 1);
});
});
const uniqueFaults = Array.from(faultCounts.keys()).map(key => {
const [operationId, code, context] = key.split('|');
return {
operationId: operationId,
code: parseInt(code, 10),
context: context || '',
count: faultCounts.get(key)
};
});
const uniqueCodes = new Set(uniqueFaults.map(fault => fault.code));
return Array.from(uniqueCodes).map(code => {
const faultsWithCode = uniqueFaults.filter(fault => fault.code === code);
const uniqueOperations = new Set(faultsWithCode.map(fault => fault.operationId));
// Operations not declared in the schema must not skew the endpoint ratio,
// so they are reported separately instead of being counted in operationCount
const undeclaredOperationCount = endpointIds
? [...uniqueOperations].filter(operation => !endpointIds.includes(operation)).length
: 0;
return {
code: code,
count: faultsWithCode.length,
operationCount: uniqueOperations.size - undeclaredOperationCount,
undeclaredOperationCount: undeclaredOperationCount,
}
}).sort((a, b) => a.code - b.code);
}
export const getFileColor = (index: number, file: string) => {
const isFault = file.includes("fault");
const isSuccess = file.includes("success");
const isOthers = file.includes("other");
if(isFault) {
return "bg-red-500";
}
if(isSuccess) {
return "bg-green-500";
}
if(isOthers) {
return "bg-yellow-500";
}
const colorList = ["bg-blue-500", "bg-green-500", "bg-red-500", "bg-yellow-500", "bg-purple-500", "bg-pink-500"];
return colorList[index % colorList.length];
}
export const getLanguage = (fileName: string) => {
switch (fileName.split('.').pop()) {
case 'java':
return 'java';
case 'js':
return 'javascript';
case 'py':
return 'python';
case 'ts':
return 'typescript';
case 'kt':
return 'kotlin';
default:
return 'plaintext';
}
}
export interface ITransformedReport {
endpoint: string;
// false when the operation is not declared in the API schema (endpointIds),
// but faults were still detected on it (e.g. an undocumented OPTIONS handler)
declared: boolean;
faults: {
code: number;
testCases: string[];
}[];
httpStatusCodes: {
code: number;
testCases: string[];
}[];
}
export const transformWebFuzzingReport = (original: WebFuzzingCommonsReport | null): Array<ITransformedReport> => {
if (!original || !original.problemDetails || !original.problemDetails.rest) {
return [];
}
const endpointMap = new Map<string, ITransformedReport>();
original.problemDetails.rest?.endpointIds.forEach(endpoint => {
endpointMap.set(endpoint, {
endpoint,
declared: true,
httpStatusCodes: [],
faults: []
});
});
original.faults.foundFaults.forEach(fault => {
if (!fault.operationId) {
return;
}
if (!endpointMap.has(fault.operationId)) {
endpointMap.set(fault.operationId, {
endpoint: fault.operationId,
declared: false,
httpStatusCodes: [],
faults: []
});
}
const endpointData = endpointMap.get(fault.operationId);
if (!endpointData) {
return;
}
fault.faultCategories.forEach(faultCat => {
let existingFault = endpointData.faults.find((f: { code: number; }) => f.code === faultCat.code);
if (!existingFault) {
existingFault = {code: faultCat.code, testCases: []};
endpointData.faults.push(existingFault);
}
if (!existingFault.testCases.includes(fault.testCaseId)) {
existingFault.testCases.push(fault.testCaseId);
}
});
});
if (original.problemDetails.rest == null) {
return Array.from([]);
}
original.problemDetails.rest.coveredHttpStatus.forEach(status => {
if (!endpointMap.has(status.endpointId)) {
console.log(`Endpoint ${status.endpointId} not found in endpointIds`);
}
const endpointData = endpointMap.get(status.endpointId);
status.httpStatus?.forEach(code => {
if (!endpointData) {
return;
}
let existingStatus = endpointData.httpStatusCodes.find((s: { code: number; }) => s.code === code);
if (!existingStatus) {
if(code === null || code === undefined) {
code = -1;
}
existingStatus = {code, testCases: []};
endpointData.httpStatusCodes.push(existingStatus);
}
if (!existingStatus.testCases.includes(status.testCaseId)) {
existingStatus.testCases.push(status.testCaseId);
}
});
});
return Array.from(endpointMap.values());
}
export const getText = (
text: string,
params?: Record<string, string | number>): string => {
return Object.entries(params || {}).reduce((result, [param, value]) => {
return result.replace(`{${param}}`, String(value));
}, text);
}