Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[7.x] [SIEM] [Detection Engine] Adds Rules Table (#50839) #51380

Merged
merged 2 commits into from
Nov 22, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view

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