-
Notifications
You must be signed in to change notification settings - Fork 8k
/
index.tsx
611 lines (573 loc) · 22.6 KB
/
index.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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
/* eslint-disable complexity */
// TODO: Disabling complexity is temporary till this component is refactored as part of lists UI integration
import {
EuiLoadingSpinner,
EuiFlexGroup,
EuiFlexItem,
EuiSpacer,
EuiTab,
EuiTabs,
EuiToolTip,
EuiWindowEvent,
} from '@elastic/eui';
import { FormattedMessage } from '@kbn/i18n/react';
import { noop } from 'lodash/fp';
import React, { FC, memo, useCallback, useEffect, useMemo, useState } from 'react';
import { useParams, useHistory } from 'react-router-dom';
import { connect, ConnectedProps } from 'react-redux';
import { useKibana } from '../../../../../common/lib/kibana';
import { TimelineId } from '../../../../../../common/types/timeline';
import { UpdateDateRange } from '../../../../../common/components/charts/common';
import { FiltersGlobal } from '../../../../../common/components/filters_global';
import { FormattedDate } from '../../../../../common/components/formatted_date';
import {
getEditRuleUrl,
getRulesUrl,
getDetectionEngineUrl,
} from '../../../../../common/components/link_to/redirect_to_detection_engine';
import { SiemSearchBar } from '../../../../../common/components/search_bar';
import { WrapperPage } from '../../../../../common/components/wrapper_page';
import { Rule } from '../../../../containers/detection_engine/rules';
import { useListsConfig } from '../../../../containers/detection_engine/lists/use_lists_config';
import { SpyRoute } from '../../../../../common/utils/route/spy_routes';
import { StepAboutRuleToggleDetails } from '../../../../components/rules/step_about_rule_details';
import { DetectionEngineHeaderPage } from '../../../../components/detection_engine_header_page';
import { AlertsHistogramPanel } from '../../../../components/alerts_histogram_panel';
import { AlertsTable } from '../../../../components/alerts_table';
import { useUserData } from '../../../../components/user_info';
import { OverviewEmpty } from '../../../../../overview/components/overview_empty';
import { useAlertInfo } from '../../../../components/alerts_info';
import { StepDefineRule } from '../../../../components/rules/step_define_rule';
import { StepScheduleRule } from '../../../../components/rules/step_schedule_rule';
import {
buildAlertsRuleIdFilter,
buildShowBuildingBlockFilter,
} from '../../../../components/alerts_table/default_config';
import { NoWriteAlertsCallOut } from '../../../../components/no_write_alerts_callout';
import * as detectionI18n from '../../translations';
import { ReadOnlyCallOut } from '../../../../components/rules/read_only_callout';
import { RuleSwitch } from '../../../../components/rules/rule_switch';
import { StepPanel } from '../../../../components/rules/step_panel';
import { getStepsData, redirectToDetections, userHasNoPermissions } from '../helpers';
import * as ruleI18n from '../translations';
import * as i18n from './translations';
import { useGlobalTime } from '../../../../../common/containers/use_global_time';
import { alertsHistogramOptions } from '../../../../components/alerts_histogram_panel/config';
import { inputsSelectors } from '../../../../../common/store/inputs';
import { State } from '../../../../../common/store';
import { InputsRange } from '../../../../../common/store/inputs/model';
import { setAbsoluteRangeDatePicker as dispatchSetAbsoluteRangeDatePicker } from '../../../../../common/store/inputs/actions';
import { RuleActionsOverflow } from '../../../../components/rules/rule_actions_overflow';
import { RuleStatusFailedCallOut } from './status_failed_callout';
import { FailureHistory } from './failure_history';
import { RuleStatus } from '../../../../components/rules//rule_status';
import { useMlCapabilities } from '../../../../../common/components/ml/hooks/use_ml_capabilities';
import { hasMlAdminPermissions } from '../../../../../../common/machine_learning/has_ml_admin_permissions';
import { hasMlLicense } from '../../../../../../common/machine_learning/has_ml_license';
import { SecurityPageName } from '../../../../../app/types';
import { LinkButton } from '../../../../../common/components/links';
import { useFormatUrl } from '../../../../../common/components/link_to';
import { ExceptionsViewer } from '../../../../../common/components/exceptions/viewer';
import { DEFAULT_INDEX_PATTERN } from '../../../../../../common/constants';
import { useFullScreen } from '../../../../../common/containers/use_full_screen';
import { Display } from '../../../../../hosts/pages/display';
import { ExceptionListTypeEnum, ExceptionListIdentifiers } from '../../../../../shared_imports';
import { isThresholdRule } from '../../../../../../common/detection_engine/utils';
import { useRuleAsync } from '../../../../containers/detection_engine/rules/use_rule_async';
import { showGlobalFilters } from '../../../../../timelines/components/timeline/helpers';
import { timelineSelectors } from '../../../../../timelines/store/timeline';
import { timelineDefaults } from '../../../../../timelines/store/timeline/defaults';
import { TimelineModel } from '../../../../../timelines/store/timeline/model';
import { useSourcererScope } from '../../../../../common/containers/sourcerer';
import { SourcererScopeName } from '../../../../../common/store/sourcerer/model';
import {
getToolTipContent,
canEditRuleWithActions,
isBoolean,
} from '../../../../../common/utils/privileges';
import { AlertsHistogramOption } from '../../../../components/alerts_histogram_panel/types';
enum RuleDetailTabs {
alerts = 'alerts',
failures = 'failures',
exceptions = 'exceptions',
}
const getRuleDetailsTabs = (rule: Rule | null) => {
const canUseExceptions = rule && !isThresholdRule(rule.type);
return [
{
id: RuleDetailTabs.alerts,
name: detectionI18n.ALERT,
disabled: false,
dataTestSubj: 'alertsTab',
},
{
id: RuleDetailTabs.exceptions,
name: i18n.EXCEPTIONS_TAB,
disabled: !canUseExceptions,
dataTestSubj: 'exceptionsTab',
},
{
id: RuleDetailTabs.failures,
name: i18n.FAILURE_HISTORY_TAB,
disabled: false,
dataTestSubj: 'failureHistoryTab',
},
];
};
export const RuleDetailsPageComponent: FC<PropsFromRedux> = ({
filters,
graphEventId,
query,
setAbsoluteRangeDatePicker,
}) => {
const { to, from, deleteQuery, setQuery } = useGlobalTime();
const [
{
loading: userInfoLoading,
isSignalIndexExists,
isAuthenticated,
hasEncryptionKey,
canUserCRUD,
hasIndexWrite,
signalIndexName,
},
] = useUserData();
const {
loading: listsConfigLoading,
needsConfiguration: needsListsConfiguration,
} = useListsConfig();
const loading = userInfoLoading || listsConfigLoading;
const { detailName: ruleId } = useParams<{ detailName: string }>();
const { rule: maybeRule, refresh: refreshRule, loading: ruleLoading } = useRuleAsync(ruleId);
const [rule, setRule] = useState<Rule | null>(null);
const isLoading = ruleLoading && rule == null;
// This is used to re-trigger api rule status when user de/activate rule
const [ruleEnabled, setRuleEnabled] = useState<boolean | null>(null);
const [ruleDetailTab, setRuleDetailTab] = useState(RuleDetailTabs.alerts);
const { aboutRuleData, modifiedAboutRuleDetailsData, defineRuleData, scheduleRuleData } =
rule != null
? getStepsData({ rule, detailsView: true })
: {
aboutRuleData: null,
modifiedAboutRuleDetailsData: null,
defineRuleData: null,
scheduleRuleData: null,
};
const [lastAlerts] = useAlertInfo({ ruleId });
const [showBuildingBlockAlerts, setShowBuildingBlockAlerts] = useState(false);
const mlCapabilities = useMlCapabilities();
const history = useHistory();
const { formatUrl } = useFormatUrl(SecurityPageName.detections);
const { globalFullScreen } = useFullScreen();
// TODO: Refactor license check + hasMlAdminPermissions to common check
const hasMlPermissions = hasMlLicense(mlCapabilities) && hasMlAdminPermissions(mlCapabilities);
const ruleDetailTabs = getRuleDetailsTabs(rule);
const {
services: {
application: {
capabilities: { actions },
},
},
} = useKibana();
const hasActionsPrivileges = useMemo(() => {
if (rule?.actions != null && rule?.actions.length > 0 && isBoolean(actions.show)) {
return actions.show;
}
return true;
}, [actions, rule?.actions]);
// persist rule until refresh is complete
useEffect(() => {
if (maybeRule != null) {
setRule(maybeRule);
}
}, [maybeRule]);
const title = rule?.name ?? <EuiLoadingSpinner size="m" />;
const subTitle = useMemo(
() =>
rule == null ? (
<EuiLoadingSpinner size="m" />
) : (
[
<FormattedMessage
id="xpack.securitySolution.detectionEngine.ruleDetails.ruleCreationDescription"
defaultMessage="Created by: {by} on {date}"
values={{
by: rule?.created_by ?? i18n.UNKNOWN,
date: (
<FormattedDate
value={rule?.created_at ?? new Date().toISOString()}
fieldName="createdAt"
/>
),
}}
/>,
rule?.updated_by != null ? (
<FormattedMessage
id="xpack.securitySolution.detectionEngine.ruleDetails.ruleUpdateDescription"
defaultMessage="Updated by: {by} on {date}"
values={{
by: rule?.updated_by ?? i18n.UNKNOWN,
date: (
<FormattedDate
value={rule?.updated_at ?? new Date().toISOString()}
fieldName="updatedAt"
/>
),
}}
/>
) : (
''
),
]
),
[rule]
);
// Set showBuildingBlockAlerts if rule is a Building Block Rule otherwise we won't show alerts
useEffect(() => {
setShowBuildingBlockAlerts(rule?.building_block_type != null);
}, [rule]);
const alertDefaultFilters = useMemo(
() => [
...(ruleId != null ? buildAlertsRuleIdFilter(ruleId) : []),
...buildShowBuildingBlockFilter(showBuildingBlockAlerts),
],
[ruleId, showBuildingBlockAlerts]
);
const alertMergedFilters = useMemo(() => [...alertDefaultFilters, ...filters], [
alertDefaultFilters,
filters,
]);
const tabs = useMemo(
() => (
<EuiTabs>
{ruleDetailTabs.map((tab) => (
<EuiTab
onClick={() => setRuleDetailTab(tab.id)}
isSelected={tab.id === ruleDetailTab}
disabled={tab.disabled}
key={tab.id}
data-test-subj={tab.dataTestSubj}
>
{tab.name}
</EuiTab>
))}
</EuiTabs>
),
[ruleDetailTabs, ruleDetailTab, setRuleDetailTab]
);
const ruleError = useMemo(
() =>
rule?.status === 'failed' &&
ruleDetailTab === RuleDetailTabs.alerts &&
rule?.last_failure_at != null ? (
<RuleStatusFailedCallOut
message={rule?.last_failure_message ?? ''}
date={rule?.last_failure_at}
/>
) : null,
[rule, ruleDetailTab]
);
const updateDateRangeCallback = useCallback<UpdateDateRange>(
({ x }) => {
if (!x) {
return;
}
const [min, max] = x;
setAbsoluteRangeDatePicker({
id: 'global',
from: new Date(min).toISOString(),
to: new Date(max).toISOString(),
});
},
[setAbsoluteRangeDatePicker]
);
const handleOnChangeEnabledRule = useCallback(
(enabled: boolean) => {
if (ruleEnabled == null || enabled !== ruleEnabled) {
setRuleEnabled(enabled);
}
},
[ruleEnabled, setRuleEnabled]
);
const goToEditRule = useCallback(
(ev) => {
ev.preventDefault();
history.push(getEditRuleUrl(ruleId ?? ''));
},
[history, ruleId]
);
const editRule = useMemo(() => {
if (!hasActionsPrivileges) {
return (
<EuiToolTip position="top" content={ruleI18n.EDIT_RULE_SETTINGS_TOOLTIP}>
<LinkButton
onClick={goToEditRule}
iconType="controlsHorizontal"
isDisabled={true}
href={formatUrl(getEditRuleUrl(ruleId ?? ''))}
>
{ruleI18n.EDIT_RULE_SETTINGS}
</LinkButton>
</EuiToolTip>
);
}
return (
<LinkButton
onClick={goToEditRule}
iconType="controlsHorizontal"
isDisabled={userHasNoPermissions(canUserCRUD) ?? true}
href={formatUrl(getEditRuleUrl(ruleId ?? ''))}
>
{ruleI18n.EDIT_RULE_SETTINGS}
</LinkButton>
);
}, [canUserCRUD, formatUrl, goToEditRule, hasActionsPrivileges, ruleId]);
const onShowBuildingBlockAlertsChangedCallback = useCallback(
(newShowBuildingBlockAlerts: boolean) => {
setShowBuildingBlockAlerts(newShowBuildingBlockAlerts);
},
[setShowBuildingBlockAlerts]
);
const { indicesExist, indexPattern } = useSourcererScope(SourcererScopeName.detections);
const exceptionLists = useMemo((): {
lists: ExceptionListIdentifiers[];
allowedExceptionListTypes: ExceptionListTypeEnum[];
} => {
if (rule != null && rule.exceptions_list != null) {
return rule.exceptions_list.reduce<{
lists: ExceptionListIdentifiers[];
allowedExceptionListTypes: ExceptionListTypeEnum[];
}>(
(acc, { id, list_id: listId, namespace_type: namespaceType, type }) => {
const { allowedExceptionListTypes, lists } = acc;
const shouldAddEndpoint =
type === ExceptionListTypeEnum.ENDPOINT &&
!allowedExceptionListTypes.includes(ExceptionListTypeEnum.ENDPOINT);
return {
lists: [...lists, { id, listId, namespaceType, type }],
allowedExceptionListTypes: shouldAddEndpoint
? [...allowedExceptionListTypes, ExceptionListTypeEnum.ENDPOINT]
: allowedExceptionListTypes,
};
},
{ lists: [], allowedExceptionListTypes: [ExceptionListTypeEnum.DETECTION] }
);
} else {
return { lists: [], allowedExceptionListTypes: [ExceptionListTypeEnum.DETECTION] };
}
}, [rule]);
if (
redirectToDetections(
isSignalIndexExists,
isAuthenticated,
hasEncryptionKey,
needsListsConfiguration
)
) {
history.replace(getDetectionEngineUrl());
return null;
}
const defaultRuleStackByOption: AlertsHistogramOption = {
text: 'event.category',
value: 'event.category',
};
return (
<>
{hasIndexWrite != null && !hasIndexWrite && <NoWriteAlertsCallOut />}
{userHasNoPermissions(canUserCRUD) && <ReadOnlyCallOut />}
{indicesExist ? (
<>
<EuiWindowEvent event="resize" handler={noop} />
<FiltersGlobal show={showGlobalFilters({ globalFullScreen, graphEventId })}>
<SiemSearchBar id="global" indexPattern={indexPattern} />
</FiltersGlobal>
<WrapperPage noPadding={globalFullScreen}>
<Display show={!globalFullScreen}>
<DetectionEngineHeaderPage
backOptions={{
href: getRulesUrl(),
text: i18n.BACK_TO_RULES,
pageId: SecurityPageName.detections,
}}
border
subtitle={subTitle}
subtitle2={[
...(lastAlerts != null
? [
<>
{detectionI18n.LAST_ALERT}
{': '}
{lastAlerts}
</>,
]
: []),
<RuleStatus ruleId={ruleId ?? null} ruleEnabled={ruleEnabled} />,
]}
title={title}
>
<EuiFlexGroup alignItems="center">
<EuiFlexItem grow={false}>
<EuiToolTip
position="top"
content={getToolTipContent(rule, hasMlPermissions, hasActionsPrivileges)}
>
<RuleSwitch
id={rule?.id ?? '-1'}
isDisabled={
!canEditRuleWithActions(rule, hasActionsPrivileges) ||
userHasNoPermissions(canUserCRUD) ||
(!hasMlPermissions && !rule?.enabled)
}
enabled={rule?.enabled ?? false}
optionLabel={i18n.ACTIVATE_RULE}
onChange={handleOnChangeEnabledRule}
/>
</EuiToolTip>
</EuiFlexItem>
<EuiFlexItem grow={false}>
<EuiFlexGroup alignItems="center" gutterSize="s" responsive={false}>
<EuiFlexItem grow={false}>{editRule}</EuiFlexItem>
<EuiFlexItem grow={false}>
<RuleActionsOverflow
rule={rule}
userHasNoPermissions={userHasNoPermissions(canUserCRUD)}
canDuplicateRuleWithActions={canEditRuleWithActions(
rule,
hasActionsPrivileges
)}
/>
</EuiFlexItem>
</EuiFlexGroup>
</EuiFlexItem>
</EuiFlexGroup>
</DetectionEngineHeaderPage>
{ruleError}
<EuiSpacer />
<EuiFlexGroup>
<EuiFlexItem data-test-subj="aboutRule" component="section" grow={1}>
<StepAboutRuleToggleDetails
loading={isLoading}
stepData={aboutRuleData}
stepDataDetails={modifiedAboutRuleDetailsData}
/>
</EuiFlexItem>
<EuiFlexItem grow={1}>
<EuiFlexGroup direction="column">
<EuiFlexItem component="section" grow={1}>
<StepPanel loading={isLoading} title={ruleI18n.DEFINITION}>
{defineRuleData != null && (
<StepDefineRule
descriptionColumns="singleSplit"
isReadOnlyView={true}
isLoading={false}
defaultValues={defineRuleData}
/>
)}
</StepPanel>
</EuiFlexItem>
<EuiSpacer />
<EuiFlexItem data-test-subj="schedule" component="section" grow={1}>
<StepPanel loading={isLoading} title={ruleI18n.SCHEDULE}>
{scheduleRuleData != null && (
<StepScheduleRule
descriptionColumns="singleSplit"
isReadOnlyView={true}
isLoading={false}
defaultValues={scheduleRuleData}
/>
)}
</StepPanel>
</EuiFlexItem>
</EuiFlexGroup>
</EuiFlexItem>
</EuiFlexGroup>
<EuiSpacer />
{tabs}
<EuiSpacer />
</Display>
{ruleDetailTab === RuleDetailTabs.alerts && (
<>
<Display show={!globalFullScreen}>
<AlertsHistogramPanel
deleteQuery={deleteQuery}
filters={alertMergedFilters}
query={query}
from={from}
signalIndexName={signalIndexName}
setQuery={setQuery}
stackByOptions={alertsHistogramOptions}
defaultStackByOption={defaultRuleStackByOption}
to={to}
updateDateRange={updateDateRangeCallback}
/>
<EuiSpacer />
</Display>
{ruleId != null && (
<AlertsTable
timelineId={TimelineId.detectionsRulesDetailsPage}
canUserCRUD={canUserCRUD ?? false}
defaultFilters={alertDefaultFilters}
hasIndexWrite={hasIndexWrite ?? false}
from={from}
loading={loading}
showBuildingBlockAlerts={showBuildingBlockAlerts}
onShowBuildingBlockAlertsChanged={onShowBuildingBlockAlertsChangedCallback}
onRuleChange={refreshRule}
to={to}
/>
)}
</>
)}
{ruleDetailTab === RuleDetailTabs.exceptions && (
<ExceptionsViewer
ruleId={ruleId ?? ''}
ruleName={rule?.name ?? ''}
ruleIndices={rule?.index ?? DEFAULT_INDEX_PATTERN}
availableListTypes={exceptionLists.allowedExceptionListTypes}
commentsAccordionId={'ruleDetailsTabExceptions'}
exceptionListsMeta={exceptionLists.lists}
onRuleChange={refreshRule}
/>
)}
{ruleDetailTab === RuleDetailTabs.failures && <FailureHistory id={rule?.id} />}
</WrapperPage>
</>
) : (
<WrapperPage>
<DetectionEngineHeaderPage border title={i18n.PAGE_TITLE} />
<OverviewEmpty />
</WrapperPage>
)}
<SpyRoute pageName={SecurityPageName.detections} state={{ ruleName: rule?.name }} />
</>
);
};
RuleDetailsPageComponent.displayName = 'RuleDetailsPageComponent';
const makeMapStateToProps = () => {
const getGlobalInputs = inputsSelectors.globalSelector();
const getTimeline = timelineSelectors.getTimelineByIdSelector();
return (state: State) => {
const globalInputs: InputsRange = getGlobalInputs(state);
const { query, filters } = globalInputs;
const timeline: TimelineModel =
getTimeline(state, TimelineId.detectionsRulesDetailsPage) ?? timelineDefaults;
const { graphEventId } = timeline;
return {
query,
filters,
graphEventId,
};
};
};
const mapDispatchToProps = {
setAbsoluteRangeDatePicker: dispatchSetAbsoluteRangeDatePicker,
};
const connector = connect(makeMapStateToProps, mapDispatchToProps);
type PropsFromRedux = ConnectedProps<typeof connector>;
export const RuleDetailsPage = connector(memo(RuleDetailsPageComponent));
RuleDetailsPage.displayName = 'RuleDetailsPage';