-
Notifications
You must be signed in to change notification settings - Fork 8.3k
/
utils.ts
262 lines (241 loc) · 6.22 KB
/
utils.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
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
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
import Boom from '@hapi/boom';
import { has, snakeCase } from 'lodash/fp';
import { BadRequestError } from '@kbn/securitysolution-es-utils';
import { SanitizedAlert } from '../../../../../alerting/common';
import {
RouteValidationFunction,
KibanaResponseFactory,
CustomHttpResponseOptions,
} from '../../../../../../../src/core/server';
import { RulesClient } from '../../../../../alerting/server';
import { RuleStatusResponse, IRuleStatusSOAttributes } from '../rules/types';
import { RuleParams } from '../schemas/rule_schemas';
export interface OutputError {
message: string;
statusCode: number;
}
export interface BulkError {
id?: string;
rule_id?: string;
error: {
status_code: number;
message: string;
};
}
export const createBulkErrorObject = ({
ruleId,
id,
statusCode,
message,
}: {
ruleId?: string;
id?: string;
statusCode: number;
message: string;
}): BulkError => {
if (id != null && ruleId != null) {
return {
id,
rule_id: ruleId,
error: {
status_code: statusCode,
message,
},
};
} else if (id != null) {
return {
id,
error: {
status_code: statusCode,
message,
},
};
} else if (ruleId != null) {
return {
rule_id: ruleId,
error: {
status_code: statusCode,
message,
},
};
} else {
return {
rule_id: '(unknown id)',
error: {
status_code: statusCode,
message,
},
};
}
};
export interface ImportRegular {
rule_id: string;
status_code: number;
message?: string;
}
export type ImportRuleResponse = ImportRegular | BulkError;
export const isBulkError = (
importRuleResponse: ImportRuleResponse
): importRuleResponse is BulkError => {
return has('error', importRuleResponse);
};
export const isImportRegular = (
importRuleResponse: ImportRuleResponse
): importRuleResponse is ImportRegular => {
return !has('error', importRuleResponse) && has('status_code', importRuleResponse);
};
export const transformBulkError = (
ruleId: string,
err: Error & { statusCode?: number }
): BulkError => {
if (Boom.isBoom(err)) {
return createBulkErrorObject({
ruleId,
statusCode: err.output.statusCode,
message: err.message,
});
} else if (err instanceof BadRequestError) {
return createBulkErrorObject({
ruleId,
statusCode: 400,
message: err.message,
});
} else {
return createBulkErrorObject({
ruleId,
statusCode: err.statusCode ?? 500,
message: err.message,
});
}
};
interface Schema {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
validate: (input: any) => { value: any; error?: Error };
}
export const buildRouteValidation =
<T>(schema: Schema): RouteValidationFunction<T> =>
(payload: T, { ok, badRequest }) => {
const { value, error } = schema.validate(payload);
if (error) {
return badRequest(error.message);
}
return ok(value);
};
const statusToErrorMessage = (statusCode: number) => {
switch (statusCode) {
case 400:
return 'Bad Request';
case 401:
return 'Unauthorized';
case 403:
return 'Forbidden';
case 404:
return 'Not Found';
case 409:
return 'Conflict';
case 500:
return 'Internal Error';
default:
return '(unknown error)';
}
};
export class SiemResponseFactory {
constructor(private response: KibanaResponseFactory) {}
error<T>({ statusCode, body, headers }: CustomHttpResponseOptions<T>) {
const contentType: CustomHttpResponseOptions<T>['headers'] = {
'content-type': 'application/json',
};
const defaultedHeaders: CustomHttpResponseOptions<T>['headers'] = {
...contentType,
...(headers ?? {}),
};
return this.response.custom({
headers: defaultedHeaders,
statusCode,
body: Buffer.from(
JSON.stringify({
message: body ?? statusToErrorMessage(statusCode),
status_code: statusCode,
})
),
});
}
}
export const buildSiemResponse = (response: KibanaResponseFactory) =>
new SiemResponseFactory(response);
export const convertToSnakeCase = <T extends Record<string, unknown>>(
obj: T
): Partial<T> | null => {
if (!obj) {
return null;
}
return Object.keys(obj).reduce((acc, item) => {
const newKey = snakeCase(item);
return { ...acc, [newKey]: obj[item] };
}, {});
};
/**
*
* @param id rule id
* @param currentStatusAndFailures array of rule statuses where the 0th status is the current status and 1-5 positions are the historical failures
* @param acc accumulated rule id : statuses
*/
export const mergeStatuses = (
id: string,
currentStatusAndFailures: IRuleStatusSOAttributes[],
acc: RuleStatusResponse
): RuleStatusResponse => {
if (currentStatusAndFailures.length === 0) {
return {
...acc,
};
}
const convertedCurrentStatus = convertToSnakeCase<IRuleStatusSOAttributes>(
currentStatusAndFailures[0]
);
return {
...acc,
[id]: {
current_status: convertedCurrentStatus,
failures: currentStatusAndFailures
.slice(1)
.map((errorItem) => convertToSnakeCase<IRuleStatusSOAttributes>(errorItem)),
},
} as RuleStatusResponse;
};
export type GetFailingRulesResult = Record<string, SanitizedAlert<RuleParams>>;
export const getFailingRules = async (
ids: string[],
rulesClient: RulesClient
): Promise<GetFailingRulesResult> => {
try {
const errorRules = await Promise.all(
ids.map(async (id) =>
rulesClient.get({
id,
})
)
);
return errorRules
.filter((rule) => rule.executionStatus.status === 'error')
.reduce<GetFailingRulesResult>((acc, failingRule) => {
return {
[failingRule.id]: {
...failingRule,
},
...acc,
};
}, {});
} catch (exc) {
if (Boom.isBoom(exc)) {
throw exc;
}
throw new Error(`Failed to get executionStatus with RulesClient: ${(exc as Error).message}`);
}
};