Skip to content

Commit

Permalink
[SIEM] [Detection Engine] Update status on rule details page (#55201)
Browse files Browse the repository at this point in the history
* adds logic for returning / updating status when a rule is switched from enabled to disabled and vice versa.

* update response for find rules statuses to include current status and failures

* update status on demand and on enable/disable

* adds ternary to allow removal of 'let'

* adds savedObjectsClient to the add and upate prepackaged rules and import rules route.

* fix bug where convertToSnakeCase would throw error 'cannot convert null or undefined to object' if passed null

* genericize snake_case converter and updates isAuthorized to snake_case (different situation)

* renaming to 'going to run' instead of executing because when task manager exits because of api key error it won't write the error status so the actual status is 'going to run' on the next interval. This is more accurate than being stuck on 'executing' because of an error we don't control and can't write a status for.

* fix missed merge conflict

Co-authored-by: Xavier Mouligneau <189600+XavierM@users.noreply.github.com>
  • Loading branch information
dhurley14 and XavierM committed Jan 18, 2020
1 parent 8ae51ab commit 9567cca
Show file tree
Hide file tree
Showing 25 changed files with 310 additions and 112 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -322,7 +322,7 @@ export const getRuleStatusById = async ({
}: {
id: string;
signal: AbortSignal;
}): Promise<Record<string, RuleStatus[]>> => {
}): Promise<Record<string, RuleStatus>> => {
const response = await fetch(
`${chrome.getBasePath()}${DETECTION_ENGINE_RULES_STATUS}?ids=${encodeURIComponent(
JSON.stringify([id])
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,4 @@ export * from './persist_rule';
export * from './types';
export * from './use_rule';
export * from './use_rules';
export * from './use_rule_status';
Original file line number Diff line number Diff line change
Expand Up @@ -181,9 +181,15 @@ export interface ExportRulesProps {
}

export interface RuleStatus {
current_status: RuleInfoStatus;
failures: RuleInfoStatus[];
}

export type RuleStatusType = 'executing' | 'failed' | 'going to run' | 'succeeded';
export interface RuleInfoStatus {
alert_id: string;
status_date: string;
status: string;
status: RuleStatusType | null;
last_failure_at: string | null;
last_success_at: string | null;
last_failure_message: string | null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,16 @@
* you may not use this file except in compliance with the Elastic License.
*/

import { useEffect, useState } from 'react';
import { useEffect, useRef, useState } from 'react';

import { useStateToaster } from '../../../components/toasters';
import { errorToToaster } from '../../../components/ml/api/error_to_toaster';
import { getRuleStatusById } from './api';
import * as i18n from './translations';
import { RuleStatus } from './types';

type Return = [boolean, RuleStatus[] | null];
type Func = (ruleId: string) => void;
type Return = [boolean, RuleStatus | null, Func | null];

/**
* Hook for using to get a Rule from the Detection Engine API
Expand All @@ -21,15 +22,16 @@ type Return = [boolean, RuleStatus[] | null];
*
*/
export const useRuleStatus = (id: string | undefined | null): Return => {
const [ruleStatus, setRuleStatus] = useState<RuleStatus[] | null>(null);
const [ruleStatus, setRuleStatus] = useState<RuleStatus | null>(null);
const fetchRuleStatus = useRef<Func | null>(null);
const [loading, setLoading] = useState(true);
const [, dispatchToaster] = useStateToaster();

useEffect(() => {
let isSubscribed = true;
const abortCtrl = new AbortController();

async function fetchData(idToFetch: string) {
const fetchData = async (idToFetch: string) => {
try {
setLoading(true);
const ruleStatusResponse = await getRuleStatusById({
Expand All @@ -49,15 +51,16 @@ export const useRuleStatus = (id: string | undefined | null): Return => {
if (isSubscribed) {
setLoading(false);
}
}
};
if (id != null) {
fetchData(id);
}
fetchRuleStatus.current = fetchData;
return () => {
isSubscribed = false;
abortCtrl.abort();
};
}, [id]);

return [loading, ruleStatus];
return [loading, ruleStatus, fetchRuleStatus.current];
};
Original file line number Diff line number Diff line change
Expand Up @@ -96,5 +96,5 @@ export interface Privilege {
write: boolean;
};
};
isAuthenticated: boolean;
is_authenticated: boolean;
}
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ export const usePrivilegeUser = (): Return => {
});

if (isSubscribed && privilege != null) {
setAuthenticated(privilege.isAuthenticated);
setAuthenticated(privilege.is_authenticated);
if (privilege.index != null && Object.keys(privilege.index).length > 0) {
const indexName = Object.keys(privilege.index)[0];
setHasIndexManage(privilege.index[indexName].manage);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import { FormattedDate } from '../../../../components/formatted_date';
import { RuleSwitch } from '../components/rule_switch';
import { SeverityBadge } from '../components/severity_badge';
import { ActionToaster } from '../../../../components/toasters';
import { getStatusColor } from '../components/rule_status/helpers';

const getActions = (
dispatch: React.Dispatch<Action>,
Expand Down Expand Up @@ -113,19 +114,11 @@ export const getColumns = (
field: 'status',
name: i18n.COLUMN_LAST_RESPONSE,
render: (value: TableData['status']) => {
const color =
value == null
? 'subdued'
: value === 'succeeded'
? 'success'
: value === 'failed'
? 'danger'
: value === 'executing'
? 'warning'
: 'subdued';
return (
<>
<EuiHealth color={color}>{value ?? getEmptyTagValue()}</EuiHealth>
<EuiHealth color={getStatusColor(value ?? null)}>
{value ?? getEmptyTagValue()}
</EuiHealth>
</>
);
},
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/*
* 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.
*/

import { RuleStatusType } from '../../../../../containers/detection_engine/rules';

export const getStatusColor = (status: RuleStatusType | string | null) =>
status == null
? 'subdued'
: status === 'succeeded'
? 'success'
: status === 'failed'
? 'danger'
: status === 'executing' || status === 'going to run'
? 'warning'
: 'subdued';
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
/*
* 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.
*/

import {
EuiButtonIcon,
EuiFlexGroup,
EuiFlexItem,
EuiHealth,
EuiLoadingSpinner,
EuiText,
} from '@elastic/eui';
import { isEqual } from 'lodash/fp';
import React, { memo, useCallback, useEffect, useState } from 'react';

import { useRuleStatus, RuleInfoStatus } from '../../../../../containers/detection_engine/rules';
import { FormattedDate } from '../../../../../components/formatted_date';
import { getEmptyTagValue } from '../../../../../components/empty_value';
import { getStatusColor } from './helpers';
import * as i18n from './translations';

interface RuleStatusProps {
ruleId: string | null;
ruleEnabled?: boolean | null;
}

const RuleStatusComponent: React.FC<RuleStatusProps> = ({ ruleId, ruleEnabled }) => {
const [loading, ruleStatus, fetchRuleStatus] = useRuleStatus(ruleId);
const [myRuleEnabled, setMyRuleEnabled] = useState<boolean | null>(ruleEnabled ?? null);
const [currentStatus, setCurrentStatus] = useState<RuleInfoStatus | null>(
ruleStatus?.current_status ?? null
);

useEffect(() => {
if (myRuleEnabled !== ruleEnabled && fetchRuleStatus != null && ruleId != null) {
fetchRuleStatus(ruleId);
if (myRuleEnabled !== ruleEnabled) {
setMyRuleEnabled(ruleEnabled ?? null);
}
}
}, [fetchRuleStatus, myRuleEnabled, ruleId, ruleEnabled, setMyRuleEnabled]);

useEffect(() => {
if (!isEqual(currentStatus, ruleStatus?.current_status)) {
setCurrentStatus(ruleStatus?.current_status ?? null);
}
}, [currentStatus, ruleStatus, setCurrentStatus]);

const handleRefresh = useCallback(() => {
if (fetchRuleStatus != null && ruleId != null) {
fetchRuleStatus(ruleId);
}
}, [fetchRuleStatus, ruleId]);

return (
<EuiFlexGroup gutterSize="xs" alignItems="center" justifyContent="flexStart">
<EuiFlexItem grow={false}>
{i18n.STATUS}
{':'}
</EuiFlexItem>
{loading && (
<EuiFlexItem>
<EuiLoadingSpinner size="m" data-test-subj="rule-status-loader" />
</EuiFlexItem>
)}
{!loading && (
<>
<EuiFlexItem grow={false}>
<EuiHealth color={getStatusColor(currentStatus?.status ?? null)}>
<EuiText size="xs">{currentStatus?.status ?? getEmptyTagValue()}</EuiText>
</EuiHealth>
</EuiFlexItem>
{currentStatus?.status_date != null && currentStatus?.status != null && (
<>
<EuiFlexItem grow={false}>
<>{i18n.STATUS_AT}</>
</EuiFlexItem>
<EuiFlexItem grow={true}>
<FormattedDate value={currentStatus?.status_date} fieldName={i18n.STATUS_DATE} />
</EuiFlexItem>
</>
)}
<EuiFlexItem grow={false}>
<EuiButtonIcon
color="primary"
onClick={handleRefresh}
iconType="refresh"
aria-label={i18n.REFRESH}
/>
</EuiFlexItem>
</>
)}
</EuiFlexGroup>
);
};

export const RuleStatus = memo(RuleStatusComponent);
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/*
* 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.
*/

import { i18n } from '@kbn/i18n';

export const STATUS = i18n.translate('xpack.siem.detectionEngine.ruleStatus.statusDescription', {
defaultMessage: 'Status',
});

export const STATUS_AT = i18n.translate(
'xpack.siem.detectionEngine.ruleStatus.statusAtDescription',
{
defaultMessage: 'at',
}
);

export const STATUS_DATE = i18n.translate(
'xpack.siem.detectionEngine.ruleStatus.statusDateDescription',
{
defaultMessage: 'Status date',
}
);

export const REFRESH = i18n.translate('xpack.siem.detectionEngine.ruleStatus.refreshButton', {
defaultMessage: 'Refresh',
});
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ export interface RuleSwitchProps {
isDisabled?: boolean;
isLoading?: boolean;
optionLabel?: string;
onChange?: (enabled: boolean) => void;
}

/**
Expand All @@ -48,6 +49,7 @@ export const RuleSwitchComponent = ({
isLoading,
enabled,
optionLabel,
onChange,
}: RuleSwitchProps) => {
const [myIsLoading, setMyIsLoading] = useState(false);
const [myEnabled, setMyEnabled] = useState(enabled ?? false);
Expand All @@ -65,6 +67,9 @@ export const RuleSwitchComponent = ({
enabled: event.target.checked!,
});
setMyEnabled(updatedRules[0].enabled);
if (onChange != null) {
onChange(updatedRules[0].enabled);
}
} catch {
setMyIsLoading(false);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,7 @@ import {
} from '@elastic/eui';
import React, { memo } from 'react';

import { useRuleStatus } from '../../../../containers/detection_engine/rules/use_rule_status';
import { RuleStatus } from '../../../../containers/detection_engine/rules';
import { useRuleStatus, RuleInfoStatus } from '../../../../containers/detection_engine/rules';
import { HeaderSection } from '../../../../components/header_section';
import * as i18n from './translations';
import { FormattedDate } from '../../../../components/formatted_date';
Expand All @@ -35,7 +34,7 @@ const FailureHistoryComponent: React.FC<FailureHistoryProps> = ({ id }) => {
</EuiPanel>
);
}
const columns: Array<EuiBasicTableColumn<RuleStatus>> = [
const columns: Array<EuiBasicTableColumn<RuleInfoStatus>> = [
{
name: i18n.COLUMN_STATUS_TYPE,
render: () => <EuiHealth color="danger">{i18n.TYPE_FAILED}</EuiHealth>,
Expand Down Expand Up @@ -65,7 +64,9 @@ const FailureHistoryComponent: React.FC<FailureHistoryProps> = ({ id }) => {
<EuiBasicTable
columns={columns}
loading={loading}
items={ruleStatus != null ? ruleStatus?.filter(rs => rs.last_failure_at != null) : []}
items={
ruleStatus != null ? ruleStatus?.failures.filter(rs => rs.last_failure_at != null) : []
}
sorting={{ sort: { field: 'status_date', direction: 'desc' } }}
/>
</EuiPanel>
Expand Down
Loading

0 comments on commit 9567cca

Please sign in to comment.