Skip to content

Commit

Permalink
[SIEM] [Detection Engine] Adds Rules Table (#50839) (#51380)
Browse files Browse the repository at this point in the history
This PR wires up the Detection Engine Rules Table and provides the following features:
 * [x] Lists all rules for a given user/space
 * [x] Search/Filtering via `Rule Name`
 * [x] Sorting via `Activate`
 * [x] Pagination
 * [x] Enable/Disable Action
 * [x] Rule Selection / Batch Actions
 * [x] Rule Import w/ validation via `io-ts`
 * [x] Batch Actions
   * [x] Activate selected
   * [x] Deactivate selected
   * [x] Export selected (as `.ndjson`)
   * [ ] ~Edit selected index patterns...~ (Waiting on supported feature)
   * [x] Delete selected
 * [x] Individual Overflow Actions
   * [ ] ~Edit rule settings~ (Waiting on supported feature)
   * [ ] ~Run rule manually...~ (Waiting on supported feature)
   * [x] Duplicate rule...
   * [X] Export rule
   * [x] Delete rule...

![sort_and_filter](https://user-images.githubusercontent.com/2946766/69286404-641d1a80-0bb0-11ea-9930-8eada88b36f6.gif)

![import_and_export](https://user-images.githubusercontent.com/2946766/69286806-79df0f80-0bb1-11ea-99c5-92df0a706f0e.gif)

![import_failed_validation](https://user-images.githubusercontent.com/2946766/69286797-72b80180-0bb1-11ea-9397-71fa0ff0b203.gif)

![batch_activate_deactivate](https://user-images.githubusercontent.com/2946766/69287019-0093ec80-0bb2-11ea-8320-57cc7fec27a8.gif)

![batch_delete](https://user-images.githubusercontent.com/2946766/69287139-6e401880-0bb2-11ea-948c-c5b92ba90e6f.gif)

![dupe_and_delete](https://user-images.githubusercontent.com/2946766/69287143-74ce9000-0bb2-11ea-88b3-db75f66ba666.gif)

Use ~~strikethroughs~~ to remove checklist items you don't feel are applicable to this PR.

- [x] This was checked for cross-browser compatibility, [including a check against IE11](https://github.com/elastic/kibana/blob/master/CONTRIBUTING.md#cross-browser-compatibility)
- [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/master/packages/kbn-i18n/README.md)
- [ ] ~[Documentation](https://github.com/elastic/kibana/blob/master/CONTRIBUTING.md#writing-documentation) was added for features that require explanation or tutorials~ --
  * Will work with @benskelker on overall Detection Engine documentation
- [x] [Unit or functional tests](https://github.com/elastic/kibana/blob/master/CONTRIBUTING.md#cross-browser-compatibility) were updated or added to match the most common scenarios
  * Includes basic tests -- will expand coverage as features solidify
- [ ] ~This was checked for [keyboard-only and screenreader accessibility](https://developer.mozilla.org/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/Accessibility#Accessibility_testing_checklist)~

- [ ] ~This was checked for breaking API changes and was [labeled appropriately](https://github.com/elastic/kibana/blob/master/CONTRIBUTING.md#release-notes-process)~
- [ ] ~This includes a feature addition or change that requires a release note and was [labeled appropriately](https://github.com/elastic/kibana/blob/master/CONTRIBUTING.md#release-notes-process)~
  • Loading branch information
spong authored Nov 22, 2019
1 parent 4f32ef4 commit ab9c3b0
Show file tree
Hide file tree
Showing 31 changed files with 2,325 additions and 1,044 deletions.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ describe('UtilityBar', () => {
</UtilityBarGroup>

<UtilityBarGroup>
<UtilityBarAction iconType="" popoverContent={<p>{'Test popover'}</p>}>
<UtilityBarAction iconType="" popoverContent={() => <p>{'Test popover'}</p>}>
{'Test action'}
</UtilityBarAction>
</UtilityBarGroup>
Expand Down Expand Up @@ -60,7 +60,7 @@ describe('UtilityBar', () => {
</UtilityBarGroup>

<UtilityBarGroup>
<UtilityBarAction iconType="" popoverContent={<p>{'Test popover'}</p>}>
<UtilityBarAction iconType="" popoverContent={() => <p>{'Test popover'}</p>}>
{'Test action'}
</UtilityBarAction>
</UtilityBarGroup>
Expand Down Expand Up @@ -90,7 +90,7 @@ describe('UtilityBar', () => {
</UtilityBarGroup>

<UtilityBarGroup>
<UtilityBarAction iconType="" popoverContent={<p>{'Test popover'}</p>}>
<UtilityBarAction iconType="" popoverContent={() => <p>{'Test popover'}</p>}>
{'Test action'}
</UtilityBarAction>
</UtilityBarGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ describe('UtilityBarAction', () => {
test('it renders a popover', () => {
const wrapper = mount(
<TestProviders>
<UtilityBarAction iconType="alert" popoverContent={<p>{'Test popover'}</p>}>
<UtilityBarAction iconType="alert" popoverContent={() => <p>{'Test popover'}</p>}>
{'Test action'}
</UtilityBarAction>
</TestProviders>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
*/

import { EuiPopover } from '@elastic/eui';
import React, { useState } from 'react';
import React, { useCallback, useState } from 'react';

import { LinkIcon, LinkIconProps } from '../../link_icon';
import { BarAction } from './styles';
Expand All @@ -14,6 +14,8 @@ const Popover = React.memo<UtilityBarActionProps>(
({ children, color, iconSide, iconSize, iconType, popoverContent }) => {
const [popoverState, setPopoverState] = useState(false);

const closePopover = useCallback(() => setPopoverState(false), [setPopoverState]);

return (
<EuiPopover
button={
Expand All @@ -30,15 +32,15 @@ const Popover = React.memo<UtilityBarActionProps>(
closePopover={() => setPopoverState(false)}
isOpen={popoverState}
>
{popoverContent}
{popoverContent?.(closePopover)}
</EuiPopover>
);
}
);
Popover.displayName = 'Popover';

export interface UtilityBarActionProps extends LinkIconProps {
popoverContent?: React.ReactNode;
popoverContent?: (closePopover: () => void) => React.ReactNode;
}

export const UtilityBarAction = React.memo<UtilityBarActionProps>(
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
/*
* 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 chrome from 'ui/chrome';
import {
DeleteRulesProps,
DuplicateRulesProps,
EnableRulesProps,
FetchRulesProps,
FetchRulesResponse,
Rule,
} from './types';
import { throwIfNotOk } from '../../../hooks/api/api';

/**
* Fetches all rules or single specified rule from the Detection Engine API
*
* @param filterOptions desired filters (e.g. filter/sortField/sortOrder)
* @param pagination desired pagination options (e.g. page/perPage)
* @param id if specified, will return specific rule if exists
* @param kbnVersion current Kibana Version to use for headers
*/
export const fetchRules = async ({
filterOptions = {
filter: '',
sortField: 'enabled',
sortOrder: 'desc',
},
pagination = {
page: 1,
perPage: 20,
total: 0,
},
id,
kbnVersion,
signal,
}: FetchRulesProps): Promise<FetchRulesResponse> => {
const queryParams = [
`page=${pagination.page}`,
`per_page=${pagination.perPage}`,
`sort_field=${filterOptions.sortField}`,
`sort_order=${filterOptions.sortOrder}`,
...(filterOptions.filter.length !== 0
? [`filter=alert.attributes.name:%20${encodeURIComponent(filterOptions.filter)}`]
: []),
];

const endpoint =
id != null
? `${chrome.getBasePath()}/api/detection_engine/rules?id="${id}"`
: `${chrome.getBasePath()}/api/detection_engine/rules/_find?${queryParams.join('&')}`;

const response = await fetch(endpoint, {
method: 'GET',
credentials: 'same-origin',
headers: {
'content-type': 'application/json',
'kbn-version': kbnVersion,
'kbn-xsrf': kbnVersion,
},
signal,
});
await throwIfNotOk(response);
return id != null
? {
page: 0,
perPage: 1,
total: 1,
data: response.json(),
}
: response.json();
};

/**
* Enables/Disables provided Rule ID's
*
* @param ids array of Rule ID's (not rule_id) to enable/disable
* @param enabled to enable or disable
* @param kbnVersion current Kibana Version to use for headers
*/
export const enableRules = async ({
ids,
enabled,
kbnVersion,
}: EnableRulesProps): Promise<Rule[]> => {
const requests = ids.map(id =>
fetch(`${chrome.getBasePath()}/api/detection_engine/rules`, {
method: 'PUT',
credentials: 'same-origin',
headers: {
'content-type': 'application/json',
'kbn-version': kbnVersion,
'kbn-xsrf': kbnVersion,
},
body: JSON.stringify({ id, enabled }),
})
);

const responses = await Promise.all(requests);
await responses.map(response => throwIfNotOk(response));
return Promise.all(
responses.map<Promise<Rule>>(response => response.json())
);
};

/**
* Deletes provided Rule ID's
*
* @param ids array of Rule ID's (not rule_id) to delete
* @param kbnVersion current Kibana Version to use for headers
*/
export const deleteRules = async ({ ids, kbnVersion }: DeleteRulesProps): Promise<Rule[]> => {
// TODO: Don't delete if immutable!
const requests = ids.map(id =>
fetch(`${chrome.getBasePath()}/api/detection_engine/rules?id=${id}`, {
method: 'DELETE',
credentials: 'same-origin',
headers: {
'content-type': 'application/json',
'kbn-version': kbnVersion,
'kbn-xsrf': kbnVersion,
},
})
);

const responses = await Promise.all(requests);
await responses.map(response => throwIfNotOk(response));
return Promise.all(
responses.map<Promise<Rule>>(response => response.json())
);
};

/**
* Duplicates provided Rules
*
* @param rule to duplicate
* @param kbnVersion current Kibana Version to use for headers
*/
export const duplicateRules = async ({
rules,
kbnVersion,
}: DuplicateRulesProps): Promise<Rule[]> => {
const requests = rules.map(rule =>
fetch(`${chrome.getBasePath()}/api/detection_engine/rules`, {
method: 'POST',
credentials: 'same-origin',
headers: {
'content-type': 'application/json',
'kbn-version': kbnVersion,
'kbn-xsrf': kbnVersion,
},
body: JSON.stringify({
...rule,
name: `${rule.name} [Duplicate]`,
created_by: undefined,
id: undefined,
rule_id: undefined,
updated_by: undefined,
enabled: rule.enabled,
}),
})
);

const responses = await Promise.all(requests);
await responses.map(response => throwIfNotOk(response));
return Promise.all(
responses.map<Promise<Rule>>(response => response.json())
);
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
/*
* 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 RULE_FETCH_FAILURE = i18n.translate('xpack.siem.containers.detectionEngine.rules', {
defaultMessage: 'Failed to fetch Rules',
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
/*
* 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 * as t from 'io-ts';

export const RuleSchema = t.intersection([
t.type({
created_by: t.string,
description: t.string,
enabled: t.boolean,
id: t.string,
index: t.array(t.string),
interval: t.string,
language: t.string,
name: t.string,
query: t.string,
rule_id: t.string,
severity: t.string,
type: t.string,
updated_by: t.string,
}),
t.partial({
false_positives: t.array(t.string),
from: t.string,
max_signals: t.number,
references: t.array(t.string),
tags: t.array(t.string),
to: t.string,
}),
]);

export const RulesSchema = t.array(RuleSchema);

export type Rule = t.TypeOf<typeof RuleSchema>;
export type Rules = t.TypeOf<typeof RulesSchema>;

export interface PaginationOptions {
page: number;
perPage: number;
total: number;
}

export interface FetchRulesProps {
pagination?: PaginationOptions;
filterOptions?: FilterOptions;
id?: string;
kbnVersion: string;
signal: AbortSignal;
}

export interface FilterOptions {
filter: string;
sortField: string;
sortOrder: 'asc' | 'desc';
}

export interface FetchRulesResponse {
page: number;
perPage: number;
total: number;
data: Rule[];
}

export interface EnableRulesProps {
ids: string[];
enabled: boolean;
kbnVersion: string;
}

export interface DeleteRulesProps {
ids: string[];
kbnVersion: string;
}

export interface DuplicateRulesProps {
rules: Rules;
kbnVersion: string;
}
Loading

0 comments on commit ab9c3b0

Please sign in to comment.