-
Notifications
You must be signed in to change notification settings - Fork 8k
/
exception_items_renderer.tsx
487 lines (445 loc) · 14.8 KB
/
exception_items_renderer.tsx
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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
/*
* 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 React, { useCallback, useEffect, useMemo, useReducer } from 'react';
import { EuiFlexGroup, EuiFlexItem, EuiSpacer } from '@elastic/eui';
import styled from 'styled-components';
import { HttpStart } from '@kbn/core/public';
import { addIdToItem } from '@kbn/securitysolution-utils';
import {
ExceptionListItemSchema,
ExceptionListType,
NamespaceType,
ListOperatorEnum as OperatorEnum,
ListOperatorTypeEnum as OperatorTypeEnum,
OsTypeArray,
entriesNested,
exceptionListItemSchema,
} from '@kbn/securitysolution-io-ts-list-types';
import {
CreateExceptionListItemBuilderSchema,
DataViewField,
ExceptionsBuilderExceptionItem,
ExceptionsBuilderReturnExceptionItem,
OperatorOption,
containsValueListEntry,
filterExceptionItems,
getDefaultEmptyEntry,
getDefaultNestedEmptyEntry,
getNewExceptionItem,
} from '@kbn/securitysolution-list-utils';
import { DataViewBase } from '@kbn/es-query';
import type { AutocompleteStart } from '@kbn/unified-search-plugin/public';
import { AndOrBadge } from '../and_or_badge';
import { BuilderExceptionListItemComponent } from './exception_item_renderer';
import { BuilderLogicButtons } from './logic_buttons';
import { getTotalErrorExist } from './selectors';
import { EntryFieldError, State, exceptionsBuilderReducer } from './reducer';
const MyInvisibleAndBadge = styled(EuiFlexItem)`
visibility: hidden;
`;
const MyAndBadge = styled(AndOrBadge)`
& > .euiFlexItem {
margin: 0;
}
`;
const MyButtonsContainer = styled(EuiFlexItem)`
margin: 16px 0;
`;
const initialState: State = {
addNested: false,
andLogicIncluded: false,
disableAnd: false,
disableNested: false,
disableOr: false,
errors: {},
exceptions: [],
exceptionsToDelete: [],
warningExists: 0,
};
export interface OnChangeProps {
errorExists: boolean;
exceptionItems: ExceptionsBuilderReturnExceptionItem[];
exceptionsToDelete: ExceptionListItemSchema[];
warningExists: boolean;
}
export interface ExceptionBuilderProps {
allowLargeValueLists: boolean;
autocompleteService: AutocompleteStart;
exceptionListItems: ExceptionsBuilderExceptionItem[];
httpService: HttpStart;
osTypes?: OsTypeArray;
indexPatterns: DataViewBase;
isAndDisabled: boolean;
isNestedDisabled: boolean;
isOrDisabled: boolean;
isOrHidden?: boolean;
listId: string | undefined;
listNamespaceType: NamespaceType | undefined;
listType: ExceptionListType;
listTypeSpecificIndexPatternFilter?: (
pattern: DataViewBase,
type: ExceptionListType
) => DataViewBase;
onChange: (arg: OnChangeProps) => void;
ruleName?: string;
isDisabled?: boolean;
operatorsList?: OperatorOption[];
exceptionItemName?: string;
allowCustomFieldOptions?: boolean;
getExtendedFields?: (fields: string[]) => Promise<DataViewField[]>;
}
export const ExceptionBuilderComponent = ({
allowLargeValueLists,
autocompleteService,
exceptionListItems,
httpService,
indexPatterns,
isAndDisabled,
isNestedDisabled,
isOrDisabled,
isOrHidden = false,
listId,
listNamespaceType,
listType,
listTypeSpecificIndexPatternFilter,
onChange,
ruleName,
exceptionItemName,
isDisabled = false,
osTypes,
operatorsList,
allowCustomFieldOptions = false,
getExtendedFields,
}: ExceptionBuilderProps): JSX.Element => {
const [state, dispatch] = useReducer(exceptionsBuilderReducer(), {
...initialState,
disableAnd: isAndDisabled,
disableNested: isNestedDisabled,
disableOr: isOrDisabled,
});
const {
addNested,
andLogicIncluded,
disableAnd,
disableNested,
disableOr,
warningExists,
exceptions,
exceptionsToDelete,
} = state;
const errorExists = getTotalErrorExist(state);
const setErrorsExist = useCallback(
(error: EntryFieldError): void => {
dispatch({
error,
type: 'setErrorsExist',
});
},
[dispatch]
);
const setWarningsExist = useCallback(
(hasWarnings: boolean): void => {
dispatch({
type: 'setWarningsExist',
warningExists: hasWarnings,
});
},
[dispatch]
);
const setUpdateExceptions = useCallback(
(items: ExceptionsBuilderExceptionItem[]): void => {
dispatch({
exceptions: items,
type: 'setExceptions',
});
},
[dispatch]
);
const setDefaultExceptions = useCallback(
(item: ExceptionsBuilderExceptionItem): void => {
dispatch({
initialState,
lastException: item,
type: 'setDefault',
});
},
[dispatch]
);
const setUpdateExceptionsToDelete = useCallback(
(items: ExceptionListItemSchema[]): void => {
dispatch({
exceptions: items,
type: 'setExceptionsToDelete',
});
},
[dispatch]
);
const setUpdateAndDisabled = useCallback(
(shouldDisable: boolean): void => {
dispatch({
shouldDisable,
type: 'setDisableAnd',
});
},
[dispatch]
);
const setUpdateOrDisabled = useCallback(
(shouldDisable: boolean): void => {
dispatch({
shouldDisable,
type: 'setDisableOr',
});
},
[dispatch]
);
const setUpdateAddNested = useCallback(
(shouldAddNested: boolean): void => {
dispatch({
addNested: shouldAddNested,
type: 'setAddNested',
});
},
[dispatch]
);
const handleExceptionItemChange = useCallback(
(item: ExceptionsBuilderExceptionItem, index: number): void => {
const updatedExceptions = [
...exceptions.slice(0, index),
{
...item,
},
...exceptions.slice(index + 1),
];
setUpdateExceptions(updatedExceptions);
},
[setUpdateExceptions, exceptions]
);
const handleDeleteExceptionItem = useCallback(
(item: ExceptionsBuilderExceptionItem, itemIndex: number): void => {
if (item.entries.length === 0) {
const updatedExceptions = [
...exceptions.slice(0, itemIndex),
...exceptions.slice(itemIndex + 1),
];
// if it's the only exception item left, don't delete it
// just add a default entry to it
if (updatedExceptions.length === 0) {
setDefaultExceptions(item);
} else if (updatedExceptions.length > 0 && exceptionListItemSchema.is(item)) {
setUpdateExceptionsToDelete([...exceptionsToDelete, item]);
} else {
setUpdateExceptions([
...exceptions.slice(0, itemIndex),
...exceptions.slice(itemIndex + 1),
]);
}
} else {
handleExceptionItemChange(item, itemIndex);
}
},
[
handleExceptionItemChange,
setUpdateExceptions,
setUpdateExceptionsToDelete,
exceptions,
exceptionsToDelete,
setDefaultExceptions,
]
);
const handleAddNewExceptionItemEntry = useCallback(
(isNested = false): void => {
const lastException = exceptions[exceptions.length - 1];
const { entries } = lastException;
const updatedException: ExceptionsBuilderExceptionItem = {
...lastException,
entries: [...entries, isNested ? getDefaultNestedEmptyEntry() : getDefaultEmptyEntry()],
};
setUpdateExceptions([...exceptions.slice(0, exceptions.length - 1), { ...updatedException }]);
},
[setUpdateExceptions, exceptions]
);
const handleAddNewExceptionItem = useCallback((): void => {
// There is a case where there are numerous exception list items, all with
// empty `entries` array. Thought about appending an entry item to one, but that
// would then be arbitrary, decided to just create a new exception list item
const newException = getNewExceptionItem({
listId,
name: exceptionItemName ?? `${ruleName ?? 'Rule'} - Exception item`,
namespaceType: listNamespaceType,
});
setUpdateExceptions([...exceptions, { ...newException }]);
}, [setUpdateExceptions, exceptions, listId, listNamespaceType, ruleName, exceptionItemName]);
// The builder can have existing exception items, or new exception items that have yet
// to be created (and thus lack an id), this was creating some React bugs with relying
// on the index, as a result, created a temporary id when new exception items are first
// instantiated that is stored in `meta` that gets stripped on it's way out
const getExceptionListItemId = (item: ExceptionsBuilderExceptionItem, index: number): string => {
if ((item as ExceptionListItemSchema).id != null) {
return (item as ExceptionListItemSchema).id;
} else if ((item as CreateExceptionListItemBuilderSchema).meta.temporaryUuid != null) {
return (item as CreateExceptionListItemBuilderSchema).meta.temporaryUuid;
} else {
return `${index}`;
}
};
const handleAddNestedExceptionItemEntry = useCallback((): void => {
const lastException = exceptions[exceptions.length - 1];
const { entries } = lastException;
const lastEntry = entries[entries.length - 1];
if (entriesNested.is(lastEntry)) {
const updatedException: ExceptionsBuilderExceptionItem = {
...lastException,
entries: [
...entries.slice(0, entries.length - 1),
{
...lastEntry,
entries: [
...lastEntry.entries,
addIdToItem({
field: '',
operator: OperatorEnum.INCLUDED,
type: OperatorTypeEnum.MATCH,
value: '',
}),
],
},
],
};
setUpdateExceptions([...exceptions.slice(0, exceptions.length - 1), { ...updatedException }]);
} else {
setUpdateExceptions(exceptions);
}
}, [setUpdateExceptions, exceptions]);
const handleAddNestedClick = useCallback((): void => {
setUpdateAddNested(true);
setUpdateOrDisabled(true);
setUpdateAndDisabled(true);
handleAddNewExceptionItemEntry(true);
}, [
handleAddNewExceptionItemEntry,
setUpdateAndDisabled,
setUpdateOrDisabled,
setUpdateAddNested,
]);
const handleAddClick = useCallback((): void => {
setUpdateAddNested(false);
setUpdateOrDisabled(false);
handleAddNewExceptionItemEntry();
}, [handleAddNewExceptionItemEntry, setUpdateOrDisabled, setUpdateAddNested]);
const memoExceptionItems = useMemo(() => {
return filterExceptionItems(exceptions);
}, [exceptions]);
// useEffect(() => {
// setUpdateExceptions([]);
// }, [osTypes, setUpdateExceptions]);
// Bubble up changes to parent
useEffect(() => {
onChange({
errorExists: errorExists > 0,
exceptionItems: memoExceptionItems,
exceptionsToDelete,
warningExists: warningExists > 0,
});
}, [onChange, exceptionsToDelete, memoExceptionItems, errorExists, warningExists]);
// Defaults builder to never be sans entry, instead
// always falls back to an empty entry if user deletes all
useEffect(() => {
if (
exceptions.length === 0 ||
(exceptions.length === 1 &&
exceptions[0].entries != null &&
exceptions[0].entries.length === 0)
) {
handleAddNewExceptionItem();
}
}, [exceptions, handleAddNewExceptionItem]);
useEffect(() => {
if (exceptionListItems.length > 0) {
setUpdateExceptions(exceptionListItems);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return (
<EuiFlexGroup gutterSize="s" direction="column" data-test-subj="exceptionsBuilderWrapper">
{exceptions.map((exceptionListItem, index) => (
<EuiFlexItem grow={1} key={getExceptionListItemId(exceptionListItem, index)}>
<EuiFlexGroup gutterSize="s" direction="column">
{index !== 0 &&
(andLogicIncluded ? (
<EuiFlexItem grow={false}>
<EuiFlexGroup gutterSize="none" direction="row">
<MyInvisibleAndBadge grow={false}>
<MyAndBadge includeAntennas type="and" />
</MyInvisibleAndBadge>
<EuiFlexItem grow={false}>
<MyAndBadge type="or" />
</EuiFlexItem>
</EuiFlexGroup>
</EuiFlexItem>
) : (
<EuiFlexItem grow={false}>
<MyAndBadge type="or" />
</EuiFlexItem>
))}
<EuiFlexItem grow={false}>
<BuilderExceptionListItemComponent
allowLargeValueLists={allowLargeValueLists}
andLogicIncluded={andLogicIncluded}
autocompleteService={autocompleteService}
exceptionItem={exceptionListItem}
exceptionItemIndex={index}
httpService={httpService}
indexPattern={indexPatterns}
isOnlyItem={exceptions.length === 1}
key={getExceptionListItemId(exceptionListItem, index)}
listType={listType}
listTypeSpecificIndexPatternFilter={listTypeSpecificIndexPatternFilter}
onChangeExceptionItem={handleExceptionItemChange}
onDeleteExceptionItem={handleDeleteExceptionItem}
onlyShowListOperators={containsValueListEntry(exceptions)}
setErrorsExist={setErrorsExist}
setWarningsExist={setWarningsExist}
osTypes={osTypes}
isDisabled={isDisabled}
operatorsList={operatorsList}
allowCustomOptions={allowCustomFieldOptions}
getExtendedFields={getExtendedFields}
/>
</EuiFlexItem>
</EuiFlexGroup>
</EuiFlexItem>
))}
<EuiSpacer size="m" />
<MyButtonsContainer data-test-subj={`andOrOperatorButtons`}>
<EuiFlexGroup gutterSize="s">
{andLogicIncluded && (
<MyInvisibleAndBadge grow={false}>
<AndOrBadge includeAntennas type="and" />
</MyInvisibleAndBadge>
)}
<EuiFlexItem grow={1}>
<BuilderLogicButtons
isOrDisabled={isOrDisabled ? isOrDisabled : disableOr}
isOrHidden={isOrHidden}
isAndDisabled={isAndDisabled ? isAndDisabled : disableAnd}
isNestedDisabled={isNestedDisabled ? isNestedDisabled : disableNested}
isNested={addNested}
showNestedButton
onOrClicked={handleAddNewExceptionItem}
onAndClicked={handleAddClick}
onNestedClicked={handleAddNestedClick}
onAddClickWhenNested={handleAddNestedExceptionItemEntry}
/>
</EuiFlexItem>
</EuiFlexGroup>
</MyButtonsContainer>
</EuiFlexGroup>
);
};
ExceptionBuilderComponent.displayName = 'ExceptionBuilder';
// eslint-disable-next-line import/no-default-export
export default ExceptionBuilderComponent;