Skip to content

Commit

Permalink
[Security Solution] Show rule actions on Rule Details page (#158189)
Browse files Browse the repository at this point in the history
**Resolves: #154879

## Summary

Adds a list of notification and response actions to the Rule Details
page.
<img width="1582" alt="Screenshot 2023-06-05 at 11 42 24"
src="https://github.com/elastic/kibana/assets/15949146/afb749d4-734e-4049-bbe2-9168186c9863">



### Checklist

- [x] Any text added follows [EUI's writing
guidelines](https://elastic.github.io/eui/#/guidelines/writing), uses
sentence case text and includes [i18n
support](https://github.com/elastic/kibana/blob/main/packages/kbn-i18n/README.md)
- [ ]
[Documentation](https://www.elastic.co/guide/en/kibana/master/development-documentation.html)
was added for features that require explanation or tutorials
- [x] [Unit or functional
tests](https://www.elastic.co/guide/en/kibana/master/development-tests.html)
were updated or added to match the most common scenarios
- [x] Any UI touched in this PR is usable by keyboard only (learn more
about [keyboard accessibility](https://webaim.org/techniques/keyboard/))
- [x] Any UI touched in this PR does not create any new axe failures
(run axe in browser:
[FF](https://addons.mozilla.org/en-US/firefox/addon/axe-devtools/),
[Chrome](https://chrome.google.com/webstore/detail/axe-web-accessibility-tes/lhdoppojpmngadmnindnejefpokejbdd?hl=en-US))
- [x] If a plugin configuration key changed, check if it needs to be
allowlisted in the cloud and added to the [docker
list](https://github.com/elastic/kibana/blob/main/src/dev/build/tasks/os_packages/docker_generator/resources/base/bin/kibana-docker)
- [x] This renders correctly on smaller devices using a responsive
layout. (You can test this [in your
browser](https://www.browserstack.com/guide/responsive-testing-on-local-server))
- [x] This was checked for [cross-browser
compatibility](https://www.elastic.co/support/matrix#matrix_browsers)
  • Loading branch information
nikitaindik authored Jun 19, 2023
1 parent 968d786 commit c191104
Show file tree
Hide file tree
Showing 11 changed files with 502 additions and 13 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,12 @@ describe('helpers', () => {

expect(result).toEqual({ unit: 'ms', value: 0 });
});

test('returns timeObj with unit of d and value 5 when time is 5d ', () => {
const result = getTimeTypeValue('5d');

expect(result).toEqual({ unit: 'd', value: 5 });
});
});

describe('filterEmptyThreats', () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ export const getTimeTypeValue = (time: string): { unit: Unit; value: number } =>
if (
!isEmpty(filterTimeType) &&
filterTimeType != null &&
['s', 'm', 'h'].includes(filterTimeType[0])
['s', 'm', 'h', 'd'].includes(filterTimeType[0])
) {
timeObj.unit = filterTimeType[0] as Unit;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ import { AlertsHistogramPanel } from '../../../../detections/components/alerts_k
import { useUserData } from '../../../../detections/components/user_info';
import { StepDefineRuleReadOnly } from '../../../../detections/components/rules/step_define_rule';
import { StepScheduleRuleReadOnly } from '../../../../detections/components/rules/step_schedule_rule';
import { StepRuleActionsReadOnly } from '../../../../detections/components/rules/step_rule_actions';
import {
buildAlertsFilter,
buildAlertStatusFilter,
Expand Down Expand Up @@ -290,14 +291,21 @@ const RuleDetailsPageComponent: React.FC<DetectionEngineComponentProps> = ({

const [pageTabs, setTabs] = useState<Partial<Record<RuleDetailTabs, NavTab>>>(ruleDetailTabs);

const { aboutRuleData, modifiedAboutRuleDetailsData, defineRuleData, scheduleRuleData } =
const {
aboutRuleData,
modifiedAboutRuleDetailsData,
defineRuleData,
scheduleRuleData,
ruleActionsData,
} =
rule != null
? getStepsData({ rule, detailsView: true })
: {
aboutRuleData: null,
modifiedAboutRuleDetailsData: null,
defineRuleData: null,
scheduleRuleData: null,
ruleActionsData: null,
};
const [dataViewTitle, setDataViewTitle] = useState<string>();
useEffect(() => {
Expand Down Expand Up @@ -644,6 +652,11 @@ const RuleDetailsPageComponent: React.FC<DetectionEngineComponentProps> = ({

const defaultRuleStackByOption: AlertsStackByField = 'event.category';

const hasNotificationActions = ruleActionsData != null && ruleActionsData.actions.length > 0;
const hasResponseActions =
ruleActionsData != null && (ruleActionsData.responseActions || []).length > 0;
const hasActions = hasNotificationActions || hasResponseActions;

return (
<>
<NeedAdminForUpdateRulesCallOut />
Expand Down Expand Up @@ -791,6 +804,16 @@ const RuleDetailsPageComponent: React.FC<DetectionEngineComponentProps> = ({
)}
</StepPanel>
</EuiFlexItem>
{hasActions && (
<EuiFlexItem data-test-subj="actions" component="section" grow={1}>
<StepPanel loading={isLoading} title={ruleI18n.ACTIONS}>
<StepRuleActionsReadOnly
addPadding={false}
defaultValues={ruleActionsData}
/>
</StepPanel>
</EuiFlexItem>
)}
</EuiFlexGroup>
</EuiFlexItem>
</EuiFlexGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ import type {
ExceptionListItemSchema,
} from '@kbn/securitysolution-io-ts-list-types';
import { INTERNAL_ALERTING_API_FIND_RULES_PATH } from '@kbn/alerting-plugin/common';
import { BASE_ACTION_API_PATH } from '@kbn/actions-plugin/common';
import type { ActionType, AsApiContract } from '@kbn/actions-plugin/common';
import type { ActionResult } from '@kbn/actions-plugin/server';
import type { BulkInstallPackagesResponse } from '@kbn/fleet-plugin/common';
import { epmRouteService } from '@kbn/fleet-plugin/common';
import type { InstallPackageResponse } from '@kbn/fleet-plugin/common/types';
Expand Down Expand Up @@ -236,6 +239,21 @@ export const fetchRulesSnoozeSettings = async ({
return result;
}, {} as RulesSnoozeSettingsMap);
};

export const fetchConnectors = (
signal?: AbortSignal
): Promise<Array<AsApiContract<ActionResult>>> =>
KibanaServices.get().http.fetch(`${BASE_ACTION_API_PATH}/connectors`, { method: 'GET', signal });

export const fetchConnectorTypes = (signal?: AbortSignal): Promise<ActionType[]> =>
KibanaServices.get().http.fetch(`${BASE_ACTION_API_PATH}/connector_types`, {
method: 'GET',
signal,
query: {
feature_id: 'siem',
},
});

export interface BulkActionSummary {
failed: number;
skipped: number;
Expand Down
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
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

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

export const CONNECTORS_FETCH_ERROR = i18n.translate(
'xpack.securitySolution.detectionEngine.ruleDetails.actions.connectorsFetchError',
{
defaultMessage: 'Failed to fetch connectors',
}
);

export const CONNECTOR_TYPES_FETCH_ERROR = i18n.translate(
'xpack.securitySolution.detectionEngine.ruleDetails.actions.connectorTypesFetchError',
{
defaultMessage: 'Failed to fetch connector types',
}
);

export const ACTIONS_FETCH_ERROR_DESCRIPTION = i18n.translate(
'xpack.securitySolution.detectionEngine.ruleDetails.actions.actionsFetchErrorDescription',
{
defaultMessage: 'Viewing actions is not available',
}
);
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
/*
* 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 { useQuery } from '@tanstack/react-query';
import { BASE_ACTION_API_PATH } from '@kbn/actions-plugin/common';
import { useAppToasts } from '../../../../common/hooks/use_app_toasts';
import { fetchConnectors, fetchConnectorTypes } from '../api';
import * as i18n from './translations';

export const useFetchConnectors = () => {
const { addError } = useAppToasts();

return useQuery(
['GET', BASE_ACTION_API_PATH, 'connectors'],
({ signal }) => fetchConnectors(signal),
{
onError: (error) => {
addError(error, {
title: i18n.CONNECTORS_FETCH_ERROR,
toastMessage: i18n.ACTIONS_FETCH_ERROR_DESCRIPTION,
});
},
}
);
};

export const useFetchConnectorTypes = () => {
const { addError } = useAppToasts();

return useQuery(
['GET', BASE_ACTION_API_PATH, 'connector_types', 'siem'],
({ signal }) => fetchConnectorTypes(signal),
{
onError: (error) => {
addError(error, {
title: i18n.CONNECTOR_TYPES_FETCH_ERROR,
toastMessage: i18n.ACTIONS_FETCH_ERROR_DESCRIPTION,
});
},
}
);
};
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

import React from 'react';
import { mount } from 'enzyme';
import { render } from '@testing-library/react';

import { TestProviders } from '../../../../common/mock';

Expand All @@ -19,6 +20,7 @@ import {
import { useRuleForms } from '../../../../detection_engine/rule_creation_ui/pages/form';
import type { FormHook } from '../../../../shared_imports';
import type { ActionsStepRule } from '../../../pages/detection_engine/rules/types';
import { FrequencyDescription } from './notification_action';

jest.mock('../../../../common/lib/kibana', () => ({
useKibana: jest.fn().mockReturnValue({
Expand Down Expand Up @@ -83,3 +85,113 @@ describe('StepRuleActions', () => {
expect(wrapper.find('Form[data-test-subj="stepRuleActions"]')).toHaveLength(1);
});
});

describe('getFrequencyDescription', () => {
it('should return empty string if frequency is not specified', () => {
const { container } = render(<FrequencyDescription />, {
wrapper: TestProviders,
});

expect(container).toBeEmptyDOMElement();
});

it('should correctly handle "For each alert. Per rule run."', async () => {
const frequency = { notifyWhen: 'onActiveAlert', summary: false, throttle: null } as const;

const { findByText } = render(<FrequencyDescription frequency={frequency} />, {
wrapper: TestProviders,
});

expect(await findByText('For each alert. Per rule run.')).toBeInTheDocument();
});

it('should correctly handle "Summary of alerts. Per rule run."', async () => {
const frequency = { notifyWhen: 'onActiveAlert', summary: true, throttle: null } as const;

const { findByText } = render(<FrequencyDescription frequency={frequency} />, {
wrapper: TestProviders,
});

expect(await findByText('Summary of alerts. Per rule run.')).toBeInTheDocument();
});

it('should return empty string if type is "onThrottleInterval" but throttle is not specified', () => {
const frequency = { notifyWhen: 'onThrottleInterval', summary: true, throttle: null } as const;

const { container } = render(<FrequencyDescription frequency={frequency} />, {
wrapper: TestProviders,
});

expect(container).toBeEmptyDOMElement();
});

it('should correctly handle "Once a second"', async () => {
const frequency = { notifyWhen: 'onThrottleInterval', summary: true, throttle: '1s' } as const;

const { findByText } = render(<FrequencyDescription frequency={frequency} />, {
wrapper: TestProviders,
});

expect(await findByText('Once a second')).toBeInTheDocument();
});

it('should correctly handle "Once in every # seconds"', async () => {
const frequency = { notifyWhen: 'onThrottleInterval', summary: true, throttle: '2s' } as const;

const { findByText } = render(<FrequencyDescription frequency={frequency} />, {
wrapper: TestProviders,
});

expect(await findByText('Once in every 2 seconds')).toBeInTheDocument();
});

it('should correctly handle "Once a minute"', async () => {
const frequency = { notifyWhen: 'onThrottleInterval', summary: true, throttle: '1m' } as const;

const { findByText } = render(<FrequencyDescription frequency={frequency} />, {
wrapper: TestProviders,
});

expect(await findByText('Once a minute')).toBeInTheDocument();
});

it('should correctly handle "Once in every # minutes"', async () => {
const frequency = { notifyWhen: 'onThrottleInterval', summary: true, throttle: '2m' } as const;

const { findByText } = render(<FrequencyDescription frequency={frequency} />, {
wrapper: TestProviders,
});

expect(await findByText('Once in every 2 minutes')).toBeInTheDocument();
});

it('should correctly handle "Once an hour"', async () => {
const frequency = { notifyWhen: 'onThrottleInterval', summary: true, throttle: '1h' } as const;

const { findByText } = render(<FrequencyDescription frequency={frequency} />, {
wrapper: TestProviders,
});

expect(await findByText('Once an hour')).toBeInTheDocument();
});

it('should correctly handle "Once in every # hours"', async () => {
const frequency = { notifyWhen: 'onThrottleInterval', summary: true, throttle: '2h' } as const;

const { findByText } = render(<FrequencyDescription frequency={frequency} />, {
wrapper: TestProviders,
});

expect(await findByText('Once in every 2 hours')).toBeInTheDocument();
});

it('should correctly handle unknown time units', async () => {
const frequency = { notifyWhen: 'onThrottleInterval', summary: true, throttle: '1z' } as const;

const { findByText } = render(<FrequencyDescription frequency={frequency} />, {
wrapper: TestProviders,
});

expect(await findByText('Periodically')).toBeInTheDocument();
});
});
Loading

0 comments on commit c191104

Please sign in to comment.