From 24ed91f5a3d9f14ad9b6952162d148faf241891b Mon Sep 17 00:00:00 2001 From: Yara Tercero Date: Tue, 2 Jun 2020 17:14:00 -0400 Subject: [PATCH 01/32] moved and_or_badge to common folder and added tests --- .../__examples__/index.stories.tsx | 39 +++++++ .../components/and_or_badge/index.test.tsx | 47 ++++++++ .../common/components/and_or_badge/index.tsx | 108 ++++++++++++++++++ .../components/and_or_badge/translations.ts | 15 +++ 4 files changed, 209 insertions(+) create mode 100644 x-pack/plugins/siem/public/common/components/and_or_badge/__examples__/index.stories.tsx create mode 100644 x-pack/plugins/siem/public/common/components/and_or_badge/index.test.tsx create mode 100644 x-pack/plugins/siem/public/common/components/and_or_badge/index.tsx create mode 100644 x-pack/plugins/siem/public/common/components/and_or_badge/translations.ts diff --git a/x-pack/plugins/siem/public/common/components/and_or_badge/__examples__/index.stories.tsx b/x-pack/plugins/siem/public/common/components/and_or_badge/__examples__/index.stories.tsx new file mode 100644 index 0000000000000..27ca464404445 --- /dev/null +++ b/x-pack/plugins/siem/public/common/components/and_or_badge/__examples__/index.stories.tsx @@ -0,0 +1,39 @@ +/* + * 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 { storiesOf } from '@storybook/react'; +import React from 'react'; +import { ThemeProvider } from 'styled-components'; +import euiLightVars from '@elastic/eui/dist/eui_theme_light.json'; +import { EuiFlexItem, EuiFlexGroup } from '@elastic/eui'; + +import { AndOrBadge } from '..'; + +const sampleText = + 'Doggo ipsum i am bekom fat snoot wow such tempt waggy wags floofs, ruff heckin good boys and girls mlem. Ruff heckin good boys and girls mlem stop it fren borkf borking doggo very hand that feed shibe, you are doing me the shock big ol heck smol borking doggo with a long snoot for pats heckin good boys. You are doing me the shock smol borking doggo with a long snoot for pats wow very biscit, length boy. Doggo ipsum i am bekom fat snoot wow such tempt waggy wags floofs, ruff heckin good boys and girls mlem. Ruff heckin good boys and girls mlem stop it fren borkf borking doggo very hand that feed shibe, you are doing me the shock big ol heck smol borking doggo with a long snoot for pats heckin good boys.'; + +storiesOf('components/AndOrBadge', module) + .add('and', () => ( + ({ eui: euiLightVars, darkMode: true })}> + + + )) + .add('or', () => ( + ({ eui: euiLightVars, darkMode: true })}> + + + )) + .add('antennas', () => ( + ({ eui: euiLightVars, darkMode: true })}> + + + + + +

{sampleText}

+
+
+
+ )); diff --git a/x-pack/plugins/siem/public/common/components/and_or_badge/index.test.tsx b/x-pack/plugins/siem/public/common/components/and_or_badge/index.test.tsx new file mode 100644 index 0000000000000..9df865193a791 --- /dev/null +++ b/x-pack/plugins/siem/public/common/components/and_or_badge/index.test.tsx @@ -0,0 +1,47 @@ +/* + * 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 React from 'react'; +import { ThemeProvider } from 'styled-components'; +import { mount } from 'enzyme'; +import euiLightVars from '@elastic/eui/dist/eui_theme_light.json'; + +import { AndOrBadge } from './'; + +describe('AndOrBadge', () => { + test('it renders top and bottom antenna bars when "includeAntenas" is true', () => { + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + + expect(wrapper.find('[data-test-subj="and-or-badge"]').at(0).text()).toEqual('AND'); + expect(wrapper.find('EuiFlexItem[data-test-subj="and-or-badge-bar"]')).toHaveLength(2); + }); + + test('it renders "and" when "type" is "and"', () => { + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + + expect(wrapper.find('[data-test-subj="and-or-badge"]').at(0).text()).toEqual('AND'); + expect(wrapper.find('EuiFlexItem[data-test-subj="and-or-badge-bar"]')).toHaveLength(0); + }); + + test('it renders "or" when "type" is "or"', () => { + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + + expect(wrapper.find('[data-test-subj="and-or-badge"]').at(0).text()).toEqual('OR'); + expect(wrapper.find('EuiFlexItem[data-test-subj="and-or-badge-bar"]')).toHaveLength(0); + }); +}); diff --git a/x-pack/plugins/siem/public/common/components/and_or_badge/index.tsx b/x-pack/plugins/siem/public/common/components/and_or_badge/index.tsx new file mode 100644 index 0000000000000..095a151a5c283 --- /dev/null +++ b/x-pack/plugins/siem/public/common/components/and_or_badge/index.tsx @@ -0,0 +1,108 @@ +/* + * 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 { EuiFlexGroup, EuiBadge, EuiFlexItem } from '@elastic/eui'; +import React from 'react'; +import styled, { css } from 'styled-components'; + +import * as i18n from './translations'; + +const AndOrBadgeAntena = styled(EuiFlexItem)` + ${({ theme }) => css` + background: ${theme.eui.euiColorLightShade}; + position: relative; + width: 2px; + &:after { + background: ${theme.eui.euiColorLightShade}; + content: ''; + height: 8px; + right: -4px; + position: absolute; + width: 9px; + clip-path: circle(); + } + &.topAndOrBadgeAntenna { + &:after { + top: -1px; + } + } + &.bottomAndOrBadgeAntenna { + &:after { + bottom: -1px; + } + } + &.euiFlexItem { + margin: 0 12px 0 0; + } + `} +`; + +const EuiFlexItemWrapper = styled(EuiFlexItem)` + &.euiFlexItem { + margin: 0 12px 0 0; + } +`; + +const RoundedBadge = (styled(EuiBadge)` + align-items: center; + border-radius: 100%; + display: inline-flex; + font-size: 9px; + height: 34px; + justify-content: center; + margin: 0 5px 0 5px; + padding: 7px 6px 4px 6px; + user-select: none; + width: 34px; + .euiBadge__content { + position: relative; + top: -1px; + } + .euiBadge__text { + text-overflow: clip; + } +` as unknown) as typeof EuiBadge; + +RoundedBadge.displayName = 'RoundedBadge'; + +export type AndOr = 'and' | 'or'; + +/** Displays AND / OR in a round badge */ +// Ref: https://github.com/elastic/eui/issues/1655 +export const AndOrBadge = React.memo<{ type: AndOr; includeAntenas?: boolean }>( + ({ type, includeAntenas = false }) => { + const getBadge = () => ( + + {type === 'and' ? i18n.AND : i18n.OR} + + ); + + const getBadgeWithAntenas = () => ( + + + {getBadge()} + + + ); + + return includeAntenas ? getBadgeWithAntenas() : getBadge(); + } +); + +AndOrBadge.displayName = 'AndOrBadge'; diff --git a/x-pack/plugins/siem/public/common/components/and_or_badge/translations.ts b/x-pack/plugins/siem/public/common/components/and_or_badge/translations.ts new file mode 100644 index 0000000000000..58bcb5130a529 --- /dev/null +++ b/x-pack/plugins/siem/public/common/components/and_or_badge/translations.ts @@ -0,0 +1,15 @@ +/* + * 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 AND = i18n.translate('xpack.siem.andOrBadge.and', { + defaultMessage: 'AND', +}); + +export const OR = i18n.translate('xpack.siem.andOrBadge.or', { + defaultMessage: 'OR', +}); From 629b832c800060660ba28b84e9b4487176ddd2a5 Mon Sep 17 00:00:00 2001 From: Yara Tercero Date: Tue, 2 Jun 2020 17:15:59 -0400 Subject: [PATCH 02/32] updated references to new and_or_badge location --- .../__examples__/index.stories.tsx | 12 ----- .../timeline/and_or_badge/index.tsx | 49 ------------------- .../timeline/and_or_badge/translations.ts | 15 ------ .../timeline/data_providers/empty.tsx | 2 +- .../timeline/data_providers/providers.tsx | 2 +- .../timeline/search_or_filter/helpers.tsx | 2 +- 6 files changed, 3 insertions(+), 79 deletions(-) delete mode 100644 x-pack/plugins/siem/public/timelines/components/timeline/and_or_badge/__examples__/index.stories.tsx delete mode 100644 x-pack/plugins/siem/public/timelines/components/timeline/and_or_badge/index.tsx delete mode 100644 x-pack/plugins/siem/public/timelines/components/timeline/and_or_badge/translations.ts diff --git a/x-pack/plugins/siem/public/timelines/components/timeline/and_or_badge/__examples__/index.stories.tsx b/x-pack/plugins/siem/public/timelines/components/timeline/and_or_badge/__examples__/index.stories.tsx deleted file mode 100644 index f34e9ee214537..0000000000000 --- a/x-pack/plugins/siem/public/timelines/components/timeline/and_or_badge/__examples__/index.stories.tsx +++ /dev/null @@ -1,12 +0,0 @@ -/* - * 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 { storiesOf } from '@storybook/react'; -import React from 'react'; -import { AndOrBadge } from '..'; - -storiesOf('components/AndOrBadge', module) - .add('and', () => ) - .add('or', () => ); diff --git a/x-pack/plugins/siem/public/timelines/components/timeline/and_or_badge/index.tsx b/x-pack/plugins/siem/public/timelines/components/timeline/and_or_badge/index.tsx deleted file mode 100644 index 28355372df146..0000000000000 --- a/x-pack/plugins/siem/public/timelines/components/timeline/and_or_badge/index.tsx +++ /dev/null @@ -1,49 +0,0 @@ -/* - * 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 { EuiBadge } from '@elastic/eui'; -import React from 'react'; -import styled from 'styled-components'; - -import * as i18n from './translations'; - -const RoundedBadge = (styled(EuiBadge)` - align-items: center; - border-radius: 100%; - display: inline-flex; - font-size: 9px; - height: 34px; - justify-content: center; - margin: 0 5px 0 5px; - padding: 7px 6px 4px 6px; - user-select: none; - width: 34px; - - .euiBadge__content { - position: relative; - top: -1px; - } - - .euiBadge__text { - text-overflow: clip; - } -` as unknown) as typeof EuiBadge; - -RoundedBadge.displayName = 'RoundedBadge'; - -export type AndOr = 'and' | 'or'; - -/** Displays AND / OR in a round badge */ -// Ref: https://github.com/elastic/eui/issues/1655 -export const AndOrBadge = React.memo<{ type: AndOr }>(({ type }) => { - return ( - - {type === 'and' ? i18n.AND : i18n.OR} - - ); -}); - -AndOrBadge.displayName = 'AndOrBadge'; diff --git a/x-pack/plugins/siem/public/timelines/components/timeline/and_or_badge/translations.ts b/x-pack/plugins/siem/public/timelines/components/timeline/and_or_badge/translations.ts deleted file mode 100644 index 58bcb5130a529..0000000000000 --- a/x-pack/plugins/siem/public/timelines/components/timeline/and_or_badge/translations.ts +++ /dev/null @@ -1,15 +0,0 @@ -/* - * 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 AND = i18n.translate('xpack.siem.andOrBadge.and', { - defaultMessage: 'AND', -}); - -export const OR = i18n.translate('xpack.siem.andOrBadge.or', { - defaultMessage: 'OR', -}); diff --git a/x-pack/plugins/siem/public/timelines/components/timeline/data_providers/empty.tsx b/x-pack/plugins/siem/public/timelines/components/timeline/data_providers/empty.tsx index 240b336f4ecce..691c919029261 100644 --- a/x-pack/plugins/siem/public/timelines/components/timeline/data_providers/empty.tsx +++ b/x-pack/plugins/siem/public/timelines/components/timeline/data_providers/empty.tsx @@ -8,7 +8,7 @@ import { EuiBadge, EuiText } from '@elastic/eui'; import React from 'react'; import styled from 'styled-components'; -import { AndOrBadge } from '../and_or_badge'; +import { AndOrBadge } from '../../../../common/components/and_or_badge'; import * as i18n from './translations'; diff --git a/x-pack/plugins/siem/public/timelines/components/timeline/data_providers/providers.tsx b/x-pack/plugins/siem/public/timelines/components/timeline/data_providers/providers.tsx index 641f6fba112fc..d6122fef91511 100644 --- a/x-pack/plugins/siem/public/timelines/components/timeline/data_providers/providers.tsx +++ b/x-pack/plugins/siem/public/timelines/components/timeline/data_providers/providers.tsx @@ -10,7 +10,7 @@ import React, { useMemo } from 'react'; import { Draggable, DraggingStyle, Droppable, NotDraggingStyle } from 'react-beautiful-dnd'; import styled, { css } from 'styled-components'; -import { AndOrBadge } from '../and_or_badge'; +import { AndOrBadge } from '../../../../common/components/and_or_badge'; import { BrowserFields } from '../../../../common/containers/source'; import { getTimelineProviderDroppableId, diff --git a/x-pack/plugins/siem/public/timelines/components/timeline/search_or_filter/helpers.tsx b/x-pack/plugins/siem/public/timelines/components/timeline/search_or_filter/helpers.tsx index 77257e367c6f5..beadc13811395 100644 --- a/x-pack/plugins/siem/public/timelines/components/timeline/search_or_filter/helpers.tsx +++ b/x-pack/plugins/siem/public/timelines/components/timeline/search_or_filter/helpers.tsx @@ -8,7 +8,7 @@ import { EuiSpacer, EuiText } from '@elastic/eui'; import React from 'react'; import styled from 'styled-components'; -import { AndOrBadge } from '../and_or_badge'; +import { AndOrBadge } from '../../../../common/components/and_or_badge'; import * as i18n from './translations'; import { KqlMode } from '../../../../timelines/store/timeline/model'; From 335a720bbd868bca45214198b27997c8d302d6fb Mon Sep 17 00:00:00 2001 From: Yara Tercero Date: Tue, 2 Jun 2020 17:16:47 -0400 Subject: [PATCH 03/32] built out exception item component for viewer --- .../exceptions/__examples__/index.stories.tsx | 188 +++++++ .../components/exceptions/helpers.test.tsx | 521 ++++++++++++++++++ .../common/components/exceptions/helpers.tsx | 197 +++++++ .../common/components/exceptions/operators.ts | 91 +++ .../components/exceptions/translations.ts | 26 + .../common/components/exceptions/types.ts | 78 +++ .../exceptions/viewer/exception_details.tsx | 79 +++ .../exceptions/viewer/exception_entries.tsx | 148 +++++ .../components/exceptions/viewer/index.tsx | 89 +++ .../plugins/siem/public/lists_plugin_deps.ts | 1 + 10 files changed, 1418 insertions(+) create mode 100644 x-pack/plugins/siem/public/common/components/exceptions/__examples__/index.stories.tsx create mode 100644 x-pack/plugins/siem/public/common/components/exceptions/helpers.test.tsx create mode 100644 x-pack/plugins/siem/public/common/components/exceptions/helpers.tsx create mode 100644 x-pack/plugins/siem/public/common/components/exceptions/operators.ts create mode 100644 x-pack/plugins/siem/public/common/components/exceptions/translations.ts create mode 100644 x-pack/plugins/siem/public/common/components/exceptions/types.ts create mode 100644 x-pack/plugins/siem/public/common/components/exceptions/viewer/exception_details.tsx create mode 100644 x-pack/plugins/siem/public/common/components/exceptions/viewer/exception_entries.tsx create mode 100644 x-pack/plugins/siem/public/common/components/exceptions/viewer/index.tsx diff --git a/x-pack/plugins/siem/public/common/components/exceptions/__examples__/index.stories.tsx b/x-pack/plugins/siem/public/common/components/exceptions/__examples__/index.stories.tsx new file mode 100644 index 0000000000000..9f3ba4341c5eb --- /dev/null +++ b/x-pack/plugins/siem/public/common/components/exceptions/__examples__/index.stories.tsx @@ -0,0 +1,188 @@ +/* + * 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 { storiesOf } from '@storybook/react'; +import React from 'react'; +import { ThemeProvider } from 'styled-components'; +import euiDarkVars from '@elastic/eui/dist/eui_theme_dark.json'; + +import { ExceptionItem } from '../viewer'; +import { ExceptionListItemSchema, Operator } from '../types'; + +const getMockExceptionItem = (): ExceptionListItemSchema => ({ + id: '[insert_uuid_here]', + item_id: 'item-id', + created_at: '2020-04-23T00:19:13.289Z', + created_by: 'user_name', + list_id: 'test-exception', + tie_breaker_id: '77fd1909-6786-428a-a671-30229a719c1f', + updated_at: '2020-04-23T00:19:13.289Z', + updated_by: 'user_name', + name: '', + description: '', + comments: [], + tags: [], + _tags: [], + type: 'simple', + namespace_type: 'single', + entries: [ + { + field: 'actingProcess.file.signer', + type: 'match', + operator: Operator.INCLUSION, + value: 'Elastic, N.V.', + }, + { + field: 'host.name', + type: 'match', + operator: Operator.EXCLUSION, + value: 'Global Signer', + }, + ], +}); + +storiesOf('components/exceptions', module) + .add('ExceptionItem', () => { + const payload = getMockExceptionItem(); + return ( + ({ eui: euiDarkVars, darkMode: true })}> + {}} handleEdit={() => {}} /> + + ); + }) + .add('with os', () => { + const payload = getMockExceptionItem(); + payload._tags = ['os:mac,windows']; + return ( + ({ eui: euiDarkVars, darkMode: true })}> + {}} handleEdit={() => {}} /> + + ); + }) + .add('with description', () => { + const payload = getMockExceptionItem(); + payload.description = 'This is my description'; + return ( + ({ eui: euiDarkVars, darkMode: true })}> + {}} handleEdit={() => {}} /> + + ); + }) + .add('with comments', () => { + const payload = getMockExceptionItem(); + payload.comments = [ + { + user: 'yoshi', + timestamp: '2020-04-23T00:19:13.289Z', + comment: 'Comment goes here', + }, + { + user: 'elastic', + timestamp: '2020-04-23T00:19:13.289Z', + comment: + 'Doggo ipsum he made many woofs fluffer pats fat boi you are doing me a frighten very good spot, doggo super chub tungg most angery pupper I have ever seen. Porgo the neighborhood pupper such treat puggorino thicc, wrinkler big ol. Very good spot big ol adorable doggo, borking doggo. Wrinkler long doggo ur givin me a spook pupperino floofs most angery pupper I have ever seen boof many pats doge, porgo long doggo doing me a frighten smol mlem maximum borkdrive super chub. Mlem clouds many pats pats what a nice floof, heckin noodle horse.', + }, + ]; + return ( + ({ eui: euiDarkVars, darkMode: true })}> + {}} handleEdit={() => {}} /> + + ); + }) + .add('with nested entries', () => { + const payload = getMockExceptionItem(); + payload.entries = [ + { + field: 'actingProcess.file.signer', + type: 'match', + operator: Operator.INCLUSION, + value: 'Elastic, N.V.', + }, + { + field: 'host.name', + type: 'match', + operator: Operator.EXCLUSION, + value: 'Global Signer', + }, + { + field: 'file.signature', + type: 'nested', + entries: [ + { + field: 'signer', + type: 'match', + operator: Operator.INCLUSION, + value: 'Evil', + }, + { + field: 'trusted', + type: 'match', + operator: Operator.INCLUSION, + value: 'true', + }, + ], + }, + ]; + return ( + ({ eui: euiDarkVars, darkMode: true })}> + {}} handleEdit={() => {}} /> + + ); + }) + .add('with everything', () => { + const payload = getMockExceptionItem(); + payload._tags = ['os:mac,windows']; + payload.description = 'This is my description'; + payload.comments = [ + { + user: 'yoshi', + timestamp: '2020-04-23T00:19:13.289Z', + comment: 'Comment goes here', + }, + { + user: 'elastic', + timestamp: '2020-04-23T00:19:13.289Z', + comment: + 'Doggo ipsum he made many woofs fluffer pats fat boi you are doing me a frighten very good spot, doggo super chub tungg most angery pupper I have ever seen. Porgo the neighborhood pupper such treat puggorino thicc, wrinkler big ol. Very good spot big ol adorable doggo, borking doggo. Wrinkler long doggo ur givin me a spook pupperino floofs most angery pupper I have ever seen boof many pats doge, porgo long doggo doing me a frighten smol mlem maximum borkdrive super chub. Mlem clouds many pats pats what a nice floof, heckin noodle horse.', + }, + ]; + payload.entries = [ + { + field: 'actingProcess.file.signer', + type: 'match', + operator: Operator.INCLUSION, + value: 'Elastic, N.V.', + }, + { + field: 'host.name', + type: 'match', + operator: Operator.EXCLUSION, + value: 'Global Signer', + }, + { + field: 'file.signature', + type: 'nested', + entries: [ + { + field: 'signer', + type: 'match', + operator: Operator.INCLUSION, + value: 'Evil', + }, + { + field: 'trusted', + type: 'match', + operator: Operator.INCLUSION, + value: 'true', + }, + ], + }, + ]; + return ( + ({ eui: euiDarkVars, darkMode: true })}> + {}} handleEdit={() => {}} /> + + ); + }); diff --git a/x-pack/plugins/siem/public/common/components/exceptions/helpers.test.tsx b/x-pack/plugins/siem/public/common/components/exceptions/helpers.test.tsx new file mode 100644 index 0000000000000..f07f3a959b40d --- /dev/null +++ b/x-pack/plugins/siem/public/common/components/exceptions/helpers.test.tsx @@ -0,0 +1,521 @@ +/* + * 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 React from 'react'; +import { mount } from 'enzyme'; + +import { + getOperatorType, + getExceptionOperatorSelect, + determineIfIsNested, + getFormattedEntries, + formatEntry, + getOperatingSystems, + getTagsInclude, + getDescriptionListContent, + getFormattedComments, +} from './helpers'; +import { + OperatorType, + Operator, + NestedExceptionEntry, + ExceptionEntry, + FormattedEntry, + DescriptionListItem, + ExceptionListItemSchema, +} from './types'; +import { + isOperator, + isNotOperator, + isOneOfOperator, + isNotOneOfOperator, + isInListOperator, + isNotInListOperator, + existsOperator, + doesNotExistOperator, +} from './operators'; + +const getExceptionItemMock = (): ExceptionListItemSchema => ({ + id: 'uuid_here', + item_id: 'item-id', + created_at: '2020-04-23T00:19:13.289Z', + created_by: 'user_name', + list_id: 'test-exception', + tie_breaker_id: '77fd1909-6786-428a-a671-30229a719c1f', + updated_at: '2020-04-23T00:19:13.289Z', + updated_by: 'user_name', + namespace_type: 'single', + name: '', + description: '', + comments: [ + { + user: 'user_name', + timestamp: '2020-04-23T00:19:13.289Z', + comment: 'Comment goes here', + }, + ], + _tags: ['os:windows'], + tags: [], + type: 'simple', + entries: [ + { + field: 'actingProcess.file.signer', + type: 'match', + operator: Operator.INCLUSION, + value: 'Elastic, N.V.', + }, + { + field: 'host.name', + type: 'match', + operator: Operator.EXCLUSION, + value: 'Global Signer', + }, + { + field: 'file.signature', + type: 'nested', + entries: [ + { + field: 'signer', + type: 'match', + operator: Operator.INCLUSION, + value: 'Evil', + }, + { + field: 'trusted', + type: 'match', + operator: Operator.INCLUSION, + value: 'true', + }, + ], + }, + ], +}); + +const getExceptionItemEntryMock = (): ExceptionEntry => ({ + field: 'host.name', + type: 'match', + operator: Operator.INCLUSION, + value: 'jibberjabber', +}); + +describe('Exception helpers', () => { + describe('#getOperatorType', () => { + test('returns operator type "match" if entry.type is "match"', () => { + const payload = getExceptionItemEntryMock(); + payload.type = 'match'; + const operatorType = getOperatorType(payload); + + expect(operatorType).toEqual(OperatorType.PHRASE); + }); + + test('returns operator type "match" if entry.type is "nested"', () => { + const payload = getExceptionItemEntryMock(); + payload.type = 'nested'; + const operatorType = getOperatorType(payload); + + expect(operatorType).toEqual(OperatorType.PHRASE); + }); + + test('returns operator type "match_any" if entry.type is "match_any"', () => { + const payload = getExceptionItemEntryMock(); + payload.type = 'match_any'; + const operatorType = getOperatorType(payload); + + expect(operatorType).toEqual(OperatorType.PHRASES); + }); + + test('returns operator type "list" if entry.type is "list"', () => { + const payload = getExceptionItemEntryMock(); + payload.type = 'list'; + const operatorType = getOperatorType(payload); + + expect(operatorType).toEqual(OperatorType.LIST); + }); + + test('returns operator type "exists" if entry.type is "exists"', () => { + const payload = getExceptionItemEntryMock(); + payload.type = 'exists'; + const operatorType = getOperatorType(payload); + + expect(operatorType).toEqual(OperatorType.EXISTS); + }); + }); + + describe('#getExceptionOperatorSelect', () => { + test('it returns "isOperator" when "operator" is "included" and operator type is "match"', () => { + const payload = getExceptionItemEntryMock(); + const result = getExceptionOperatorSelect(payload); + + expect(result).toEqual(isOperator); + }); + + test('it returns "isNotOperator" when "operator" is "excluded" and operator type is "match"', () => { + const payload = getExceptionItemEntryMock(); + payload.operator = Operator.EXCLUSION; + const result = getExceptionOperatorSelect(payload); + + expect(result).toEqual(isNotOperator); + }); + + test('it returns "isOneOfOperator" when "operator" is "included" and operator type is "match_any"', () => { + const payload = getExceptionItemEntryMock(); + payload.type = 'match_any'; + payload.operator = Operator.INCLUSION; + const result = getExceptionOperatorSelect(payload); + + expect(result).toEqual(isOneOfOperator); + }); + + test('it returns "isNotOneOfOperator" when "operator" is "excluded" and operator type is "match_any"', () => { + const payload = getExceptionItemEntryMock(); + payload.type = 'match_any'; + payload.operator = Operator.EXCLUSION; + const result = getExceptionOperatorSelect(payload); + + expect(result).toEqual(isNotOneOfOperator); + }); + + test('it returns "existsOperator" when "operator" is "included" and no operator type is provided', () => { + const payload = getExceptionItemEntryMock(); + payload.type = 'exists'; + payload.operator = Operator.INCLUSION; + const result = getExceptionOperatorSelect(payload); + + expect(result).toEqual(existsOperator); + }); + + test('it returns "doesNotExistsOperator" when "operator" is "excluded" and no operator type is provided', () => { + const payload = getExceptionItemEntryMock(); + payload.type = 'exists'; + payload.operator = Operator.EXCLUSION; + const result = getExceptionOperatorSelect(payload); + + expect(result).toEqual(doesNotExistOperator); + }); + + test('it returns "isInList" when "operator" is "included" and operator type is "list"', () => { + const payload = getExceptionItemEntryMock(); + payload.type = 'list'; + payload.operator = Operator.INCLUSION; + const result = getExceptionOperatorSelect(payload); + + expect(result).toEqual(isInListOperator); + }); + + test('it returns "isNotInList" when "operator" is "excluded" and operator type is "list"', () => { + const payload = getExceptionItemEntryMock(); + payload.type = 'list'; + payload.operator = Operator.EXCLUSION; + const result = getExceptionOperatorSelect(payload); + + expect(result).toEqual(isNotInListOperator); + }); + }); + + describe('#determineIfIsNested', () => { + test('it returns true if type NestedExceptionEntry', () => { + const payload: NestedExceptionEntry = { + field: 'host.name', + type: 'nested', + entries: [], + }; + const result = determineIfIsNested(payload); + + expect(result).toBeTruthy(); + }); + + test('it returns false if NOT type NestedExceptionEntry', () => { + const payload = getExceptionItemEntryMock(); + const result = determineIfIsNested(payload); + + expect(result).toBeFalsy(); + }); + }); + + describe('#getFormattedEntries', () => { + test('it returns empty array if no entries passed', () => { + const result = getFormattedEntries([]); + + expect(result).toEqual([]); + }); + + test('it formats nested entries as expected', () => { + const payload = [ + { + field: 'file.signature', + type: 'nested', + entries: [ + { + field: 'signer', + type: 'match', + operator: Operator.INCLUSION, + value: 'Evil', + }, + { + field: 'trusted', + type: 'match', + operator: Operator.INCLUSION, + value: 'true', + }, + ], + }, + ]; + const result = getFormattedEntries(payload); + const expected: FormattedEntry[] = [ + { + fieldName: 'file.signature', + operator: null, + value: null, + isNested: false, + }, + { + fieldName: 'file.signature.signer', + isNested: true, + operator: 'is', + value: 'Evil', + }, + { + fieldName: 'file.signature.trusted', + isNested: true, + operator: 'is', + value: 'true', + }, + ]; + expect(result).toEqual(expected); + }); + + test('it formats non-nested entries as expected', () => { + const payload = [ + { + field: 'actingProcess.file.signer', + type: 'match', + operator: Operator.INCLUSION, + value: 'Elastic, N.V.', + }, + { + field: 'host.name', + type: 'match', + operator: Operator.EXCLUSION, + value: 'Global Signer', + }, + ]; + const result = getFormattedEntries(payload); + const expected: FormattedEntry[] = [ + { + fieldName: 'actingProcess.file.signer', + isNested: false, + operator: 'is', + value: 'Elastic, N.V.', + }, + { + fieldName: 'host.name', + isNested: false, + operator: 'is not', + value: 'Global Signer', + }, + ]; + expect(result).toEqual(expected); + }); + + test('it formats a mix of nested and non-nested entries as expected', () => { + const payload = getExceptionItemMock(); + const result = getFormattedEntries(payload.entries); + const expected: FormattedEntry[] = [ + { + fieldName: 'actingProcess.file.signer', + isNested: false, + operator: 'is', + value: 'Elastic, N.V.', + }, + { + fieldName: 'host.name', + isNested: false, + operator: 'is not', + value: 'Global Signer', + }, + { + fieldName: 'file.signature', + isNested: false, + operator: null, + value: null, + }, + { + fieldName: 'file.signature.signer', + isNested: true, + operator: 'is', + value: 'Evil', + }, + { + fieldName: 'file.signature.trusted', + isNested: true, + operator: 'is', + value: 'true', + }, + ]; + expect(result).toEqual(expected); + }); + }); + + describe('#formatEntry', () => { + test('it formats an entry', () => { + const payload = getExceptionItemEntryMock(); + const formattedEntry = formatEntry({ isNested: false, item: payload }); + const expected: FormattedEntry = { + fieldName: 'host.name', + isNested: false, + operator: 'is', + value: 'jibberjabber', + }; + + expect(formattedEntry).toEqual(expected); + }); + + test('it formats a nested entry', () => { + const payload = getExceptionItemEntryMock(); + const formattedEntry = formatEntry({ isNested: true, parent: 'parent', item: payload }); + const expected: FormattedEntry = { + fieldName: 'parent.host.name', + isNested: true, + operator: 'is', + value: 'jibberjabber', + }; + + expect(formattedEntry).toEqual(expected); + }); + }); + + describe('#getOperatingSystems', () => { + test('it returns null if no operating system tag specified', () => { + const result = getOperatingSystems(['some tag', 'some other tag']); + + expect(result).toBeNull(); + }); + + test('it returns null if operating system tag malformed', () => { + const result = getOperatingSystems(['some tag', 'jibberos:mac,windows', 'some other tag']); + + expect(result).toBeNull(); + }); + + test('it returns formatted operating systems if specified in tags', () => { + const result = getOperatingSystems(['some tag', 'os:mac,windows', 'some other tag']); + + expect(result).toEqual('Mac, Windows'); + }); + + test('it returns formatted operating systems if space included in os tag', () => { + const result = getOperatingSystems(['some tag', 'os: mac, windows', 'some other tag']); + + expect(result).toEqual('Mac, Windows'); + }); + }); + + describe('#getTagsInclude', () => { + test('it returns a tuple of "false" and "null" if no matches found', () => { + const result = getTagsInclude({ tags: ['some', 'tags', 'here'], regex: /(no match)/ }); + + expect(result).toEqual([false, null]); + }); + + test('it returns a tuple of "true" and matching string if matches found', () => { + const result = getTagsInclude({ tags: ['some', 'tags', 'here'], regex: /(some)/ }); + + expect(result).toEqual([true, 'some']); + }); + }); + + describe('#getDescriptionListContent', () => { + test('it returns formatted description list with os if one is specified', () => { + const payload = getExceptionItemMock(); + const result = getDescriptionListContent(payload); + const expected: DescriptionListItem[] = [ + { + description: 'Windows', + title: 'OS', + }, + { + description: 'April 22nd 2020 @ 20:19:13', + title: 'Date Created', + }, + { + description: 'user_name', + title: 'Created by', + }, + ]; + + expect(result).toEqual(expected); + }); + + test('it returns formatted description list with a description if one specified', () => { + const payload = getExceptionItemMock(); + payload._tags = []; + payload.description = 'Im a description'; + const result = getDescriptionListContent(payload); + const expected: DescriptionListItem[] = [ + { + description: 'April 22nd 2020 @ 20:19:13', + title: 'Date Created', + }, + { + description: 'user_name', + title: 'Created by', + }, + { + description: 'Im a description', + title: 'Comment', + }, + ]; + + expect(result).toEqual(expected); + }); + + test('it returns just user and date created if no other fields specified', () => { + const payload = getExceptionItemMock(); + payload._tags = []; + payload.description = ''; + const result = getDescriptionListContent(payload); + const expected: DescriptionListItem[] = [ + { + description: 'April 22nd 2020 @ 20:19:13', + title: 'Date Created', + }, + { + description: 'user_name', + title: 'Created by', + }, + ]; + + expect(result).toEqual(expected); + }); + }); + + describe('#getFormattedComments', () => { + test('it returns formatted comment object with username and timestamp', () => { + const payload = getExceptionItemMock().comments; + const result = getFormattedComments(payload); + + expect(result[0].username).toEqual('user_name'); + expect(result[0].timestamp).toEqual('on Apr 22nd 2020 @ 20:19:13'); + }); + + test('it returns formatted timeline icon with comment users initial', () => { + const payload = getExceptionItemMock().comments; + const result = getFormattedComments(payload); + + const wrapper = mount(result[0].timelineIcon as React.ReactElement); + + expect(wrapper.text()).toEqual('U'); + }); + + test('it returns comment text', () => { + const payload = getExceptionItemMock().comments; + const result = getFormattedComments(payload); + + const wrapper = mount(result[0].children as React.ReactElement); + + expect(wrapper.text()).toEqual('Comment goes here'); + }); + }); +}); diff --git a/x-pack/plugins/siem/public/common/components/exceptions/helpers.tsx b/x-pack/plugins/siem/public/common/components/exceptions/helpers.tsx new file mode 100644 index 0000000000000..b94c15e8ac153 --- /dev/null +++ b/x-pack/plugins/siem/public/common/components/exceptions/helpers.tsx @@ -0,0 +1,197 @@ +/* + * 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 React from 'react'; +import { EuiText, EuiCommentProps, EuiAvatar } from '@elastic/eui'; +import { flatten, capitalize } from 'lodash'; +import moment from 'moment'; + +import { + FormattedEntry, + OperatorType, + OperatorOption, + ExceptionEntry, + NestedExceptionEntry, + DescriptionListItem, + Comment, + ExceptionListItemSchema, +} from './types'; +import { EXCEPTION_OPERATORS, isOperator } from './operators'; + +export const getEmptyValue = () => '—'; + +/** + * Returns the operator type, may not need this if using io-ts types + * + * @param entry a single ExceptionItem entry + */ +export const getOperatorType = (entry: ExceptionEntry): OperatorType => { + switch (entry.type) { + case 'nested': + case 'match': + return OperatorType.PHRASE; + case 'match_any': + return OperatorType.PHRASES; + case 'list': + return OperatorType.LIST; + default: + return OperatorType.EXISTS; + } +}; + +/** + * Determines operator selection (is/is not/is one of, etc.) + * Default operator is "is" + * + * @param entry a single ExceptionItem entry + */ +export const getExceptionOperatorSelect = (entry: ExceptionEntry): OperatorOption => { + const operatorType = getOperatorType(entry); + const foundOperator = EXCEPTION_OPERATORS.find((operatorOption) => { + return entry.operator === operatorOption.operator && operatorType === operatorOption.type; + }); + + return foundOperator ?? isOperator; +}; + +export const determineIfIsNested = ( + tbd: ExceptionEntry | NestedExceptionEntry +): tbd is NestedExceptionEntry => { + if (tbd.type === 'nested') { + return true; + } + return false; +}; + +/** + * Formats ExceptionItem entries into simple field, operator, value + * for use in rendering items in table + * + * @param entries an ExceptionItem's entries + */ +export const getFormattedEntries = ( + entries: Array +): FormattedEntry[] => { + const formattedEntries = entries.map((entry) => { + if (determineIfIsNested(entry)) { + const parent = { fieldName: entry.field, operator: null, value: null, isNested: false }; + return entry.entries.reduce( + (acc, nestedEntry) => { + const formattedEntry = formatEntry({ + isNested: true, + parent: entry.field, + item: nestedEntry, + }); + return [...acc, { ...formattedEntry }]; + }, + [parent] + ); + } else { + return formatEntry({ isNested: false, item: entry }); + } + }); + + return flatten(formattedEntries); +}; + +/** + * Helper method for `getFormattedEntries` + */ +export const formatEntry = ({ + isNested, + parent, + item, +}: { + isNested: boolean; + parent?: string; + item: ExceptionEntry; +}) => { + const operator = getExceptionOperatorSelect(item); + const operatorType = getOperatorType(item); + const value = operatorType === OperatorType.EXISTS ? null : item.value; + + return { + fieldName: isNested ? `${parent}.${item.field}` : item.field, + operator: operator.message, + value, + isNested, + }; +}; + +export const getOperatingSystems = (tags: string[]): string | null => { + const [includesOs, osMatch] = getTagsInclude({ tags, regex: /(?<=\b)(os:[^;]*)(?=\b)/ }); + if (includesOs && osMatch !== null) { + const os = osMatch.split(':')[1]; + const items = os.split(',').map((item) => { + return capitalize(item.trim()); + }); + return items.join(', '); + } else { + return null; + } +}; + +export const getTagsInclude = ({ + tags, + regex, +}: { + tags: string[]; + regex: RegExp; +}): [boolean, string | null] => { + const matches: string[] | null = tags.join(';').match(regex); + const match = matches !== null ? matches[1] : null; + return [matches !== null, match]; +}; + +/** + * Formats ExceptionItem information for description list component + * + * @param exceptionItem an ExceptionItem + */ +export const getDescriptionListContent = ( + exceptionItem: ExceptionListItemSchema +): DescriptionListItem[] => { + const details = [ + { + title: 'OS', + value: getOperatingSystems(exceptionItem._tags), + }, + { + title: 'Date Created', + value: moment(exceptionItem.created_at).format('MMMM Do YYYY @ HH:mm:ss'), + }, + { + title: 'Created by', + value: exceptionItem.created_by, + }, + { + title: 'Comment', + value: exceptionItem.description, + }, + ]; + + return details.reduce((acc, { value, title }) => { + if (value !== null && value) { + return [...acc, { title, description: value }]; + } else { + return acc; + } + }, []); +}; + +/** + * Formats ExceptionItem.comments into EuiCommentList format + * + * @param comments ExceptionItem.comments + */ +export const getFormattedComments = (comments: Comment[]): EuiCommentProps[] => + comments.map((comment) => ({ + username: comment.user, + timestamp: moment(comment.timestamp).format('on MMM Do YYYY @ HH:mm:ss'), + event: 'added a comment', + timelineIcon: , + children: {comment.comment}, + })); diff --git a/x-pack/plugins/siem/public/common/components/exceptions/operators.ts b/x-pack/plugins/siem/public/common/components/exceptions/operators.ts new file mode 100644 index 0000000000000..9b553c5af9bd5 --- /dev/null +++ b/x-pack/plugins/siem/public/common/components/exceptions/operators.ts @@ -0,0 +1,91 @@ +/* + * 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'; +import { OperatorOption, OperatorType, Operator } from './types'; + +export const isOperator: OperatorOption = { + message: i18n.translate('xpack.siem.exceptions.isOperatorLabel', { + defaultMessage: 'is', + }), + value: 'is', + type: OperatorType.PHRASE, + operator: Operator.INCLUSION, +}; + +export const isNotOperator: OperatorOption = { + message: i18n.translate('xpack.siem.exceptions.isNotOperatorLabel', { + defaultMessage: 'is not', + }), + value: 'is_not', + type: OperatorType.PHRASE, + operator: Operator.EXCLUSION, +}; + +export const isOneOfOperator: OperatorOption = { + message: i18n.translate('xpack.siem.exceptions.isOneOfOperatorLabel', { + defaultMessage: 'is one of', + }), + value: 'is_one_of', + type: OperatorType.PHRASES, + operator: Operator.INCLUSION, +}; + +export const isNotOneOfOperator: OperatorOption = { + message: i18n.translate('xpack.siem.exceptions.isNotOneOfOperatorLabel', { + defaultMessage: 'is not one of', + }), + value: 'is_not_one_of', + type: OperatorType.PHRASES, + operator: Operator.EXCLUSION, +}; + +export const existsOperator: OperatorOption = { + message: i18n.translate('xpack.siem.exceptions.existsOperatorLabel', { + defaultMessage: 'exists', + }), + value: 'exists', + type: OperatorType.EXISTS, + operator: Operator.INCLUSION, +}; + +export const doesNotExistOperator: OperatorOption = { + message: i18n.translate('xpack.siem.exceptions.doesNotExistOperatorLabel', { + defaultMessage: 'does not exist', + }), + value: 'does_not_exist', + type: OperatorType.EXISTS, + operator: Operator.EXCLUSION, +}; + +export const isInListOperator: OperatorOption = { + message: i18n.translate('xpack.siem.exceptions.isInListOperatorLabel', { + defaultMessage: 'is in list', + }), + value: 'is_in_list', + type: OperatorType.LIST, + operator: Operator.INCLUSION, +}; + +export const isNotInListOperator: OperatorOption = { + message: i18n.translate('xpack.siem.exceptions.isNotInListOperatorLabel', { + defaultMessage: 'is not in list', + }), + value: 'is_not_in_list', + type: OperatorType.LIST, + operator: Operator.EXCLUSION, +}; + +export const EXCEPTION_OPERATORS: OperatorOption[] = [ + isOperator, + isNotOperator, + isOneOfOperator, + isNotOneOfOperator, + existsOperator, + doesNotExistOperator, + isInListOperator, + isNotInListOperator, +]; diff --git a/x-pack/plugins/siem/public/common/components/exceptions/translations.ts b/x-pack/plugins/siem/public/common/components/exceptions/translations.ts new file mode 100644 index 0000000000000..8c69de5b2a371 --- /dev/null +++ b/x-pack/plugins/siem/public/common/components/exceptions/translations.ts @@ -0,0 +1,26 @@ +/* + * 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 EDIT = i18n.translate('xpack.siem.exceptions.editButtonLabel', { + defaultMessage: 'Edit', +}); + +export const REMOVE = i18n.translate('xpack.siem.exceptions.removeButtonLabel', { + defaultMessage: 'Remove', +}); + +export const COMMENTS_SHOW = (comments: number) => + i18n.translate('xpack.siem.exceptions.showCommentsLabel', { + values: { comments }, + defaultMessage: 'Show ({comments}) {comments, plural, =1 {Comment} other {Comments}}', + }); + +export const COMMENTS_HIDE = (comments: number) => + i18n.translate('xpack.siem.exceptions.hideCommentsLabel', { + values: { comments }, + defaultMessage: 'Hide ({comments}) {comments, plural, =1 {Comment} other {Comments}}', + }); diff --git a/x-pack/plugins/siem/public/common/components/exceptions/types.ts b/x-pack/plugins/siem/public/common/components/exceptions/types.ts new file mode 100644 index 0000000000000..e8393610e459d --- /dev/null +++ b/x-pack/plugins/siem/public/common/components/exceptions/types.ts @@ -0,0 +1,78 @@ +/* + * 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 { ReactNode } from 'react'; + +export interface OperatorOption { + message: string; + value: string; + operator: Operator; + type: OperatorType; +} + +export enum Operator { + INCLUSION = 'included', + EXCLUSION = 'excluded', +} + +export enum OperatorType { + NESTED = 'nested', + PHRASE = 'match', + PHRASES = 'match_any', + EXISTS = 'exists', + LIST = 'list', +} + +export interface FormattedEntry { + fieldName: string; + operator: string | null; + value: string | null; + isNested: boolean; +} + +export interface NestedExceptionEntry { + field: string; + type: string; + entries: ExceptionEntry[]; +} + +export interface ExceptionEntry { + field: string; + type: string; + operator: Operator; + value: string; +} + +export interface DescriptionListItem { + title: NonNullable; + description: NonNullable; +} + +export interface Comment { + user: string; + timestamp: string; + comment: string; +} + +// TODO: Delete once types are updated +export interface ExceptionListItemSchema { + _tags: string[]; + comments: Comment[]; + created_at: string; + created_by: string; + description?: string; + entries: Array; + id: string; + item_id: string; + list_id: string; + meta?: unknown; + name: string; + namespace_type: 'single' | 'agnostic'; + tags: string[]; + tie_breaker_id: string; + type: string; + updated_at: string; + updated_by: string; +} diff --git a/x-pack/plugins/siem/public/common/components/exceptions/viewer/exception_details.tsx b/x-pack/plugins/siem/public/common/components/exceptions/viewer/exception_details.tsx new file mode 100644 index 0000000000000..c3edccba5a660 --- /dev/null +++ b/x-pack/plugins/siem/public/common/components/exceptions/viewer/exception_details.tsx @@ -0,0 +1,79 @@ +/* + * 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 { EuiFlexItem, EuiFlexGroup, EuiDescriptionList, EuiButtonEmpty } from '@elastic/eui'; +import React, { useMemo } from 'react'; +import styled, { css } from 'styled-components'; +import { transparentize } from 'polished'; + +import { ExceptionListItemSchema } from '../types'; +import { getDescriptionListContent } from '../helpers'; +import * as i18n from '../translations'; + +const StyledExceptionDetails = styled(EuiFlexItem)` + ${({ theme }) => css` + background-color: ${transparentize(0.95, theme.eui.euiColorPrimary)}; + padding: 16px; + + .euiDescriptionList__title.listTitle--width { + width: 40%; + } + + .euiDescriptionList__description.listDescription--width { + width: 60%; + } + `} +`; + +const ExceptionDetailsComponent = ({ + showComments, + onCommentsClick, + exceptionItem, +}: { + showComments: boolean; + exceptionItem: ExceptionListItemSchema; + onCommentsClick: () => void; +}) => { + const descriptionList = useMemo(() => getDescriptionListContent(exceptionItem), [exceptionItem]); + + const commentsSection = useMemo(() => { + const { comments } = exceptionItem; + if (comments !== null && comments && comments.length > 0) { + return ( + + {!showComments + ? i18n.COMMENTS_SHOW(comments.length) + : i18n.COMMENTS_HIDE(comments.length)} + + ); + } else { + return <>; + } + }, [showComments, onCommentsClick, exceptionItem]); + + return ( + + + + + + {commentsSection} + + + ); +}; + +ExceptionDetailsComponent.displayName = 'ExceptionDetailsComponent'; + +export const ExceptionDetails = React.memo(ExceptionDetailsComponent); + +ExceptionDetails.displayName = 'ExceptionDetails'; diff --git a/x-pack/plugins/siem/public/common/components/exceptions/viewer/exception_entries.tsx b/x-pack/plugins/siem/public/common/components/exceptions/viewer/exception_entries.tsx new file mode 100644 index 0000000000000..373ecedc95441 --- /dev/null +++ b/x-pack/plugins/siem/public/common/components/exceptions/viewer/exception_entries.tsx @@ -0,0 +1,148 @@ +/* + * 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 { EuiBasicTable, EuiIconTip, EuiFlexItem, EuiFlexGroup, EuiButton } from '@elastic/eui'; +import React, { useMemo } from 'react'; +import styled, { css } from 'styled-components'; +import { transparentize } from 'polished'; + +import { AndOrBadge } from '../../and_or_badge'; +import { getEmptyValue } from '../helpers'; +import * as i18n from '../translations'; +import { FormattedEntry } from '../types'; + +const EntriesDetails = styled(EuiFlexItem)` + padding: 16px; +`; + +const StyledEditButton = styled(EuiButton)` + ${({ theme }) => css` + background-color: ${transparentize(0.9, theme.eui.euiColorPrimary)}; + width: 111px; + border: none; + font-weight: 600; + `} +`; + +const StyledRemoveButton = styled(EuiButton)` + ${({ theme }) => css` + background-color: ${transparentize(0.9, theme.eui.euiColorDanger)}; + width: 111px; + border: none; + font-weight: 600; + `} +`; + +const AndOrBadgeContainer = styled(EuiFlexItem)` + padding-top: 32px; +`; + +interface ExceptionEntriesComponentProps { + entries: FormattedEntry[]; + handleDelete: () => void; + handleEdit: () => void; +} + +const ExceptionEntriesComponent = ({ + entries, + handleDelete, + handleEdit, +}: ExceptionEntriesComponentProps) => { + const columns = useMemo( + () => [ + { + field: 'fieldName', + name: 'Field', + sortable: false, + truncateText: true, + 'data-test-subj': 'exceptionFieldNameCell', + width: '30%', + render: (value: string | null, data: FormattedEntry) => { + if (value !== null && data.isNested) { + return ( + <> + + {value} + + ); + } else { + return value ?? getEmptyValue(); + } + }, + }, + { + field: 'operator', + name: 'Operator', + sortable: false, + truncateText: true, + 'data-test-subj': 'exceptionFieldOperatorCell', + width: '20%', + render: (value: string | null) => value ?? getEmptyValue(), + }, + { + field: 'value', + name: 'Value', + sortable: false, + truncateText: true, + 'data-test-subj': 'exceptionFieldValueCell', + width: '60%', + render: (values: string | string[] | null) => { + if (Array.isArray(values)) { + return ( + + {values.map((value) => { + return {value}; + })} + + ); + } else { + return values ?? getEmptyValue(); + } + }, + }, + ], + [entries] + ); + + return ( + + + + + {entries.length > 1 && ( + + + + )} + + + + + + + + + + {i18n.EDIT} + + + + handleDelete()}> + {i18n.REMOVE} + + + + + + + ); +}; + +ExceptionEntriesComponent.displayName = 'ExceptionEntriesComponent'; + +export const ExceptionEntries = React.memo(ExceptionEntriesComponent); + +ExceptionEntries.displayName = 'ExceptionEntries'; diff --git a/x-pack/plugins/siem/public/common/components/exceptions/viewer/index.tsx b/x-pack/plugins/siem/public/common/components/exceptions/viewer/index.tsx new file mode 100644 index 0000000000000..a35ec3521e84c --- /dev/null +++ b/x-pack/plugins/siem/public/common/components/exceptions/viewer/index.tsx @@ -0,0 +1,89 @@ +/* + * 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 { EuiPanel, EuiFlexGroup, EuiCommentList, EuiAccordion, EuiFlexItem } from '@elastic/eui'; +import React, { useEffect, useState, useMemo, useCallback } from 'react'; +import styled from 'styled-components'; + +import { ExceptionDetails } from './exception_details'; +import { ExceptionEntries } from './exception_entries'; +import { getFormattedEntries, getFormattedComments } from '../helpers'; +import { FormattedEntry, ExceptionListItemSchema } from '../types'; + +const MyFlexItem = styled(EuiFlexItem)` + &.comments--show { + padding: 16px; + border-top: 1px solid #d3dae6; + } +`; + +interface ExceptionItemProps { + exceptionItem: ExceptionListItemSchema; + handleDelete: ({ id }: { id: string }) => void; + handleEdit: (item: ExceptionListItemSchema) => void; +} + +const ExceptionItemComponent = ({ + exceptionItem, + handleDelete, + handleEdit, +}: ExceptionItemProps) => { + const [entryItems, setEntryItems] = useState([]); + const [showComments, setShowComments] = useState(false); + + useEffect(() => { + const formattedEntries = getFormattedEntries(exceptionItem.entries ?? []); + setEntryItems([...formattedEntries]); + }, [exceptionItem.entries]); + + const onDelete = useCallback(() => { + handleDelete({ id: exceptionItem.id }); + }, [handleDelete, exceptionItem]); + + const onEdit = useCallback(() => { + handleEdit(exceptionItem); + }, [handleEdit, exceptionItem]); + + const onCommentsClick = useCallback(() => { + setShowComments(!showComments); + }, [setShowComments, showComments]); + + const formattedComments = useMemo(() => { + return getFormattedComments(exceptionItem.comments ?? []); + }, [exceptionItem]); + + return ( + + + + + + + + + + + + + + + + ); +}; + +ExceptionItemComponent.displayName = 'ExceptionItemComponent'; + +export const ExceptionItem = React.memo(ExceptionItemComponent); + +ExceptionItem.displayName = 'ExceptionItem'; diff --git a/x-pack/plugins/siem/public/lists_plugin_deps.ts b/x-pack/plugins/siem/public/lists_plugin_deps.ts index d2ee5ae56b7d9..350b53ef52f4e 100644 --- a/x-pack/plugins/siem/public/lists_plugin_deps.ts +++ b/x-pack/plugins/siem/public/lists_plugin_deps.ts @@ -11,3 +11,4 @@ export { mockNewExceptionItem, mockNewExceptionList, } from '../../lists/public'; +export { ExceptionListItemSchema, Entries } from '../../lists/common/schemas'; From dd2b8c8bc327ab7a940384ef06b516fe0de9b992 Mon Sep 17 00:00:00 2001 From: Yara Tercero Date: Tue, 2 Jun 2020 17:17:14 -0400 Subject: [PATCH 04/32] added exception item component stories for easy testing --- x-pack/plugins/siem/scripts/storybook.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/x-pack/plugins/siem/scripts/storybook.js b/x-pack/plugins/siem/scripts/storybook.js index 6566236704936..5f06f2a4ebb12 100644 --- a/x-pack/plugins/siem/scripts/storybook.js +++ b/x-pack/plugins/siem/scripts/storybook.js @@ -9,5 +9,5 @@ import { join } from 'path'; // eslint-disable-next-line require('@kbn/storybook').runStorybookCli({ name: 'siem', - storyGlobs: [join(__dirname, '..', 'public', 'components', '**', '*.stories.tsx')], + storyGlobs: [join(__dirname, '..', 'public', '**', 'components', '**', '*.stories.tsx')], }); From 990d656db5f522b141750b4bb64e8cadeb468e75 Mon Sep 17 00:00:00 2001 From: Yara Tercero Date: Tue, 2 Jun 2020 17:34:24 -0400 Subject: [PATCH 05/32] updated text to use i18n in spots missed --- .../common/components/exceptions/helpers.tsx | 11 ++++++----- .../common/components/exceptions/translations.ts | 16 ++++++++++++++++ 2 files changed, 22 insertions(+), 5 deletions(-) diff --git a/x-pack/plugins/siem/public/common/components/exceptions/helpers.tsx b/x-pack/plugins/siem/public/common/components/exceptions/helpers.tsx index b94c15e8ac153..2182b6cf79925 100644 --- a/x-pack/plugins/siem/public/common/components/exceptions/helpers.tsx +++ b/x-pack/plugins/siem/public/common/components/exceptions/helpers.tsx @@ -9,6 +9,7 @@ import { EuiText, EuiCommentProps, EuiAvatar } from '@elastic/eui'; import { flatten, capitalize } from 'lodash'; import moment from 'moment'; +import * as i18n from './translations'; import { FormattedEntry, OperatorType, @@ -156,19 +157,19 @@ export const getDescriptionListContent = ( ): DescriptionListItem[] => { const details = [ { - title: 'OS', + title: i18n.OPERATING_SYSTEM, value: getOperatingSystems(exceptionItem._tags), }, { - title: 'Date Created', + title: i18n.DATE_CREATED, value: moment(exceptionItem.created_at).format('MMMM Do YYYY @ HH:mm:ss'), }, { - title: 'Created by', + title: i18n.CREATED_BY, value: exceptionItem.created_by, }, { - title: 'Comment', + title: i18n.COMMENT, value: exceptionItem.description, }, ]; @@ -191,7 +192,7 @@ export const getFormattedComments = (comments: Comment[]): EuiCommentProps[] => comments.map((comment) => ({ username: comment.user, timestamp: moment(comment.timestamp).format('on MMM Do YYYY @ HH:mm:ss'), - event: 'added a comment', + event: i18n.COMMENT_EVENT, timelineIcon: , children: {comment.comment}, })); diff --git a/x-pack/plugins/siem/public/common/components/exceptions/translations.ts b/x-pack/plugins/siem/public/common/components/exceptions/translations.ts index 8c69de5b2a371..5f7f5b2811921 100644 --- a/x-pack/plugins/siem/public/common/components/exceptions/translations.ts +++ b/x-pack/plugins/siem/public/common/components/exceptions/translations.ts @@ -24,3 +24,19 @@ export const COMMENTS_HIDE = (comments: number) => values: { comments }, defaultMessage: 'Hide ({comments}) {comments, plural, =1 {Comment} other {Comments}}', }); + +export const DATE_CREATED = i18n.translate('xpack.siem.exceptions.dateCreatedLabel', { + defaultMessage: 'Date created', +}); + +export const CREATED_BY = i18n.translate('xpack.siem.exceptions.createdByLabel', { + defaultMessage: 'Created by', +}); + +export const COMMENT = i18n.translate('xpack.siem.exceptions.commentLabel', { + defaultMessage: 'Comment', +}); + +export const OPERATING_SYSTEM = i18n.translate('xpack.siem.exceptions.operatingSystemLabel', { + defaultMessage: 'OS', +}); From bac11c98eb2b6a192e538b3693f0982a7f975d14 Mon Sep 17 00:00:00 2001 From: Yara Tercero Date: Tue, 2 Jun 2020 19:42:02 -0400 Subject: [PATCH 06/32] added tests for exception detail component and updated braking tests --- .../components/exceptions/helpers.test.tsx | 6 +- .../common/components/exceptions/mocks.ts | 63 +++++ .../viewer/exception_details.test.tsx | 221 ++++++++++++++++++ .../exceptions/viewer/exception_details.tsx | 8 +- 4 files changed, 294 insertions(+), 4 deletions(-) create mode 100644 x-pack/plugins/siem/public/common/components/exceptions/mocks.ts create mode 100644 x-pack/plugins/siem/public/common/components/exceptions/viewer/exception_details.test.tsx diff --git a/x-pack/plugins/siem/public/common/components/exceptions/helpers.test.tsx b/x-pack/plugins/siem/public/common/components/exceptions/helpers.test.tsx index f07f3a959b40d..4b74b47d8e433 100644 --- a/x-pack/plugins/siem/public/common/components/exceptions/helpers.test.tsx +++ b/x-pack/plugins/siem/public/common/components/exceptions/helpers.test.tsx @@ -437,7 +437,7 @@ describe('Exception helpers', () => { }, { description: 'April 22nd 2020 @ 20:19:13', - title: 'Date Created', + title: 'Date created', }, { description: 'user_name', @@ -456,7 +456,7 @@ describe('Exception helpers', () => { const expected: DescriptionListItem[] = [ { description: 'April 22nd 2020 @ 20:19:13', - title: 'Date Created', + title: 'Date created', }, { description: 'user_name', @@ -479,7 +479,7 @@ describe('Exception helpers', () => { const expected: DescriptionListItem[] = [ { description: 'April 22nd 2020 @ 20:19:13', - title: 'Date Created', + title: 'Date created', }, { description: 'user_name', diff --git a/x-pack/plugins/siem/public/common/components/exceptions/mocks.ts b/x-pack/plugins/siem/public/common/components/exceptions/mocks.ts new file mode 100644 index 0000000000000..4135840e63d10 --- /dev/null +++ b/x-pack/plugins/siem/public/common/components/exceptions/mocks.ts @@ -0,0 +1,63 @@ +/* + * 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 { Operator } from './types'; + +export const getExceptionItemMock = (): ExceptionListItemSchema => ({ + id: 'uuid_here', + item_id: 'item-id', + created_at: '2020-04-23T00:19:13.289Z', + created_by: 'user_name', + list_id: 'test-exception', + tie_breaker_id: '77fd1909-6786-428a-a671-30229a719c1f', + updated_at: '2020-04-23T00:19:13.289Z', + updated_by: 'user_name', + namespace_type: 'single', + name: '', + description: 'This is a description', + comments: [ + { + user: 'user_name', + timestamp: '2020-04-23T00:19:13.289Z', + comment: 'Comment goes here', + }, + ], + _tags: ['os:windows'], + tags: [], + type: 'simple', + entries: [ + { + field: 'actingProcess.file.signer', + type: 'match', + operator: Operator.INCLUSION, + value: 'Elastic, N.V.', + }, + { + field: 'host.name', + type: 'match', + operator: Operator.EXCLUSION, + value: 'Global Signer', + }, + { + field: 'file.signature', + type: 'nested', + entries: [ + { + field: 'signer', + type: 'match', + operator: Operator.INCLUSION, + value: 'Evil', + }, + { + field: 'trusted', + type: 'match', + operator: Operator.INCLUSION, + value: 'true', + }, + ], + }, + ], +}); diff --git a/x-pack/plugins/siem/public/common/components/exceptions/viewer/exception_details.test.tsx b/x-pack/plugins/siem/public/common/components/exceptions/viewer/exception_details.test.tsx new file mode 100644 index 0000000000000..b104e7806f9fc --- /dev/null +++ b/x-pack/plugins/siem/public/common/components/exceptions/viewer/exception_details.test.tsx @@ -0,0 +1,221 @@ +/* + * 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 React from 'react'; +import { ThemeProvider } from 'styled-components'; +import { mount } from 'enzyme'; +import euiLightVars from '@elastic/eui/dist/eui_theme_light.json'; + +import { ExceptionDetails } from './exception_details'; +import { getExceptionItemMock } from '../mocks'; + +describe('ExceptionDetails', () => { + test('it renders no comments button if no comments exist', () => { + const exceptionItem = getExceptionItemMock(); + exceptionItem.comments = []; + + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + + expect( + wrapper.find('EuiButtonEmpty[data-test-subj="exceptionsViewerItemCommentsBtn"]') + ).toHaveLength(0); + }); + + test('it renders comments button if comments exist', () => { + const exceptionItem = getExceptionItemMock(); + + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + + expect( + wrapper.find('EuiButtonEmpty[data-test-subj="exceptionsViewerItemCommentsBtn"]') + ).toHaveLength(1); + }); + + test('it renders correct number of comments', () => { + const exceptionItem = getExceptionItemMock(); + + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + + expect( + wrapper.find('EuiButtonEmpty[data-test-subj="exceptionsViewerItemCommentsBtn"]').at(0).text() + ).toEqual('Show (1) Comment'); + }); + + test('it renders comments plural if more than one', () => { + const exceptionItem = getExceptionItemMock(); + exceptionItem.comments = [ + { + user: 'user_1', + timestamp: '2020-04-23T00:19:13.289Z', + comment: 'Comment goes here', + }, + { + user: 'user_2', + timestamp: '2020-04-23T00:19:13.289Z', + comment: 'Comment goes here', + }, + ]; + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + + expect( + wrapper.find('EuiButtonEmpty[data-test-subj="exceptionsViewerItemCommentsBtn"]').at(0).text() + ).toEqual('Show (2) Comments'); + }); + + test('it renders comments show text if "showComments" is false', () => { + const exceptionItem = getExceptionItemMock(); + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + + expect( + wrapper.find('EuiButtonEmpty[data-test-subj="exceptionsViewerItemCommentsBtn"]').at(0).text() + ).toEqual('Show (1) Comment'); + }); + + test('it renders comments hide text if "showComments" is true', () => { + const exceptionItem = getExceptionItemMock(); + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + + expect( + wrapper.find('EuiButtonEmpty[data-test-subj="exceptionsViewerItemCommentsBtn"]').at(0).text() + ).toEqual('Hide (1) Comment'); + }); + + test('it invokes "onCommentsClick" when comments button clicked', () => { + const mockOnCommentsClick = jest.fn(); + const exceptionItem = getExceptionItemMock(); + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + const commentsBtn = wrapper + .find('EuiButtonEmpty[data-test-subj="exceptionsViewerItemCommentsBtn"]') + .at(0); + commentsBtn.simulate('click'); + + expect(mockOnCommentsClick).toHaveBeenCalledTimes(1); + }); + + test('it renders the operating system if one is specified in the exception item', () => { + const exceptionItem = getExceptionItemMock(); + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + + expect(wrapper.find('EuiDescriptionListTitle').at(0).text()).toEqual('OS'); + expect(wrapper.find('EuiDescriptionListDescription').at(0).text()).toEqual('Windows'); + }); + + test('it renders the exception item creator', () => { + const exceptionItem = getExceptionItemMock(); + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + + expect(wrapper.find('EuiDescriptionListTitle').at(1).text()).toEqual('Date created'); + expect(wrapper.find('EuiDescriptionListDescription').at(1).text()).toEqual( + 'April 22nd 2020 @ 20:19:13' + ); + }); + + test('it renders the exception item creation timestamp', () => { + const exceptionItem = getExceptionItemMock(); + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + + expect(wrapper.find('EuiDescriptionListTitle').at(2).text()).toEqual('Created by'); + expect(wrapper.find('EuiDescriptionListDescription').at(2).text()).toEqual('user_name'); + }); + + test('it renders the description if one is included on the exception item', () => { + const exceptionItem = getExceptionItemMock(); + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + + expect(wrapper.find('EuiDescriptionListTitle').at(3).text()).toEqual('Comment'); + expect(wrapper.find('EuiDescriptionListDescription').at(3).text()).toEqual( + 'This is a description' + ); + }); +}); diff --git a/x-pack/plugins/siem/public/common/components/exceptions/viewer/exception_details.tsx b/x-pack/plugins/siem/public/common/components/exceptions/viewer/exception_details.tsx index c3edccba5a660..15b6425956c34 100644 --- a/x-pack/plugins/siem/public/common/components/exceptions/viewer/exception_details.tsx +++ b/x-pack/plugins/siem/public/common/components/exceptions/viewer/exception_details.tsx @@ -43,7 +43,12 @@ const ExceptionDetailsComponent = ({ const { comments } = exceptionItem; if (comments !== null && comments && comments.length > 0) { return ( - + {!showComments ? i18n.COMMENTS_SHOW(comments.length) : i18n.COMMENTS_HIDE(comments.length)} @@ -64,6 +69,7 @@ const ExceptionDetailsComponent = ({ listItems={descriptionList} titleProps={{ className: 'listTitle--width' }} descriptionProps={{ className: 'listDescription--width' }} + data-test-subj="exceptionsViewerItemDetails" /> {commentsSection} From 94960850386ded56ebb7986be953d0f321e4d63b Mon Sep 17 00:00:00 2001 From: Yara Tercero Date: Tue, 2 Jun 2020 22:22:46 -0400 Subject: [PATCH 07/32] finished adding tests and fixing lint issue --- .../components/exceptions/helpers.test.tsx | 81 ++-------- .../common/components/exceptions/mocks.ts | 28 +++- .../components/exceptions/translations.ts | 4 + .../viewer/exception_entries.test.tsx | 149 ++++++++++++++++++ .../exceptions/viewer/exception_entries.tsx | 24 ++- .../exceptions/viewer/index.test.tsx | 111 +++++++++++++ .../components/exceptions/viewer/index.tsx | 1 + x-pack/plugins/siem/public/graphql/types.ts | 2 + 8 files changed, 323 insertions(+), 77 deletions(-) create mode 100644 x-pack/plugins/siem/public/common/components/exceptions/viewer/exception_entries.test.tsx create mode 100644 x-pack/plugins/siem/public/common/components/exceptions/viewer/index.test.tsx diff --git a/x-pack/plugins/siem/public/common/components/exceptions/helpers.test.tsx b/x-pack/plugins/siem/public/common/components/exceptions/helpers.test.tsx index 4b74b47d8e433..85221b9da0803 100644 --- a/x-pack/plugins/siem/public/common/components/exceptions/helpers.test.tsx +++ b/x-pack/plugins/siem/public/common/components/exceptions/helpers.test.tsx @@ -21,10 +21,8 @@ import { OperatorType, Operator, NestedExceptionEntry, - ExceptionEntry, FormattedEntry, DescriptionListItem, - ExceptionListItemSchema, } from './types'; import { isOperator, @@ -36,69 +34,7 @@ import { existsOperator, doesNotExistOperator, } from './operators'; - -const getExceptionItemMock = (): ExceptionListItemSchema => ({ - id: 'uuid_here', - item_id: 'item-id', - created_at: '2020-04-23T00:19:13.289Z', - created_by: 'user_name', - list_id: 'test-exception', - tie_breaker_id: '77fd1909-6786-428a-a671-30229a719c1f', - updated_at: '2020-04-23T00:19:13.289Z', - updated_by: 'user_name', - namespace_type: 'single', - name: '', - description: '', - comments: [ - { - user: 'user_name', - timestamp: '2020-04-23T00:19:13.289Z', - comment: 'Comment goes here', - }, - ], - _tags: ['os:windows'], - tags: [], - type: 'simple', - entries: [ - { - field: 'actingProcess.file.signer', - type: 'match', - operator: Operator.INCLUSION, - value: 'Elastic, N.V.', - }, - { - field: 'host.name', - type: 'match', - operator: Operator.EXCLUSION, - value: 'Global Signer', - }, - { - field: 'file.signature', - type: 'nested', - entries: [ - { - field: 'signer', - type: 'match', - operator: Operator.INCLUSION, - value: 'Evil', - }, - { - field: 'trusted', - type: 'match', - operator: Operator.INCLUSION, - value: 'true', - }, - ], - }, - ], -}); - -const getExceptionItemEntryMock = (): ExceptionEntry => ({ - field: 'host.name', - type: 'match', - operator: Operator.INCLUSION, - value: 'jibberjabber', -}); +import { getExceptionItemEntryMock, getExceptionItemMock } from './mocks'; describe('Exception helpers', () => { describe('#getOperatorType', () => { @@ -217,7 +153,7 @@ describe('Exception helpers', () => { describe('#determineIfIsNested', () => { test('it returns true if type NestedExceptionEntry', () => { const payload: NestedExceptionEntry = { - field: 'host.name', + field: 'actingProcess.file.signer', type: 'nested', entries: [], }; @@ -295,7 +231,7 @@ describe('Exception helpers', () => { value: 'Elastic, N.V.', }, { - field: 'host.name', + field: 'actingProcess.file.signer', type: 'match', operator: Operator.EXCLUSION, value: 'Global Signer', @@ -310,7 +246,7 @@ describe('Exception helpers', () => { value: 'Elastic, N.V.', }, { - fieldName: 'host.name', + fieldName: 'actingProcess.file.signer', isNested: false, operator: 'is not', value: 'Global Signer', @@ -363,10 +299,10 @@ describe('Exception helpers', () => { const payload = getExceptionItemEntryMock(); const formattedEntry = formatEntry({ isNested: false, item: payload }); const expected: FormattedEntry = { - fieldName: 'host.name', + fieldName: 'actingProcess.file.signer', isNested: false, operator: 'is', - value: 'jibberjabber', + value: 'Elastic, N.V.', }; expect(formattedEntry).toEqual(expected); @@ -376,10 +312,10 @@ describe('Exception helpers', () => { const payload = getExceptionItemEntryMock(); const formattedEntry = formatEntry({ isNested: true, parent: 'parent', item: payload }); const expected: FormattedEntry = { - fieldName: 'parent.host.name', + fieldName: 'parent.actingProcess.file.signer', isNested: true, operator: 'is', - value: 'jibberjabber', + value: 'Elastic, N.V.', }; expect(formattedEntry).toEqual(expected); @@ -429,6 +365,7 @@ describe('Exception helpers', () => { describe('#getDescriptionListContent', () => { test('it returns formatted description list with os if one is specified', () => { const payload = getExceptionItemMock(); + payload.description = ''; const result = getDescriptionListContent(payload); const expected: DescriptionListItem[] = [ { diff --git a/x-pack/plugins/siem/public/common/components/exceptions/mocks.ts b/x-pack/plugins/siem/public/common/components/exceptions/mocks.ts index 4135840e63d10..15aec3533b325 100644 --- a/x-pack/plugins/siem/public/common/components/exceptions/mocks.ts +++ b/x-pack/plugins/siem/public/common/components/exceptions/mocks.ts @@ -4,7 +4,33 @@ * you may not use this file except in compliance with the Elastic License. */ -import { Operator } from './types'; +import { + Operator, + ExceptionListItemSchema, + ExceptionEntry, + NestedExceptionEntry, + FormattedEntry, +} from './types'; + +export const getExceptionItemEntryMock = (): ExceptionEntry => ({ + field: 'actingProcess.file.signer', + type: 'match', + operator: Operator.INCLUSION, + value: 'Elastic, N.V.', +}); + +export const getNestedExceptionItemEntryMock = (): NestedExceptionEntry => ({ + field: 'actingProcess.file.signer', + type: 'nested', + entries: [{ ...getExceptionItemEntryMock() }], +}); + +export const getFormattedEntryMock = (isNested = false): FormattedEntry => ({ + fieldName: 'host.name', + operator: 'is', + value: 'some name', + isNested, +}); export const getExceptionItemMock = (): ExceptionListItemSchema => ({ id: 'uuid_here', diff --git a/x-pack/plugins/siem/public/common/components/exceptions/translations.ts b/x-pack/plugins/siem/public/common/components/exceptions/translations.ts index 5f7f5b2811921..b60b87d98de02 100644 --- a/x-pack/plugins/siem/public/common/components/exceptions/translations.ts +++ b/x-pack/plugins/siem/public/common/components/exceptions/translations.ts @@ -37,6 +37,10 @@ export const COMMENT = i18n.translate('xpack.siem.exceptions.commentLabel', { defaultMessage: 'Comment', }); +export const COMMENT_EVENT = i18n.translate('xpack.siem.exceptions.commentEventLabel', { + defaultMessage: 'added a comment', +}); + export const OPERATING_SYSTEM = i18n.translate('xpack.siem.exceptions.operatingSystemLabel', { defaultMessage: 'OS', }); diff --git a/x-pack/plugins/siem/public/common/components/exceptions/viewer/exception_entries.test.tsx b/x-pack/plugins/siem/public/common/components/exceptions/viewer/exception_entries.test.tsx new file mode 100644 index 0000000000000..05d31d99c90cf --- /dev/null +++ b/x-pack/plugins/siem/public/common/components/exceptions/viewer/exception_entries.test.tsx @@ -0,0 +1,149 @@ +/* + * 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 React from 'react'; +import { ThemeProvider } from 'styled-components'; +import { mount } from 'enzyme'; +import euiLightVars from '@elastic/eui/dist/eui_theme_light.json'; + +import { ExceptionEntries } from './exception_entries'; +import { getFormattedEntryMock } from '../mocks'; + +describe('ExceptionEntries', () => { + test('it does NOT render the and badge if only one exception item entry exists', () => { + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + + expect(wrapper.find('AndOrBadge[data-test-subj="exceptionsViewerAndBadge"]')).toHaveLength(0); + }); + + test('it renders the and badge if more than one exception item exists', () => { + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + + expect(wrapper.find('AndOrBadge[data-test-subj="exceptionsViewerAndBadge"]')).toHaveLength(1); + }); + + test('it invokes "handlEdit" when edit button clicked', () => { + const mockHandleEdit = jest.fn(); + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + const editBtn = wrapper.find('[data-test-subj="exceptionsViewerEditBtn"] button').at(0); + editBtn.simulate('click'); + + expect(mockHandleEdit).toHaveBeenCalledTimes(1); + }); + + test('it invokes "handleDelete" when delete button clicked', () => { + const mockHandleDelete = jest.fn(); + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + const deleteBtn = wrapper.find('[data-test-subj="exceptionsViewerDeleteBtn"] button').at(0); + deleteBtn.simulate('click'); + + expect(mockHandleDelete).toHaveBeenCalledTimes(1); + }); + + test('it renders nested entry', () => { + const parentEntry = getFormattedEntryMock(); + parentEntry.operator = null; + parentEntry.value = null; + + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + + const parentField = wrapper + .find('EuiTableRowCell[data-test-subj="exceptionFieldNameCell"] .euiTableCellContent') + .at(0); + const parentOperator = wrapper + .find('EuiTableRowCell[data-test-subj="exceptionFieldOperatorCell"] .euiTableCellContent') + .at(0); + const parentValue = wrapper + .find('EuiTableRowCell[data-test-subj="exceptionFieldValueCell"] .euiTableCellContent') + .at(0); + + const nestedField = wrapper + .find('EuiTableRowCell[data-test-subj="exceptionFieldNameCell"] .euiTableCellContent') + .at(1); + const nestedOperator = wrapper + .find('EuiTableRowCell[data-test-subj="exceptionFieldOperatorCell"] .euiTableCellContent') + .at(1); + const nestedValue = wrapper + .find('EuiTableRowCell[data-test-subj="exceptionFieldValueCell"] .euiTableCellContent') + .at(1); + + expect(parentField.text()).toEqual('host.name'); + expect(parentOperator.text()).toEqual('—'); + expect(parentValue.text()).toEqual('—'); + + expect(nestedField.exists('EuiToolTip')).toBeTruthy(); + expect(nestedField.text()).toEqual('host.name'); + expect(nestedOperator.text()).toEqual('is'); + expect(nestedValue.text()).toEqual('some name'); + }); + + test('it renders non-nested entries', () => { + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + + const field = wrapper + .find('EuiTableRowCell[data-test-subj="exceptionFieldNameCell"] .euiTableCellContent') + .at(0); + const operator = wrapper + .find('EuiTableRowCell[data-test-subj="exceptionFieldOperatorCell"] .euiTableCellContent') + .at(0); + const value = wrapper + .find('EuiTableRowCell[data-test-subj="exceptionFieldValueCell"] .euiTableCellContent') + .at(0); + + expect(field.exists('EuiToolTip')).toBeFalsy(); + expect(field.text()).toEqual('host.name'); + expect(operator.text()).toEqual('is'); + expect(value.text()).toEqual('some name'); + }); +}); diff --git a/x-pack/plugins/siem/public/common/components/exceptions/viewer/exception_entries.tsx b/x-pack/plugins/siem/public/common/components/exceptions/viewer/exception_entries.tsx index 373ecedc95441..896d27088df7e 100644 --- a/x-pack/plugins/siem/public/common/components/exceptions/viewer/exception_entries.tsx +++ b/x-pack/plugins/siem/public/common/components/exceptions/viewer/exception_entries.tsx @@ -114,23 +114,39 @@ const ExceptionEntriesComponent = ({ {entries.length > 1 && ( - + )} - + - + {i18n.EDIT} - handleDelete()}> + {i18n.REMOVE} diff --git a/x-pack/plugins/siem/public/common/components/exceptions/viewer/index.test.tsx b/x-pack/plugins/siem/public/common/components/exceptions/viewer/index.test.tsx new file mode 100644 index 0000000000000..43c326f6c5314 --- /dev/null +++ b/x-pack/plugins/siem/public/common/components/exceptions/viewer/index.test.tsx @@ -0,0 +1,111 @@ +/* + * 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 React from 'react'; +import { ThemeProvider } from 'styled-components'; +import { mount } from 'enzyme'; +import euiLightVars from '@elastic/eui/dist/eui_theme_light.json'; + +import { ExceptionItem } from './'; +import { getExceptionItemMock } from '../mocks'; + +describe('ExceptionItem', () => { + it('it renders ExceptionDetails and ExceptionEntries', () => { + const exceptionItem = getExceptionItemMock(); + + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + + expect(wrapper.find('ExceptionDetails')).toHaveLength(1); + expect(wrapper.find('ExceptionEntries')).toHaveLength(1); + }); + + it('it invokes "handleEdit" when edit button clicked', () => { + const mockHandleEdit = jest.fn(); + const exceptionItem = getExceptionItemMock(); + + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + + const editBtn = wrapper.find('[data-test-subj="exceptionsViewerEditBtn"] button').at(0); + editBtn.simulate('click'); + + expect(mockHandleEdit).toHaveBeenCalledTimes(1); + }); + + it('it invokes "handleDelete" when delete button clicked', () => { + const mockHandleDelete = jest.fn(); + const exceptionItem = getExceptionItemMock(); + + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + + const editBtn = wrapper.find('[data-test-subj="exceptionsViewerDeleteBtn"] button').at(0); + editBtn.simulate('click'); + + expect(mockHandleDelete).toHaveBeenCalledTimes(1); + }); + + it('it renders comment accordion closed to begin with', () => { + const mockHandleDelete = jest.fn(); + const exceptionItem = getExceptionItemMock(); + + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + + expect(wrapper.find('.euiAccordion-isOpen')).toHaveLength(0); + }); + + it('it renders comment accordion open when showComments is true', () => { + const mockHandleDelete = jest.fn(); + const exceptionItem = getExceptionItemMock(); + + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + + const commentsBtn = wrapper + .find('EuiButtonEmpty[data-test-subj="exceptionsViewerItemCommentsBtn"]') + .at(0); + commentsBtn.simulate('click'); + + expect(wrapper.find('.euiAccordion-isOpen')).toHaveLength(1); + }); +}); diff --git a/x-pack/plugins/siem/public/common/components/exceptions/viewer/index.tsx b/x-pack/plugins/siem/public/common/components/exceptions/viewer/index.tsx index a35ec3521e84c..0599d5dd93b7f 100644 --- a/x-pack/plugins/siem/public/common/components/exceptions/viewer/index.tsx +++ b/x-pack/plugins/siem/public/common/components/exceptions/viewer/index.tsx @@ -73,6 +73,7 @@ const ExceptionItemComponent = ({ id="accordion--comments" arrowDisplay="none" forceState={showComments ? 'open' : 'closed'} + data-test-subj="exceptionsViewerCommentAccordion" > diff --git a/x-pack/plugins/siem/public/graphql/types.ts b/x-pack/plugins/siem/public/graphql/types.ts index eae3887ec0636..628d56ebb647c 100644 --- a/x-pack/plugins/siem/public/graphql/types.ts +++ b/x-pack/plugins/siem/public/graphql/types.ts @@ -5405,6 +5405,8 @@ export namespace GetOneTimeline { pinnedEventsSaveObject: Maybe; + status: Maybe; + title: Maybe; timelineType: Maybe; From f3a1fba60ddb4f6e703d87cc7c98772cccdb5386 Mon Sep 17 00:00:00 2001 From: Yara Tercero Date: Wed, 3 Jun 2020 07:53:42 -0400 Subject: [PATCH 08/32] fixed test timestamps to be UTC --- .../components/exceptions/helpers.test.tsx | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/x-pack/plugins/siem/public/common/components/exceptions/helpers.test.tsx b/x-pack/plugins/siem/public/common/components/exceptions/helpers.test.tsx index 85221b9da0803..2b59b758b43ad 100644 --- a/x-pack/plugins/siem/public/common/components/exceptions/helpers.test.tsx +++ b/x-pack/plugins/siem/public/common/components/exceptions/helpers.test.tsx @@ -5,6 +5,7 @@ */ import React from 'react'; import { mount } from 'enzyme'; +import moment from 'moment-timezone'; import { getOperatorType, @@ -37,6 +38,14 @@ import { import { getExceptionItemEntryMock, getExceptionItemMock } from './mocks'; describe('Exception helpers', () => { + beforeEach(() => { + moment.tz.setDefault('UTC'); + }); + + afterEach(() => { + moment.tz.setDefault('Browser'); + }); + describe('#getOperatorType', () => { test('returns operator type "match" if entry.type is "match"', () => { const payload = getExceptionItemEntryMock(); @@ -373,7 +382,7 @@ describe('Exception helpers', () => { title: 'OS', }, { - description: 'April 22nd 2020 @ 20:19:13', + description: 'April 23rd 2020 @ 00:19:13', title: 'Date created', }, { @@ -392,7 +401,7 @@ describe('Exception helpers', () => { const result = getDescriptionListContent(payload); const expected: DescriptionListItem[] = [ { - description: 'April 22nd 2020 @ 20:19:13', + description: 'April 23rd 2020 @ 00:19:13', title: 'Date created', }, { @@ -415,7 +424,7 @@ describe('Exception helpers', () => { const result = getDescriptionListContent(payload); const expected: DescriptionListItem[] = [ { - description: 'April 22nd 2020 @ 20:19:13', + description: 'April 23rd 2020 @ 00:19:13', title: 'Date created', }, { @@ -434,7 +443,7 @@ describe('Exception helpers', () => { const result = getFormattedComments(payload); expect(result[0].username).toEqual('user_name'); - expect(result[0].timestamp).toEqual('on Apr 22nd 2020 @ 20:19:13'); + expect(result[0].timestamp).toEqual('on Apr 23rd 2020 @ 00:19:13'); }); test('it returns formatted timeline icon with comment users initial', () => { From a8a68fabc074f41ecf3d6abf59f25db1a2d8fa26 Mon Sep 17 00:00:00 2001 From: Yara Tercero Date: Wed, 3 Jun 2020 09:46:01 -0400 Subject: [PATCH 09/32] fix failing test that was passing locally --- .../exception_item/exception_details.test.tsx | 230 ++++++++++++++++++ 1 file changed, 230 insertions(+) create mode 100644 x-pack/plugins/siem/public/common/components/exceptions/viewer/exception_item/exception_details.test.tsx diff --git a/x-pack/plugins/siem/public/common/components/exceptions/viewer/exception_item/exception_details.test.tsx b/x-pack/plugins/siem/public/common/components/exceptions/viewer/exception_item/exception_details.test.tsx new file mode 100644 index 0000000000000..e468a5330c286 --- /dev/null +++ b/x-pack/plugins/siem/public/common/components/exceptions/viewer/exception_item/exception_details.test.tsx @@ -0,0 +1,230 @@ +/* + * 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 React from 'react'; +import { ThemeProvider } from 'styled-components'; +import { mount } from 'enzyme'; +import euiLightVars from '@elastic/eui/dist/eui_theme_light.json'; +import moment from 'moment-timezone'; + +import { ExceptionDetails } from './exception_details'; +import { getExceptionItemMock } from '../../mocks'; + +describe('ExceptionDetails', () => { + beforeEach(() => { + moment.tz.setDefault('UTC'); + }); + + afterEach(() => { + moment.tz.setDefault('Browser'); + }); + + test('it renders no comments button if no comments exist', () => { + const exceptionItem = getExceptionItemMock(); + exceptionItem.comments = []; + + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + + expect( + wrapper.find('EuiButtonEmpty[data-test-subj="exceptionsViewerItemCommentsBtn"]') + ).toHaveLength(0); + }); + + test('it renders comments button if comments exist', () => { + const exceptionItem = getExceptionItemMock(); + + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + + expect( + wrapper.find('EuiButtonEmpty[data-test-subj="exceptionsViewerItemCommentsBtn"]') + ).toHaveLength(1); + }); + + test('it renders correct number of comments', () => { + const exceptionItem = getExceptionItemMock(); + + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + + expect( + wrapper.find('EuiButtonEmpty[data-test-subj="exceptionsViewerItemCommentsBtn"]').at(0).text() + ).toEqual('Show (1) Comment'); + }); + + test('it renders comments plural if more than one', () => { + const exceptionItem = getExceptionItemMock(); + exceptionItem.comments = [ + { + user: 'user_1', + timestamp: '2020-04-23T00:19:13.289Z', + comment: 'Comment goes here', + }, + { + user: 'user_2', + timestamp: '2020-04-23T00:19:13.289Z', + comment: 'Comment goes here', + }, + ]; + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + + expect( + wrapper.find('EuiButtonEmpty[data-test-subj="exceptionsViewerItemCommentsBtn"]').at(0).text() + ).toEqual('Show (2) Comments'); + }); + + test('it renders comments show text if "showComments" is false', () => { + const exceptionItem = getExceptionItemMock(); + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + + expect( + wrapper.find('EuiButtonEmpty[data-test-subj="exceptionsViewerItemCommentsBtn"]').at(0).text() + ).toEqual('Show (1) Comment'); + }); + + test('it renders comments hide text if "showComments" is true', () => { + const exceptionItem = getExceptionItemMock(); + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + + expect( + wrapper.find('EuiButtonEmpty[data-test-subj="exceptionsViewerItemCommentsBtn"]').at(0).text() + ).toEqual('Hide (1) Comment'); + }); + + test('it invokes "onCommentsClick" when comments button clicked', () => { + const mockOnCommentsClick = jest.fn(); + const exceptionItem = getExceptionItemMock(); + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + const commentsBtn = wrapper + .find('EuiButtonEmpty[data-test-subj="exceptionsViewerItemCommentsBtn"]') + .at(0); + commentsBtn.simulate('click'); + + expect(mockOnCommentsClick).toHaveBeenCalledTimes(1); + }); + + test('it renders the operating system if one is specified in the exception item', () => { + const exceptionItem = getExceptionItemMock(); + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + + expect(wrapper.find('EuiDescriptionListTitle').at(0).text()).toEqual('OS'); + expect(wrapper.find('EuiDescriptionListDescription').at(0).text()).toEqual('Windows'); + }); + + test('it renders the exception item creator', () => { + const exceptionItem = getExceptionItemMock(); + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + + expect(wrapper.find('EuiDescriptionListTitle').at(1).text()).toEqual('Date created'); + expect(wrapper.find('EuiDescriptionListDescription').at(1).text()).toEqual( + 'April 23rd 2020 @ 00:19:13' + ); + }); + + test('it renders the exception item creation timestamp', () => { + const exceptionItem = getExceptionItemMock(); + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + + expect(wrapper.find('EuiDescriptionListTitle').at(2).text()).toEqual('Created by'); + expect(wrapper.find('EuiDescriptionListDescription').at(2).text()).toEqual('user_name'); + }); + + test('it renders the description if one is included on the exception item', () => { + const exceptionItem = getExceptionItemMock(); + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + + expect(wrapper.find('EuiDescriptionListTitle').at(3).text()).toEqual('Comment'); + expect(wrapper.find('EuiDescriptionListDescription').at(3).text()).toEqual( + 'This is a description' + ); + }); +}); From f0aeda863c695580ae0d49346d69f3b36e3aa45a Mon Sep 17 00:00:00 2001 From: Yara Tercero Date: Wed, 3 Jun 2020 11:00:02 -0400 Subject: [PATCH 10/32] tests --- .../exception_item/exception_details.test.tsx | 230 ------------------ 1 file changed, 230 deletions(-) delete mode 100644 x-pack/plugins/siem/public/common/components/exceptions/viewer/exception_item/exception_details.test.tsx diff --git a/x-pack/plugins/siem/public/common/components/exceptions/viewer/exception_item/exception_details.test.tsx b/x-pack/plugins/siem/public/common/components/exceptions/viewer/exception_item/exception_details.test.tsx deleted file mode 100644 index e468a5330c286..0000000000000 --- a/x-pack/plugins/siem/public/common/components/exceptions/viewer/exception_item/exception_details.test.tsx +++ /dev/null @@ -1,230 +0,0 @@ -/* - * 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 React from 'react'; -import { ThemeProvider } from 'styled-components'; -import { mount } from 'enzyme'; -import euiLightVars from '@elastic/eui/dist/eui_theme_light.json'; -import moment from 'moment-timezone'; - -import { ExceptionDetails } from './exception_details'; -import { getExceptionItemMock } from '../../mocks'; - -describe('ExceptionDetails', () => { - beforeEach(() => { - moment.tz.setDefault('UTC'); - }); - - afterEach(() => { - moment.tz.setDefault('Browser'); - }); - - test('it renders no comments button if no comments exist', () => { - const exceptionItem = getExceptionItemMock(); - exceptionItem.comments = []; - - const wrapper = mount( - ({ eui: euiLightVars, darkMode: false })}> - - - ); - - expect( - wrapper.find('EuiButtonEmpty[data-test-subj="exceptionsViewerItemCommentsBtn"]') - ).toHaveLength(0); - }); - - test('it renders comments button if comments exist', () => { - const exceptionItem = getExceptionItemMock(); - - const wrapper = mount( - ({ eui: euiLightVars, darkMode: false })}> - - - ); - - expect( - wrapper.find('EuiButtonEmpty[data-test-subj="exceptionsViewerItemCommentsBtn"]') - ).toHaveLength(1); - }); - - test('it renders correct number of comments', () => { - const exceptionItem = getExceptionItemMock(); - - const wrapper = mount( - ({ eui: euiLightVars, darkMode: false })}> - - - ); - - expect( - wrapper.find('EuiButtonEmpty[data-test-subj="exceptionsViewerItemCommentsBtn"]').at(0).text() - ).toEqual('Show (1) Comment'); - }); - - test('it renders comments plural if more than one', () => { - const exceptionItem = getExceptionItemMock(); - exceptionItem.comments = [ - { - user: 'user_1', - timestamp: '2020-04-23T00:19:13.289Z', - comment: 'Comment goes here', - }, - { - user: 'user_2', - timestamp: '2020-04-23T00:19:13.289Z', - comment: 'Comment goes here', - }, - ]; - const wrapper = mount( - ({ eui: euiLightVars, darkMode: false })}> - - - ); - - expect( - wrapper.find('EuiButtonEmpty[data-test-subj="exceptionsViewerItemCommentsBtn"]').at(0).text() - ).toEqual('Show (2) Comments'); - }); - - test('it renders comments show text if "showComments" is false', () => { - const exceptionItem = getExceptionItemMock(); - const wrapper = mount( - ({ eui: euiLightVars, darkMode: false })}> - - - ); - - expect( - wrapper.find('EuiButtonEmpty[data-test-subj="exceptionsViewerItemCommentsBtn"]').at(0).text() - ).toEqual('Show (1) Comment'); - }); - - test('it renders comments hide text if "showComments" is true', () => { - const exceptionItem = getExceptionItemMock(); - const wrapper = mount( - ({ eui: euiLightVars, darkMode: false })}> - - - ); - - expect( - wrapper.find('EuiButtonEmpty[data-test-subj="exceptionsViewerItemCommentsBtn"]').at(0).text() - ).toEqual('Hide (1) Comment'); - }); - - test('it invokes "onCommentsClick" when comments button clicked', () => { - const mockOnCommentsClick = jest.fn(); - const exceptionItem = getExceptionItemMock(); - const wrapper = mount( - ({ eui: euiLightVars, darkMode: false })}> - - - ); - const commentsBtn = wrapper - .find('EuiButtonEmpty[data-test-subj="exceptionsViewerItemCommentsBtn"]') - .at(0); - commentsBtn.simulate('click'); - - expect(mockOnCommentsClick).toHaveBeenCalledTimes(1); - }); - - test('it renders the operating system if one is specified in the exception item', () => { - const exceptionItem = getExceptionItemMock(); - const wrapper = mount( - ({ eui: euiLightVars, darkMode: false })}> - - - ); - - expect(wrapper.find('EuiDescriptionListTitle').at(0).text()).toEqual('OS'); - expect(wrapper.find('EuiDescriptionListDescription').at(0).text()).toEqual('Windows'); - }); - - test('it renders the exception item creator', () => { - const exceptionItem = getExceptionItemMock(); - const wrapper = mount( - ({ eui: euiLightVars, darkMode: false })}> - - - ); - - expect(wrapper.find('EuiDescriptionListTitle').at(1).text()).toEqual('Date created'); - expect(wrapper.find('EuiDescriptionListDescription').at(1).text()).toEqual( - 'April 23rd 2020 @ 00:19:13' - ); - }); - - test('it renders the exception item creation timestamp', () => { - const exceptionItem = getExceptionItemMock(); - const wrapper = mount( - ({ eui: euiLightVars, darkMode: false })}> - - - ); - - expect(wrapper.find('EuiDescriptionListTitle').at(2).text()).toEqual('Created by'); - expect(wrapper.find('EuiDescriptionListDescription').at(2).text()).toEqual('user_name'); - }); - - test('it renders the description if one is included on the exception item', () => { - const exceptionItem = getExceptionItemMock(); - const wrapper = mount( - ({ eui: euiLightVars, darkMode: false })}> - - - ); - - expect(wrapper.find('EuiDescriptionListTitle').at(3).text()).toEqual('Comment'); - expect(wrapper.find('EuiDescriptionListDescription').at(3).text()).toEqual( - 'This is a description' - ); - }); -}); From b19237f4a5c5d221e79c6378ab754de3d9e798fc Mon Sep 17 00:00:00 2001 From: Yara Tercero Date: Wed, 3 Jun 2020 11:28:35 -0400 Subject: [PATCH 11/32] fix dates --- .../components/exceptions/viewer/exception_details.test.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/x-pack/plugins/siem/public/common/components/exceptions/viewer/exception_details.test.tsx b/x-pack/plugins/siem/public/common/components/exceptions/viewer/exception_details.test.tsx index b104e7806f9fc..02a8e5c96de6f 100644 --- a/x-pack/plugins/siem/public/common/components/exceptions/viewer/exception_details.test.tsx +++ b/x-pack/plugins/siem/public/common/components/exceptions/viewer/exception_details.test.tsx @@ -181,7 +181,7 @@ describe('ExceptionDetails', () => { expect(wrapper.find('EuiDescriptionListTitle').at(1).text()).toEqual('Date created'); expect(wrapper.find('EuiDescriptionListDescription').at(1).text()).toEqual( - 'April 22nd 2020 @ 20:19:13' + 'April 23rd 2020 @ 00:19:13' ); }); From 3a314522e7e9115eb41bb91fbe747cc5e4306f8c Mon Sep 17 00:00:00 2001 From: Yara Tercero Date: Wed, 3 Jun 2020 15:52:31 -0400 Subject: [PATCH 12/32] fixes per feedback --- .../__examples__/index.stories.tsx | 2 +- .../components/and_or_badge/index.test.tsx | 11 +- .../common/components/and_or_badge/index.tsx | 14 +- .../exceptions/__examples__/index.stories.tsx | 220 ++++++------------ .../components/exceptions/helpers.test.tsx | 14 +- .../common/components/exceptions/helpers.tsx | 30 +-- .../viewer/exception_details.test.tsx | 43 ++-- .../exceptions/viewer/exception_details.tsx | 6 +- .../viewer/exception_entries.test.tsx | 31 +-- .../exceptions/viewer/exception_entries.tsx | 18 +- .../exceptions/viewer/index.test.tsx | 7 +- .../components/exceptions/viewer/index.tsx | 22 +- 12 files changed, 179 insertions(+), 239 deletions(-) diff --git a/x-pack/plugins/siem/public/common/components/and_or_badge/__examples__/index.stories.tsx b/x-pack/plugins/siem/public/common/components/and_or_badge/__examples__/index.stories.tsx index 27ca464404445..f939cf81d1bd3 100644 --- a/x-pack/plugins/siem/public/common/components/and_or_badge/__examples__/index.stories.tsx +++ b/x-pack/plugins/siem/public/common/components/and_or_badge/__examples__/index.stories.tsx @@ -29,7 +29,7 @@ storiesOf('components/AndOrBadge', module) ({ eui: euiLightVars, darkMode: true })}> - +

{sampleText}

diff --git a/x-pack/plugins/siem/public/common/components/and_or_badge/index.test.tsx b/x-pack/plugins/siem/public/common/components/and_or_badge/index.test.tsx index 9df865193a791..3c92e06810c8e 100644 --- a/x-pack/plugins/siem/public/common/components/and_or_badge/index.test.tsx +++ b/x-pack/plugins/siem/public/common/components/and_or_badge/index.test.tsx @@ -12,15 +12,20 @@ import euiLightVars from '@elastic/eui/dist/eui_theme_light.json'; import { AndOrBadge } from './'; describe('AndOrBadge', () => { - test('it renders top and bottom antenna bars when "includeAntenas" is true', () => { + test('it renders top and bottom antenna bars when "includeAntennas" is true', () => { const wrapper = mount( ({ eui: euiLightVars, darkMode: false })}> - + ); expect(wrapper.find('[data-test-subj="and-or-badge"]').at(0).text()).toEqual('AND'); - expect(wrapper.find('EuiFlexItem[data-test-subj="and-or-badge-bar"]')).toHaveLength(2); + expect(wrapper.find('.topAndOrBadgeAntenna[data-test-subj="and-or-badge-bar"]')).toHaveLength( + 1 + ); + expect( + wrapper.find('.bottomAndOrBadgeAntenna[data-test-subj="and-or-badge-bar"]') + ).toHaveLength(1); }); test('it renders "and" when "type" is "and"', () => { diff --git a/x-pack/plugins/siem/public/common/components/and_or_badge/index.tsx b/x-pack/plugins/siem/public/common/components/and_or_badge/index.tsx index 095a151a5c283..bed1412dda28b 100644 --- a/x-pack/plugins/siem/public/common/components/and_or_badge/index.tsx +++ b/x-pack/plugins/siem/public/common/components/and_or_badge/index.tsx @@ -10,7 +10,7 @@ import styled, { css } from 'styled-components'; import * as i18n from './translations'; -const AndOrBadgeAntena = styled(EuiFlexItem)` +const AndOrBadgeAntenna = styled(EuiFlexItem)` ${({ theme }) => css` background: ${theme.eui.euiColorLightShade}; position: relative; @@ -72,28 +72,28 @@ export type AndOr = 'and' | 'or'; /** Displays AND / OR in a round badge */ // Ref: https://github.com/elastic/eui/issues/1655 -export const AndOrBadge = React.memo<{ type: AndOr; includeAntenas?: boolean }>( - ({ type, includeAntenas = false }) => { +export const AndOrBadge = React.memo<{ type: AndOr; includeAntennas?: boolean }>( + ({ type, includeAntennas = false }) => { const getBadge = () => ( {type === 'and' ? i18n.AND : i18n.OR} ); - const getBadgeWithAntenas = () => ( + const getBadgeWithAntennas = () => ( - {getBadge()} - ( ); - return includeAntenas ? getBadgeWithAntenas() : getBadge(); + return includeAntennas ? getBadgeWithAntennas() : getBadge(); } ); diff --git a/x-pack/plugins/siem/public/common/components/exceptions/__examples__/index.stories.tsx b/x-pack/plugins/siem/public/common/components/exceptions/__examples__/index.stories.tsx index 9f3ba4341c5eb..b6620ed103bc8 100644 --- a/x-pack/plugins/siem/public/common/components/exceptions/__examples__/index.stories.tsx +++ b/x-pack/plugins/siem/public/common/components/exceptions/__examples__/index.stories.tsx @@ -6,93 +6,41 @@ import { storiesOf } from '@storybook/react'; import React from 'react'; import { ThemeProvider } from 'styled-components'; -import euiDarkVars from '@elastic/eui/dist/eui_theme_dark.json'; +import euiLightVars from '@elastic/eui/dist/eui_theme_light.json'; import { ExceptionItem } from '../viewer'; -import { ExceptionListItemSchema, Operator } from '../types'; - -const getMockExceptionItem = (): ExceptionListItemSchema => ({ - id: '[insert_uuid_here]', - item_id: 'item-id', - created_at: '2020-04-23T00:19:13.289Z', - created_by: 'user_name', - list_id: 'test-exception', - tie_breaker_id: '77fd1909-6786-428a-a671-30229a719c1f', - updated_at: '2020-04-23T00:19:13.289Z', - updated_by: 'user_name', - name: '', - description: '', - comments: [], - tags: [], - _tags: [], - type: 'simple', - namespace_type: 'single', - entries: [ - { - field: 'actingProcess.file.signer', - type: 'match', - operator: Operator.INCLUSION, - value: 'Elastic, N.V.', - }, - { - field: 'host.name', - type: 'match', - operator: Operator.EXCLUSION, - value: 'Global Signer', - }, - ], -}); +import { Operator } from '../types'; +import { getExceptionItemMock } from '../mocks'; storiesOf('components/exceptions', module) - .add('ExceptionItem', () => { - const payload = getMockExceptionItem(); - return ( - ({ eui: euiDarkVars, darkMode: true })}> - {}} handleEdit={() => {}} /> - - ); - }) - .add('with os', () => { - const payload = getMockExceptionItem(); - payload._tags = ['os:mac,windows']; - return ( - ({ eui: euiDarkVars, darkMode: true })}> - {}} handleEdit={() => {}} /> - - ); - }) - .add('with description', () => { - const payload = getMockExceptionItem(); - payload.description = 'This is my description'; - return ( - ({ eui: euiDarkVars, darkMode: true })}> - {}} handleEdit={() => {}} /> - - ); - }) - .add('with comments', () => { - const payload = getMockExceptionItem(); - payload.comments = [ - { - user: 'yoshi', - timestamp: '2020-04-23T00:19:13.289Z', - comment: 'Comment goes here', - }, + .add('ExceptionItem/with os', () => { + const payload = getExceptionItemMock(); + payload.description = ''; + payload.comments = []; + payload.entries = [ { - user: 'elastic', - timestamp: '2020-04-23T00:19:13.289Z', - comment: - 'Doggo ipsum he made many woofs fluffer pats fat boi you are doing me a frighten very good spot, doggo super chub tungg most angery pupper I have ever seen. Porgo the neighborhood pupper such treat puggorino thicc, wrinkler big ol. Very good spot big ol adorable doggo, borking doggo. Wrinkler long doggo ur givin me a spook pupperino floofs most angery pupper I have ever seen boof many pats doge, porgo long doggo doing me a frighten smol mlem maximum borkdrive super chub. Mlem clouds many pats pats what a nice floof, heckin noodle horse.', + field: 'actingProcess.file.signer', + type: 'match', + operator: Operator.INCLUSION, + value: 'Elastic, N.V.', }, ]; + return ( - ({ eui: euiDarkVars, darkMode: true })}> - {}} handleEdit={() => {}} /> + ({ eui: euiLightVars, darkMode: false })}> + {}} + handleEdit={() => {}} + /> ); }) - .add('with nested entries', () => { - const payload = getMockExceptionItem(); + .add('ExceptionItem/with description', () => { + const payload = getExceptionItemMock(); + payload._tags = []; + payload.comments = []; payload.entries = [ { field: 'actingProcess.file.signer', @@ -100,54 +48,23 @@ storiesOf('components/exceptions', module) operator: Operator.INCLUSION, value: 'Elastic, N.V.', }, - { - field: 'host.name', - type: 'match', - operator: Operator.EXCLUSION, - value: 'Global Signer', - }, - { - field: 'file.signature', - type: 'nested', - entries: [ - { - field: 'signer', - type: 'match', - operator: Operator.INCLUSION, - value: 'Evil', - }, - { - field: 'trusted', - type: 'match', - operator: Operator.INCLUSION, - value: 'true', - }, - ], - }, ]; + return ( - ({ eui: euiDarkVars, darkMode: true })}> - {}} handleEdit={() => {}} /> + ({ eui: euiLightVars, darkMode: false })}> + {}} + handleEdit={() => {}} + /> ); }) - .add('with everything', () => { - const payload = getMockExceptionItem(); - payload._tags = ['os:mac,windows']; - payload.description = 'This is my description'; - payload.comments = [ - { - user: 'yoshi', - timestamp: '2020-04-23T00:19:13.289Z', - comment: 'Comment goes here', - }, - { - user: 'elastic', - timestamp: '2020-04-23T00:19:13.289Z', - comment: - 'Doggo ipsum he made many woofs fluffer pats fat boi you are doing me a frighten very good spot, doggo super chub tungg most angery pupper I have ever seen. Porgo the neighborhood pupper such treat puggorino thicc, wrinkler big ol. Very good spot big ol adorable doggo, borking doggo. Wrinkler long doggo ur givin me a spook pupperino floofs most angery pupper I have ever seen boof many pats doge, porgo long doggo doing me a frighten smol mlem maximum borkdrive super chub. Mlem clouds many pats pats what a nice floof, heckin noodle horse.', - }, - ]; + .add('ExceptionItem/with comments', () => { + const payload = getExceptionItemMock(); + payload._tags = []; + payload.description = ''; payload.entries = [ { field: 'actingProcess.file.signer', @@ -155,34 +72,47 @@ storiesOf('components/exceptions', module) operator: Operator.INCLUSION, value: 'Elastic, N.V.', }, - { - field: 'host.name', - type: 'match', - operator: Operator.EXCLUSION, - value: 'Global Signer', - }, - { - field: 'file.signature', - type: 'nested', - entries: [ - { - field: 'signer', - type: 'match', - operator: Operator.INCLUSION, - value: 'Evil', - }, - { - field: 'trusted', - type: 'match', - operator: Operator.INCLUSION, - value: 'true', - }, - ], - }, ]; + + return ( + ({ eui: euiLightVars, darkMode: false })}> + {}} + handleEdit={() => {}} + /> + + ); + }) + .add('ExceptionItem/with nested entries', () => { + const payload = getExceptionItemMock(); + payload._tags = []; + payload.description = ''; + payload.comments = []; + + return ( + ({ eui: euiLightVars, darkMode: false })}> + {}} + handleEdit={() => {}} + /> + + ); + }) + .add('ExceptionItem/with everything', () => { + const payload = getExceptionItemMock(); + return ( - ({ eui: euiDarkVars, darkMode: true })}> - {}} handleEdit={() => {}} /> + ({ eui: euiLightVars, darkMode: false })}> + {}} + handleEdit={() => {}} + /> ); }); diff --git a/x-pack/plugins/siem/public/common/components/exceptions/helpers.test.tsx b/x-pack/plugins/siem/public/common/components/exceptions/helpers.test.tsx index 2b59b758b43ad..223eabb0ea4ee 100644 --- a/x-pack/plugins/siem/public/common/components/exceptions/helpers.test.tsx +++ b/x-pack/plugins/siem/public/common/components/exceptions/helpers.test.tsx @@ -335,23 +335,23 @@ describe('Exception helpers', () => { test('it returns null if no operating system tag specified', () => { const result = getOperatingSystems(['some tag', 'some other tag']); - expect(result).toBeNull(); + expect(result).toEqual(''); }); test('it returns null if operating system tag malformed', () => { const result = getOperatingSystems(['some tag', 'jibberos:mac,windows', 'some other tag']); - expect(result).toBeNull(); + expect(result).toEqual(''); }); - test('it returns formatted operating systems if specified in tags', () => { - const result = getOperatingSystems(['some tag', 'os:mac,windows', 'some other tag']); + test('it returns formatted operating systems if space included in os tag', () => { + const result = getOperatingSystems(['some tag', 'os: mac', 'some other tag']); - expect(result).toEqual('Mac, Windows'); + expect(result).toEqual('Mac'); }); - test('it returns formatted operating systems if space included in os tag', () => { - const result = getOperatingSystems(['some tag', 'os: mac, windows', 'some other tag']); + test('it returns formatted operating systems if multiple os tags specified', () => { + const result = getOperatingSystems(['some tag', 'os: mac', 'some other tag', 'os:windows']); expect(result).toEqual('Mac, Windows'); }); diff --git a/x-pack/plugins/siem/public/common/components/exceptions/helpers.tsx b/x-pack/plugins/siem/public/common/components/exceptions/helpers.tsx index 2182b6cf79925..41d9ed39a326c 100644 --- a/x-pack/plugins/siem/public/common/components/exceptions/helpers.tsx +++ b/x-pack/plugins/siem/public/common/components/exceptions/helpers.tsx @@ -6,7 +6,7 @@ import React from 'react'; import { EuiText, EuiCommentProps, EuiAvatar } from '@elastic/eui'; -import { flatten, capitalize } from 'lodash'; +import { capitalize } from 'lodash'; import moment from 'moment'; import * as i18n from './translations'; @@ -22,8 +22,6 @@ import { } from './types'; import { EXCEPTION_OPERATORS, isOperator } from './operators'; -export const getEmptyValue = () => '—'; - /** * Returns the operator type, may not need this if using io-ts types * @@ -95,7 +93,7 @@ export const getFormattedEntries = ( } }); - return flatten(formattedEntries); + return formattedEntries.flat(); }; /** @@ -122,17 +120,13 @@ export const formatEntry = ({ }; }; -export const getOperatingSystems = (tags: string[]): string | null => { - const [includesOs, osMatch] = getTagsInclude({ tags, regex: /(?<=\b)(os:[^;]*)(?=\b)/ }); - if (includesOs && osMatch !== null) { - const os = osMatch.split(':')[1]; - const items = os.split(',').map((item) => { - return capitalize(item.trim()); - }); - return items.join(', '); - } else { - return null; - } +export const getOperatingSystems = (tags: string[]): string => { + const osMatches = tags + .filter((tag) => tag.startsWith('os:')) + .map((os) => capitalize(os.substring(3).trim())) + .join(', '); + + return osMatches; }; export const getTagsInclude = ({ @@ -143,8 +137,8 @@ export const getTagsInclude = ({ regex: RegExp; }): [boolean, string | null] => { const matches: string[] | null = tags.join(';').match(regex); - const match = matches !== null ? matches[1] : null; - return [matches !== null, match]; + const match = matches != null ? matches[1] : null; + return [matches != null, match]; }; /** @@ -175,7 +169,7 @@ export const getDescriptionListContent = ( ]; return details.reduce((acc, { value, title }) => { - if (value !== null && value) { + if (value != null && value.trim() !== '') { return [...acc, { title, description: value }]; } else { return acc; diff --git a/x-pack/plugins/siem/public/common/components/exceptions/viewer/exception_details.test.tsx b/x-pack/plugins/siem/public/common/components/exceptions/viewer/exception_details.test.tsx index 02a8e5c96de6f..536d005c57b6e 100644 --- a/x-pack/plugins/siem/public/common/components/exceptions/viewer/exception_details.test.tsx +++ b/x-pack/plugins/siem/public/common/components/exceptions/viewer/exception_details.test.tsx @@ -8,11 +8,20 @@ import React from 'react'; import { ThemeProvider } from 'styled-components'; import { mount } from 'enzyme'; import euiLightVars from '@elastic/eui/dist/eui_theme_light.json'; +import moment from 'moment-timezone'; import { ExceptionDetails } from './exception_details'; import { getExceptionItemMock } from '../mocks'; describe('ExceptionDetails', () => { + beforeEach(() => { + moment.tz.setDefault('UTC'); + }); + + afterEach(() => { + moment.tz.setDefault('Browser'); + }); + test('it renders no comments button if no comments exist', () => { const exceptionItem = getExceptionItemMock(); exceptionItem.comments = []; @@ -27,9 +36,7 @@ describe('ExceptionDetails', () => { ); - expect( - wrapper.find('EuiButtonEmpty[data-test-subj="exceptionsViewerItemCommentsBtn"]') - ).toHaveLength(0); + expect(wrapper.find('[data-test-subj="exceptionsViewerItemCommentsBtn"]')).toHaveLength(0); }); test('it renders comments button if comments exist', () => { @@ -46,7 +53,7 @@ describe('ExceptionDetails', () => { ); expect( - wrapper.find('EuiButtonEmpty[data-test-subj="exceptionsViewerItemCommentsBtn"]') + wrapper.find('.euiButtonEmpty[data-test-subj="exceptionsViewerItemCommentsBtn"]') ).toHaveLength(1); }); @@ -63,9 +70,9 @@ describe('ExceptionDetails', () => { ); - expect( - wrapper.find('EuiButtonEmpty[data-test-subj="exceptionsViewerItemCommentsBtn"]').at(0).text() - ).toEqual('Show (1) Comment'); + expect(wrapper.find('[data-test-subj="exceptionsViewerItemCommentsBtn"]').at(0).text()).toEqual( + 'Show (1) Comment' + ); }); test('it renders comments plural if more than one', () => { @@ -92,9 +99,9 @@ describe('ExceptionDetails', () => { ); - expect( - wrapper.find('EuiButtonEmpty[data-test-subj="exceptionsViewerItemCommentsBtn"]').at(0).text() - ).toEqual('Show (2) Comments'); + expect(wrapper.find('[data-test-subj="exceptionsViewerItemCommentsBtn"]').at(0).text()).toEqual( + 'Show (2) Comments' + ); }); test('it renders comments show text if "showComments" is false', () => { @@ -109,9 +116,9 @@ describe('ExceptionDetails', () => {
); - expect( - wrapper.find('EuiButtonEmpty[data-test-subj="exceptionsViewerItemCommentsBtn"]').at(0).text() - ).toEqual('Show (1) Comment'); + expect(wrapper.find('[data-test-subj="exceptionsViewerItemCommentsBtn"]').at(0).text()).toEqual( + 'Show (1) Comment' + ); }); test('it renders comments hide text if "showComments" is true', () => { @@ -126,9 +133,9 @@ describe('ExceptionDetails', () => { ); - expect( - wrapper.find('EuiButtonEmpty[data-test-subj="exceptionsViewerItemCommentsBtn"]').at(0).text() - ).toEqual('Hide (1) Comment'); + expect(wrapper.find('[data-test-subj="exceptionsViewerItemCommentsBtn"]').at(0).text()).toEqual( + 'Hide (1) Comment' + ); }); test('it invokes "onCommentsClick" when comments button clicked', () => { @@ -143,9 +150,7 @@ describe('ExceptionDetails', () => { /> ); - const commentsBtn = wrapper - .find('EuiButtonEmpty[data-test-subj="exceptionsViewerItemCommentsBtn"]') - .at(0); + const commentsBtn = wrapper.find('[data-test-subj="exceptionsViewerItemCommentsBtn"]').at(0); commentsBtn.simulate('click'); expect(mockOnCommentsClick).toHaveBeenCalledTimes(1); diff --git a/x-pack/plugins/siem/public/common/components/exceptions/viewer/exception_details.tsx b/x-pack/plugins/siem/public/common/components/exceptions/viewer/exception_details.tsx index 15b6425956c34..bcaa1abb23727 100644 --- a/x-pack/plugins/siem/public/common/components/exceptions/viewer/exception_details.tsx +++ b/x-pack/plugins/siem/public/common/components/exceptions/viewer/exception_details.tsx @@ -16,7 +16,7 @@ import * as i18n from '../translations'; const StyledExceptionDetails = styled(EuiFlexItem)` ${({ theme }) => css` background-color: ${transparentize(0.95, theme.eui.euiColorPrimary)}; - padding: 16px; + padding: ${theme.eui.euiSize}; .euiDescriptionList__title.listTitle--width { width: 40%; @@ -36,12 +36,12 @@ const ExceptionDetailsComponent = ({ showComments: boolean; exceptionItem: ExceptionListItemSchema; onCommentsClick: () => void; -}) => { +}): JSX.Element => { const descriptionList = useMemo(() => getDescriptionListContent(exceptionItem), [exceptionItem]); const commentsSection = useMemo(() => { const { comments } = exceptionItem; - if (comments !== null && comments && comments.length > 0) { + if (comments.length > 0) { return ( { test('it does NOT render the and badge if only one exception item entry exists', () => { @@ -24,7 +25,7 @@ describe('ExceptionEntries', () => { ); - expect(wrapper.find('AndOrBadge[data-test-subj="exceptionsViewerAndBadge"]')).toHaveLength(0); + expect(wrapper.find('[data-test-subj="exceptionsViewerAndBadge"]')).toHaveLength(0); }); test('it renders the and badge if more than one exception item exists', () => { @@ -38,7 +39,7 @@ describe('ExceptionEntries', () => { ); - expect(wrapper.find('AndOrBadge[data-test-subj="exceptionsViewerAndBadge"]')).toHaveLength(1); + expect(wrapper.find('[data-test-subj="exceptionsViewerAndBadge"]')).toHaveLength(1); }); test('it invokes "handlEdit" when edit button clicked', () => { @@ -91,30 +92,30 @@ describe('ExceptionEntries', () => { ); const parentField = wrapper - .find('EuiTableRowCell[data-test-subj="exceptionFieldNameCell"] .euiTableCellContent') + .find('[data-test-subj="exceptionFieldNameCell"] .euiTableCellContent') .at(0); const parentOperator = wrapper - .find('EuiTableRowCell[data-test-subj="exceptionFieldOperatorCell"] .euiTableCellContent') + .find('[data-test-subj="exceptionFieldOperatorCell"] .euiTableCellContent') .at(0); const parentValue = wrapper - .find('EuiTableRowCell[data-test-subj="exceptionFieldValueCell"] .euiTableCellContent') + .find('[data-test-subj="exceptionFieldValueCell"] .euiTableCellContent') .at(0); const nestedField = wrapper - .find('EuiTableRowCell[data-test-subj="exceptionFieldNameCell"] .euiTableCellContent') + .find('[data-test-subj="exceptionFieldNameCell"] .euiTableCellContent') .at(1); const nestedOperator = wrapper - .find('EuiTableRowCell[data-test-subj="exceptionFieldOperatorCell"] .euiTableCellContent') + .find('[data-test-subj="exceptionFieldOperatorCell"] .euiTableCellContent') .at(1); const nestedValue = wrapper - .find('EuiTableRowCell[data-test-subj="exceptionFieldValueCell"] .euiTableCellContent') + .find('[data-test-subj="exceptionFieldValueCell"] .euiTableCellContent') .at(1); expect(parentField.text()).toEqual('host.name'); - expect(parentOperator.text()).toEqual('—'); - expect(parentValue.text()).toEqual('—'); + expect(parentOperator.text()).toEqual(getEmptyValue()); + expect(parentValue.text()).toEqual(getEmptyValue()); - expect(nestedField.exists('EuiToolTip')).toBeTruthy(); + expect(nestedField.exists('.euiToolTipAnchor')).toBeTruthy(); expect(nestedField.text()).toEqual('host.name'); expect(nestedOperator.text()).toEqual('is'); expect(nestedValue.text()).toEqual('some name'); @@ -132,16 +133,16 @@ describe('ExceptionEntries', () => { ); const field = wrapper - .find('EuiTableRowCell[data-test-subj="exceptionFieldNameCell"] .euiTableCellContent') + .find('[data-test-subj="exceptionFieldNameCell"] .euiTableCellContent') .at(0); const operator = wrapper - .find('EuiTableRowCell[data-test-subj="exceptionFieldOperatorCell"] .euiTableCellContent') + .find('[data-test-subj="exceptionFieldOperatorCell"] .euiTableCellContent') .at(0); const value = wrapper - .find('EuiTableRowCell[data-test-subj="exceptionFieldValueCell"] .euiTableCellContent') + .find('[data-test-subj="exceptionFieldValueCell"] .euiTableCellContent') .at(0); - expect(field.exists('EuiToolTip')).toBeFalsy(); + expect(field.exists('.euiToolTipAnchor')).toBeFalsy(); expect(field.text()).toEqual('host.name'); expect(operator.text()).toEqual('is'); expect(value.text()).toEqual('some name'); diff --git a/x-pack/plugins/siem/public/common/components/exceptions/viewer/exception_entries.tsx b/x-pack/plugins/siem/public/common/components/exceptions/viewer/exception_entries.tsx index 896d27088df7e..63bba06a03ccf 100644 --- a/x-pack/plugins/siem/public/common/components/exceptions/viewer/exception_entries.tsx +++ b/x-pack/plugins/siem/public/common/components/exceptions/viewer/exception_entries.tsx @@ -10,34 +10,32 @@ import styled, { css } from 'styled-components'; import { transparentize } from 'polished'; import { AndOrBadge } from '../../and_or_badge'; -import { getEmptyValue } from '../helpers'; +import { getEmptyValue } from '../../empty_value'; import * as i18n from '../translations'; import { FormattedEntry } from '../types'; const EntriesDetails = styled(EuiFlexItem)` - padding: 16px; + padding: ${({ theme }) => theme.eui.euiSize}; `; const StyledEditButton = styled(EuiButton)` ${({ theme }) => css` background-color: ${transparentize(0.9, theme.eui.euiColorPrimary)}; - width: 111px; border: none; - font-weight: 600; + font-weight: ${theme.eui.euiFontWeightSemiBold}; `} `; const StyledRemoveButton = styled(EuiButton)` ${({ theme }) => css` background-color: ${transparentize(0.9, theme.eui.euiColorDanger)}; - width: 111px; border: none; - font-weight: 600; + font-weight: ${theme.eui.euiFontWeightSemiBold}; `} `; const AndOrBadgeContainer = styled(EuiFlexItem)` - padding-top: 32px; + padding-top: ${({ theme }) => theme.eui.euiSizeXL}; `; interface ExceptionEntriesComponentProps { @@ -50,7 +48,7 @@ const ExceptionEntriesComponent = ({ entries, handleDelete, handleEdit, -}: ExceptionEntriesComponentProps) => { +}: ExceptionEntriesComponentProps): JSX.Element => { const columns = useMemo( () => [ { @@ -61,7 +59,7 @@ const ExceptionEntriesComponent = ({ 'data-test-subj': 'exceptionFieldNameCell', width: '30%', render: (value: string | null, data: FormattedEntry) => { - if (value !== null && data.isNested) { + if (value != null && data.isNested) { return ( <> @@ -114,7 +112,7 @@ const ExceptionEntriesComponent = ({ {entries.length > 1 && ( - + )} diff --git a/x-pack/plugins/siem/public/common/components/exceptions/viewer/index.test.tsx b/x-pack/plugins/siem/public/common/components/exceptions/viewer/index.test.tsx index 43c326f6c5314..7d3b7195def80 100644 --- a/x-pack/plugins/siem/public/common/components/exceptions/viewer/index.test.tsx +++ b/x-pack/plugins/siem/public/common/components/exceptions/viewer/index.test.tsx @@ -19,6 +19,7 @@ describe('ExceptionItem', () => { const wrapper = mount( ({ eui: euiLightVars, darkMode: false })}> { const wrapper = mount( ({ eui: euiLightVars, darkMode: false })}> { const wrapper = mount( ({ eui: euiLightVars, darkMode: false })}> { const wrapper = mount( ({ eui: euiLightVars, darkMode: false })}> { const wrapper = mount( ({ eui: euiLightVars, darkMode: false })}> { ); const commentsBtn = wrapper - .find('EuiButtonEmpty[data-test-subj="exceptionsViewerItemCommentsBtn"]') + .find('.euiButtonEmpty[data-test-subj="exceptionsViewerItemCommentsBtn"]') .at(0); commentsBtn.simulate('click'); diff --git a/x-pack/plugins/siem/public/common/components/exceptions/viewer/index.tsx b/x-pack/plugins/siem/public/common/components/exceptions/viewer/index.tsx index 0599d5dd93b7f..ab22cb364c539 100644 --- a/x-pack/plugins/siem/public/common/components/exceptions/viewer/index.tsx +++ b/x-pack/plugins/siem/public/common/components/exceptions/viewer/index.tsx @@ -14,29 +14,31 @@ import { getFormattedEntries, getFormattedComments } from '../helpers'; import { FormattedEntry, ExceptionListItemSchema } from '../types'; const MyFlexItem = styled(EuiFlexItem)` - &.comments--show { - padding: 16px; - border-top: 1px solid #d3dae6; - } + &.comments--show { + padding: ${({ theme }) => theme.eui.euiSize}; + border-top: ${({ theme }) => `${theme.eui.euiBorderThin}`} + `; interface ExceptionItemProps { exceptionItem: ExceptionListItemSchema; + commentsAccordionId: string; handleDelete: ({ id }: { id: string }) => void; handleEdit: (item: ExceptionListItemSchema) => void; } const ExceptionItemComponent = ({ exceptionItem, + commentsAccordionId, handleDelete, handleEdit, -}: ExceptionItemProps) => { +}: ExceptionItemProps): JSX.Element => { const [entryItems, setEntryItems] = useState([]); - const [showComments, setShowComments] = useState(false); + const [showComments, setShowComments] = useState(false); useEffect(() => { - const formattedEntries = getFormattedEntries(exceptionItem.entries ?? []); - setEntryItems([...formattedEntries]); + const formattedEntries = getFormattedEntries(exceptionItem.entries); + setEntryItems(formattedEntries); }, [exceptionItem.entries]); const onDelete = useCallback(() => { @@ -52,7 +54,7 @@ const ExceptionItemComponent = ({ }, [setShowComments, showComments]); const formattedComments = useMemo(() => { - return getFormattedComments(exceptionItem.comments ?? []); + return getFormattedComments(exceptionItem.comments); }, [exceptionItem]); return ( @@ -70,7 +72,7 @@ const ExceptionItemComponent = ({ Date: Wed, 3 Jun 2020 16:19:26 -0400 Subject: [PATCH 13/32] cleanup --- .../common/components/exceptions/helpers.tsx | 2 +- .../exceptions/viewer/exception_details.tsx | 2 +- .../exceptions/viewer/exception_entries.tsx | 11 +++++++++-- .../components/exceptions/viewer/index.tsx | 19 +++++++++++++------ 4 files changed, 24 insertions(+), 10 deletions(-) diff --git a/x-pack/plugins/siem/public/common/components/exceptions/helpers.tsx b/x-pack/plugins/siem/public/common/components/exceptions/helpers.tsx index 41d9ed39a326c..bd22de636bf6c 100644 --- a/x-pack/plugins/siem/public/common/components/exceptions/helpers.tsx +++ b/x-pack/plugins/siem/public/common/components/exceptions/helpers.tsx @@ -107,7 +107,7 @@ export const formatEntry = ({ isNested: boolean; parent?: string; item: ExceptionEntry; -}) => { +}): FormattedEntry => { const operator = getExceptionOperatorSelect(item); const operatorType = getOperatorType(item); const value = operatorType === OperatorType.EXISTS ? null : item.value; diff --git a/x-pack/plugins/siem/public/common/components/exceptions/viewer/exception_details.tsx b/x-pack/plugins/siem/public/common/components/exceptions/viewer/exception_details.tsx index bcaa1abb23727..8745e80a21548 100644 --- a/x-pack/plugins/siem/public/common/components/exceptions/viewer/exception_details.tsx +++ b/x-pack/plugins/siem/public/common/components/exceptions/viewer/exception_details.tsx @@ -39,7 +39,7 @@ const ExceptionDetailsComponent = ({ }): JSX.Element => { const descriptionList = useMemo(() => getDescriptionListContent(exceptionItem), [exceptionItem]); - const commentsSection = useMemo(() => { + const commentsSection = useMemo((): JSX.Element => { const { comments } = exceptionItem; if (comments.length > 0) { return ( diff --git a/x-pack/plugins/siem/public/common/components/exceptions/viewer/exception_entries.tsx b/x-pack/plugins/siem/public/common/components/exceptions/viewer/exception_entries.tsx index 63bba06a03ccf..d0236adc27c6c 100644 --- a/x-pack/plugins/siem/public/common/components/exceptions/viewer/exception_entries.tsx +++ b/x-pack/plugins/siem/public/common/components/exceptions/viewer/exception_entries.tsx @@ -4,7 +4,14 @@ * you may not use this file except in compliance with the Elastic License. */ -import { EuiBasicTable, EuiIconTip, EuiFlexItem, EuiFlexGroup, EuiButton } from '@elastic/eui'; +import { + EuiBasicTable, + EuiIconTip, + EuiFlexItem, + EuiFlexGroup, + EuiButton, + EuiTableFieldDataColumnType, +} from '@elastic/eui'; import React, { useMemo } from 'react'; import styled, { css } from 'styled-components'; import { transparentize } from 'polished'; @@ -50,7 +57,7 @@ const ExceptionEntriesComponent = ({ handleEdit, }: ExceptionEntriesComponentProps): JSX.Element => { const columns = useMemo( - () => [ + (): Array> => [ { field: 'fieldName', name: 'Field', diff --git a/x-pack/plugins/siem/public/common/components/exceptions/viewer/index.tsx b/x-pack/plugins/siem/public/common/components/exceptions/viewer/index.tsx index ab22cb364c539..f4cdce62f56b3 100644 --- a/x-pack/plugins/siem/public/common/components/exceptions/viewer/index.tsx +++ b/x-pack/plugins/siem/public/common/components/exceptions/viewer/index.tsx @@ -4,7 +4,14 @@ * you may not use this file except in compliance with the Elastic License. */ -import { EuiPanel, EuiFlexGroup, EuiCommentList, EuiAccordion, EuiFlexItem } from '@elastic/eui'; +import { + EuiPanel, + EuiFlexGroup, + EuiCommentProps, + EuiCommentList, + EuiAccordion, + EuiFlexItem, +} from '@elastic/eui'; import React, { useEffect, useState, useMemo, useCallback } from 'react'; import styled from 'styled-components'; @@ -36,24 +43,24 @@ const ExceptionItemComponent = ({ const [entryItems, setEntryItems] = useState([]); const [showComments, setShowComments] = useState(false); - useEffect(() => { + useEffect((): void => { const formattedEntries = getFormattedEntries(exceptionItem.entries); setEntryItems(formattedEntries); }, [exceptionItem.entries]); - const onDelete = useCallback(() => { + const onDelete = useCallback((): void => { handleDelete({ id: exceptionItem.id }); }, [handleDelete, exceptionItem]); - const onEdit = useCallback(() => { + const onEdit = useCallback((): void => { handleEdit(exceptionItem); }, [handleEdit, exceptionItem]); - const onCommentsClick = useCallback(() => { + const onCommentsClick = useCallback((): void => { setShowComments(!showComments); }, [setShowComments, showComments]); - const formattedComments = useMemo(() => { + const formattedComments = useMemo((): EuiCommentProps[] => { return getFormattedComments(exceptionItem.comments); }, [exceptionItem]); From c24c1ff665cdf76cb1cc34b1393cc9609d29abf7 Mon Sep 17 00:00:00 2001 From: Yara Tercero Date: Wed, 3 Jun 2020 17:26:27 -0400 Subject: [PATCH 14/32] updated tests --- .../public/common/components/and_or_badge/index.test.tsx | 8 ++------ .../siem/public/common/components/and_or_badge/index.tsx | 4 ++-- 2 files changed, 4 insertions(+), 8 deletions(-) diff --git a/x-pack/plugins/siem/public/common/components/and_or_badge/index.test.tsx b/x-pack/plugins/siem/public/common/components/and_or_badge/index.test.tsx index 3c92e06810c8e..ed918a59a514a 100644 --- a/x-pack/plugins/siem/public/common/components/and_or_badge/index.test.tsx +++ b/x-pack/plugins/siem/public/common/components/and_or_badge/index.test.tsx @@ -20,12 +20,8 @@ describe('AndOrBadge', () => { ); expect(wrapper.find('[data-test-subj="and-or-badge"]').at(0).text()).toEqual('AND'); - expect(wrapper.find('.topAndOrBadgeAntenna[data-test-subj="and-or-badge-bar"]')).toHaveLength( - 1 - ); - expect( - wrapper.find('.bottomAndOrBadgeAntenna[data-test-subj="and-or-badge-bar"]') - ).toHaveLength(1); + expect(wrapper.find('EuiFlexItem[data-test-subj="andOrBadgeBarTop"]')).toHaveLength(1); + expect(wrapper.find('EuiFlexItem[data-test-subj="andOrBadgeBarBottom"]')).toHaveLength(1); }); test('it renders "and" when "type" is "and"', () => { diff --git a/x-pack/plugins/siem/public/common/components/and_or_badge/index.tsx b/x-pack/plugins/siem/public/common/components/and_or_badge/index.tsx index bed1412dda28b..ba3f880d9757e 100644 --- a/x-pack/plugins/siem/public/common/components/and_or_badge/index.tsx +++ b/x-pack/plugins/siem/public/common/components/and_or_badge/index.tsx @@ -89,13 +89,13 @@ export const AndOrBadge = React.memo<{ type: AndOr; includeAntennas?: boolean }> > {getBadge()} From 878547eb39e287b43ca15d69d42ff6ff25ee3485 Mon Sep 17 00:00:00 2001 From: Yara Tercero Date: Thu, 4 Jun 2020 10:23:07 -0400 Subject: [PATCH 15/32] updated translations to use securitySolution after rename --- .../common/components/exceptions/operators.ts | 16 ++++++------ .../components/exceptions/translations.ts | 25 +++++++++++-------- 2 files changed, 22 insertions(+), 19 deletions(-) diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/operators.ts b/x-pack/plugins/security_solution/public/common/components/exceptions/operators.ts index 9b553c5af9bd5..19c726893e682 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/operators.ts +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/operators.ts @@ -8,7 +8,7 @@ import { i18n } from '@kbn/i18n'; import { OperatorOption, OperatorType, Operator } from './types'; export const isOperator: OperatorOption = { - message: i18n.translate('xpack.siem.exceptions.isOperatorLabel', { + message: i18n.translate('xpack.securitySolution.exceptions.isOperatorLabel', { defaultMessage: 'is', }), value: 'is', @@ -17,7 +17,7 @@ export const isOperator: OperatorOption = { }; export const isNotOperator: OperatorOption = { - message: i18n.translate('xpack.siem.exceptions.isNotOperatorLabel', { + message: i18n.translate('xpack.securitySolution.exceptions.isNotOperatorLabel', { defaultMessage: 'is not', }), value: 'is_not', @@ -26,7 +26,7 @@ export const isNotOperator: OperatorOption = { }; export const isOneOfOperator: OperatorOption = { - message: i18n.translate('xpack.siem.exceptions.isOneOfOperatorLabel', { + message: i18n.translate('xpack.securitySolution.exceptions.isOneOfOperatorLabel', { defaultMessage: 'is one of', }), value: 'is_one_of', @@ -35,7 +35,7 @@ export const isOneOfOperator: OperatorOption = { }; export const isNotOneOfOperator: OperatorOption = { - message: i18n.translate('xpack.siem.exceptions.isNotOneOfOperatorLabel', { + message: i18n.translate('xpack.securitySolution.exceptions.isNotOneOfOperatorLabel', { defaultMessage: 'is not one of', }), value: 'is_not_one_of', @@ -44,7 +44,7 @@ export const isNotOneOfOperator: OperatorOption = { }; export const existsOperator: OperatorOption = { - message: i18n.translate('xpack.siem.exceptions.existsOperatorLabel', { + message: i18n.translate('xpack.securitySolution.exceptions.existsOperatorLabel', { defaultMessage: 'exists', }), value: 'exists', @@ -53,7 +53,7 @@ export const existsOperator: OperatorOption = { }; export const doesNotExistOperator: OperatorOption = { - message: i18n.translate('xpack.siem.exceptions.doesNotExistOperatorLabel', { + message: i18n.translate('xpack.securitySolution.exceptions.doesNotExistOperatorLabel', { defaultMessage: 'does not exist', }), value: 'does_not_exist', @@ -62,7 +62,7 @@ export const doesNotExistOperator: OperatorOption = { }; export const isInListOperator: OperatorOption = { - message: i18n.translate('xpack.siem.exceptions.isInListOperatorLabel', { + message: i18n.translate('xpack.securitySolution.exceptions.isInListOperatorLabel', { defaultMessage: 'is in list', }), value: 'is_in_list', @@ -71,7 +71,7 @@ export const isInListOperator: OperatorOption = { }; export const isNotInListOperator: OperatorOption = { - message: i18n.translate('xpack.siem.exceptions.isNotInListOperatorLabel', { + message: i18n.translate('xpack.securitySolution.exceptions.isNotInListOperatorLabel', { defaultMessage: 'is not in list', }), value: 'is_not_in_list', diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/translations.ts b/x-pack/plugins/security_solution/public/common/components/exceptions/translations.ts index b60b87d98de02..704849430daf9 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/translations.ts +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/translations.ts @@ -5,42 +5,45 @@ */ import { i18n } from '@kbn/i18n'; -export const EDIT = i18n.translate('xpack.siem.exceptions.editButtonLabel', { +export const EDIT = i18n.translate('xpack.securitySolution.exceptions.editButtonLabel', { defaultMessage: 'Edit', }); -export const REMOVE = i18n.translate('xpack.siem.exceptions.removeButtonLabel', { +export const REMOVE = i18n.translate('xpack.securitySolution.exceptions.removeButtonLabel', { defaultMessage: 'Remove', }); export const COMMENTS_SHOW = (comments: number) => - i18n.translate('xpack.siem.exceptions.showCommentsLabel', { + i18n.translate('xpack.securitySolution.exceptions.showCommentsLabel', { values: { comments }, defaultMessage: 'Show ({comments}) {comments, plural, =1 {Comment} other {Comments}}', }); export const COMMENTS_HIDE = (comments: number) => - i18n.translate('xpack.siem.exceptions.hideCommentsLabel', { + i18n.translate('xpack.securitySolution.exceptions.hideCommentsLabel', { values: { comments }, defaultMessage: 'Hide ({comments}) {comments, plural, =1 {Comment} other {Comments}}', }); -export const DATE_CREATED = i18n.translate('xpack.siem.exceptions.dateCreatedLabel', { +export const DATE_CREATED = i18n.translate('xpack.securitySolution.exceptions.dateCreatedLabel', { defaultMessage: 'Date created', }); -export const CREATED_BY = i18n.translate('xpack.siem.exceptions.createdByLabel', { +export const CREATED_BY = i18n.translate('xpack.securitySolution.exceptions.createdByLabel', { defaultMessage: 'Created by', }); -export const COMMENT = i18n.translate('xpack.siem.exceptions.commentLabel', { +export const COMMENT = i18n.translate('xpack.securitySolution.exceptions.commentLabel', { defaultMessage: 'Comment', }); -export const COMMENT_EVENT = i18n.translate('xpack.siem.exceptions.commentEventLabel', { +export const COMMENT_EVENT = i18n.translate('xpack.securitySolution.exceptions.commentEventLabel', { defaultMessage: 'added a comment', }); -export const OPERATING_SYSTEM = i18n.translate('xpack.siem.exceptions.operatingSystemLabel', { - defaultMessage: 'OS', -}); +export const OPERATING_SYSTEM = i18n.translate( + 'xpack.securitySolution.exceptions.operatingSystemLabel', + { + defaultMessage: 'OS', + } +); From bc7b81ea1efb3f805867930689121927e71ee3f0 Mon Sep 17 00:00:00 2001 From: Yara Tercero Date: Thu, 4 Jun 2020 12:55:51 -0400 Subject: [PATCH 16/32] updated useExceptionList hook to use different refresh pattern, updated tests --- .../hooks/use_exception_list.test.tsx | 38 ++++-- .../exceptions/hooks/use_exception_list.tsx | 124 +++++++++--------- .../plugins/lists/public/exceptions/types.ts | 9 +- x-pack/plugins/lists/public/index.tsx | 1 + 4 files changed, 92 insertions(+), 80 deletions(-) diff --git a/x-pack/plugins/lists/public/exceptions/hooks/use_exception_list.test.tsx b/x-pack/plugins/lists/public/exceptions/hooks/use_exception_list.test.tsx index a6a25ab4d4e9d..26ebb7ff5d359 100644 --- a/x-pack/plugins/lists/public/exceptions/hooks/use_exception_list.test.tsx +++ b/x-pack/plugins/lists/public/exceptions/hooks/use_exception_list.test.tsx @@ -10,7 +10,8 @@ import * as api from '../api'; import { createKibanaCoreStartMock } from '../../common/mocks/kibana_core'; import { getExceptionListSchemaMock } from '../../../common/schemas/response/exception_list_schema.mock'; import { getExceptionListItemSchemaMock } from '../../../common/schemas/response/exception_list_item_schema.mock'; -import { ExceptionListAndItems, UseExceptionListProps } from '../types'; +import { ExceptionListSchema } from '../../../common/schemas'; +import { ExceptionItemsAndPagination, UseExceptionListProps } from '../types'; import { ReturnExceptionListAndItems, useExceptionList } from './use_exception_list'; @@ -41,8 +42,7 @@ describe('useExceptionList', () => { ); await waitForNextUpdate(); - expect(result.current).toEqual([true, null, result.current[2]]); - expect(typeof result.current[2]).toEqual('function'); + expect(result.current).toEqual([true, null, null, null]); }); }); @@ -62,19 +62,23 @@ describe('useExceptionList', () => { await waitForNextUpdate(); await waitForNextUpdate(); - const expectedResult: ExceptionListAndItems = { - ...getExceptionListSchemaMock(), - exceptionItems: { - items: [{ ...getExceptionListItemSchemaMock() }], - pagination: { - page: 1, - perPage: 20, - total: 1, - }, + const expectedListResult: ExceptionListSchema = getExceptionListSchemaMock(); + + const expectedListItemsResult: ExceptionItemsAndPagination = { + items: [getExceptionListItemSchemaMock()], + pagination: { + page: 1, + perPage: 20, + total: 1, }, }; - expect(result.current).toEqual([false, expectedResult, result.current[2]]); + expect(result.current).toEqual([ + false, + expectedListResult, + expectedListItemsResult, + result.current[3], + ]); }); }); @@ -128,7 +132,13 @@ describe('useExceptionList', () => { ); await waitForNextUpdate(); await waitForNextUpdate(); - result.current[2](); + + expect(typeof result.current[3]).toEqual('function'); + + if (result.current[3] != null) { + result.current[3]({ listId: 'myListId', listNamespaceType: 'single' }); + } + await waitForNextUpdate(); expect(spyOnfetchExceptionListById).toHaveBeenCalledTimes(2); diff --git a/x-pack/plugins/lists/public/exceptions/hooks/use_exception_list.tsx b/x-pack/plugins/lists/public/exceptions/hooks/use_exception_list.tsx index 116233cd89348..881e9facd8d3b 100644 --- a/x-pack/plugins/lists/public/exceptions/hooks/use_exception_list.tsx +++ b/x-pack/plugins/lists/public/exceptions/hooks/use_exception_list.tsx @@ -4,12 +4,23 @@ * you may not use this file except in compliance with the Elastic License. */ -import { useCallback, useEffect, useState } from 'react'; +import { useEffect, useMemo, useRef, useState } from 'react'; import { fetchExceptionListById, fetchExceptionListItemsByListId } from '../api'; -import { ExceptionListAndItems, UseExceptionListProps } from '../types'; +import { + ExceptionItemsAndPagination, + UseExceptionListProps, + UseExceptionListRefreshProps, +} from '../types'; +import { ExceptionListSchema } from '../../../common/schemas'; -export type ReturnExceptionListAndItems = [boolean, ExceptionListAndItems | null, () => void]; +type Func = (arg: UseExceptionListRefreshProps) => void; +export type ReturnExceptionListAndItems = [ + boolean, + ExceptionListSchema | null, + ExceptionItemsAndPagination | null, + Func | null +]; /** * Hook for using to get an ExceptionList and it's ExceptionListItems @@ -37,64 +48,60 @@ export const useExceptionList = ({ }, onError, }: UseExceptionListProps): ReturnExceptionListAndItems => { - const [exceptionListAndItems, setExceptionList] = useState(null); - const [shouldRefresh, setRefresh] = useState(true); - const refreshExceptionList = useCallback(() => setRefresh(true), [setRefresh]); + const [exceptionList, setExceptionList] = useState(null); + const [exceptionItems, setExceptionListItems] = useState( + null + ); + const fetchExceptionList = useRef(null); const [loading, setLoading] = useState(true); - const tags = filterOptions.tags.sort().join(); + const tags = useMemo(() => filterOptions.tags.sort().join(), [filterOptions.tags]); useEffect( () => { let isSubscribed = true; const abortCtrl = new AbortController(); - const fetchData = async (idToFetch: string): Promise => { - if (shouldRefresh) { - try { - setLoading(true); + const fetchData = async ({ + listId, + listNamespaceType, + }: UseExceptionListRefreshProps): Promise => { + try { + setLoading(true); + + const { list_id, namespace_type, ...restOfExceptionList } = await fetchExceptionListById({ + http, + id: listId, + namespaceType: listNamespaceType, + signal: abortCtrl.signal, + }); + const fetchListItemsResult = await fetchExceptionListItemsByListId({ + filterOptions, + http, + listId: list_id, + namespaceType: namespace_type, + pagination, + signal: abortCtrl.signal, + }); - const { + if (isSubscribed) { + setExceptionList({ list_id, namespace_type, - ...restOfExceptionList - } = await fetchExceptionListById({ - http, - id: idToFetch, - namespaceType, - signal: abortCtrl.signal, + ...restOfExceptionList, }); - const fetchListItemsResult = await fetchExceptionListItemsByListId({ - filterOptions, - http, - listId: list_id, - namespaceType: namespace_type, - pagination, - signal: abortCtrl.signal, + setExceptionListItems({ + items: [...fetchListItemsResult.data], + pagination: { + page: fetchListItemsResult.page, + perPage: fetchListItemsResult.per_page, + total: fetchListItemsResult.total, + }, }); - - setRefresh(false); - - if (isSubscribed) { - setExceptionList({ - list_id, - namespace_type, - ...restOfExceptionList, - exceptionItems: { - items: [...fetchListItemsResult.data], - pagination: { - page: fetchListItemsResult.page, - perPage: fetchListItemsResult.per_page, - total: fetchListItemsResult.total, - }, - }, - }); - } - } catch (error) { - setRefresh(false); - if (isSubscribed) { - setExceptionList(null); - onError(error); - } + } + } catch (error) { + if (isSubscribed) { + setExceptionList(null); + onError(error); } } @@ -103,25 +110,18 @@ export const useExceptionList = ({ } }; - if (id != null) { - fetchData(id); + if (id != null && namespaceType != null) { + fetchData({ listId: id, listNamespaceType: namespaceType }); } + + fetchExceptionList.current = fetchData; return (): void => { isSubscribed = false; abortCtrl.abort(); }; }, // eslint-disable-next-line react-hooks/exhaustive-deps - [ - http, - id, - onError, - shouldRefresh, - pagination.page, - pagination.perPage, - filterOptions.filter, - tags, - ] + [http, id, namespaceType, pagination.page, pagination.perPage, filterOptions.filter, tags] ); - return [loading, exceptionListAndItems, refreshExceptionList]; + return [loading, exceptionList, exceptionItems, fetchExceptionList.current]; }; diff --git a/x-pack/plugins/lists/public/exceptions/types.ts b/x-pack/plugins/lists/public/exceptions/types.ts index cf6b6c3ec1c59..e3daf7c28fc88 100644 --- a/x-pack/plugins/lists/public/exceptions/types.ts +++ b/x-pack/plugins/lists/public/exceptions/types.ts @@ -29,10 +29,6 @@ export interface ExceptionItemsAndPagination { pagination: Pagination; } -export interface ExceptionListAndItems extends ExceptionListSchema { - exceptionItems: ExceptionItemsAndPagination; -} - export type AddExceptionList = ExceptionListSchema | CreateExceptionListSchemaPartial; export type AddExceptionListItem = CreateExceptionListItemSchemaPartial | ExceptionListItemSchema; @@ -51,6 +47,11 @@ export interface UseExceptionListProps { pagination?: Pagination; } +export interface UseExceptionListRefreshProps { + listId: string; + listNamespaceType: NamespaceType; +} + export interface ApiCallByListIdProps { http: HttpStart; listId: string; diff --git a/x-pack/plugins/lists/public/index.tsx b/x-pack/plugins/lists/public/index.tsx index fb4d5de06ae54..10f87c407df51 100644 --- a/x-pack/plugins/lists/public/index.tsx +++ b/x-pack/plugins/lists/public/index.tsx @@ -7,4 +7,5 @@ export { usePersistExceptionItem } from './exceptions/hooks/persist_exception_item'; export { usePersistExceptionList } from './exceptions/hooks/persist_exception_list'; export { useExceptionList } from './exceptions/hooks/use_exception_list'; +export { deleteExceptionListItemById } from './exceptions/api'; export { mockNewExceptionItem, mockNewExceptionList } from './exceptions/mock'; From 798b1ddf96590351d73925efc2838f68de578297 Mon Sep 17 00:00:00 2001 From: Yara Tercero Date: Thu, 4 Jun 2020 12:56:47 -0400 Subject: [PATCH 17/32] moved exception item component into its own folder --- .../exception_item/exception_details.test.tsx | 226 ++++++++++++++++++ .../exception_item/exception_details.tsx | 85 +++++++ .../exception_item/exception_entries.test.tsx | 150 ++++++++++++ .../exception_item/exception_entries.tsx | 169 +++++++++++++ .../viewer/exception_item/index.test.tsx | 116 +++++++++ .../viewer/exception_item/index.tsx | 99 ++++++++ 6 files changed, 845 insertions(+) create mode 100644 x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/exception_details.test.tsx create mode 100644 x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/exception_details.tsx create mode 100644 x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/exception_entries.test.tsx create mode 100644 x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/exception_entries.tsx create mode 100644 x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/index.test.tsx create mode 100644 x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/index.tsx diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/exception_details.test.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/exception_details.test.tsx new file mode 100644 index 0000000000000..fee9c4165972d --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/exception_details.test.tsx @@ -0,0 +1,226 @@ +/* + * 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 React from 'react'; +import { ThemeProvider } from 'styled-components'; +import { mount } from 'enzyme'; +import euiLightVars from '@elastic/eui/dist/eui_theme_light.json'; +import moment from 'moment-timezone'; + +import { ExceptionDetails } from './exception_details'; +import { getExceptionItemMock } from '../../mocks'; + +describe('ExceptionDetails', () => { + beforeEach(() => { + moment.tz.setDefault('UTC'); + }); + + afterEach(() => { + moment.tz.setDefault('Browser'); + }); + + test('it renders no comments button if no comments exist', () => { + const exceptionItem = getExceptionItemMock(); + exceptionItem.comments = []; + + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + + expect(wrapper.find('[data-test-subj="exceptionsViewerItemCommentsBtn"]')).toHaveLength(0); + }); + + test('it renders comments button if comments exist', () => { + const exceptionItem = getExceptionItemMock(); + + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + + expect( + wrapper.find('.euiButtonEmpty[data-test-subj="exceptionsViewerItemCommentsBtn"]') + ).toHaveLength(1); + }); + + test('it renders correct number of comments', () => { + const exceptionItem = getExceptionItemMock(); + + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + + expect(wrapper.find('[data-test-subj="exceptionsViewerItemCommentsBtn"]').at(0).text()).toEqual( + 'Show (1) Comment' + ); + }); + + test('it renders comments plural if more than one', () => { + const exceptionItem = getExceptionItemMock(); + exceptionItem.comments = [ + { + user: 'user_1', + timestamp: '2020-04-23T00:19:13.289Z', + comment: 'Comment goes here', + }, + { + user: 'user_2', + timestamp: '2020-04-23T00:19:13.289Z', + comment: 'Comment goes here', + }, + ]; + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + + expect(wrapper.find('[data-test-subj="exceptionsViewerItemCommentsBtn"]').at(0).text()).toEqual( + 'Show (2) Comments' + ); + }); + + test('it renders comments show text if "showComments" is false', () => { + const exceptionItem = getExceptionItemMock(); + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + + expect(wrapper.find('[data-test-subj="exceptionsViewerItemCommentsBtn"]').at(0).text()).toEqual( + 'Show (1) Comment' + ); + }); + + test('it renders comments hide text if "showComments" is true', () => { + const exceptionItem = getExceptionItemMock(); + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + + expect(wrapper.find('[data-test-subj="exceptionsViewerItemCommentsBtn"]').at(0).text()).toEqual( + 'Hide (1) Comment' + ); + }); + + test('it invokes "onCommentsClick" when comments button clicked', () => { + const mockOnCommentsClick = jest.fn(); + const exceptionItem = getExceptionItemMock(); + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + const commentsBtn = wrapper.find('[data-test-subj="exceptionsViewerItemCommentsBtn"]').at(0); + commentsBtn.simulate('click'); + + expect(mockOnCommentsClick).toHaveBeenCalledTimes(1); + }); + + test('it renders the operating system if one is specified in the exception item', () => { + const exceptionItem = getExceptionItemMock(); + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + + expect(wrapper.find('EuiDescriptionListTitle').at(0).text()).toEqual('OS'); + expect(wrapper.find('EuiDescriptionListDescription').at(0).text()).toEqual('Windows'); + }); + + test('it renders the exception item creator', () => { + const exceptionItem = getExceptionItemMock(); + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + + expect(wrapper.find('EuiDescriptionListTitle').at(1).text()).toEqual('Date created'); + expect(wrapper.find('EuiDescriptionListDescription').at(1).text()).toEqual( + 'April 23rd 2020 @ 00:19:13' + ); + }); + + test('it renders the exception item creation timestamp', () => { + const exceptionItem = getExceptionItemMock(); + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + + expect(wrapper.find('EuiDescriptionListTitle').at(2).text()).toEqual('Created by'); + expect(wrapper.find('EuiDescriptionListDescription').at(2).text()).toEqual('user_name'); + }); + + test('it renders the description if one is included on the exception item', () => { + const exceptionItem = getExceptionItemMock(); + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + + expect(wrapper.find('EuiDescriptionListTitle').at(3).text()).toEqual('Comment'); + expect(wrapper.find('EuiDescriptionListDescription').at(3).text()).toEqual( + 'This is a description' + ); + }); +}); diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/exception_details.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/exception_details.tsx new file mode 100644 index 0000000000000..596ef996a4571 --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/exception_details.tsx @@ -0,0 +1,85 @@ +/* + * 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 { EuiFlexItem, EuiFlexGroup, EuiDescriptionList, EuiButtonEmpty } from '@elastic/eui'; +import React, { useMemo } from 'react'; +import styled, { css } from 'styled-components'; +import { transparentize } from 'polished'; + +import { ExceptionListItemSchema } from '../../types'; +import { getDescriptionListContent } from '../../helpers'; +import * as i18n from '../../translations'; + +const StyledExceptionDetails = styled(EuiFlexItem)` + ${({ theme }) => css` + background-color: ${transparentize(0.95, theme.eui.euiColorPrimary)}; + padding: ${theme.eui.euiSize}; + + .euiDescriptionList__title.listTitle--width { + width: 40%; + } + + .euiDescriptionList__description.listDescription--width { + width: 60%; + } + `} +`; + +const ExceptionDetailsComponent = ({ + showComments, + onCommentsClick, + exceptionItem, +}: { + showComments: boolean; + exceptionItem: ExceptionListItemSchema; + onCommentsClick: () => void; +}): JSX.Element => { + const descriptionList = useMemo(() => getDescriptionListContent(exceptionItem), [exceptionItem]); + + const commentsSection = useMemo((): JSX.Element => { + const { comments } = exceptionItem; + if (comments.length > 0) { + return ( + + {!showComments + ? i18n.COMMENTS_SHOW(comments.length) + : i18n.COMMENTS_HIDE(comments.length)} + + ); + } else { + return <>; + } + }, [showComments, onCommentsClick, exceptionItem]); + + return ( + + + + + + {commentsSection} + + + ); +}; + +ExceptionDetailsComponent.displayName = 'ExceptionDetailsComponent'; + +export const ExceptionDetails = React.memo(ExceptionDetailsComponent); + +ExceptionDetails.displayName = 'ExceptionDetails'; diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/exception_entries.test.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/exception_entries.test.tsx new file mode 100644 index 0000000000000..3d0e5a97f6d05 --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/exception_entries.test.tsx @@ -0,0 +1,150 @@ +/* + * 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 React from 'react'; +import { ThemeProvider } from 'styled-components'; +import { mount } from 'enzyme'; +import euiLightVars from '@elastic/eui/dist/eui_theme_light.json'; + +import { ExceptionEntries } from './exception_entries'; +import { getFormattedEntryMock } from '../../mocks'; +import { getEmptyValue } from '../../../empty_value'; + +describe('ExceptionEntries', () => { + test('it does NOT render the and badge if only one exception item entry exists', () => { + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + + expect(wrapper.find('[data-test-subj="exceptionsViewerAndBadge"]')).toHaveLength(0); + }); + + test('it renders the and badge if more than one exception item exists', () => { + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + + expect(wrapper.find('[data-test-subj="exceptionsViewerAndBadge"]')).toHaveLength(1); + }); + + test('it invokes "handlEdit" when edit button clicked', () => { + const mockHandleEdit = jest.fn(); + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + const editBtn = wrapper.find('[data-test-subj="exceptionsViewerEditBtn"] button').at(0); + editBtn.simulate('click'); + + expect(mockHandleEdit).toHaveBeenCalledTimes(1); + }); + + test('it invokes "handleDelete" when delete button clicked', () => { + const mockHandleDelete = jest.fn(); + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + const deleteBtn = wrapper.find('[data-test-subj="exceptionsViewerDeleteBtn"] button').at(0); + deleteBtn.simulate('click'); + + expect(mockHandleDelete).toHaveBeenCalledTimes(1); + }); + + test('it renders nested entry', () => { + const parentEntry = getFormattedEntryMock(); + parentEntry.operator = null; + parentEntry.value = null; + + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + + const parentField = wrapper + .find('[data-test-subj="exceptionFieldNameCell"] .euiTableCellContent') + .at(0); + const parentOperator = wrapper + .find('[data-test-subj="exceptionFieldOperatorCell"] .euiTableCellContent') + .at(0); + const parentValue = wrapper + .find('[data-test-subj="exceptionFieldValueCell"] .euiTableCellContent') + .at(0); + + const nestedField = wrapper + .find('[data-test-subj="exceptionFieldNameCell"] .euiTableCellContent') + .at(1); + const nestedOperator = wrapper + .find('[data-test-subj="exceptionFieldOperatorCell"] .euiTableCellContent') + .at(1); + const nestedValue = wrapper + .find('[data-test-subj="exceptionFieldValueCell"] .euiTableCellContent') + .at(1); + + expect(parentField.text()).toEqual('host.name'); + expect(parentOperator.text()).toEqual(getEmptyValue()); + expect(parentValue.text()).toEqual(getEmptyValue()); + + expect(nestedField.exists('.euiToolTipAnchor')).toBeTruthy(); + expect(nestedField.text()).toEqual('host.name'); + expect(nestedOperator.text()).toEqual('is'); + expect(nestedValue.text()).toEqual('some name'); + }); + + test('it renders non-nested entries', () => { + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + + const field = wrapper + .find('[data-test-subj="exceptionFieldNameCell"] .euiTableCellContent') + .at(0); + const operator = wrapper + .find('[data-test-subj="exceptionFieldOperatorCell"] .euiTableCellContent') + .at(0); + const value = wrapper + .find('[data-test-subj="exceptionFieldValueCell"] .euiTableCellContent') + .at(0); + + expect(field.exists('.euiToolTipAnchor')).toBeFalsy(); + expect(field.text()).toEqual('host.name'); + expect(operator.text()).toEqual('is'); + expect(value.text()).toEqual('some name'); + }); +}); diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/exception_entries.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/exception_entries.tsx new file mode 100644 index 0000000000000..74d0020c6c77e --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/exception_entries.tsx @@ -0,0 +1,169 @@ +/* + * 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 { + EuiBasicTable, + EuiIconTip, + EuiFlexItem, + EuiFlexGroup, + EuiButton, + EuiTableFieldDataColumnType, +} from '@elastic/eui'; +import React, { useMemo } from 'react'; +import styled, { css } from 'styled-components'; +import { transparentize } from 'polished'; + +import { AndOrBadge } from '../../../and_or_badge'; +import { getEmptyValue } from '../../../empty_value'; +import * as i18n from '../../translations'; +import { FormattedEntry } from '../../types'; + +const EntriesDetails = styled(EuiFlexItem)` + padding: ${({ theme }) => theme.eui.euiSize}; +`; + +const StyledEditButton = styled(EuiButton)` + ${({ theme }) => css` + background-color: ${transparentize(0.9, theme.eui.euiColorPrimary)}; + border: none; + font-weight: ${theme.eui.euiFontWeightSemiBold}; + `} +`; + +const StyledRemoveButton = styled(EuiButton)` + ${({ theme }) => css` + background-color: ${transparentize(0.9, theme.eui.euiColorDanger)}; + border: none; + font-weight: ${theme.eui.euiFontWeightSemiBold}; + `} +`; + +const AndOrBadgeContainer = styled(EuiFlexItem)` + padding-top: ${({ theme }) => theme.eui.euiSizeXL}; +`; + +interface ExceptionEntriesComponentProps { + entries: FormattedEntry[]; + handleDelete: () => void; + handleEdit: () => void; +} + +const ExceptionEntriesComponent = ({ + entries, + handleDelete, + handleEdit, +}: ExceptionEntriesComponentProps): JSX.Element => { + const columns = useMemo( + (): Array> => [ + { + field: 'fieldName', + name: 'Field', + sortable: false, + truncateText: true, + 'data-test-subj': 'exceptionFieldNameCell', + width: '30%', + render: (value: string | null, data: FormattedEntry) => { + if (value != null && data.isNested) { + return ( + <> + + {value} + + ); + } else { + return value ?? getEmptyValue(); + } + }, + }, + { + field: 'operator', + name: 'Operator', + sortable: false, + truncateText: true, + 'data-test-subj': 'exceptionFieldOperatorCell', + width: '20%', + render: (value: string | null) => value ?? getEmptyValue(), + }, + { + field: 'value', + name: 'Value', + sortable: false, + truncateText: true, + 'data-test-subj': 'exceptionFieldValueCell', + width: '60%', + render: (values: string | string[] | null) => { + if (Array.isArray(values)) { + return ( + + {values.map((value) => { + return {value}; + })} + + ); + } else { + return values ?? getEmptyValue(); + } + }, + }, + ], + [entries] + ); + + return ( + + + + + {entries.length > 1 && ( + + + + )} + + + + + + + + + + {i18n.EDIT} + + + + + {i18n.REMOVE} + + + + + + + ); +}; + +ExceptionEntriesComponent.displayName = 'ExceptionEntriesComponent'; + +export const ExceptionEntries = React.memo(ExceptionEntriesComponent); + +ExceptionEntries.displayName = 'ExceptionEntries'; diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/index.test.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/index.test.tsx new file mode 100644 index 0000000000000..ebfa9b7b9998a --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/index.test.tsx @@ -0,0 +1,116 @@ +/* + * 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 React from 'react'; +import { ThemeProvider } from 'styled-components'; +import { mount } from 'enzyme'; +import euiLightVars from '@elastic/eui/dist/eui_theme_light.json'; + +import { ExceptionItem } from './'; +import { getExceptionItemMock } from '../../mocks'; + +describe('ExceptionItem', () => { + it('it renders ExceptionDetails and ExceptionEntries', () => { + const exceptionItem = getExceptionItemMock(); + + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + + expect(wrapper.find('ExceptionDetails')).toHaveLength(1); + expect(wrapper.find('ExceptionEntries')).toHaveLength(1); + }); + + it('it invokes "handleEdit" when edit button clicked', () => { + const mockHandleEdit = jest.fn(); + const exceptionItem = getExceptionItemMock(); + + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + + const editBtn = wrapper.find('[data-test-subj="exceptionsViewerEditBtn"] button').at(0); + editBtn.simulate('click'); + + expect(mockHandleEdit).toHaveBeenCalledTimes(1); + }); + + it('it invokes "handleDelete" when delete button clicked', () => { + const mockHandleDelete = jest.fn(); + const exceptionItem = getExceptionItemMock(); + + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + + const editBtn = wrapper.find('[data-test-subj="exceptionsViewerDeleteBtn"] button').at(0); + editBtn.simulate('click'); + + expect(mockHandleDelete).toHaveBeenCalledTimes(1); + }); + + it('it renders comment accordion closed to begin with', () => { + const mockHandleDelete = jest.fn(); + const exceptionItem = getExceptionItemMock(); + + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + + expect(wrapper.find('.euiAccordion-isOpen')).toHaveLength(0); + }); + + it('it renders comment accordion open when showComments is true', () => { + const mockHandleDelete = jest.fn(); + const exceptionItem = getExceptionItemMock(); + + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + + const commentsBtn = wrapper + .find('.euiButtonEmpty[data-test-subj="exceptionsViewerItemCommentsBtn"]') + .at(0); + commentsBtn.simulate('click'); + + expect(wrapper.find('.euiAccordion-isOpen')).toHaveLength(1); + }); +}); diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/index.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/index.tsx new file mode 100644 index 0000000000000..16dd67c9071fd --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/index.tsx @@ -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 { + EuiPanel, + EuiFlexGroup, + EuiCommentProps, + EuiCommentList, + EuiAccordion, + EuiFlexItem, +} from '@elastic/eui'; +import React, { useEffect, useState, useMemo, useCallback } from 'react'; +import styled from 'styled-components'; + +import { ExceptionDetails } from './exception_details'; +import { ExceptionEntries } from './exception_entries'; +import { getFormattedEntries, getFormattedComments } from '../../helpers'; +import { FormattedEntry, ExceptionListItemSchema } from '../../types'; + +const MyFlexItem = styled(EuiFlexItem)` + &.comments--show { + padding: ${({ theme }) => theme.eui.euiSize}; + border-top: ${({ theme }) => `${theme.eui.euiBorderThin}`} + +`; + +interface ExceptionItemProps { + exceptionItem: ExceptionListItemSchema; + commentsAccordionId: string; + handleDelete: ({ id }: { id: string }) => void; + handleEdit: (item: ExceptionListItemSchema) => void; +} + +const ExceptionItemComponent = ({ + exceptionItem, + commentsAccordionId, + handleDelete, + handleEdit, +}: ExceptionItemProps): JSX.Element => { + const [entryItems, setEntryItems] = useState([]); + const [showComments, setShowComments] = useState(false); + + useEffect((): void => { + const formattedEntries = getFormattedEntries(exceptionItem.entries); + setEntryItems(formattedEntries); + }, [exceptionItem.entries]); + + const onDelete = useCallback((): void => { + handleDelete({ id: exceptionItem.id }); + }, [handleDelete, exceptionItem]); + + const onEdit = useCallback((): void => { + handleEdit(exceptionItem); + }, [handleEdit, exceptionItem]); + + const onCommentsClick = useCallback((): void => { + setShowComments(!showComments); + }, [setShowComments, showComments]); + + const formattedComments = useMemo((): EuiCommentProps[] => { + return getFormattedComments(exceptionItem.comments); + }, [exceptionItem]); + + return ( + + + + + + + + + + + + + + + + ); +}; + +ExceptionItemComponent.displayName = 'ExceptionItemComponent'; + +export const ExceptionItem = React.memo(ExceptionItemComponent); + +ExceptionItem.displayName = 'ExceptionItem'; From 29810e754c00739b00b20cb3611f0543a4eb7aa0 Mon Sep 17 00:00:00 2001 From: Yara Tercero Date: Thu, 4 Jun 2020 12:59:09 -0400 Subject: [PATCH 18/32] added search bar, toggle, and buttons --- .../components/exceptions/translations.ts | 57 ++++ .../common/components/exceptions/types.ts | 23 ++ .../viewer/exception_details.test.tsx | 226 -------------- .../exceptions/viewer/exception_details.tsx | 85 ------ .../viewer/exception_entries.test.tsx | 150 --------- .../exceptions/viewer/exception_entries.tsx | 169 ----------- .../viewer/exceptions_viewer_header.test.tsx | 285 ++++++++++++++++++ .../viewer/exceptions_viewer_header.tsx | 181 +++++++++++ 8 files changed, 546 insertions(+), 630 deletions(-) delete mode 100644 x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_details.test.tsx delete mode 100644 x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_details.tsx delete mode 100644 x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_entries.test.tsx delete mode 100644 x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_entries.tsx create mode 100644 x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exceptions_viewer_header.test.tsx create mode 100644 x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exceptions_viewer_header.tsx diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/translations.ts b/x-pack/plugins/security_solution/public/common/components/exceptions/translations.ts index 704849430daf9..956f65de645b4 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/translations.ts +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/translations.ts @@ -47,3 +47,60 @@ export const OPERATING_SYSTEM = i18n.translate( defaultMessage: 'OS', } ); + +export const SEARCH_DEFAULT = i18n.translate( + 'xpack.securitySolution.exceptions.viewer.searchDefaultPlaceholder', + { + defaultMessage: 'Search field (default)', + } +); + +export const ADD_EXCEPTION_LABEL = i18n.translate( + 'xpack.securitySolution.exceptions.viewer.addExceptionLabel', + { + defaultMessage: 'Add new exception', + } +); + +export const ADD_TO_ENDPOINT_LIST = i18n.translate( + 'xpack.securitySolution.exceptions.viewer.addToEndpointListLabel', + { + defaultMessage: 'Add to endpoint list', + } +); + +export const ADD_TO_DETECTIONS_LIST = i18n.translate( + 'xpack.securitySolution.exceptions.viewer.addToDetectionsListLabel', + { + defaultMessage: 'Add to detections list', + } +); + +export const EXCEPTION_EMPTY_PROMPT_TITLE = i18n.translate( + 'xpack.securitySolution.exceptions.viewer.emptyPromptTitle', + { + defaultMessage: 'You have no exceptions', + } +); + +export const EXCEPTION_EMPTY_PROMPT_BODY = i18n.translate( + 'xpack.securitySolution.exceptions.viewer.emptyPromptBody', + { + defaultMessage: + 'This could be a description of what exceptions are and what their use case could be. Wow such tempt much ruin diet wrinkler clouds, you are doin me a concern. H*cksub woofer shibe clouds.', + } +); + +export const FETCH_LIST_ERROR = i18n.translate( + 'xpack.securitySolution.exceptions.viewer.fetchingListError', + { + defaultMessage: 'Error fetching exceptions', + } +); + +export const DELETE_EXCEPTION_ERROR = i18n.translate( + 'xpack.securitySolution.exceptions.viewer.deleteExceptionError', + { + defaultMessage: 'Error deleting exception', + } +); diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/types.ts b/x-pack/plugins/security_solution/public/common/components/exceptions/types.ts index e8393610e459d..f4707efa76a0f 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/types.ts +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/types.ts @@ -5,6 +5,8 @@ */ import { ReactNode } from 'react'; +import { NamespaceType } from '../../../lists_plugin_deps'; + export interface OperatorOption { message: string; value: string; @@ -56,6 +58,27 @@ export interface Comment { comment: string; } +export enum ToggleId { + DETECTION_ENGINE = 'detection', + ENDPOINT = 'endpoint', +} + +export interface RuleExceptionList { + id: string | null; + type: string | null; + namespaceType: NamespaceType | null; +} + +export interface FilterOptions { + filter: string; + tags: string[]; +} + +export interface ApiProps { + id: string | null; + namespaceType: NamespaceType | null; +} + // TODO: Delete once types are updated export interface ExceptionListItemSchema { _tags: string[]; diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_details.test.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_details.test.tsx deleted file mode 100644 index 536d005c57b6e..0000000000000 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_details.test.tsx +++ /dev/null @@ -1,226 +0,0 @@ -/* - * 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 React from 'react'; -import { ThemeProvider } from 'styled-components'; -import { mount } from 'enzyme'; -import euiLightVars from '@elastic/eui/dist/eui_theme_light.json'; -import moment from 'moment-timezone'; - -import { ExceptionDetails } from './exception_details'; -import { getExceptionItemMock } from '../mocks'; - -describe('ExceptionDetails', () => { - beforeEach(() => { - moment.tz.setDefault('UTC'); - }); - - afterEach(() => { - moment.tz.setDefault('Browser'); - }); - - test('it renders no comments button if no comments exist', () => { - const exceptionItem = getExceptionItemMock(); - exceptionItem.comments = []; - - const wrapper = mount( - ({ eui: euiLightVars, darkMode: false })}> - - - ); - - expect(wrapper.find('[data-test-subj="exceptionsViewerItemCommentsBtn"]')).toHaveLength(0); - }); - - test('it renders comments button if comments exist', () => { - const exceptionItem = getExceptionItemMock(); - - const wrapper = mount( - ({ eui: euiLightVars, darkMode: false })}> - - - ); - - expect( - wrapper.find('.euiButtonEmpty[data-test-subj="exceptionsViewerItemCommentsBtn"]') - ).toHaveLength(1); - }); - - test('it renders correct number of comments', () => { - const exceptionItem = getExceptionItemMock(); - - const wrapper = mount( - ({ eui: euiLightVars, darkMode: false })}> - - - ); - - expect(wrapper.find('[data-test-subj="exceptionsViewerItemCommentsBtn"]').at(0).text()).toEqual( - 'Show (1) Comment' - ); - }); - - test('it renders comments plural if more than one', () => { - const exceptionItem = getExceptionItemMock(); - exceptionItem.comments = [ - { - user: 'user_1', - timestamp: '2020-04-23T00:19:13.289Z', - comment: 'Comment goes here', - }, - { - user: 'user_2', - timestamp: '2020-04-23T00:19:13.289Z', - comment: 'Comment goes here', - }, - ]; - const wrapper = mount( - ({ eui: euiLightVars, darkMode: false })}> - - - ); - - expect(wrapper.find('[data-test-subj="exceptionsViewerItemCommentsBtn"]').at(0).text()).toEqual( - 'Show (2) Comments' - ); - }); - - test('it renders comments show text if "showComments" is false', () => { - const exceptionItem = getExceptionItemMock(); - const wrapper = mount( - ({ eui: euiLightVars, darkMode: false })}> - - - ); - - expect(wrapper.find('[data-test-subj="exceptionsViewerItemCommentsBtn"]').at(0).text()).toEqual( - 'Show (1) Comment' - ); - }); - - test('it renders comments hide text if "showComments" is true', () => { - const exceptionItem = getExceptionItemMock(); - const wrapper = mount( - ({ eui: euiLightVars, darkMode: false })}> - - - ); - - expect(wrapper.find('[data-test-subj="exceptionsViewerItemCommentsBtn"]').at(0).text()).toEqual( - 'Hide (1) Comment' - ); - }); - - test('it invokes "onCommentsClick" when comments button clicked', () => { - const mockOnCommentsClick = jest.fn(); - const exceptionItem = getExceptionItemMock(); - const wrapper = mount( - ({ eui: euiLightVars, darkMode: false })}> - - - ); - const commentsBtn = wrapper.find('[data-test-subj="exceptionsViewerItemCommentsBtn"]').at(0); - commentsBtn.simulate('click'); - - expect(mockOnCommentsClick).toHaveBeenCalledTimes(1); - }); - - test('it renders the operating system if one is specified in the exception item', () => { - const exceptionItem = getExceptionItemMock(); - const wrapper = mount( - ({ eui: euiLightVars, darkMode: false })}> - - - ); - - expect(wrapper.find('EuiDescriptionListTitle').at(0).text()).toEqual('OS'); - expect(wrapper.find('EuiDescriptionListDescription').at(0).text()).toEqual('Windows'); - }); - - test('it renders the exception item creator', () => { - const exceptionItem = getExceptionItemMock(); - const wrapper = mount( - ({ eui: euiLightVars, darkMode: false })}> - - - ); - - expect(wrapper.find('EuiDescriptionListTitle').at(1).text()).toEqual('Date created'); - expect(wrapper.find('EuiDescriptionListDescription').at(1).text()).toEqual( - 'April 23rd 2020 @ 00:19:13' - ); - }); - - test('it renders the exception item creation timestamp', () => { - const exceptionItem = getExceptionItemMock(); - const wrapper = mount( - ({ eui: euiLightVars, darkMode: false })}> - - - ); - - expect(wrapper.find('EuiDescriptionListTitle').at(2).text()).toEqual('Created by'); - expect(wrapper.find('EuiDescriptionListDescription').at(2).text()).toEqual('user_name'); - }); - - test('it renders the description if one is included on the exception item', () => { - const exceptionItem = getExceptionItemMock(); - const wrapper = mount( - ({ eui: euiLightVars, darkMode: false })}> - - - ); - - expect(wrapper.find('EuiDescriptionListTitle').at(3).text()).toEqual('Comment'); - expect(wrapper.find('EuiDescriptionListDescription').at(3).text()).toEqual( - 'This is a description' - ); - }); -}); diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_details.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_details.tsx deleted file mode 100644 index 8745e80a21548..0000000000000 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_details.tsx +++ /dev/null @@ -1,85 +0,0 @@ -/* - * 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 { EuiFlexItem, EuiFlexGroup, EuiDescriptionList, EuiButtonEmpty } from '@elastic/eui'; -import React, { useMemo } from 'react'; -import styled, { css } from 'styled-components'; -import { transparentize } from 'polished'; - -import { ExceptionListItemSchema } from '../types'; -import { getDescriptionListContent } from '../helpers'; -import * as i18n from '../translations'; - -const StyledExceptionDetails = styled(EuiFlexItem)` - ${({ theme }) => css` - background-color: ${transparentize(0.95, theme.eui.euiColorPrimary)}; - padding: ${theme.eui.euiSize}; - - .euiDescriptionList__title.listTitle--width { - width: 40%; - } - - .euiDescriptionList__description.listDescription--width { - width: 60%; - } - `} -`; - -const ExceptionDetailsComponent = ({ - showComments, - onCommentsClick, - exceptionItem, -}: { - showComments: boolean; - exceptionItem: ExceptionListItemSchema; - onCommentsClick: () => void; -}): JSX.Element => { - const descriptionList = useMemo(() => getDescriptionListContent(exceptionItem), [exceptionItem]); - - const commentsSection = useMemo((): JSX.Element => { - const { comments } = exceptionItem; - if (comments.length > 0) { - return ( - - {!showComments - ? i18n.COMMENTS_SHOW(comments.length) - : i18n.COMMENTS_HIDE(comments.length)} - - ); - } else { - return <>; - } - }, [showComments, onCommentsClick, exceptionItem]); - - return ( - - - - - - {commentsSection} - - - ); -}; - -ExceptionDetailsComponent.displayName = 'ExceptionDetailsComponent'; - -export const ExceptionDetails = React.memo(ExceptionDetailsComponent); - -ExceptionDetails.displayName = 'ExceptionDetails'; diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_entries.test.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_entries.test.tsx deleted file mode 100644 index e0c62f51d032a..0000000000000 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_entries.test.tsx +++ /dev/null @@ -1,150 +0,0 @@ -/* - * 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 React from 'react'; -import { ThemeProvider } from 'styled-components'; -import { mount } from 'enzyme'; -import euiLightVars from '@elastic/eui/dist/eui_theme_light.json'; - -import { ExceptionEntries } from './exception_entries'; -import { getFormattedEntryMock } from '../mocks'; -import { getEmptyValue } from '../../empty_value'; - -describe('ExceptionEntries', () => { - test('it does NOT render the and badge if only one exception item entry exists', () => { - const wrapper = mount( - ({ eui: euiLightVars, darkMode: false })}> - - - ); - - expect(wrapper.find('[data-test-subj="exceptionsViewerAndBadge"]')).toHaveLength(0); - }); - - test('it renders the and badge if more than one exception item exists', () => { - const wrapper = mount( - ({ eui: euiLightVars, darkMode: false })}> - - - ); - - expect(wrapper.find('[data-test-subj="exceptionsViewerAndBadge"]')).toHaveLength(1); - }); - - test('it invokes "handlEdit" when edit button clicked', () => { - const mockHandleEdit = jest.fn(); - const wrapper = mount( - ({ eui: euiLightVars, darkMode: false })}> - - - ); - const editBtn = wrapper.find('[data-test-subj="exceptionsViewerEditBtn"] button').at(0); - editBtn.simulate('click'); - - expect(mockHandleEdit).toHaveBeenCalledTimes(1); - }); - - test('it invokes "handleDelete" when delete button clicked', () => { - const mockHandleDelete = jest.fn(); - const wrapper = mount( - ({ eui: euiLightVars, darkMode: false })}> - - - ); - const deleteBtn = wrapper.find('[data-test-subj="exceptionsViewerDeleteBtn"] button').at(0); - deleteBtn.simulate('click'); - - expect(mockHandleDelete).toHaveBeenCalledTimes(1); - }); - - test('it renders nested entry', () => { - const parentEntry = getFormattedEntryMock(); - parentEntry.operator = null; - parentEntry.value = null; - - const wrapper = mount( - ({ eui: euiLightVars, darkMode: false })}> - - - ); - - const parentField = wrapper - .find('[data-test-subj="exceptionFieldNameCell"] .euiTableCellContent') - .at(0); - const parentOperator = wrapper - .find('[data-test-subj="exceptionFieldOperatorCell"] .euiTableCellContent') - .at(0); - const parentValue = wrapper - .find('[data-test-subj="exceptionFieldValueCell"] .euiTableCellContent') - .at(0); - - const nestedField = wrapper - .find('[data-test-subj="exceptionFieldNameCell"] .euiTableCellContent') - .at(1); - const nestedOperator = wrapper - .find('[data-test-subj="exceptionFieldOperatorCell"] .euiTableCellContent') - .at(1); - const nestedValue = wrapper - .find('[data-test-subj="exceptionFieldValueCell"] .euiTableCellContent') - .at(1); - - expect(parentField.text()).toEqual('host.name'); - expect(parentOperator.text()).toEqual(getEmptyValue()); - expect(parentValue.text()).toEqual(getEmptyValue()); - - expect(nestedField.exists('.euiToolTipAnchor')).toBeTruthy(); - expect(nestedField.text()).toEqual('host.name'); - expect(nestedOperator.text()).toEqual('is'); - expect(nestedValue.text()).toEqual('some name'); - }); - - test('it renders non-nested entries', () => { - const wrapper = mount( - ({ eui: euiLightVars, darkMode: false })}> - - - ); - - const field = wrapper - .find('[data-test-subj="exceptionFieldNameCell"] .euiTableCellContent') - .at(0); - const operator = wrapper - .find('[data-test-subj="exceptionFieldOperatorCell"] .euiTableCellContent') - .at(0); - const value = wrapper - .find('[data-test-subj="exceptionFieldValueCell"] .euiTableCellContent') - .at(0); - - expect(field.exists('.euiToolTipAnchor')).toBeFalsy(); - expect(field.text()).toEqual('host.name'); - expect(operator.text()).toEqual('is'); - expect(value.text()).toEqual('some name'); - }); -}); diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_entries.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_entries.tsx deleted file mode 100644 index d0236adc27c6c..0000000000000 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_entries.tsx +++ /dev/null @@ -1,169 +0,0 @@ -/* - * 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 { - EuiBasicTable, - EuiIconTip, - EuiFlexItem, - EuiFlexGroup, - EuiButton, - EuiTableFieldDataColumnType, -} from '@elastic/eui'; -import React, { useMemo } from 'react'; -import styled, { css } from 'styled-components'; -import { transparentize } from 'polished'; - -import { AndOrBadge } from '../../and_or_badge'; -import { getEmptyValue } from '../../empty_value'; -import * as i18n from '../translations'; -import { FormattedEntry } from '../types'; - -const EntriesDetails = styled(EuiFlexItem)` - padding: ${({ theme }) => theme.eui.euiSize}; -`; - -const StyledEditButton = styled(EuiButton)` - ${({ theme }) => css` - background-color: ${transparentize(0.9, theme.eui.euiColorPrimary)}; - border: none; - font-weight: ${theme.eui.euiFontWeightSemiBold}; - `} -`; - -const StyledRemoveButton = styled(EuiButton)` - ${({ theme }) => css` - background-color: ${transparentize(0.9, theme.eui.euiColorDanger)}; - border: none; - font-weight: ${theme.eui.euiFontWeightSemiBold}; - `} -`; - -const AndOrBadgeContainer = styled(EuiFlexItem)` - padding-top: ${({ theme }) => theme.eui.euiSizeXL}; -`; - -interface ExceptionEntriesComponentProps { - entries: FormattedEntry[]; - handleDelete: () => void; - handleEdit: () => void; -} - -const ExceptionEntriesComponent = ({ - entries, - handleDelete, - handleEdit, -}: ExceptionEntriesComponentProps): JSX.Element => { - const columns = useMemo( - (): Array> => [ - { - field: 'fieldName', - name: 'Field', - sortable: false, - truncateText: true, - 'data-test-subj': 'exceptionFieldNameCell', - width: '30%', - render: (value: string | null, data: FormattedEntry) => { - if (value != null && data.isNested) { - return ( - <> - - {value} - - ); - } else { - return value ?? getEmptyValue(); - } - }, - }, - { - field: 'operator', - name: 'Operator', - sortable: false, - truncateText: true, - 'data-test-subj': 'exceptionFieldOperatorCell', - width: '20%', - render: (value: string | null) => value ?? getEmptyValue(), - }, - { - field: 'value', - name: 'Value', - sortable: false, - truncateText: true, - 'data-test-subj': 'exceptionFieldValueCell', - width: '60%', - render: (values: string | string[] | null) => { - if (Array.isArray(values)) { - return ( - - {values.map((value) => { - return {value}; - })} - - ); - } else { - return values ?? getEmptyValue(); - } - }, - }, - ], - [entries] - ); - - return ( - - - - - {entries.length > 1 && ( - - - - )} - - - - - - - - - - {i18n.EDIT} - - - - - {i18n.REMOVE} - - - - - - - ); -}; - -ExceptionEntriesComponent.displayName = 'ExceptionEntriesComponent'; - -export const ExceptionEntries = React.memo(ExceptionEntriesComponent); - -ExceptionEntries.displayName = 'ExceptionEntries'; diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exceptions_viewer_header.test.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exceptions_viewer_header.test.tsx new file mode 100644 index 0000000000000..2b0d7d9384aa2 --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exceptions_viewer_header.test.tsx @@ -0,0 +1,285 @@ +/* + * 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 React from 'react'; +import { ThemeProvider } from 'styled-components'; +import { mount } from 'enzyme'; +import euiLightVars from '@elastic/eui/dist/eui_theme_light.json'; + +import { ExceptionsViewerHeader } from './exceptions_viewer_header'; +import { ToggleId } from '../types'; + +describe('ExceptionsViewerHeader', () => { + it('it renders all disabled if "isInitLoading" is true', () => { + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + + expect( + wrapper.find('input[data-test-subj="exceptionsHeaderSearch"]').at(0).prop('disabled') + ).toBeTruthy(); + expect( + wrapper.find('[data-test-subj="exceptionsHeaderListToggle"] button').at(0).prop('disabled') + ).toBeTruthy(); + expect( + wrapper.find('[data-test-subj="exceptionsHeaderListToggle"] button').at(1).prop('disabled') + ).toBeTruthy(); + expect( + wrapper + .find('[data-test-subj="exceptionsHeaderAddExceptionBtn"] button') + .at(0) + .prop('disabled') + ).toBeTruthy(); + }); + + it('it disables Endpoint toggle when only Detections list available', () => { + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + + expect( + wrapper.find('input[data-test-subj="detectionsToggle"]').at(0).prop('disabled') + ).toBeFalsy(); + expect( + wrapper.find('input[data-test-subj="detectionsToggle"]').at(0).prop('checked') + ).toBeTruthy(); + expect( + wrapper.find('input[data-test-subj="endpointToggle"]').at(0).prop('disabled') + ).toBeTruthy(); + expect( + wrapper.find('input[data-test-subj="endpointToggle"]').at(0).prop('checked') + ).toBeFalsy(); + }); + + it('it disables Detections toggle when only Endpoint list available', () => { + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + + expect( + wrapper.find('input[data-test-subj="detectionsToggle"]').at(0).prop('disabled') + ).toBeTruthy(); + expect( + wrapper.find('input[data-test-subj="detectionsToggle"]').at(0).prop('checked') + ).toBeFalsy(); + expect( + wrapper.find('input[data-test-subj="endpointToggle"]').at(0).prop('disabled') + ).toBeFalsy(); + expect( + wrapper.find('input[data-test-subj="endpointToggle"]').at(0).prop('checked') + ).toBeTruthy(); + }); + + it('it renders Detections toggle selected when "selectedListType" is detections', () => { + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + + expect( + wrapper.find('input[data-test-subj="detectionsToggle"]').at(0).prop('checked') + ).toBeTruthy(); + }); + + it('it renders Endpoint toggle selected when "selectedListType" is endpoint', () => { + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + + expect( + wrapper.find('input[data-test-subj="endpointToggle"]').at(0).prop('checked') + ).toBeTruthy(); + }); + + it('it invokes "onToggleListType" with appropriate toggle value on click', () => { + const mockOnToggleListType = jest.fn(); + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + + wrapper.find('input[data-test-subj="endpointToggle"]').simulate('change', { + target: { value: 'endpoint' }, + }); + + expect(mockOnToggleListType).toHaveBeenCalledWith('endpoint'); + + wrapper.find('input[data-test-subj="detectionsToggle"]').simulate('change', { + target: { value: 'detection' }, + }); + + expect(mockOnToggleListType).toHaveBeenCalledWith('detection'); + }); + + it('it invokes "onAddExceptionClick" with value "endpoint" when add exception to endpoint list clicked', () => { + const mockAddExceptionClick = jest.fn(); + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + + wrapper.find('[data-test-subj="exceptionsHeaderAddExceptionBtn"] button').simulate('click'); + wrapper.find('[data-test-subj="addEndpointExceptionBtn"] button').simulate('click'); + + expect(mockAddExceptionClick).toHaveBeenCalledWith('endpoint'); + }); + + it('it invokes "onAddExceptionClick" with value "detection" when add exception to detections list clicked', () => { + const mockAddExceptionClick = jest.fn(); + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + + wrapper.find('[data-test-subj="exceptionsHeaderAddExceptionBtn"] button').simulate('click'); + wrapper.find('[data-test-subj="addDetectionsExceptionBtn"] button').simulate('click'); + + expect(mockAddExceptionClick).toHaveBeenCalledWith('detection'); + }); + + it('it invokes "onFiltersChange" with filter value "host" when "host" searched', () => { + const mockOnFiltersChange = jest.fn(); + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + + wrapper + .find('input[data-test-subj="exceptionsHeaderSearch"]') + .at(0) + .simulate('change', { + target: { value: 'host' }, + }); + + expect(mockOnFiltersChange).toHaveBeenCalledWith({ filter: 'host', tags: [] }); + }); + + it('it invokes "onFiltersChange" with tags value when tags searched', () => { + const mockOnFiltersChange = jest.fn(); + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + + wrapper + .find('input[data-test-subj="exceptionsHeaderSearch"]') + .at(0) + .simulate('change', { + target: { value: 'tags:malware' }, + }); + + expect(mockOnFiltersChange).toHaveBeenCalledWith({ filter: '', tags: ['malware'] }); + }); + + it('it invokes "onFiltersChange" with tags and filter value when tags and fields searched', () => { + const mockOnFiltersChange = jest.fn(); + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + + wrapper + .find('input[data-test-subj="exceptionsHeaderSearch"]') + .at(0) + .simulate('change', { + target: { value: 'host.name tags:malware' }, + }); + + expect(mockOnFiltersChange).toHaveBeenCalledWith({ filter: 'host.name', tags: ['malware'] }); + }); +}); diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exceptions_viewer_header.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exceptions_viewer_header.tsx new file mode 100644 index 0000000000000..251048b632275 --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exceptions_viewer_header.tsx @@ -0,0 +1,181 @@ +/* + * 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 { + EuiFieldSearch, + EuiButtonGroup, + EuiFlexGroup, + EuiFlexItem, + EuiPopover, + EuiContextMenu, + EuiButton, + EuiContextMenuPanelDescriptor, + EuiButtonGroupOption, +} from '@elastic/eui'; +import React, { useState, useCallback, useMemo } from 'react'; + +import * as i18n from '../translations'; +import { ToggleId } from '../types'; + +interface ExceptionsViewerHeaderProps { + selectedListType: ToggleId; + isInitLoading: boolean; + listTypes: ToggleId[]; + onFiltersChange: ({ filter, tags }: { filter: string; tags: string[] }) => void; + onAddExceptionClick: (type: ToggleId) => void; + onToggleListType: (type: ToggleId) => void; +} + +/** + * Collection of filters and toggles for filtering exception items. + */ +const ExceptionsViewerHeaderComponent = ({ + selectedListType, + isInitLoading, + listTypes, + onFiltersChange, + onToggleListType, + onAddExceptionClick, +}: ExceptionsViewerHeaderProps): JSX.Element => { + const [isAddExceptionMenuOpen, setAddExceptionMenuOpen] = useState(false); + + const onToggle = useCallback( + (id: string): void => { + const toggle = + id === ToggleId.DETECTION_ENGINE ? ToggleId.DETECTION_ENGINE : ToggleId.ENDPOINT; + onToggleListType(toggle); + }, + [onToggleListType] + ); + + const handleOnSearch = useCallback( + (event: React.ChangeEvent): void => { + const searchValue = event.target.value; + const tagsRegex = /(tags:[^\s]*)/i; + const tagsMatch = searchValue.match(tagsRegex); + const foundTags: string = tagsMatch != null ? tagsMatch[0].split(':')[1] : ''; + const filterString = tagsMatch != null ? searchValue.replace(tagsRegex, '') : searchValue; + onFiltersChange({ + filter: filterString.trim(), + tags: foundTags.length ? foundTags.split(',') : [], + }); + }, + [onFiltersChange] + ); + + const onAddExceptionDropdownClick = useCallback( + (): void => setAddExceptionMenuOpen(!isAddExceptionMenuOpen), + [setAddExceptionMenuOpen] + ); + + const onAddException = useCallback( + (type: ToggleId): void => { + onAddExceptionClick(type); + setAddExceptionMenuOpen(false); + }, + [onAddExceptionClick, setAddExceptionMenuOpen] + ); + + const getAddExceptionOptions = useMemo( + (): EuiContextMenuPanelDescriptor[] => [ + { + id: 0, + items: [ + { + name: i18n.ADD_TO_ENDPOINT_LIST, + onClick: () => { + onAddException(ToggleId.ENDPOINT); + }, + 'data-test-subj': 'addEndpointExceptionBtn', + }, + { + name: i18n.ADD_TO_DETECTIONS_LIST, + onClick: () => { + onAddException(ToggleId.DETECTION_ENGINE); + }, + 'data-test-subj': 'addDetectionsExceptionBtn', + }, + ], + }, + ], + [onAddException] + ); + + const toggleOptions = useMemo((): EuiButtonGroupOption[] => { + return [ + { + id: ToggleId.DETECTION_ENGINE, + label: 'Detection Engine', + isDisabled: !listTypes.includes(ToggleId.DETECTION_ENGINE), + 'data-test-subj': 'detectionsToggle', + }, + { + id: ToggleId.ENDPOINT, + label: 'Endpoint', + isDisabled: !listTypes.includes(ToggleId.ENDPOINT), + 'data-test-subj': 'endpointToggle', + }, + ]; + }, [listTypes]); + + return ( + + + + + + + + + + + + {i18n.ADD_EXCEPTION_LABEL} + + } + isOpen={isAddExceptionMenuOpen} + closePopover={onAddExceptionDropdownClick} + panelPaddingSize="none" + withTitle + anchorPosition="upLeft" + > + + + + + ); +}; + +ExceptionsViewerHeaderComponent.displayName = 'ExceptionsViewerHeaderComponent'; + +export const ExceptionsViewerHeader = React.memo(ExceptionsViewerHeaderComponent); + +ExceptionsViewerHeader.displayName = 'ExceptionsViewerHeader'; From da467bf93bfa6f68527f0346276acd3b02e0e33d Mon Sep 17 00:00:00 2001 From: Yara Tercero Date: Thu, 4 Jun 2020 12:59:43 -0400 Subject: [PATCH 19/32] added exceptions viewer component --- .../exceptions/viewer/index.test.tsx | 116 ----- .../components/exceptions/viewer/index.tsx | 419 +++++++++++++++--- .../components/exceptions/viewer/reducer.ts | 103 +++++ .../public/lists_plugin_deps.ts | 3 +- 4 files changed, 455 insertions(+), 186 deletions(-) delete mode 100644 x-pack/plugins/security_solution/public/common/components/exceptions/viewer/index.test.tsx create mode 100644 x-pack/plugins/security_solution/public/common/components/exceptions/viewer/reducer.ts diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/index.test.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/index.test.tsx deleted file mode 100644 index 7d3b7195def80..0000000000000 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/index.test.tsx +++ /dev/null @@ -1,116 +0,0 @@ -/* - * 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 React from 'react'; -import { ThemeProvider } from 'styled-components'; -import { mount } from 'enzyme'; -import euiLightVars from '@elastic/eui/dist/eui_theme_light.json'; - -import { ExceptionItem } from './'; -import { getExceptionItemMock } from '../mocks'; - -describe('ExceptionItem', () => { - it('it renders ExceptionDetails and ExceptionEntries', () => { - const exceptionItem = getExceptionItemMock(); - - const wrapper = mount( - ({ eui: euiLightVars, darkMode: false })}> - - - ); - - expect(wrapper.find('ExceptionDetails')).toHaveLength(1); - expect(wrapper.find('ExceptionEntries')).toHaveLength(1); - }); - - it('it invokes "handleEdit" when edit button clicked', () => { - const mockHandleEdit = jest.fn(); - const exceptionItem = getExceptionItemMock(); - - const wrapper = mount( - ({ eui: euiLightVars, darkMode: false })}> - - - ); - - const editBtn = wrapper.find('[data-test-subj="exceptionsViewerEditBtn"] button').at(0); - editBtn.simulate('click'); - - expect(mockHandleEdit).toHaveBeenCalledTimes(1); - }); - - it('it invokes "handleDelete" when delete button clicked', () => { - const mockHandleDelete = jest.fn(); - const exceptionItem = getExceptionItemMock(); - - const wrapper = mount( - ({ eui: euiLightVars, darkMode: false })}> - - - ); - - const editBtn = wrapper.find('[data-test-subj="exceptionsViewerDeleteBtn"] button').at(0); - editBtn.simulate('click'); - - expect(mockHandleDelete).toHaveBeenCalledTimes(1); - }); - - it('it renders comment accordion closed to begin with', () => { - const mockHandleDelete = jest.fn(); - const exceptionItem = getExceptionItemMock(); - - const wrapper = mount( - ({ eui: euiLightVars, darkMode: false })}> - - - ); - - expect(wrapper.find('.euiAccordion-isOpen')).toHaveLength(0); - }); - - it('it renders comment accordion open when showComments is true', () => { - const mockHandleDelete = jest.fn(); - const exceptionItem = getExceptionItemMock(); - - const wrapper = mount( - ({ eui: euiLightVars, darkMode: false })}> - - - ); - - const commentsBtn = wrapper - .find('.euiButtonEmpty[data-test-subj="exceptionsViewerItemCommentsBtn"]') - .at(0); - commentsBtn.simulate('click'); - - expect(wrapper.find('.euiAccordion-isOpen')).toHaveLength(1); - }); -}); diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/index.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/index.tsx index f4cdce62f56b3..ac75bc3a8c2f4 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/index.tsx +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/index.tsx @@ -4,96 +4,377 @@ * you may not use this file except in compliance with the Elastic License. */ +import React, { useCallback, useState, useMemo, useEffect, useReducer } from 'react'; import { - EuiPanel, - EuiFlexGroup, - EuiCommentProps, - EuiCommentList, - EuiAccordion, - EuiFlexItem, + EuiEmptyPrompt, + EuiText, + EuiLink, + EuiLoadingContent, + EuiOverlayMask, + EuiModal, + EuiModalBody, + EuiCodeBlock, } from '@elastic/eui'; -import React, { useEffect, useState, useMemo, useCallback } from 'react'; +import { FormattedMessage } from 'react-intl'; import styled from 'styled-components'; +import uuid from 'uuid'; -import { ExceptionDetails } from './exception_details'; -import { ExceptionEntries } from './exception_entries'; -import { getFormattedEntries, getFormattedComments } from '../helpers'; -import { FormattedEntry, ExceptionListItemSchema } from '../types'; +import * as i18n from '../translations'; +import { useStateToaster } from '../../toasters'; +import { useKibana } from '../../../../common/lib/kibana'; +import { ExceptionsViewerHeader } from './exceptions_viewer_header'; +import { ToggleId, RuleExceptionList, ExceptionListItemSchema, ApiProps } from '../types'; +import { allExceptionItemsReducer, State } from './reducer'; +import { + useExceptionList, + deleteExceptionListItemById, + NamespaceType, +} from '../../../../../public/lists_plugin_deps'; +import { ExceptionItem } from './exception_item'; +import { AndOrBadge } from '../../and_or_badge'; -const MyFlexItem = styled(EuiFlexItem)` - &.comments--show { - padding: ${({ theme }) => theme.eui.euiSize}; - border-top: ${({ theme }) => `${theme.eui.euiBorderThin}`} +const StyledText = styled(EuiText)` + font-style: italic; + margin: 16px 0; +`; +const OrBadgeWrapper = styled.div` + .euiBadge { + margin: 16px 0; + } `; -interface ExceptionItemProps { - exceptionItem: ExceptionListItemSchema; - commentsAccordionId: string; - handleDelete: ({ id }: { id: string }) => void; - handleEdit: (item: ExceptionListItemSchema) => void; +const initialState: State = { + filterOptions: { filter: '', tags: [] }, + availableListTypes: [], + selectedListType: ToggleId.DETECTION_ENGINE, + selectedListId: null, + selectedListNamespaceType: null, + endpointList: { id: null, type: null, namespaceType: null }, + detectionsList: { id: null, type: null, namespaceType: null }, + exceptionToEdit: null, + exceptionToDelete: null, + isModalOpen: false, +}; + +enum ModalAction { + CREATE = 'CREATE', + EDIT = 'EDIT', } -const ExceptionItemComponent = ({ - exceptionItem, - commentsAccordionId, - handleDelete, - handleEdit, -}: ExceptionItemProps): JSX.Element => { - const [entryItems, setEntryItems] = useState([]); - const [showComments, setShowComments] = useState(false); +interface ExceptionsViewerProps { + exceptionLists: RuleExceptionList[]; + onAssociateList: (listId: string) => void; +} + +const ExceptionsViewerComponent = ({ + exceptionLists, + onAssociateList, +}: ExceptionsViewerProps): JSX.Element => { + const [initLoading, setInitLoading] = useState(true); + const [ + { + availableListTypes, + selectedListType, + selectedListId, + selectedListNamespaceType, + filterOptions, + isModalOpen, + }, + dispatch, + ] = useReducer(allExceptionItemsReducer(), initialState); + + // for fetching lists + const { http } = useKibana().services; + const [, dispatchToaster] = useStateToaster(); + const onDispatchToaster = useCallback( + ({ title, color, iconType }) => (): void => { + dispatchToaster({ + type: 'addToaster', + toast: { + id: uuid.v4(), + title, + color, + iconType, + }, + }); + }, + [dispatchToaster] + ); + const [loadingList, exceptionList, exceptionItems, fetchList] = useExceptionList({ + http, + id: selectedListId, + namespaceType: selectedListNamespaceType, + filterOptions, + onError: onDispatchToaster({ + color: 'danger', + title: i18n.FETCH_LIST_ERROR, + iconType: 'alert', + }), + }); + + const setSelectedListType = useCallback( + (type: ToggleId): void => { + dispatch({ + type: 'updateSelectedListType', + listType: type, + }); + }, + [dispatch] + ); + + const setIsModalOpen = useCallback( + (isOpen: boolean): void => { + dispatch({ + type: 'updateModalOpen', + isOpen, + }); + }, + [dispatch] + ); + + const setExceptionToDelete = useCallback( + (id: string | null): void => { + dispatch({ + type: 'updateExceptionToDelete', + id, + }); + }, + [dispatch] + ); + + const onFetchList = useCallback( + ({ id, namespaceType }: ApiProps): void => { + if (fetchList != null && id != null && namespaceType != null) { + fetchList({ + listId: id, + listNamespaceType: namespaceType, + }); + } + }, + [fetchList] + ); + + const onFiltersChange = useCallback( + (filter: { filter: string; tags: string[] }): void => { + dispatch({ + type: 'updateFilterOptions', + filterOptions: filter, + }); + }, + [dispatch] + ); + + const onAddExceptionItem = useCallback((): void => { + setIsModalOpen(true); + }, [setIsModalOpen]); + + const onEditExceptionItem = useCallback( + (exception: ExceptionListItemSchema): void => { + dispatch({ + type: 'updateExceptionToEdit', + exception, + }); + + setIsModalOpen(true); + }, + [setIsModalOpen] + ); + + const onCloseExceptionModal = useCallback( + ({ actionType, listId, listNamespaceType }): void => { + setIsModalOpen(false); + + // TODO: This callback along with fetchList can probably get + // passed to the modal for it to call itself maybe + if (actionType === ModalAction.CREATE && listId != null) { + onAssociateList(listId); + } + + onFetchList({ id: listId, namespaceType: listNamespaceType }); + }, + [setIsModalOpen, onFetchList] + ); + + const onDeleteException = useCallback( + async ({ id, namespaceType }: { id: string; namespaceType: NamespaceType }) => { + try { + const deleteTask = new AbortController(); + setExceptionToDelete(id); + await deleteExceptionListItemById({ http, id, namespaceType, signal: deleteTask.signal }); + setExceptionToDelete(null); + + onFetchList({ id: selectedListId, namespaceType: selectedListNamespaceType }); + } catch (error) { + onDispatchToaster({ + color: 'danger', + title: i18n.DELETE_EXCEPTION_ERROR, + iconType: 'alert', + }); + setExceptionToDelete(null); + } + }, + [ + dispatch, + http, + setExceptionToDelete, + onDispatchToaster, + selectedListNamespaceType, + selectedListId, + ] + ); + + const getListTypes = ({ + detectionsRuleExcList, + endpointRuleExcList, + }: { + detectionsRuleExcList: RuleExceptionList | undefined; + endpointRuleExcList: RuleExceptionList | undefined; + }): ToggleId[] => { + if (detectionsRuleExcList == null) { + setSelectedListType(ToggleId.ENDPOINT); + return [ToggleId.ENDPOINT]; + } else if (endpointRuleExcList == null) { + setSelectedListType(ToggleId.DETECTION_ENGINE); + return [ToggleId.DETECTION_ENGINE]; + } else { + setSelectedListType(ToggleId.DETECTION_ENGINE); + return [ToggleId.DETECTION_ENGINE, ToggleId.ENDPOINT]; + } + }; + + // Logic for initial render + useEffect((): void => { + if (initLoading && (exceptionLists.length === 0 || exceptionList != null)) { + setInitLoading(false); + } + }, [initLoading, exceptionLists, loadingList, exceptionList]); useEffect((): void => { - const formattedEntries = getFormattedEntries(exceptionItem.entries); - setEntryItems(formattedEntries); - }, [exceptionItem.entries]); + if (exceptionLists.length) { + const [endpointRuleExcList] = exceptionLists.filter((t) => t.type === ToggleId.ENDPOINT); + const [detectionsRuleExcList] = exceptionLists.filter( + (t) => t.type === ToggleId.DETECTION_ENGINE + ); + const listTypes = getListTypes({ endpointRuleExcList, detectionsRuleExcList }); - const onDelete = useCallback((): void => { - handleDelete({ id: exceptionItem.id }); - }, [handleDelete, exceptionItem]); + dispatch({ + type: 'updateAvailableListTypes', + listTypes, + endpointList: endpointRuleExcList ?? null, + detectionsList: detectionsRuleExcList ?? null, + }); - const onEdit = useCallback((): void => { - handleEdit(exceptionItem); - }, [handleEdit, exceptionItem]); + setInitLoading(false); + } + }, [ + exceptionLists + .map((t) => t.id) + .sort() + .join(), + dispatch, + ]); - const onCommentsClick = useCallback((): void => { - setShowComments(!showComments); - }, [setShowComments, showComments]); + const exceptionsSubtext = useMemo((): JSX.Element => { + if (selectedListType === ToggleId.ENDPOINT) { + return ( + + + + ), + }} + /> + ); + } else { + return ( + + + + ), + }} + /> + ); + } + }, [selectedListType]); - const formattedComments = useMemo((): EuiCommentProps[] => { - return getFormattedComments(exceptionItem.comments); - }, [exceptionItem]); + const exceptions = useMemo(() => { + if (exceptionItems != null) { + return exceptionItems.items; + } else { + return []; + } + }, [exceptionItems]); return ( - - - - - + {isModalOpen && ( + + + + + {JSON.stringify(exceptionList)} + + + + + )} + + + {exceptionsSubtext} + + {initLoading && ( + + )} + + {!initLoading && !exceptions.length && ( + {i18n.EXCEPTION_EMPTY_PROMPT_TITLE}} + body={

{i18n.EXCEPTION_EMPTY_PROMPT_BODY}

} + /> + )} + + {!initLoading && + exceptions.length && + exceptions.map((exception, index) => ( + <> + {index !== 0 && } + - -
-
- - - - - -
-
+ + ))} + ); }; -ExceptionItemComponent.displayName = 'ExceptionItemComponent'; +ExceptionsViewerComponent.displayName = 'ExceptionsViewerComponent'; -export const ExceptionItem = React.memo(ExceptionItemComponent); +export const ExceptionsViewer = React.memo(ExceptionsViewerComponent); -ExceptionItem.displayName = 'ExceptionItem'; +ExceptionsViewer.displayName = 'ExceptionsViewer'; diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/reducer.ts b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/reducer.ts new file mode 100644 index 0000000000000..899a403ff0785 --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/reducer.ts @@ -0,0 +1,103 @@ +/* + * 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 { FilterOptions, RuleExceptionList, ToggleId, ExceptionListItemSchema } from '../types'; +import { NamespaceType } from '../../../../../public/lists_plugin_deps'; + +export interface State { + filterOptions: FilterOptions; + availableListTypes: ToggleId[]; + selectedListType: ToggleId; + selectedListId: string | null; + selectedListNamespaceType: NamespaceType | null; + endpointList: RuleExceptionList; + detectionsList: RuleExceptionList; + exceptionToEdit: ExceptionListItemSchema | null; + exceptionToDelete: string | null; + isModalOpen: boolean; +} + +export type Action = + | { + type: 'updateAvailableListTypes'; + listTypes: ToggleId[]; + endpointList: RuleExceptionList; + detectionsList: RuleExceptionList; + } + | { type: 'updateSelectedListType'; listType: ToggleId } + | { + type: 'updateFilterOptions'; + filterOptions: Partial; + } + | { type: 'updateModalOpen'; isOpen: boolean } + | { type: 'updateExceptionToEdit'; exception: ExceptionListItemSchema } + | { type: 'updateExceptionToDelete'; id: string | null }; + +export const allExceptionItemsReducer = () => (state: State, action: Action): State => { + switch (action.type) { + case 'updateAvailableListTypes': { + return { + ...state, + availableListTypes: action.listTypes, + endpointList: action.endpointList, + detectionsList: action.detectionsList, + selectedListId: + state.selectedListType === ToggleId.ENDPOINT + ? action.endpointList.id + : action.detectionsList.id, + selectedListNamespaceType: + state.selectedListType === ToggleId.ENDPOINT + ? action.endpointList.namespaceType + : action.detectionsList.namespaceType, + }; + } + case 'updateSelectedListType': { + if (action.listType === ToggleId.ENDPOINT) { + return { + ...state, + selectedListType: action.listType, + selectedListId: state.endpointList.id, + selectedListNamespaceType: state.endpointList.namespaceType, + }; + } else { + return { + ...state, + selectedListType: action.listType, + selectedListId: state.detectionsList.id, + selectedListNamespaceType: state.detectionsList.namespaceType, + }; + } + } + case 'updateFilterOptions': { + return { + ...state, + filterOptions: { + ...state.filterOptions, + ...action.filterOptions, + }, + }; + } + case 'updateExceptionToDelete': { + return { + ...state, + exceptionToDelete: action.id, + }; + } + case 'updateExceptionToEdit': { + return { + ...state, + exceptionToEdit: action.exception, + }; + } + case 'updateModalOpen': { + return { + ...state, + isModalOpen: action.isOpen, + }; + } + default: + return state; + } +}; diff --git a/x-pack/plugins/security_solution/public/lists_plugin_deps.ts b/x-pack/plugins/security_solution/public/lists_plugin_deps.ts index 350b53ef52f4e..3acdf42d27fd0 100644 --- a/x-pack/plugins/security_solution/public/lists_plugin_deps.ts +++ b/x-pack/plugins/security_solution/public/lists_plugin_deps.ts @@ -8,7 +8,8 @@ export { useExceptionList, usePersistExceptionItem, usePersistExceptionList, + deleteExceptionListItemById, mockNewExceptionItem, mockNewExceptionList, } from '../../lists/public'; -export { ExceptionListItemSchema, Entries } from '../../lists/common/schemas'; +export { ExceptionListItemSchema, Entries, NamespaceType } from '../../lists/common/schemas'; From 32f66d26be7c4aca86a8891c4ba1372d810d02bd Mon Sep 17 00:00:00 2001 From: Yara Tercero Date: Thu, 4 Jun 2020 13:11:25 -0400 Subject: [PATCH 20/32] fix merge issue --- .../viewer/exception_details.test.tsx | 226 ------------------ .../exceptions/viewer/exception_details.tsx | 85 ------- .../viewer/exception_entries.test.tsx | 150 ------------ .../exceptions/viewer/exception_entries.tsx | 169 ------------- .../exceptions/viewer/index.test.tsx | 116 --------- 5 files changed, 746 deletions(-) delete mode 100644 x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_details.test.tsx delete mode 100644 x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_details.tsx delete mode 100644 x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_entries.test.tsx delete mode 100644 x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_entries.tsx delete mode 100644 x-pack/plugins/security_solution/public/common/components/exceptions/viewer/index.test.tsx diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_details.test.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_details.test.tsx deleted file mode 100644 index 536d005c57b6e..0000000000000 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_details.test.tsx +++ /dev/null @@ -1,226 +0,0 @@ -/* - * 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 React from 'react'; -import { ThemeProvider } from 'styled-components'; -import { mount } from 'enzyme'; -import euiLightVars from '@elastic/eui/dist/eui_theme_light.json'; -import moment from 'moment-timezone'; - -import { ExceptionDetails } from './exception_details'; -import { getExceptionItemMock } from '../mocks'; - -describe('ExceptionDetails', () => { - beforeEach(() => { - moment.tz.setDefault('UTC'); - }); - - afterEach(() => { - moment.tz.setDefault('Browser'); - }); - - test('it renders no comments button if no comments exist', () => { - const exceptionItem = getExceptionItemMock(); - exceptionItem.comments = []; - - const wrapper = mount( - ({ eui: euiLightVars, darkMode: false })}> - - - ); - - expect(wrapper.find('[data-test-subj="exceptionsViewerItemCommentsBtn"]')).toHaveLength(0); - }); - - test('it renders comments button if comments exist', () => { - const exceptionItem = getExceptionItemMock(); - - const wrapper = mount( - ({ eui: euiLightVars, darkMode: false })}> - - - ); - - expect( - wrapper.find('.euiButtonEmpty[data-test-subj="exceptionsViewerItemCommentsBtn"]') - ).toHaveLength(1); - }); - - test('it renders correct number of comments', () => { - const exceptionItem = getExceptionItemMock(); - - const wrapper = mount( - ({ eui: euiLightVars, darkMode: false })}> - - - ); - - expect(wrapper.find('[data-test-subj="exceptionsViewerItemCommentsBtn"]').at(0).text()).toEqual( - 'Show (1) Comment' - ); - }); - - test('it renders comments plural if more than one', () => { - const exceptionItem = getExceptionItemMock(); - exceptionItem.comments = [ - { - user: 'user_1', - timestamp: '2020-04-23T00:19:13.289Z', - comment: 'Comment goes here', - }, - { - user: 'user_2', - timestamp: '2020-04-23T00:19:13.289Z', - comment: 'Comment goes here', - }, - ]; - const wrapper = mount( - ({ eui: euiLightVars, darkMode: false })}> - - - ); - - expect(wrapper.find('[data-test-subj="exceptionsViewerItemCommentsBtn"]').at(0).text()).toEqual( - 'Show (2) Comments' - ); - }); - - test('it renders comments show text if "showComments" is false', () => { - const exceptionItem = getExceptionItemMock(); - const wrapper = mount( - ({ eui: euiLightVars, darkMode: false })}> - - - ); - - expect(wrapper.find('[data-test-subj="exceptionsViewerItemCommentsBtn"]').at(0).text()).toEqual( - 'Show (1) Comment' - ); - }); - - test('it renders comments hide text if "showComments" is true', () => { - const exceptionItem = getExceptionItemMock(); - const wrapper = mount( - ({ eui: euiLightVars, darkMode: false })}> - - - ); - - expect(wrapper.find('[data-test-subj="exceptionsViewerItemCommentsBtn"]').at(0).text()).toEqual( - 'Hide (1) Comment' - ); - }); - - test('it invokes "onCommentsClick" when comments button clicked', () => { - const mockOnCommentsClick = jest.fn(); - const exceptionItem = getExceptionItemMock(); - const wrapper = mount( - ({ eui: euiLightVars, darkMode: false })}> - - - ); - const commentsBtn = wrapper.find('[data-test-subj="exceptionsViewerItemCommentsBtn"]').at(0); - commentsBtn.simulate('click'); - - expect(mockOnCommentsClick).toHaveBeenCalledTimes(1); - }); - - test('it renders the operating system if one is specified in the exception item', () => { - const exceptionItem = getExceptionItemMock(); - const wrapper = mount( - ({ eui: euiLightVars, darkMode: false })}> - - - ); - - expect(wrapper.find('EuiDescriptionListTitle').at(0).text()).toEqual('OS'); - expect(wrapper.find('EuiDescriptionListDescription').at(0).text()).toEqual('Windows'); - }); - - test('it renders the exception item creator', () => { - const exceptionItem = getExceptionItemMock(); - const wrapper = mount( - ({ eui: euiLightVars, darkMode: false })}> - - - ); - - expect(wrapper.find('EuiDescriptionListTitle').at(1).text()).toEqual('Date created'); - expect(wrapper.find('EuiDescriptionListDescription').at(1).text()).toEqual( - 'April 23rd 2020 @ 00:19:13' - ); - }); - - test('it renders the exception item creation timestamp', () => { - const exceptionItem = getExceptionItemMock(); - const wrapper = mount( - ({ eui: euiLightVars, darkMode: false })}> - - - ); - - expect(wrapper.find('EuiDescriptionListTitle').at(2).text()).toEqual('Created by'); - expect(wrapper.find('EuiDescriptionListDescription').at(2).text()).toEqual('user_name'); - }); - - test('it renders the description if one is included on the exception item', () => { - const exceptionItem = getExceptionItemMock(); - const wrapper = mount( - ({ eui: euiLightVars, darkMode: false })}> - - - ); - - expect(wrapper.find('EuiDescriptionListTitle').at(3).text()).toEqual('Comment'); - expect(wrapper.find('EuiDescriptionListDescription').at(3).text()).toEqual( - 'This is a description' - ); - }); -}); diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_details.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_details.tsx deleted file mode 100644 index 8745e80a21548..0000000000000 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_details.tsx +++ /dev/null @@ -1,85 +0,0 @@ -/* - * 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 { EuiFlexItem, EuiFlexGroup, EuiDescriptionList, EuiButtonEmpty } from '@elastic/eui'; -import React, { useMemo } from 'react'; -import styled, { css } from 'styled-components'; -import { transparentize } from 'polished'; - -import { ExceptionListItemSchema } from '../types'; -import { getDescriptionListContent } from '../helpers'; -import * as i18n from '../translations'; - -const StyledExceptionDetails = styled(EuiFlexItem)` - ${({ theme }) => css` - background-color: ${transparentize(0.95, theme.eui.euiColorPrimary)}; - padding: ${theme.eui.euiSize}; - - .euiDescriptionList__title.listTitle--width { - width: 40%; - } - - .euiDescriptionList__description.listDescription--width { - width: 60%; - } - `} -`; - -const ExceptionDetailsComponent = ({ - showComments, - onCommentsClick, - exceptionItem, -}: { - showComments: boolean; - exceptionItem: ExceptionListItemSchema; - onCommentsClick: () => void; -}): JSX.Element => { - const descriptionList = useMemo(() => getDescriptionListContent(exceptionItem), [exceptionItem]); - - const commentsSection = useMemo((): JSX.Element => { - const { comments } = exceptionItem; - if (comments.length > 0) { - return ( - - {!showComments - ? i18n.COMMENTS_SHOW(comments.length) - : i18n.COMMENTS_HIDE(comments.length)} - - ); - } else { - return <>; - } - }, [showComments, onCommentsClick, exceptionItem]); - - return ( - - - - - - {commentsSection} - - - ); -}; - -ExceptionDetailsComponent.displayName = 'ExceptionDetailsComponent'; - -export const ExceptionDetails = React.memo(ExceptionDetailsComponent); - -ExceptionDetails.displayName = 'ExceptionDetails'; diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_entries.test.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_entries.test.tsx deleted file mode 100644 index e0c62f51d032a..0000000000000 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_entries.test.tsx +++ /dev/null @@ -1,150 +0,0 @@ -/* - * 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 React from 'react'; -import { ThemeProvider } from 'styled-components'; -import { mount } from 'enzyme'; -import euiLightVars from '@elastic/eui/dist/eui_theme_light.json'; - -import { ExceptionEntries } from './exception_entries'; -import { getFormattedEntryMock } from '../mocks'; -import { getEmptyValue } from '../../empty_value'; - -describe('ExceptionEntries', () => { - test('it does NOT render the and badge if only one exception item entry exists', () => { - const wrapper = mount( - ({ eui: euiLightVars, darkMode: false })}> - - - ); - - expect(wrapper.find('[data-test-subj="exceptionsViewerAndBadge"]')).toHaveLength(0); - }); - - test('it renders the and badge if more than one exception item exists', () => { - const wrapper = mount( - ({ eui: euiLightVars, darkMode: false })}> - - - ); - - expect(wrapper.find('[data-test-subj="exceptionsViewerAndBadge"]')).toHaveLength(1); - }); - - test('it invokes "handlEdit" when edit button clicked', () => { - const mockHandleEdit = jest.fn(); - const wrapper = mount( - ({ eui: euiLightVars, darkMode: false })}> - - - ); - const editBtn = wrapper.find('[data-test-subj="exceptionsViewerEditBtn"] button').at(0); - editBtn.simulate('click'); - - expect(mockHandleEdit).toHaveBeenCalledTimes(1); - }); - - test('it invokes "handleDelete" when delete button clicked', () => { - const mockHandleDelete = jest.fn(); - const wrapper = mount( - ({ eui: euiLightVars, darkMode: false })}> - - - ); - const deleteBtn = wrapper.find('[data-test-subj="exceptionsViewerDeleteBtn"] button').at(0); - deleteBtn.simulate('click'); - - expect(mockHandleDelete).toHaveBeenCalledTimes(1); - }); - - test('it renders nested entry', () => { - const parentEntry = getFormattedEntryMock(); - parentEntry.operator = null; - parentEntry.value = null; - - const wrapper = mount( - ({ eui: euiLightVars, darkMode: false })}> - - - ); - - const parentField = wrapper - .find('[data-test-subj="exceptionFieldNameCell"] .euiTableCellContent') - .at(0); - const parentOperator = wrapper - .find('[data-test-subj="exceptionFieldOperatorCell"] .euiTableCellContent') - .at(0); - const parentValue = wrapper - .find('[data-test-subj="exceptionFieldValueCell"] .euiTableCellContent') - .at(0); - - const nestedField = wrapper - .find('[data-test-subj="exceptionFieldNameCell"] .euiTableCellContent') - .at(1); - const nestedOperator = wrapper - .find('[data-test-subj="exceptionFieldOperatorCell"] .euiTableCellContent') - .at(1); - const nestedValue = wrapper - .find('[data-test-subj="exceptionFieldValueCell"] .euiTableCellContent') - .at(1); - - expect(parentField.text()).toEqual('host.name'); - expect(parentOperator.text()).toEqual(getEmptyValue()); - expect(parentValue.text()).toEqual(getEmptyValue()); - - expect(nestedField.exists('.euiToolTipAnchor')).toBeTruthy(); - expect(nestedField.text()).toEqual('host.name'); - expect(nestedOperator.text()).toEqual('is'); - expect(nestedValue.text()).toEqual('some name'); - }); - - test('it renders non-nested entries', () => { - const wrapper = mount( - ({ eui: euiLightVars, darkMode: false })}> - - - ); - - const field = wrapper - .find('[data-test-subj="exceptionFieldNameCell"] .euiTableCellContent') - .at(0); - const operator = wrapper - .find('[data-test-subj="exceptionFieldOperatorCell"] .euiTableCellContent') - .at(0); - const value = wrapper - .find('[data-test-subj="exceptionFieldValueCell"] .euiTableCellContent') - .at(0); - - expect(field.exists('.euiToolTipAnchor')).toBeFalsy(); - expect(field.text()).toEqual('host.name'); - expect(operator.text()).toEqual('is'); - expect(value.text()).toEqual('some name'); - }); -}); diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_entries.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_entries.tsx deleted file mode 100644 index d0236adc27c6c..0000000000000 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_entries.tsx +++ /dev/null @@ -1,169 +0,0 @@ -/* - * 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 { - EuiBasicTable, - EuiIconTip, - EuiFlexItem, - EuiFlexGroup, - EuiButton, - EuiTableFieldDataColumnType, -} from '@elastic/eui'; -import React, { useMemo } from 'react'; -import styled, { css } from 'styled-components'; -import { transparentize } from 'polished'; - -import { AndOrBadge } from '../../and_or_badge'; -import { getEmptyValue } from '../../empty_value'; -import * as i18n from '../translations'; -import { FormattedEntry } from '../types'; - -const EntriesDetails = styled(EuiFlexItem)` - padding: ${({ theme }) => theme.eui.euiSize}; -`; - -const StyledEditButton = styled(EuiButton)` - ${({ theme }) => css` - background-color: ${transparentize(0.9, theme.eui.euiColorPrimary)}; - border: none; - font-weight: ${theme.eui.euiFontWeightSemiBold}; - `} -`; - -const StyledRemoveButton = styled(EuiButton)` - ${({ theme }) => css` - background-color: ${transparentize(0.9, theme.eui.euiColorDanger)}; - border: none; - font-weight: ${theme.eui.euiFontWeightSemiBold}; - `} -`; - -const AndOrBadgeContainer = styled(EuiFlexItem)` - padding-top: ${({ theme }) => theme.eui.euiSizeXL}; -`; - -interface ExceptionEntriesComponentProps { - entries: FormattedEntry[]; - handleDelete: () => void; - handleEdit: () => void; -} - -const ExceptionEntriesComponent = ({ - entries, - handleDelete, - handleEdit, -}: ExceptionEntriesComponentProps): JSX.Element => { - const columns = useMemo( - (): Array> => [ - { - field: 'fieldName', - name: 'Field', - sortable: false, - truncateText: true, - 'data-test-subj': 'exceptionFieldNameCell', - width: '30%', - render: (value: string | null, data: FormattedEntry) => { - if (value != null && data.isNested) { - return ( - <> - - {value} - - ); - } else { - return value ?? getEmptyValue(); - } - }, - }, - { - field: 'operator', - name: 'Operator', - sortable: false, - truncateText: true, - 'data-test-subj': 'exceptionFieldOperatorCell', - width: '20%', - render: (value: string | null) => value ?? getEmptyValue(), - }, - { - field: 'value', - name: 'Value', - sortable: false, - truncateText: true, - 'data-test-subj': 'exceptionFieldValueCell', - width: '60%', - render: (values: string | string[] | null) => { - if (Array.isArray(values)) { - return ( - - {values.map((value) => { - return {value}; - })} - - ); - } else { - return values ?? getEmptyValue(); - } - }, - }, - ], - [entries] - ); - - return ( - - - - - {entries.length > 1 && ( - - - - )} - - - - - - - - - - {i18n.EDIT} - - - - - {i18n.REMOVE} - - - - - - - ); -}; - -ExceptionEntriesComponent.displayName = 'ExceptionEntriesComponent'; - -export const ExceptionEntries = React.memo(ExceptionEntriesComponent); - -ExceptionEntries.displayName = 'ExceptionEntries'; diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/index.test.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/index.test.tsx deleted file mode 100644 index 7d3b7195def80..0000000000000 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/index.test.tsx +++ /dev/null @@ -1,116 +0,0 @@ -/* - * 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 React from 'react'; -import { ThemeProvider } from 'styled-components'; -import { mount } from 'enzyme'; -import euiLightVars from '@elastic/eui/dist/eui_theme_light.json'; - -import { ExceptionItem } from './'; -import { getExceptionItemMock } from '../mocks'; - -describe('ExceptionItem', () => { - it('it renders ExceptionDetails and ExceptionEntries', () => { - const exceptionItem = getExceptionItemMock(); - - const wrapper = mount( - ({ eui: euiLightVars, darkMode: false })}> - - - ); - - expect(wrapper.find('ExceptionDetails')).toHaveLength(1); - expect(wrapper.find('ExceptionEntries')).toHaveLength(1); - }); - - it('it invokes "handleEdit" when edit button clicked', () => { - const mockHandleEdit = jest.fn(); - const exceptionItem = getExceptionItemMock(); - - const wrapper = mount( - ({ eui: euiLightVars, darkMode: false })}> - - - ); - - const editBtn = wrapper.find('[data-test-subj="exceptionsViewerEditBtn"] button').at(0); - editBtn.simulate('click'); - - expect(mockHandleEdit).toHaveBeenCalledTimes(1); - }); - - it('it invokes "handleDelete" when delete button clicked', () => { - const mockHandleDelete = jest.fn(); - const exceptionItem = getExceptionItemMock(); - - const wrapper = mount( - ({ eui: euiLightVars, darkMode: false })}> - - - ); - - const editBtn = wrapper.find('[data-test-subj="exceptionsViewerDeleteBtn"] button').at(0); - editBtn.simulate('click'); - - expect(mockHandleDelete).toHaveBeenCalledTimes(1); - }); - - it('it renders comment accordion closed to begin with', () => { - const mockHandleDelete = jest.fn(); - const exceptionItem = getExceptionItemMock(); - - const wrapper = mount( - ({ eui: euiLightVars, darkMode: false })}> - - - ); - - expect(wrapper.find('.euiAccordion-isOpen')).toHaveLength(0); - }); - - it('it renders comment accordion open when showComments is true', () => { - const mockHandleDelete = jest.fn(); - const exceptionItem = getExceptionItemMock(); - - const wrapper = mount( - ({ eui: euiLightVars, darkMode: false })}> - - - ); - - const commentsBtn = wrapper - .find('.euiButtonEmpty[data-test-subj="exceptionsViewerItemCommentsBtn"]') - .at(0); - commentsBtn.simulate('click'); - - expect(wrapper.find('.euiAccordion-isOpen')).toHaveLength(1); - }); -}); From 8de74693c27ccde058d0df0151e5e00615b0702b Mon Sep 17 00:00:00 2001 From: Yara Tercero Date: Thu, 4 Jun 2020 14:37:22 -0400 Subject: [PATCH 21/32] some cleanup --- .../detection_engine/rules/details/index.tsx | 13 ++++++++++++ .../rules/details/translations.ts | 7 +++++++ .../exception_item/exception_details.tsx | 9 ++++---- .../viewer/exception_item/index.tsx | 8 ++++--- .../components/exceptions/viewer/index.tsx | 21 ++++++++++++------- 5 files changed, 43 insertions(+), 15 deletions(-) diff --git a/x-pack/plugins/security_solution/public/alerts/pages/detection_engine/rules/details/index.tsx b/x-pack/plugins/security_solution/public/alerts/pages/detection_engine/rules/details/index.tsx index ebd6ed118f937..a38a56555c7a9 100644 --- a/x-pack/plugins/security_solution/public/alerts/pages/detection_engine/rules/details/index.tsx +++ b/x-pack/plugins/security_solution/public/alerts/pages/detection_engine/rules/details/index.tsx @@ -70,10 +70,12 @@ import { FailureHistory } from './failure_history'; import { RuleStatus } from '../../../../components/rules//rule_status'; import { useMlCapabilities } from '../../../../../common/components/ml_popover/hooks/use_ml_capabilities'; import { hasMlAdminPermissions } from '../../../../../../common/machine_learning/has_ml_admin_permissions'; +import { ExceptionsViewer } from '../../../../../common/components/exceptions/viewer'; enum RuleDetailTabs { alerts = 'alerts', failures = 'failures', + exceptions = 'exceptions', } const ruleDetailTabs = [ @@ -82,6 +84,11 @@ const ruleDetailTabs = [ name: detectionI18n.ALERT, disabled: false, }, + { + id: RuleDetailTabs.exceptions, + name: i18n.EXCEPTIONS_TAB, + disabled: false, + }, { id: RuleDetailTabs.failures, name: i18n.FAILURE_HISTORY_TAB, @@ -385,6 +392,12 @@ export const RuleDetailsPageComponent: FC = ({ )} )} + {ruleDetailTab === RuleDetailTabs.exceptions && ( + + )} {ruleDetailTab === RuleDetailTabs.failures && } diff --git a/x-pack/plugins/security_solution/public/alerts/pages/detection_engine/rules/details/translations.ts b/x-pack/plugins/security_solution/public/alerts/pages/detection_engine/rules/details/translations.ts index 9cf510f4a9b5d..94dfdc3e9daa0 100644 --- a/x-pack/plugins/security_solution/public/alerts/pages/detection_engine/rules/details/translations.ts +++ b/x-pack/plugins/security_solution/public/alerts/pages/detection_engine/rules/details/translations.ts @@ -89,3 +89,10 @@ export const TYPE_FAILED = i18n.translate( defaultMessage: 'Failed', } ); + +export const EXCEPTIONS_TAB = i18n.translate( + 'xpack.securitySolution.detectionEngine.ruleDetails.exceptionsTab', + { + defaultMessage: 'Exceptions', + } +); diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/exception_details.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/exception_details.tsx index 596ef996a4571..6f418808b239a 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/exception_details.tsx +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/exception_details.tsx @@ -40,8 +40,9 @@ const ExceptionDetailsComponent = ({ const descriptionList = useMemo(() => getDescriptionListContent(exceptionItem), [exceptionItem]); const commentsSection = useMemo((): JSX.Element => { - const { comments } = exceptionItem; - if (comments.length > 0) { + // TODO: return back to exceptionItem.comments once updated + const { comment } = exceptionItem; + if (comment.length > 0) { return ( - {!showComments - ? i18n.COMMENTS_SHOW(comments.length) - : i18n.COMMENTS_HIDE(comments.length)} + {!showComments ? i18n.COMMENTS_SHOW(comment.length) : i18n.COMMENTS_HIDE(comment.length)} ); } else { diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/index.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/index.tsx index 16dd67c9071fd..98c6f62dd8a3d 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/index.tsx +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/index.tsx @@ -19,6 +19,7 @@ import { ExceptionDetails } from './exception_details'; import { ExceptionEntries } from './exception_entries'; import { getFormattedEntries, getFormattedComments } from '../../helpers'; import { FormattedEntry, ExceptionListItemSchema } from '../../types'; +import { NamespaceType } from '../../../../../../public/lists_plugin_deps'; const MyFlexItem = styled(EuiFlexItem)` &.comments--show { @@ -30,7 +31,7 @@ const MyFlexItem = styled(EuiFlexItem)` interface ExceptionItemProps { exceptionItem: ExceptionListItemSchema; commentsAccordionId: string; - handleDelete: ({ id }: { id: string }) => void; + handleDelete: ({ id, namespaceType }: { id: string; namespaceType: NamespaceType }) => void; handleEdit: (item: ExceptionListItemSchema) => void; } @@ -49,7 +50,7 @@ const ExceptionItemComponent = ({ }, [exceptionItem.entries]); const onDelete = useCallback((): void => { - handleDelete({ id: exceptionItem.id }); + handleDelete({ id: exceptionItem.id, namespaceType: exceptionItem.namespaceType }); }, [handleDelete, exceptionItem]); const onEdit = useCallback((): void => { @@ -61,7 +62,8 @@ const ExceptionItemComponent = ({ }, [setShowComments, showComments]); const formattedComments = useMemo((): EuiCommentProps[] => { - return getFormattedComments(exceptionItem.comments); + // TODO: return back to exceptionItem.comments once updated + return getFormattedComments(exceptionItem.comment); }, [exceptionItem]); return ( diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/index.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/index.tsx index ac75bc3a8c2f4..21cea588e907a 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/index.tsx +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/index.tsx @@ -64,12 +64,14 @@ enum ModalAction { interface ExceptionsViewerProps { exceptionLists: RuleExceptionList[]; - onAssociateList: (listId: string) => void; + commentsAccordionId: string; + onAssociateList?: (listId: string) => void; } const ExceptionsViewerComponent = ({ exceptionLists, onAssociateList, + commentsAccordionId, }: ExceptionsViewerProps): JSX.Element => { const [initLoading, setInitLoading] = useState(true); const [ @@ -187,13 +189,13 @@ const ExceptionsViewerComponent = ({ // TODO: This callback along with fetchList can probably get // passed to the modal for it to call itself maybe - if (actionType === ModalAction.CREATE && listId != null) { + if (actionType === ModalAction.CREATE && listId != null && onAssociateList != null) { onAssociateList(listId); } onFetchList({ id: listId, namespaceType: listNamespaceType }); }, - [setIsModalOpen, onFetchList] + [setIsModalOpen, onFetchList, onAssociateList] ); const onDeleteException = useCallback( @@ -321,6 +323,10 @@ const ExceptionsViewerComponent = ({ } }, [exceptionItems]); + const showEmpty = useMemo((): boolean => { + return !initLoading && exceptions.length === 0; + }, [initLoading, exceptions.length]); + return ( <> {isModalOpen && ( @@ -349,7 +355,7 @@ const ExceptionsViewerComponent = ({ )} - {!initLoading && !exceptions.length && ( + {showEmpty && ( {i18n.EXCEPTION_EMPTY_PROMPT_TITLE}} @@ -358,16 +364,17 @@ const ExceptionsViewerComponent = ({ )} {!initLoading && - exceptions.length && + exceptions.length > 0 && exceptions.map((exception, index) => ( - <> +
{index !== 0 && } - +
))} ); From c33356788eb422d1786e9e29a9343fb5dadf9418 Mon Sep 17 00:00:00 2001 From: Yara Tercero Date: Fri, 5 Jun 2020 09:19:11 -0400 Subject: [PATCH 22/32] modified list scripts for help with testing --- .../new/exception_list_detection.json | 9 +++++++ .../new/exception_list_item_auto_id.json | 1 + ...exception_list_item_detection_auto_id.json | 26 +++++++++++++++++++ 3 files changed, 36 insertions(+) create mode 100644 x-pack/plugins/lists/server/scripts/exception_lists/new/exception_list_detection.json create mode 100644 x-pack/plugins/lists/server/scripts/exception_lists/new/exception_list_item_detection_auto_id.json diff --git a/x-pack/plugins/lists/server/scripts/exception_lists/new/exception_list_detection.json b/x-pack/plugins/lists/server/scripts/exception_lists/new/exception_list_detection.json new file mode 100644 index 0000000000000..306195f4226e3 --- /dev/null +++ b/x-pack/plugins/lists/server/scripts/exception_lists/new/exception_list_detection.json @@ -0,0 +1,9 @@ +{ + "list_id": "detection_list", + "_tags": ["detection"], + "tags": ["detection", "sample_tag"], + "type": "detection", + "description": "This is a sample detection type exception list", + "name": "Sample Detection Exception List", + "namespace_type": "single" +} diff --git a/x-pack/plugins/lists/server/scripts/exception_lists/new/exception_list_item_auto_id.json b/x-pack/plugins/lists/server/scripts/exception_lists/new/exception_list_item_auto_id.json index d68a26eb8ffe2..c89c7a8f080cf 100644 --- a/x-pack/plugins/lists/server/scripts/exception_lists/new/exception_list_item_auto_id.json +++ b/x-pack/plugins/lists/server/scripts/exception_lists/new/exception_list_item_auto_id.json @@ -5,6 +5,7 @@ "type": "simple", "description": "This is a sample endpoint type exception that has no item_id so it creates a new id each time", "name": "Sample Endpoint Exception List", + "comment": [], "entries": [ { "field": "actingProcess.file.signer", diff --git a/x-pack/plugins/lists/server/scripts/exception_lists/new/exception_list_item_detection_auto_id.json b/x-pack/plugins/lists/server/scripts/exception_lists/new/exception_list_item_detection_auto_id.json new file mode 100644 index 0000000000000..3fe4458a73769 --- /dev/null +++ b/x-pack/plugins/lists/server/scripts/exception_lists/new/exception_list_item_detection_auto_id.json @@ -0,0 +1,26 @@ +{ + "list_id": "detection_list", + "_tags": ["detection"], + "tags": ["test_tag", "detection", "no_more_bad_guys"], + "type": "simple", + "description": "This is a sample detection type exception that has no item_id so it creates a new id each time", + "name": "Sample Detection Exception List Item", + "comment": [], + "entries": [ + { + "field": "host.name", + "operator": "included", + "match": "sampleHostName" + }, + { + "field": "event.category", + "operator": "included", + "match_any": ["process", "malware"] + }, + { + "field": "event.action", + "operator": "included", + "match": "user-password-change" + } + ] +} From 8a51155295c00fd545e30c9c48282ede9d74470f Mon Sep 17 00:00:00 2001 From: Yara Tercero Date: Mon, 8 Jun 2020 15:32:53 -0400 Subject: [PATCH 23/32] added exceptions hook for general api usage, updated exception item --- .../lists/public/exceptions/hooks/use_api.tsx | 111 +++ .../__examples__/exception_item.stories.tsx | 118 +++ .../exceptions_search.stories.tsx | 73 ++ .../exceptions_viewer_header.test.tsx.snap | 688 ++++++++++++++++++ .../exception_item/exception_details.test.tsx | 4 +- .../exception_item/exception_entries.tsx | 4 + .../viewer/exception_item/index.test.tsx | 5 + .../viewer/exception_item/index.tsx | 21 +- .../viewer/exceptions_pagination.tsx | 109 +++ 9 files changed, 1126 insertions(+), 7 deletions(-) create mode 100644 x-pack/plugins/lists/public/exceptions/hooks/use_api.tsx create mode 100644 x-pack/plugins/security_solution/public/common/components/exceptions/__examples__/exception_item.stories.tsx create mode 100644 x-pack/plugins/security_solution/public/common/components/exceptions/__examples__/exceptions_search.stories.tsx create mode 100644 x-pack/plugins/security_solution/public/common/components/exceptions/viewer/__snapshots__/exceptions_viewer_header.test.tsx.snap create mode 100644 x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exceptions_pagination.tsx diff --git a/x-pack/plugins/lists/public/exceptions/hooks/use_api.tsx b/x-pack/plugins/lists/public/exceptions/hooks/use_api.tsx new file mode 100644 index 0000000000000..dec00747c9e91 --- /dev/null +++ b/x-pack/plugins/lists/public/exceptions/hooks/use_api.tsx @@ -0,0 +1,111 @@ +/* + * 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 { useMemo } from 'react'; + +import * as Api from '../api'; +import { HttpStart } from '../../../../../../src/core/public'; +import { ExceptionListItemSchema, ExceptionListSchema } from '../../../common/schemas'; +import { ApiCallMemoProps } from '../types'; + +interface ExceptionsApi { + deleteExceptionItem: (arg: ApiCallMemoProps) => Promise; + deleteExceptionList: (arg: ApiCallMemoProps) => Promise; + getExceptionItem: ( + arg: ApiCallMemoProps & { onSuccess: (arg: ExceptionListItemSchema) => void } + ) => Promise; + getExceptionList: ( + arg: ApiCallMemoProps & { onSuccess: (arg: ExceptionListSchema) => void } + ) => Promise; +} + +export const useApi = (http: HttpStart): ExceptionsApi => { + return useMemo( + () => ({ + async deleteExceptionItem({ + id, + namespaceType, + onSuccess, + onError, + }: ApiCallMemoProps): Promise { + const abortCtrl = new AbortController(); + + try { + await Api.deleteExceptionListItemById({ + http, + id, + namespaceType, + signal: abortCtrl.signal, + }); + onSuccess(); + } catch (error) { + onError(error); + } + }, + async deleteExceptionList({ + id, + namespaceType, + onSuccess, + onError, + }: ApiCallMemoProps): Promise { + const abortCtrl = new AbortController(); + + try { + await Api.deleteExceptionListById({ + http, + id, + namespaceType, + signal: abortCtrl.signal, + }); + onSuccess(); + } catch (error) { + onError(error); + } + }, + async getExceptionItem({ + id, + namespaceType, + onSuccess, + onError, + }: ApiCallMemoProps & { onSuccess: (arg: ExceptionListItemSchema) => void }): Promise { + const abortCtrl = new AbortController(); + + try { + const item = await Api.fetchExceptionListItemById({ + http, + id, + namespaceType, + signal: abortCtrl.signal, + }); + onSuccess(item); + } catch (error) { + onError(error); + } + }, + async getExceptionList({ + id, + namespaceType, + onSuccess, + onError, + }: ApiCallMemoProps & { onSuccess: (arg: ExceptionListSchema) => void }): Promise { + const abortCtrl = new AbortController(); + + try { + const list = await Api.fetchExceptionListById({ + http, + id, + namespaceType, + signal: abortCtrl.signal, + }); + onSuccess(list); + } catch (error) { + onError(error); + } + }, + }), + [http] + ); +}; diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/__examples__/exception_item.stories.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/__examples__/exception_item.stories.tsx new file mode 100644 index 0000000000000..af3b20d14e690 --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/__examples__/exception_item.stories.tsx @@ -0,0 +1,118 @@ +/* + * 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 { storiesOf } from '@storybook/react'; +import React from 'react'; +import { ThemeProvider } from 'styled-components'; +import euiLightVars from '@elastic/eui/dist/eui_theme_light.json'; + +import { ExceptionItem } from '../viewer/exception_item'; +import { Operator } from '../types'; +import { getExceptionItemMock } from '../mocks'; + +storiesOf('ExceptionItem', module) + .add('with os', () => { + const payload = getExceptionItemMock(); + payload.description = ''; + payload.comments = []; + payload.entries = [ + { + field: 'actingProcess.file.signer', + type: 'match', + operator: Operator.INCLUSION, + value: 'Elastic, N.V.', + }, + ]; + + return ( + ({ eui: euiLightVars, darkMode: false })}> + {}} + handleEdit={() => {}} + /> + + ); + }) + .add('with description', () => { + const payload = getExceptionItemMock(); + payload._tags = []; + payload.comments = []; + payload.entries = [ + { + field: 'actingProcess.file.signer', + type: 'match', + operator: Operator.INCLUSION, + value: 'Elastic, N.V.', + }, + ]; + + return ( + ({ eui: euiLightVars, darkMode: false })}> + {}} + handleEdit={() => {}} + /> + + ); + }) + .add('with comments', () => { + const payload = getExceptionItemMock(); + payload._tags = []; + payload.description = ''; + payload.entries = [ + { + field: 'actingProcess.file.signer', + type: 'match', + operator: Operator.INCLUSION, + value: 'Elastic, N.V.', + }, + ]; + + return ( + ({ eui: euiLightVars, darkMode: false })}> + {}} + handleEdit={() => {}} + /> + + ); + }) + .add('with nested entries', () => { + const payload = getExceptionItemMock(); + payload._tags = []; + payload.description = ''; + payload.comments = []; + + return ( + ({ eui: euiLightVars, darkMode: false })}> + {}} + handleEdit={() => {}} + /> + + ); + }) + .add('with everything', () => { + const payload = getExceptionItemMock(); + + return ( + ({ eui: euiLightVars, darkMode: false })}> + {}} + handleEdit={() => {}} + /> + + ); + }); diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/__examples__/exceptions_search.stories.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/__examples__/exceptions_search.stories.tsx new file mode 100644 index 0000000000000..e9f93930c5919 --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/__examples__/exceptions_search.stories.tsx @@ -0,0 +1,73 @@ +/* + * 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 { storiesOf } from '@storybook/react'; +import React from 'react'; +import { ThemeProvider } from 'styled-components'; +import euiLightVars from '@elastic/eui/dist/eui_theme_light.json'; + +import { ExceptionsViewerHeader } from '../viewer/exceptions_viewer_header'; + +storiesOf('ExceptionsViewerHeader', module) + .add('loading', () => { + return ( + ({ eui: euiLightVars, darkMode: false })}> + {}} + onAddEndpointExceptionClick={() => {}} + onAddDetectionsExceptionClick={() => {}} + /> + + ); + }) + .add('all lists', () => { + return ( + ({ eui: euiLightVars, darkMode: false })}> + {}} + onAddEndpointExceptionClick={() => {}} + onAddDetectionsExceptionClick={() => {}} + /> + + ); + }) + .add('endpoint only', () => { + return ( + ({ eui: euiLightVars, darkMode: false })}> + {}} + onAddEndpointExceptionClick={() => {}} + onAddDetectionsExceptionClick={() => {}} + /> + + ); + }) + .add('detections only', () => { + return ( + ({ eui: euiLightVars, darkMode: false })}> + {}} + onAddEndpointExceptionClick={() => {}} + onAddDetectionsExceptionClick={() => {}} + /> + + ); + }); diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/__snapshots__/exceptions_viewer_header.test.tsx.snap b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/__snapshots__/exceptions_viewer_header.test.tsx.snap new file mode 100644 index 0000000000000..73ebd4df627b2 --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/__snapshots__/exceptions_viewer_header.test.tsx.snap @@ -0,0 +1,688 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`ExceptionsViewerHeader it renders Detections toggle selected when clicked 1`] = ` + + + +
+ +
+ + +
+
+ + + + +
+ + +
+
+ + +
+ + +
+ +
+ +
+ +
+ + + + + + + + + + +
+
+
+
+ +
+ + Add new exception + + } + closePopover={[Function]} + display="inlineBlock" + hasArrow={true} + isOpen={false} + ownFocus={false} + panelPaddingSize="none" + repositionOnScroll={true} + > + +
+
+ + + +
+
+
+
+
+
+
+
+
+
+
+ + + +`; + +exports[`ExceptionsViewerHeader it renders all disabled if "isInitLoading" is true 1`] = ` + + + +
+ +
+ + +
+
+ + + + +
+ + +
+
+ + +
+ + +
+ +
+ +
+ +
+ + + + + + + + + + +
+
+
+
+ +
+ + Add new exception + + } + closePopover={[Function]} + display="inlineBlock" + hasArrow={true} + isOpen={false} + ownFocus={false} + panelPaddingSize="none" + repositionOnScroll={true} + > + +
+
+ + + +
+
+
+
+
+
+
+
+
+
+
+ + + +`; diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/exception_details.test.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/exception_details.test.tsx index fee9c4165972d..c5d2ffc7ac2bf 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/exception_details.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/exception_details.test.tsx @@ -24,7 +24,7 @@ describe('ExceptionDetails', () => { test('it renders no comments button if no comments exist', () => { const exceptionItem = getExceptionItemMock(); - exceptionItem.comments = []; + exceptionItem.comment = []; const wrapper = mount( ({ eui: euiLightVars, darkMode: false })}> @@ -77,7 +77,7 @@ describe('ExceptionDetails', () => { test('it renders comments plural if more than one', () => { const exceptionItem = getExceptionItemMock(); - exceptionItem.comments = [ + exceptionItem.comment = [ { user: 'user_1', timestamp: '2020-04-23T00:19:13.289Z', diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/exception_entries.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/exception_entries.tsx index 74d0020c6c77e..73774f2f3c8f8 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/exception_entries.tsx +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/exception_entries.tsx @@ -47,12 +47,14 @@ const AndOrBadgeContainer = styled(EuiFlexItem)` interface ExceptionEntriesComponentProps { entries: FormattedEntry[]; + disableDelete: boolean; handleDelete: () => void; handleEdit: () => void; } const ExceptionEntriesComponent = ({ entries, + disableDelete, handleDelete, handleEdit, }: ExceptionEntriesComponentProps): JSX.Element => { @@ -140,6 +142,7 @@ const ExceptionEntriesComponent = ({ size="s" color="primary" onClick={handleEdit} + isDisabled={disableDelete} data-test-subj="exceptionsViewerEditBtn" > {i18n.EDIT} @@ -150,6 +153,7 @@ const ExceptionEntriesComponent = ({ size="s" color="danger" onClick={handleDelete} + isLoading={disableDelete} data-test-subj="exceptionsViewerDeleteBtn" > {i18n.REMOVE} diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/index.test.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/index.test.tsx index ebfa9b7b9998a..784fc4336a5ff 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/index.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/index.test.tsx @@ -19,6 +19,7 @@ describe('ExceptionItem', () => { const wrapper = mount( ({ eui: euiLightVars, darkMode: false })}> { const wrapper = mount( ({ eui: euiLightVars, darkMode: false })}> { const wrapper = mount( ({ eui: euiLightVars, darkMode: false })}> { const wrapper = mount( ({ eui: euiLightVars, darkMode: false })}> { const wrapper = mount( ({ eui: euiLightVars, darkMode: false })}> void; + handleDelete: (arg: ApiProps) => void; handleEdit: (item: ExceptionListItemSchema) => void; } const ExceptionItemComponent = ({ + loadingItemIds, exceptionItem, commentsAccordionId, handleDelete, @@ -50,7 +51,7 @@ const ExceptionItemComponent = ({ }, [exceptionItem.entries]); const onDelete = useCallback((): void => { - handleDelete({ id: exceptionItem.id, namespaceType: exceptionItem.namespaceType }); + handleDelete({ id: exceptionItem.id, namespaceType: exceptionItem.namespace_type }); }, [handleDelete, exceptionItem]); const onEdit = useCallback((): void => { @@ -66,6 +67,11 @@ const ExceptionItemComponent = ({ return getFormattedComments(exceptionItem.comment); }, [exceptionItem]); + const disableDelete = useMemo((): boolean => { + const foundItems = loadingItemIds.filter((t) => t.id === exceptionItem.id); + return foundItems.length > 0; + }, [loadingItemIds, exceptionItem.id]); + return ( @@ -76,7 +82,12 @@ const ExceptionItemComponent = ({ exceptionItem={exceptionItem} onCommentsClick={onCommentsClick} /> - +
diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exceptions_pagination.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exceptions_pagination.tsx new file mode 100644 index 0000000000000..8d72afe3d47de --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exceptions_pagination.tsx @@ -0,0 +1,109 @@ +/* + * 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 React, { useCallback, useState, useMemo } from 'react'; +import { + EuiContextMenuItem, + EuiButtonEmpty, + EuiPagination, + EuiFlexItem, + EuiFlexGroup, + EuiPopover, + EuiContextMenuPanel, +} from '@elastic/eui'; + +import * as i18n from '../translations'; +import { ExceptionsPagination, Pagination } from '../types'; + +interface ExceptionsViewerPaginationProps { + pagination: ExceptionsPagination; + onPaginationChange: (arg: Pagination) => void; +} + +const ExceptionsViewerPaginationComponent = ({ + pagination, + onPaginationChange, +}: ExceptionsViewerPaginationProps): JSX.Element => { + const [isOpen, setIsOpen] = useState(false); + + const closePerPageMenu = useCallback((): void => setIsOpen(false), [setIsOpen]); + + const onPerPageMenuClick = useCallback((): void => setIsOpen((isPopoverOpen) => !isPopoverOpen), [ + setIsOpen, + ]); + + const onPageClick = useCallback( + (pageIndex: number): void => { + onPaginationChange({ + page: pageIndex + 1, + pageSize: pagination.pageSize, + total: pagination.totalItemCount, + }); + }, + [pagination, onPaginationChange] + ); + + const items = useMemo(() => { + return pagination.pageSizeOptions.map((rows) => ( + { + onPaginationChange({ + page: pagination.pageIndex, + pageSize: rows, + total: pagination.totalItemCount, + }); + }} + > + {i18n.NUMBER_OF_ITEMS(rows)} + + )); + }, [pagination, onPaginationChange]); + + const totalPages = useMemo((): number => { + return Math.ceil(pagination.totalItemCount / pagination.pageSize); + }, [pagination]); + + return ( + + + + {i18n.ITEMS_PER_PAGE(pagination.pageSize)} + + } + isOpen={isOpen} + closePopover={closePerPageMenu} + panelPaddingSize="none" + > + + + + + + + + + ); +}; + +ExceptionsViewerPaginationComponent.displayName = 'ExceptionsViewerPaginationComponent'; + +export const ExceptionsViewerPagination = React.memo(ExceptionsViewerPaginationComponent); + +ExceptionsViewerPagination.displayName = 'ExceptionsViewerPagination'; From 9196387b58ad20cfd04ed01406342ff711f736a2 Mon Sep 17 00:00:00 2001 From: Yara Tercero Date: Mon, 8 Jun 2020 15:33:35 -0400 Subject: [PATCH 24/32] updated per feedback to allow for different filtering --- .../exceptions/hooks/use_exception_list.tsx | 178 +++-- .../plugins/lists/public/exceptions/types.ts | 37 +- x-pack/plugins/lists/public/index.tsx | 3 +- .../detection_engine/rules/details/index.tsx | 20 +- .../exceptions/__examples__/index.stories.tsx | 118 --- .../components/exceptions/helpers.test.tsx | 6 +- .../common/components/exceptions/mocks.ts | 2 +- .../components/exceptions/translations.ts | 35 +- .../common/components/exceptions/types.ts | 42 +- .../exceptions_viewer_header.test.tsx.snap | 688 ------------------ .../viewer/exceptions_pagination.tsx | 26 +- .../viewer/exceptions_viewer_header.test.tsx | 278 ++++--- .../viewer/exceptions_viewer_header.tsx | 209 +++--- .../components/exceptions/viewer/index.tsx | 412 ++++++----- .../components/exceptions/viewer/reducer.ts | 114 +-- .../public/lists_plugin_deps.ts | 11 +- 16 files changed, 830 insertions(+), 1349 deletions(-) delete mode 100644 x-pack/plugins/security_solution/public/common/components/exceptions/__examples__/index.stories.tsx delete mode 100644 x-pack/plugins/security_solution/public/common/components/exceptions/viewer/__snapshots__/exceptions_viewer_header.test.tsx.snap diff --git a/x-pack/plugins/lists/public/exceptions/hooks/use_exception_list.tsx b/x-pack/plugins/lists/public/exceptions/hooks/use_exception_list.tsx index 881e9facd8d3b..9d80dd367efc1 100644 --- a/x-pack/plugins/lists/public/exceptions/hooks/use_exception_list.tsx +++ b/x-pack/plugins/lists/public/exceptions/hooks/use_exception_list.tsx @@ -7,18 +7,15 @@ import { useEffect, useMemo, useRef, useState } from 'react'; import { fetchExceptionListById, fetchExceptionListItemsByListId } from '../api'; -import { - ExceptionItemsAndPagination, - UseExceptionListProps, - UseExceptionListRefreshProps, -} from '../types'; -import { ExceptionListSchema } from '../../../common/schemas'; - -type Func = (arg: UseExceptionListRefreshProps) => void; +import { ExceptionIdentifiers, ExceptionList, Pagination, UseExceptionListProps } from '../types'; +import { ExceptionListItemSchema, ExceptionListSchema } from '../../../common/schemas'; + +type Func = () => void; export type ReturnExceptionListAndItems = [ boolean, - ExceptionListSchema | null, - ExceptionItemsAndPagination | null, + ExceptionList[], + ExceptionListItemSchema[], + Pagination, Func | null ]; @@ -35,11 +32,10 @@ export type ReturnExceptionListAndItems = [ */ export const useExceptionList = ({ http, - id, - namespaceType, + lists, pagination = { page: 1, - perPage: 20, + perPage: 5, total: 0, }, filterOptions = { @@ -47,81 +43,139 @@ export const useExceptionList = ({ tags: [], }, onError, + dispatchListsInReducer, }: UseExceptionListProps): ReturnExceptionListAndItems => { - const [exceptionList, setExceptionList] = useState(null); - const [exceptionItems, setExceptionListItems] = useState( - null - ); + const [exceptionLists, setExceptionLists] = useState< + Array + >([]); + const [exceptionItems, setExceptionListItems] = useState([]); + const [paginationInfo, setPagination] = useState(pagination); const fetchExceptionList = useRef(null); const [loading, setLoading] = useState(true); const tags = useMemo(() => filterOptions.tags.sort().join(), [filterOptions.tags]); + const listIds = useMemo( + () => + lists + .map((t) => t.id) + .sort() + .join(), + [lists] + ); useEffect( () => { - let isSubscribed = true; - const abortCtrl = new AbortController(); - - const fetchData = async ({ - listId, - listNamespaceType, - }: UseExceptionListRefreshProps): Promise => { - try { - setLoading(true); - - const { list_id, namespace_type, ...restOfExceptionList } = await fetchExceptionListById({ - http, - id: listId, - namespaceType: listNamespaceType, - signal: abortCtrl.signal, - }); - const fetchListItemsResult = await fetchExceptionListItemsByListId({ - filterOptions, - http, - listId: list_id, - namespaceType: namespace_type, - pagination, - signal: abortCtrl.signal, - }); + let isSubscribed = false; + let abortCtrl: AbortController; - if (isSubscribed) { - setExceptionList({ + const fetchLists = async (): Promise => { + isSubscribed = true; + abortCtrl = new AbortController(); + + // TODO: workaround until api updated, will be cleaned up + let exceptions: ExceptionListItemSchema[] = []; + let exceptionListsReturned: ExceptionList[] = []; + + const fetchData = async ({ id, namespaceType }: ExceptionIdentifiers): Promise => { + try { + setLoading(true); + + const { list_id, namespace_type, - ...restOfExceptionList, + ...restOfExceptionList + } = await fetchExceptionListById({ + http, + id, + namespaceType, + signal: abortCtrl.signal, }); - setExceptionListItems({ - items: [...fetchListItemsResult.data], - pagination: { + const fetchListItemsResult = await fetchExceptionListItemsByListId({ + filterOptions, + http, + listId: list_id, + namespaceType: namespace_type, + pagination, + signal: abortCtrl.signal, + }); + + if (isSubscribed) { + exceptionListsReturned = [ + ...exceptionListsReturned, + { + list_id, + namespace_type, + ...restOfExceptionList, + totalItems: fetchListItemsResult.total, + }, + ]; + setExceptionLists(exceptionListsReturned); + setPagination({ page: fetchListItemsResult.page, perPage: fetchListItemsResult.per_page, total: fetchListItemsResult.total, - }, - }); + }); + + exceptions = [...exceptions, ...fetchListItemsResult.data]; + setExceptionListItems(exceptions); + + if (dispatchListsInReducer != null) { + dispatchListsInReducer({ + exceptions, + lists: exceptionListsReturned, + pagination: { + page: fetchListItemsResult.page, + perPage: fetchListItemsResult.per_page, + total: fetchListItemsResult.total, + }, + }); + } + } + } catch (error) { + if (isSubscribed) { + setExceptionLists([]); + setExceptionListItems([]); + setPagination({ + page: 1, + perPage: 20, + total: 0, + }); + onError(error); + } } - } catch (error) { + if (isSubscribed) { - setExceptionList(null); - onError(error); + setLoading(false); } - } + }; - if (isSubscribed) { - setLoading(false); - } + // TODO: Workaround for now. Once api updated, we can pass in array of lists to fetch + await Promise.all( + lists.map( + ({ id, namespaceType }: ExceptionIdentifiers): Promise => + fetchData({ id, namespaceType }) + ) + ); }; - if (id != null && namespaceType != null) { - fetchData({ listId: id, listNamespaceType: namespaceType }); - } + fetchLists(); - fetchExceptionList.current = fetchData; + fetchExceptionList.current = fetchLists; return (): void => { isSubscribed = false; abortCtrl.abort(); }; }, // eslint-disable-next-line react-hooks/exhaustive-deps - [http, id, namespaceType, pagination.page, pagination.perPage, filterOptions.filter, tags] + [ + http, + listIds, + setExceptionLists, + setExceptionListItems, + pagination.page, + pagination.perPage, + filterOptions.filter, + tags, + ] ); - return [loading, exceptionList, exceptionItems, fetchExceptionList.current]; + return [loading, exceptionLists, exceptionItems, paginationInfo, fetchExceptionList.current]; }; diff --git a/x-pack/plugins/lists/public/exceptions/types.ts b/x-pack/plugins/lists/public/exceptions/types.ts index e3daf7c28fc88..286eb0570ebb8 100644 --- a/x-pack/plugins/lists/public/exceptions/types.ts +++ b/x-pack/plugins/lists/public/exceptions/types.ts @@ -24,11 +24,6 @@ export interface Pagination { total: number; } -export interface ExceptionItemsAndPagination { - items: ExceptionListItemSchema[]; - pagination: Pagination; -} - export type AddExceptionList = ExceptionListSchema | CreateExceptionListSchemaPartial; export type AddExceptionListItem = CreateExceptionListItemSchemaPartial | ExceptionListItemSchema; @@ -38,18 +33,31 @@ export interface PersistHookProps { onError: (arg: Error) => void; } +export interface ExceptionList extends ExceptionListSchema { + totalItems: number; +} + export interface UseExceptionListProps { - filterOptions?: FilterExceptionsOptions; http: HttpStart; - id: string | undefined; - namespaceType: NamespaceType; + lists: ExceptionIdentifiers[]; onError: (arg: Error) => void; + filterOptions?: FilterExceptionsOptions; pagination?: Pagination; + dispatchListsInReducer?: ({ + lists, + exceptions, + pagination, + }: { + lists: ExceptionList[]; + exceptions: ExceptionListItemSchema[]; + pagination: Pagination; + }) => void; } -export interface UseExceptionListRefreshProps { - listId: string; - listNamespaceType: NamespaceType; +export interface ExceptionIdentifiers { + id: string; + namespaceType: NamespaceType; + type?: string; } export interface ApiCallByListIdProps { @@ -68,6 +76,13 @@ export interface ApiCallByIdProps { signal: AbortSignal; } +export interface ApiCallMemoProps { + id: string; + namespaceType: NamespaceType; + onError: (arg: Error) => void; + onSuccess: () => void; +} + export interface AddExceptionListProps { http: HttpStart; list: AddExceptionList; diff --git a/x-pack/plugins/lists/public/index.tsx b/x-pack/plugins/lists/public/index.tsx index 10f87c407df51..1e25275a0d38b 100644 --- a/x-pack/plugins/lists/public/index.tsx +++ b/x-pack/plugins/lists/public/index.tsx @@ -4,8 +4,9 @@ * you may not use this file except in compliance with the Elastic License. */ // Exports to be shared with plugins +export { useApi } from './exceptions/hooks/use_api'; export { usePersistExceptionItem } from './exceptions/hooks/persist_exception_item'; export { usePersistExceptionList } from './exceptions/hooks/persist_exception_list'; export { useExceptionList } from './exceptions/hooks/use_exception_list'; -export { deleteExceptionListItemById } from './exceptions/api'; +export { ExceptionList, ExceptionIdentifiers } from './exceptions/types'; export { mockNewExceptionItem, mockNewExceptionList } from './exceptions/mock'; diff --git a/x-pack/plugins/security_solution/public/alerts/pages/detection_engine/rules/details/index.tsx b/x-pack/plugins/security_solution/public/alerts/pages/detection_engine/rules/details/index.tsx index a38a56555c7a9..a7c9332c55daf 100644 --- a/x-pack/plugins/security_solution/public/alerts/pages/detection_engine/rules/details/index.tsx +++ b/x-pack/plugins/security_solution/public/alerts/pages/detection_engine/rules/details/index.tsx @@ -71,6 +71,7 @@ import { RuleStatus } from '../../../../components/rules//rule_status'; import { useMlCapabilities } from '../../../../../common/components/ml_popover/hooks/use_ml_capabilities'; import { hasMlAdminPermissions } from '../../../../../../common/machine_learning/has_ml_admin_permissions'; import { ExceptionsViewer } from '../../../../../common/components/exceptions/viewer'; +import { ExceptionListType } from '../../../../../common/components/exceptions/types'; enum RuleDetailTabs { alerts = 'alerts', @@ -394,11 +395,26 @@ export const RuleDetailsPageComponent: FC = ({ )} {ruleDetailTab === RuleDetailTabs.exceptions && ( )} - {ruleDetailTab === RuleDetailTabs.failures && } )} diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/__examples__/index.stories.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/__examples__/index.stories.tsx deleted file mode 100644 index b6620ed103bc8..0000000000000 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/__examples__/index.stories.tsx +++ /dev/null @@ -1,118 +0,0 @@ -/* - * 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 { storiesOf } from '@storybook/react'; -import React from 'react'; -import { ThemeProvider } from 'styled-components'; -import euiLightVars from '@elastic/eui/dist/eui_theme_light.json'; - -import { ExceptionItem } from '../viewer'; -import { Operator } from '../types'; -import { getExceptionItemMock } from '../mocks'; - -storiesOf('components/exceptions', module) - .add('ExceptionItem/with os', () => { - const payload = getExceptionItemMock(); - payload.description = ''; - payload.comments = []; - payload.entries = [ - { - field: 'actingProcess.file.signer', - type: 'match', - operator: Operator.INCLUSION, - value: 'Elastic, N.V.', - }, - ]; - - return ( - ({ eui: euiLightVars, darkMode: false })}> - {}} - handleEdit={() => {}} - /> - - ); - }) - .add('ExceptionItem/with description', () => { - const payload = getExceptionItemMock(); - payload._tags = []; - payload.comments = []; - payload.entries = [ - { - field: 'actingProcess.file.signer', - type: 'match', - operator: Operator.INCLUSION, - value: 'Elastic, N.V.', - }, - ]; - - return ( - ({ eui: euiLightVars, darkMode: false })}> - {}} - handleEdit={() => {}} - /> - - ); - }) - .add('ExceptionItem/with comments', () => { - const payload = getExceptionItemMock(); - payload._tags = []; - payload.description = ''; - payload.entries = [ - { - field: 'actingProcess.file.signer', - type: 'match', - operator: Operator.INCLUSION, - value: 'Elastic, N.V.', - }, - ]; - - return ( - ({ eui: euiLightVars, darkMode: false })}> - {}} - handleEdit={() => {}} - /> - - ); - }) - .add('ExceptionItem/with nested entries', () => { - const payload = getExceptionItemMock(); - payload._tags = []; - payload.description = ''; - payload.comments = []; - - return ( - ({ eui: euiLightVars, darkMode: false })}> - {}} - handleEdit={() => {}} - /> - - ); - }) - .add('ExceptionItem/with everything', () => { - const payload = getExceptionItemMock(); - - return ( - ({ eui: euiLightVars, darkMode: false })}> - {}} - handleEdit={() => {}} - /> - - ); - }); diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/helpers.test.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/helpers.test.tsx index 223eabb0ea4ee..7698605588e76 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/helpers.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/helpers.test.tsx @@ -439,7 +439,7 @@ describe('Exception helpers', () => { describe('#getFormattedComments', () => { test('it returns formatted comment object with username and timestamp', () => { - const payload = getExceptionItemMock().comments; + const payload = getExceptionItemMock().comment; const result = getFormattedComments(payload); expect(result[0].username).toEqual('user_name'); @@ -447,7 +447,7 @@ describe('Exception helpers', () => { }); test('it returns formatted timeline icon with comment users initial', () => { - const payload = getExceptionItemMock().comments; + const payload = getExceptionItemMock().comment; const result = getFormattedComments(payload); const wrapper = mount(result[0].timelineIcon as React.ReactElement); @@ -456,7 +456,7 @@ describe('Exception helpers', () => { }); test('it returns comment text', () => { - const payload = getExceptionItemMock().comments; + const payload = getExceptionItemMock().comment; const result = getFormattedComments(payload); const wrapper = mount(result[0].children as React.ReactElement); diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/mocks.ts b/x-pack/plugins/security_solution/public/common/components/exceptions/mocks.ts index 15aec3533b325..5b28cdd491beb 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/mocks.ts +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/mocks.ts @@ -44,7 +44,7 @@ export const getExceptionItemMock = (): ExceptionListItemSchema => ({ namespace_type: 'single', name: '', description: 'This is a description', - comments: [ + comment: [ { user: 'user_name', timestamp: '2020-04-23T00:19:13.289Z', diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/translations.ts b/x-pack/plugins/security_solution/public/common/components/exceptions/translations.ts index 956f65de645b4..4e6092af3882b 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/translations.ts +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/translations.ts @@ -5,6 +5,17 @@ */ import { i18n } from '@kbn/i18n'; +export const DETECTION_LIST = i18n.translate( + 'xpack.securitySolution.exceptions.detectionListLabel', + { + defaultMessage: 'Detection list', + } +); + +export const ENDPOINT_LIST = i18n.translate('xpack.securitySolution.exceptions.endpointListLabel', { + defaultMessage: 'Endpoint list', +}); + export const EDIT = i18n.translate('xpack.securitySolution.exceptions.editButtonLabel', { defaultMessage: 'Edit', }); @@ -87,7 +98,7 @@ export const EXCEPTION_EMPTY_PROMPT_BODY = i18n.translate( 'xpack.securitySolution.exceptions.viewer.emptyPromptBody', { defaultMessage: - 'This could be a description of what exceptions are and what their use case could be. Wow such tempt much ruin diet wrinkler clouds, you are doin me a concern. H*cksub woofer shibe clouds.', + 'You can add an exception to fine tune the rule so that it suppresses alerts that meet specified conditions. Exceptions leverage detection accuracy, which can help reduce the number of false positives.', } ); @@ -104,3 +115,25 @@ export const DELETE_EXCEPTION_ERROR = i18n.translate( defaultMessage: 'Error deleting exception', } ); + +export const ITEMS_PER_PAGE = (items: number) => + i18n.translate('xpack.securitySolution.exceptions.exceptionsPaginationLabel', { + values: { items }, + defaultMessage: 'Items per page: {items}', + }); + +export const NUMBER_OF_ITEMS = (items: number) => + i18n.translate('xpack.securitySolution.exceptions.paginationNumberOfItemsLabel', { + values: { items }, + defaultMessage: '{items} items', + }); + +export const REFRESH = i18n.translate('xpack.securitySolution.exceptions.utilityRefreshLabel', { + defaultMessage: 'Refresh', +}); + +export const SHOWING_EXCEPTIONS = (items: number) => + i18n.translate('xpack.securitySolution.exceptions.utilityNumberExceptionsLabel', { + values: { items }, + defaultMessage: 'Showing {items} exceptions', + }); diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/types.ts b/x-pack/plugins/security_solution/public/common/components/exceptions/types.ts index f4707efa76a0f..8364df81a6d8f 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/types.ts +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/types.ts @@ -5,7 +5,7 @@ */ import { ReactNode } from 'react'; -import { NamespaceType } from '../../../lists_plugin_deps'; +import { NamespaceType, ExceptionList } from '../../../lists_plugin_deps'; export interface OperatorOption { message: string; @@ -58,31 +58,51 @@ export interface Comment { comment: string; } -export enum ToggleId { +export enum ExceptionListType { DETECTION_ENGINE = 'detection', ENDPOINT = 'endpoint', } -export interface RuleExceptionList { - id: string | null; - type: string | null; - namespaceType: NamespaceType | null; -} - export interface FilterOptions { filter: string; + showDetectionsList: boolean; + showEndpointList: boolean; tags: string[]; } +export interface Filter { + filter: Partial; + pagination: Partial; +} + +export interface SetExceptionsProps { + lists: ExceptionList[]; + exceptions: ExceptionListItemSchema[]; + pagination: Pagination; +} + export interface ApiProps { - id: string | null; - namespaceType: NamespaceType | null; + id: string; + namespaceType: NamespaceType; +} + +export interface Pagination { + page: number; + perPage: number; + total: number; +} + +export interface ExceptionsPagination { + pageIndex: number; + pageSize: number; + totalItemCount: number; + pageSizeOptions: number[]; } // TODO: Delete once types are updated export interface ExceptionListItemSchema { _tags: string[]; - comments: Comment[]; + comment: Comment[]; created_at: string; created_by: string; description?: string; diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/__snapshots__/exceptions_viewer_header.test.tsx.snap b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/__snapshots__/exceptions_viewer_header.test.tsx.snap deleted file mode 100644 index 73ebd4df627b2..0000000000000 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/__snapshots__/exceptions_viewer_header.test.tsx.snap +++ /dev/null @@ -1,688 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`ExceptionsViewerHeader it renders Detections toggle selected when clicked 1`] = ` - - - -
- -
- - -
-
- - - - -
- - -
-
- - -
- - -
- -
- -
- -
- - - - - - - - - - -
-
-
-
- -
- - Add new exception - - } - closePopover={[Function]} - display="inlineBlock" - hasArrow={true} - isOpen={false} - ownFocus={false} - panelPaddingSize="none" - repositionOnScroll={true} - > - -
-
- - - -
-
-
-
-
-
-
-
-
-
-
- - - -`; - -exports[`ExceptionsViewerHeader it renders all disabled if "isInitLoading" is true 1`] = ` - - - -
- -
- - -
-
- - - - -
- - -
-
- - -
- - -
- -
- -
- -
- - - - - - - - - - -
-
-
-
- -
- - Add new exception - - } - closePopover={[Function]} - display="inlineBlock" - hasArrow={true} - isOpen={false} - ownFocus={false} - panelPaddingSize="none" - repositionOnScroll={true} - > - -
-
- - - -
-
-
-
-
-
-
-
-
-
-
- - - -`; diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exceptions_pagination.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exceptions_pagination.tsx index 8d72afe3d47de..48d15dd6ae333 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exceptions_pagination.tsx +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exceptions_pagination.tsx @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import React, { useCallback, useState, useMemo } from 'react'; +import React, { ReactElement, useCallback, useState, useMemo } from 'react'; import { EuiContextMenuItem, EuiButtonEmpty, @@ -16,11 +16,11 @@ import { } from '@elastic/eui'; import * as i18n from '../translations'; -import { ExceptionsPagination, Pagination } from '../types'; +import { ExceptionsPagination, Filter } from '../types'; interface ExceptionsViewerPaginationProps { pagination: ExceptionsPagination; - onPaginationChange: (arg: Pagination) => void; + onPaginationChange: (arg: Filter) => void; } const ExceptionsViewerPaginationComponent = ({ @@ -38,24 +38,30 @@ const ExceptionsViewerPaginationComponent = ({ const onPageClick = useCallback( (pageIndex: number): void => { onPaginationChange({ - page: pageIndex + 1, - pageSize: pagination.pageSize, - total: pagination.totalItemCount, + filter: {}, + pagination: { + page: pageIndex + 1, + perPage: pagination.pageSize, + total: pagination.totalItemCount, + }, }); }, [pagination, onPaginationChange] ); - const items = useMemo(() => { + const items = useMemo((): ReactElement[] => { return pagination.pageSizeOptions.map((rows) => ( { onPaginationChange({ - page: pagination.pageIndex, - pageSize: rows, - total: pagination.totalItemCount, + filter: {}, + pagination: { + page: pagination.pageIndex, + perPage: rows, + total: pagination.totalItemCount, + }, }); }} > diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exceptions_viewer_header.test.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exceptions_viewer_header.test.tsx index 2b0d7d9384aa2..bdc99370a6293 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exceptions_viewer_header.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exceptions_viewer_header.test.tsx @@ -10,18 +10,18 @@ import { mount } from 'enzyme'; import euiLightVars from '@elastic/eui/dist/eui_theme_light.json'; import { ExceptionsViewerHeader } from './exceptions_viewer_header'; -import { ToggleId } from '../types'; +import { ExceptionListType } from '../types'; describe('ExceptionsViewerHeader', () => { it('it renders all disabled if "isInitLoading" is true', () => { const wrapper = mount( ({ eui: euiLightVars, darkMode: false })}> @@ -31,218 +31,254 @@ describe('ExceptionsViewerHeader', () => { wrapper.find('input[data-test-subj="exceptionsHeaderSearch"]').at(0).prop('disabled') ).toBeTruthy(); expect( - wrapper.find('[data-test-subj="exceptionsHeaderListToggle"] button').at(0).prop('disabled') + wrapper.find('[data-test-subj="exceptionsDetectionFilterBtn"] button').at(0).prop('disabled') ).toBeTruthy(); expect( - wrapper.find('[data-test-subj="exceptionsHeaderListToggle"] button').at(1).prop('disabled') + wrapper.find('[data-test-subj="exceptionsEndpointFilterBtn"] button').at(0).prop('disabled') ).toBeTruthy(); expect( wrapper - .find('[data-test-subj="exceptionsHeaderAddExceptionBtn"] button') + .find('[data-test-subj="exceptionsHeaderAddExceptionPopoverBtn"] button') .at(0) .prop('disabled') ).toBeTruthy(); }); - it('it disables Endpoint toggle when only Detections list available', () => { + it('it displays toggles and add exception popover when more than one list type available', () => { const wrapper = mount( ({ eui: euiLightVars, darkMode: false })}> ); + expect(wrapper.find('[data-test-subj="exceptionsFilterGroupBtns"]').exists()).toBeTruthy(); expect( - wrapper.find('input[data-test-subj="detectionsToggle"]').at(0).prop('disabled') - ).toBeFalsy(); - expect( - wrapper.find('input[data-test-subj="detectionsToggle"]').at(0).prop('checked') - ).toBeTruthy(); - expect( - wrapper.find('input[data-test-subj="endpointToggle"]').at(0).prop('disabled') + wrapper.find('[data-test-subj="exceptionsHeaderAddExceptionPopoverBtn"]').exists() ).toBeTruthy(); - expect( - wrapper.find('input[data-test-subj="endpointToggle"]').at(0).prop('checked') - ).toBeFalsy(); }); - it('it disables Detections toggle when only Endpoint list available', () => { + it('it does not display toggles and add exception popover if only one list type is available', () => { const wrapper = mount( ({ eui: euiLightVars, darkMode: false })}> ); - expect( - wrapper.find('input[data-test-subj="detectionsToggle"]').at(0).prop('disabled') - ).toBeTruthy(); - expect( - wrapper.find('input[data-test-subj="detectionsToggle"]').at(0).prop('checked') - ).toBeFalsy(); - expect( - wrapper.find('input[data-test-subj="endpointToggle"]').at(0).prop('disabled') - ).toBeFalsy(); - expect( - wrapper.find('input[data-test-subj="endpointToggle"]').at(0).prop('checked') - ).toBeTruthy(); + expect(wrapper.find('[data-test-subj="exceptionsFilterGroupBtns"]')).toHaveLength(0); + expect(wrapper.find('[data-test-subj="exceptionsHeaderAddExceptionPopoverBtn"]')).toHaveLength( + 0 + ); }); - it('it renders Detections toggle selected when "selectedListType" is detections', () => { + it('it displays add exception button without popover if only one list type is available', () => { const wrapper = mount( ({ eui: euiLightVars, darkMode: false })}> ); expect( - wrapper.find('input[data-test-subj="detectionsToggle"]').at(0).prop('checked') + wrapper.find('[data-test-subj="exceptionsHeaderAddExceptionBtn"]').exists() ).toBeTruthy(); }); - it('it renders Endpoint toggle selected when "selectedListType" is endpoint', () => { + it('it renders detections filter toggle selected when clicked', () => { + const mockOnFilterChange = jest.fn(); const wrapper = mount( ({ eui: euiLightVars, darkMode: false })}> ); + wrapper.find('[data-test-subj="exceptionsDetectionFilterBtn"] button').simulate('click'); + expect( - wrapper.find('input[data-test-subj="endpointToggle"]').at(0).prop('checked') + wrapper + .find('EuiFilterButton[data-test-subj="exceptionsDetectionFilterBtn"]') + .at(0) + .prop('hasActiveFilters') ).toBeTruthy(); + expect( + wrapper + .find('EuiFilterButton[data-test-subj="exceptionsEndpointFilterBtn"]') + .at(0) + .prop('hasActiveFilters') + ).toBeFalsy(); + expect(mockOnFilterChange).toHaveBeenCalledWith({ + filter: { + filter: '', + showDetectionsList: true, + showEndpointList: false, + tags: [], + }, + pagination: {}, + }); }); - it('it invokes "onToggleListType" with appropriate toggle value on click', () => { - const mockOnToggleListType = jest.fn(); + it('it renders endpoint filter toggle selected and invokes "onFilterChange" when clicked', () => { + const mockOnFilterChange = jest.fn(); const wrapper = mount( ({ eui: euiLightVars, darkMode: false })}> ); - wrapper.find('input[data-test-subj="endpointToggle"]').simulate('change', { - target: { value: 'endpoint' }, + wrapper.find('[data-test-subj="exceptionsEndpointFilterBtn"] button').simulate('click'); + + expect( + wrapper + .find('EuiFilterButton[data-test-subj="exceptionsEndpointFilterBtn"]') + .at(0) + .prop('hasActiveFilters') + ).toBeTruthy(); + expect( + wrapper + .find('EuiFilterButton[data-test-subj="exceptionsDetectionFilterBtn"]') + .at(0) + .prop('hasActiveFilters') + ).toBeFalsy(); + expect(mockOnFilterChange).toHaveBeenCalledWith({ + filter: { + filter: '', + showDetectionsList: false, + showEndpointList: true, + tags: [], + }, + pagination: {}, }); + }); - expect(mockOnToggleListType).toHaveBeenCalledWith('endpoint'); + it('it invokes "onAddExceptionClick" when user selects to add an exception item and only endpoint exception lists are available', () => { + const mockOnAddExceptionClick = jest.fn(); + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); - wrapper.find('input[data-test-subj="detectionsToggle"]').simulate('change', { - target: { value: 'detection' }, - }); + wrapper.find('[data-test-subj="exceptionsHeaderAddExceptionBtn"] button').simulate('click'); - expect(mockOnToggleListType).toHaveBeenCalledWith('detection'); + expect(mockOnAddExceptionClick).toHaveBeenCalledTimes(1); }); - it('it invokes "onAddExceptionClick" with value "endpoint" when add exception to endpoint list clicked', () => { - const mockAddExceptionClick = jest.fn(); + it('it invokes "onAddDetectionsExceptionClick" when user selects to add an exception item and only endpoint detections lists are available', () => { + const mockOnAddExceptionClick = jest.fn(); const wrapper = mount( ({ eui: euiLightVars, darkMode: false })}> ); wrapper.find('[data-test-subj="exceptionsHeaderAddExceptionBtn"] button').simulate('click'); - wrapper.find('[data-test-subj="addEndpointExceptionBtn"] button').simulate('click'); - expect(mockAddExceptionClick).toHaveBeenCalledWith('endpoint'); + expect(mockOnAddExceptionClick).toHaveBeenCalledTimes(1); }); - it('it invokes "onAddExceptionClick" with value "detection" when add exception to detections list clicked', () => { - const mockAddExceptionClick = jest.fn(); + it('it invokes "onAddEndpointExceptionClick" when user selects to add an exception item to endpoint list from popover', () => { + const mockOnAddExceptionClick = jest.fn(); const wrapper = mount( ({ eui: euiLightVars, darkMode: false })}> ); - wrapper.find('[data-test-subj="exceptionsHeaderAddExceptionBtn"] button').simulate('click'); - wrapper.find('[data-test-subj="addDetectionsExceptionBtn"] button').simulate('click'); + wrapper + .find('[data-test-subj="exceptionsHeaderAddExceptionPopoverBtn"] button') + .simulate('click'); + wrapper.find('[data-test-subj="addEndpointExceptionBtn"] button').simulate('click'); - expect(mockAddExceptionClick).toHaveBeenCalledWith('detection'); + expect(mockOnAddExceptionClick).toHaveBeenCalledTimes(1); }); - it('it invokes "onFiltersChange" with filter value "host" when "host" searched', () => { - const mockOnFiltersChange = jest.fn(); + it('it invokes "onAddDetectionsExceptionClick" when user selects to add an exception item to endpoint list from popover', () => { + const mockOnAddExceptionClick = jest.fn(); const wrapper = mount( ({ eui: euiLightVars, darkMode: false })}> ); wrapper - .find('input[data-test-subj="exceptionsHeaderSearch"]') - .at(0) - .simulate('change', { - target: { value: 'host' }, - }); + .find('[data-test-subj="exceptionsHeaderAddExceptionPopoverBtn"] button') + .simulate('click'); + wrapper.find('[data-test-subj="addDetectionsExceptionBtn"] button').simulate('click'); - expect(mockOnFiltersChange).toHaveBeenCalledWith({ filter: 'host', tags: [] }); + expect(mockOnAddExceptionClick).toHaveBeenCalledTimes(1); }); - it('it invokes "onFiltersChange" with tags value when tags searched', () => { - const mockOnFiltersChange = jest.fn(); + it('it invokes "onFilterChange" with filter value when search used', () => { + const mockOnFilterChange = jest.fn(); const wrapper = mount( ({ eui: euiLightVars, darkMode: false })}> @@ -252,22 +288,30 @@ describe('ExceptionsViewerHeader', () => { .find('input[data-test-subj="exceptionsHeaderSearch"]') .at(0) .simulate('change', { - target: { value: 'tags:malware' }, + target: { value: 'host' }, }); - expect(mockOnFiltersChange).toHaveBeenCalledWith({ filter: '', tags: ['malware'] }); + expect(mockOnFilterChange).toHaveBeenCalledWith({ + filter: { + filter: 'host', + showDetectionsList: false, + showEndpointList: false, + tags: [], + }, + pagination: {}, + }); }); - it('it invokes "onFiltersChange" with tags and filter value when tags and fields searched', () => { - const mockOnFiltersChange = jest.fn(); + it('it invokes "onFilterChange" with tags values when search value includes "tags:..."', () => { + const mockOnFilterChange = jest.fn(); const wrapper = mount( ({ eui: euiLightVars, darkMode: false })}> @@ -277,9 +321,17 @@ describe('ExceptionsViewerHeader', () => { .find('input[data-test-subj="exceptionsHeaderSearch"]') .at(0) .simulate('change', { - target: { value: 'host.name tags:malware' }, + target: { value: 'tags:malware' }, }); - expect(mockOnFiltersChange).toHaveBeenCalledWith({ filter: 'host.name', tags: ['malware'] }); + expect(mockOnFilterChange).toHaveBeenCalledWith({ + filter: { + filter: '', + showDetectionsList: false, + showEndpointList: false, + tags: ['malware'], + }, + pagination: {}, + }); }); }); diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exceptions_viewer_header.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exceptions_viewer_header.tsx index 251048b632275..a819539fc5d94 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exceptions_viewer_header.tsx +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exceptions_viewer_header.tsx @@ -6,51 +6,68 @@ import { EuiFieldSearch, - EuiButtonGroup, EuiFlexGroup, EuiFlexItem, EuiPopover, EuiContextMenu, EuiButton, + EuiFilterGroup, + EuiFilterButton, EuiContextMenuPanelDescriptor, - EuiButtonGroupOption, } from '@elastic/eui'; -import React, { useState, useCallback, useMemo } from 'react'; +import React, { useEffect, useState, useCallback, useMemo } from 'react'; import * as i18n from '../translations'; -import { ToggleId } from '../types'; +import { ExceptionListType, Filter } from '../types'; interface ExceptionsViewerHeaderProps { - selectedListType: ToggleId; isInitLoading: boolean; - listTypes: ToggleId[]; - onFiltersChange: ({ filter, tags }: { filter: string; tags: string[] }) => void; - onAddExceptionClick: (type: ToggleId) => void; - onToggleListType: (type: ToggleId) => void; + supportedListTypes: ExceptionListType[]; + detectionsListItems: number; + endpointListItems: number; + onFilterChange: (arg: Filter) => void; + onAddExceptionClick: (type: ExceptionListType) => void; } /** * Collection of filters and toggles for filtering exception items. */ const ExceptionsViewerHeaderComponent = ({ - selectedListType, isInitLoading, - listTypes, - onFiltersChange, - onToggleListType, + supportedListTypes, + detectionsListItems, + endpointListItems, + onFilterChange, onAddExceptionClick, }: ExceptionsViewerHeaderProps): JSX.Element => { + const [filter, setFilter] = useState(''); + const [tags, setTags] = useState([]); + const [showDetectionsList, setShowDetectionsList] = useState(false); + const [showEndpointList, setShowEndpointList] = useState(false); const [isAddExceptionMenuOpen, setAddExceptionMenuOpen] = useState(false); - const onToggle = useCallback( - (id: string): void => { - const toggle = - id === ToggleId.DETECTION_ENGINE ? ToggleId.DETECTION_ENGINE : ToggleId.ENDPOINT; - onToggleListType(toggle); - }, - [onToggleListType] + useEffect((): void => { + onFilterChange({ + filter: { filter, showDetectionsList, showEndpointList, tags }, + pagination: {}, + }); + }, [filter, tags, showDetectionsList, showEndpointList]); + + const onAddExceptionDropdownClick = useCallback( + (): void => setAddExceptionMenuOpen(!isAddExceptionMenuOpen), + [setAddExceptionMenuOpen, isAddExceptionMenuOpen] ); + const handleDetectionsListClick = useCallback((): void => { + setShowDetectionsList(!showDetectionsList); + setShowEndpointList(false); + }, [showDetectionsList, setShowDetectionsList, setShowEndpointList]); + + const handleEndpointListClick = useCallback((): void => { + setShowEndpointList(!showEndpointList); + setShowDetectionsList(false); + }, [showEndpointList, setShowEndpointList, setShowDetectionsList]); + const handleOnSearch = useCallback( (event: React.ChangeEvent): void => { const searchValue = event.target.value; @@ -58,44 +75,37 @@ const ExceptionsViewerHeaderComponent = ({ const tagsMatch = searchValue.match(tagsRegex); const foundTags: string = tagsMatch != null ? tagsMatch[0].split(':')[1] : ''; const filterString = tagsMatch != null ? searchValue.replace(tagsRegex, '') : searchValue; - onFiltersChange({ - filter: filterString.trim(), - tags: foundTags.length ? foundTags.split(',') : [], - }); - }, - [onFiltersChange] - ); - const onAddExceptionDropdownClick = useCallback( - (): void => setAddExceptionMenuOpen(!isAddExceptionMenuOpen), - [setAddExceptionMenuOpen] + if (foundTags.length > 0) { + setTags(foundTags.split(',')); + } + + setFilter(filterString.trim()); + }, + [setTags, setFilter] ); const onAddException = useCallback( - (type: ToggleId): void => { + (type: ExceptionListType): void => { onAddExceptionClick(type); setAddExceptionMenuOpen(false); }, [onAddExceptionClick, setAddExceptionMenuOpen] ); - const getAddExceptionOptions = useMemo( + const addExceptionButtonOptions = useMemo( (): EuiContextMenuPanelDescriptor[] => [ { id: 0, items: [ { name: i18n.ADD_TO_ENDPOINT_LIST, - onClick: () => { - onAddException(ToggleId.ENDPOINT); - }, + onClick: () => onAddException(ExceptionListType.ENDPOINT), 'data-test-subj': 'addEndpointExceptionBtn', }, { name: i18n.ADD_TO_DETECTIONS_LIST, - onClick: () => { - onAddException(ToggleId.DETECTION_ENGINE); - }, + onClick: () => onAddException(ExceptionListType.DETECTION_ENGINE), 'data-test-subj': 'addDetectionsExceptionBtn', }, ], @@ -104,72 +114,85 @@ const ExceptionsViewerHeaderComponent = ({ [onAddException] ); - const toggleOptions = useMemo((): EuiButtonGroupOption[] => { - return [ - { - id: ToggleId.DETECTION_ENGINE, - label: 'Detection Engine', - isDisabled: !listTypes.includes(ToggleId.DETECTION_ENGINE), - 'data-test-subj': 'detectionsToggle', - }, - { - id: ToggleId.ENDPOINT, - label: 'Endpoint', - isDisabled: !listTypes.includes(ToggleId.ENDPOINT), - 'data-test-subj': 'endpointToggle', - }, - ]; - }, [listTypes]); - return ( - - - - - - - {i18n.ADD_EXCEPTION_LABEL} - - } - isOpen={isAddExceptionMenuOpen} - closePopover={onAddExceptionDropdownClick} - panelPaddingSize="none" - withTitle - anchorPosition="upLeft" - > - - - + {supportedListTypes.length < 2 && ( + + onAddException(supportedListTypes[0])} + isDisabled={isInitLoading} + fill + > + {i18n.ADD_EXCEPTION_LABEL} + + + )} + + {supportedListTypes.length > 1 && ( + + + + + + {i18n.DETECTION_LIST} + {detectionsListItems != null ? ` (${detectionsListItems})` : ''} + + + {i18n.ENDPOINT_LIST} + {endpointListItems != null ? ` (${endpointListItems})` : ''} + + + + + + + {i18n.ADD_EXCEPTION_LABEL} + + } + isOpen={isAddExceptionMenuOpen} + closePopover={onAddExceptionDropdownClick} + anchorPosition="downCenter" + panelPaddingSize="none" + repositionOnScroll + > + + + + + + )} ); }; diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/index.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/index.tsx index 21cea588e907a..9ae694b49a936 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/index.tsx +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/index.tsx @@ -14,6 +14,9 @@ import { EuiModal, EuiModalBody, EuiCodeBlock, + EuiFlexGroup, + EuiFlexItem, + EuiSpacer, } from '@elastic/eui'; import { FormattedMessage } from 'react-intl'; import styled from 'styled-components'; @@ -22,38 +25,56 @@ import uuid from 'uuid'; import * as i18n from '../translations'; import { useStateToaster } from '../../toasters'; import { useKibana } from '../../../../common/lib/kibana'; +import { Panel } from '../../../../common/components/panel'; +import { Loader } from '../../../../common/components/loader'; import { ExceptionsViewerHeader } from './exceptions_viewer_header'; -import { ToggleId, RuleExceptionList, ExceptionListItemSchema, ApiProps } from '../types'; +import { + ExceptionListType, + ExceptionListItemSchema, + ApiProps, + Filter, + SetExceptionsProps, +} from '../types'; import { allExceptionItemsReducer, State } from './reducer'; import { useExceptionList, - deleteExceptionListItemById, - NamespaceType, + ExceptionIdentifiers, + useApi, } from '../../../../../public/lists_plugin_deps'; import { ExceptionItem } from './exception_item'; import { AndOrBadge } from '../../and_or_badge'; +import { ExceptionsViewerPagination } from './exceptions_pagination'; +import { + UtilityBar, + UtilityBarSection, + UtilityBarGroup, + UtilityBarText, + UtilityBarAction, +} from '../../utility_bar'; const StyledText = styled(EuiText)` font-style: italic; - margin: 16px 0; `; -const OrBadgeWrapper = styled.div` - .euiBadge { - margin: 16px 0; - } +const MyExceptionsContainer = styled.div` + height: 600px; + overflow: hidden; `; const initialState: State = { - filterOptions: { filter: '', tags: [] }, - availableListTypes: [], - selectedListType: ToggleId.DETECTION_ENGINE, - selectedListId: null, - selectedListNamespaceType: null, - endpointList: { id: null, type: null, namespaceType: null }, - detectionsList: { id: null, type: null, namespaceType: null }, + filterOptions: { filter: '', showEndpointList: false, showDetectionsList: false, tags: [] }, + pagination: { + pageIndex: 0, + pageSize: 20, + totalItemCount: 0, + pageSizeOptions: [5, 10, 20, 50, 100, 200, 300], + }, + endpointList: null, + detectionsList: null, + exceptions: [], exceptionToEdit: null, - exceptionToDelete: null, + loadingItemIds: [], + isLoading: false, isModalOpen: false, }; @@ -63,32 +84,23 @@ enum ModalAction { } interface ExceptionsViewerProps { - exceptionLists: RuleExceptionList[]; + ruleId: string; + exceptionListsMeta: ExceptionIdentifiers[]; + availableListTypes: ExceptionListType[]; commentsAccordionId: string; onAssociateList?: (listId: string) => void; } const ExceptionsViewerComponent = ({ - exceptionLists, + ruleId, + exceptionListsMeta, + availableListTypes, onAssociateList, commentsAccordionId, }: ExceptionsViewerProps): JSX.Element => { - const [initLoading, setInitLoading] = useState(true); - const [ - { - availableListTypes, - selectedListType, - selectedListId, - selectedListNamespaceType, - filterOptions, - isModalOpen, - }, - dispatch, - ] = useReducer(allExceptionItemsReducer(), initialState); - - // for fetching lists - const { http } = useKibana().services; + const { services } = useKibana(); const [, dispatchToaster] = useStateToaster(); + const [initLoading, setInitLoading] = useState(true); const onDispatchToaster = useCallback( ({ title, color, iconType }) => (): void => { dispatchToaster({ @@ -103,11 +115,46 @@ const ExceptionsViewerComponent = ({ }, [dispatchToaster] ); - const [loadingList, exceptionList, exceptionItems, fetchList] = useExceptionList({ - http, - id: selectedListId, - namespaceType: selectedListNamespaceType, + const { deleteExceptionItem } = useApi(services.http); + const [ + { + isLoading, + endpointList, + detectionsList, + exceptions, + filterOptions, + pagination, + loadingItemIds, + isModalOpen, + }, + dispatch, + ] = useReducer(allExceptionItemsReducer(), initialState); + + const setExceptions = useCallback( + ({ + lists: newLists, + exceptions: newExceptions, + pagination: newPagination, + }: SetExceptionsProps) => { + dispatch({ + type: 'setExceptions', + lists: newLists, + exceptions: newExceptions, + pagination: newPagination, + }); + }, + [dispatch] + ); + const [loadingList, , , , fetchList] = useExceptionList({ + http: services.http, + lists: exceptionListsMeta, filterOptions, + pagination: { + page: pagination.pageIndex + 1, + perPage: pagination.pageSize, + total: pagination.totalItemCount, + }, + dispatchListsInReducer: setExceptions, onError: onDispatchToaster({ color: 'danger', title: i18n.FETCH_LIST_ERROR, @@ -115,16 +162,6 @@ const ExceptionsViewerComponent = ({ }), }); - const setSelectedListType = useCallback( - (type: ToggleId): void => { - dispatch({ - type: 'updateSelectedListType', - listType: type, - }); - }, - [dispatch] - ); - const setIsModalOpen = useCallback( (isOpen: boolean): void => { dispatch({ @@ -135,44 +172,35 @@ const ExceptionsViewerComponent = ({ [dispatch] ); - const setExceptionToDelete = useCallback( - (id: string | null): void => { - dispatch({ - type: 'updateExceptionToDelete', - id, - }); - }, - [dispatch] - ); - - const onFetchList = useCallback( - ({ id, namespaceType }: ApiProps): void => { - if (fetchList != null && id != null && namespaceType != null) { - fetchList({ - listId: id, - listNamespaceType: namespaceType, - }); - } - }, - [fetchList] - ); + const onFetchList = useCallback((): void => { + if (fetchList != null) { + fetchList(); + } + }, [fetchList]); const onFiltersChange = useCallback( - (filter: { filter: string; tags: string[] }): void => { + ({ filter, pagination: pag }: Filter): void => { dispatch({ type: 'updateFilterOptions', filterOptions: filter, + pagination: pag, + ruleExceptionLists: exceptionListsMeta, }); }, - [dispatch] + [dispatch, exceptionListsMeta] ); - const onAddExceptionItem = useCallback((): void => { - setIsModalOpen(true); - }, [setIsModalOpen]); + const onAddException = useCallback( + (type: ExceptionListType): void => { + setIsModalOpen(true); + }, + [setIsModalOpen] + ); const onEditExceptionItem = useCallback( (exception: ExceptionListItemSchema): void => { + // TODO: Added this just for testing. Update + // modal state logic as needed once ready dispatch({ type: 'updateExceptionToEdit', exception, @@ -193,99 +221,74 @@ const ExceptionsViewerComponent = ({ onAssociateList(listId); } - onFetchList({ id: listId, namespaceType: listNamespaceType }); + onFetchList(); }, [setIsModalOpen, onFetchList, onAssociateList] ); + const setLoadingItemIds = useCallback( + (items: ApiProps[]): void => { + dispatch({ + type: 'updateLoadingItemIds', + items, + }); + }, + [dispatch] + ); + const onDeleteException = useCallback( - async ({ id, namespaceType }: { id: string; namespaceType: NamespaceType }) => { - try { - const deleteTask = new AbortController(); - setExceptionToDelete(id); - await deleteExceptionListItemById({ http, id, namespaceType, signal: deleteTask.signal }); - setExceptionToDelete(null); - - onFetchList({ id: selectedListId, namespaceType: selectedListNamespaceType }); - } catch (error) { - onDispatchToaster({ - color: 'danger', - title: i18n.DELETE_EXCEPTION_ERROR, - iconType: 'alert', - }); - setExceptionToDelete(null); - } + ({ id, namespaceType }: ApiProps) => { + deleteExceptionItem({ + id, + namespaceType, + onSuccess: () => { + setLoadingItemIds(loadingItemIds.filter((t) => t.id !== id)); + onFetchList(); + }, + onError: () => { + const dispatchToasterError = onDispatchToaster({ + color: 'danger', + title: i18n.DELETE_EXCEPTION_ERROR, + iconType: 'alert', + }); + + dispatchToasterError(); + setLoadingItemIds(loadingItemIds.filter((t) => t.id !== id)); + }, + }); }, [ dispatch, - http, - setExceptionToDelete, + setLoadingItemIds, + deleteExceptionItem, + loadingItemIds, + onFetchList, onDispatchToaster, - selectedListNamespaceType, - selectedListId, ] ); - const getListTypes = ({ - detectionsRuleExcList, - endpointRuleExcList, - }: { - detectionsRuleExcList: RuleExceptionList | undefined; - endpointRuleExcList: RuleExceptionList | undefined; - }): ToggleId[] => { - if (detectionsRuleExcList == null) { - setSelectedListType(ToggleId.ENDPOINT); - return [ToggleId.ENDPOINT]; - } else if (endpointRuleExcList == null) { - setSelectedListType(ToggleId.DETECTION_ENGINE); - return [ToggleId.DETECTION_ENGINE]; - } else { - setSelectedListType(ToggleId.DETECTION_ENGINE); - return [ToggleId.DETECTION_ENGINE, ToggleId.ENDPOINT]; - } - }; - // Logic for initial render useEffect((): void => { - if (initLoading && (exceptionLists.length === 0 || exceptionList != null)) { + if (initLoading && (exceptions.length === 0 || exceptions != null)) { setInitLoading(false); } - }, [initLoading, exceptionLists, loadingList, exceptionList]); - - useEffect((): void => { - if (exceptionLists.length) { - const [endpointRuleExcList] = exceptionLists.filter((t) => t.type === ToggleId.ENDPOINT); - const [detectionsRuleExcList] = exceptionLists.filter( - (t) => t.type === ToggleId.DETECTION_ENGINE - ); - const listTypes = getListTypes({ endpointRuleExcList, detectionsRuleExcList }); + }, [initLoading, exceptions, loadingList]); - dispatch({ - type: 'updateAvailableListTypes', - listTypes, - endpointList: endpointRuleExcList ?? null, - detectionsList: detectionsRuleExcList ?? null, - }); - - setInitLoading(false); - } - }, [ - exceptionLists - .map((t) => t.id) - .sort() - .join(), - dispatch, - ]); + const ruleSettingsUrl = useMemo((): string => { + return services.application.getUrlForApp( + `security#/detections/rules/id/${encodeURI(ruleId)}/edit` + ); + }, [ruleId, services.application]); const exceptionsSubtext = useMemo((): JSX.Element => { - if (selectedListType === ToggleId.ENDPOINT) { + if (filterOptions.showEndpointList) { return ( + ); - } else { + } else if (filterOptions.showDetectionsList) { return ( + ); - } - }, [selectedListType]); - - const exceptions = useMemo(() => { - if (exceptionItems != null) { - return exceptionItems.items; } else { - return []; + return <>; } - }, [exceptionItems]); + }, [filterOptions.showEndpointList, filterOptions.showDetectionsList, ruleSettingsUrl]); const showEmpty = useMemo((): boolean => { - return !initLoading && exceptions.length === 0; - }, [initLoading, exceptions.length]); + return !initLoading && !isLoading && exceptions.length === 0; + }, [initLoading, exceptions.length, isLoading]); return ( <> @@ -334,48 +331,91 @@ const ExceptionsViewerComponent = ({ - {JSON.stringify(exceptionList)} + {`Modal goes here`} )} - - {exceptionsSubtext} - - {initLoading && ( - - )} - - {showEmpty && ( - {i18n.EXCEPTION_EMPTY_PROMPT_TITLE}} - body={

{i18n.EXCEPTION_EMPTY_PROMPT_BODY}

} + + {initLoading && ( + + )} + + - )} - {!initLoading && - exceptions.length > 0 && - exceptions.map((exception, index) => ( -
- {index !== 0 && } - + + {(filterOptions.showEndpointList || filterOptions.showDetectionsList) && ( + <> + {exceptionsSubtext} + + )} + + + + + + {i18n.SHOWING_EXCEPTIONS(pagination.totalItemCount ?? 0)} + + + + + + {i18n.REFRESH} + + + + + + + + + {isLoading && } + + {showEmpty && ( + {i18n.EXCEPTION_EMPTY_PROMPT_TITLE}} + body={

{i18n.EXCEPTION_EMPTY_PROMPT_BODY}

} /> -
- ))} + )} + + + + + {!initLoading && + !isLoading && + exceptions.length > 0 && + exceptions.map((exception, index) => ( + + {index !== 0 && ( + <> + + + + )} + + + ))} + + + +
); }; diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/reducer.ts b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/reducer.ts index 899a403ff0785..142f750f383fc 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/reducer.ts +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/reducer.ts @@ -3,86 +3,106 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -import { FilterOptions, RuleExceptionList, ToggleId, ExceptionListItemSchema } from '../types'; -import { NamespaceType } from '../../../../../public/lists_plugin_deps'; +import { + ApiProps, + FilterOptions, + ExceptionsPagination, + ExceptionListItemSchema, + Pagination, +} from '../types'; +import { ExceptionList, ExceptionIdentifiers } from '../../../../../public/lists_plugin_deps'; export interface State { filterOptions: FilterOptions; - availableListTypes: ToggleId[]; - selectedListType: ToggleId; - selectedListId: string | null; - selectedListNamespaceType: NamespaceType | null; - endpointList: RuleExceptionList; - detectionsList: RuleExceptionList; + pagination: ExceptionsPagination; + endpointList: ExceptionList | null; + detectionsList: ExceptionList | null; + exceptions: ExceptionListItemSchema[]; exceptionToEdit: ExceptionListItemSchema | null; - exceptionToDelete: string | null; + loadingItemIds: ApiProps[]; isModalOpen: boolean; + isLoading: boolean; } export type Action = | { - type: 'updateAvailableListTypes'; - listTypes: ToggleId[]; - endpointList: RuleExceptionList; - detectionsList: RuleExceptionList; + type: 'setExceptions'; + lists: ExceptionList[]; + exceptions: ExceptionListItemSchema[]; + pagination: Pagination; } - | { type: 'updateSelectedListType'; listType: ToggleId } | { type: 'updateFilterOptions'; filterOptions: Partial; + pagination: Partial; + ruleExceptionLists: ExceptionIdentifiers[]; } | { type: 'updateModalOpen'; isOpen: boolean } | { type: 'updateExceptionToEdit'; exception: ExceptionListItemSchema } - | { type: 'updateExceptionToDelete'; id: string | null }; + | { type: 'updateLoadingItemIds'; items: ApiProps[] }; export const allExceptionItemsReducer = () => (state: State, action: Action): State => { switch (action.type) { - case 'updateAvailableListTypes': { + case 'setExceptions': { + const endpointList = action.lists.filter((t) => t.type === 'endpoint'); + const detectionsList = action.lists.filter((t) => t.type === 'detection'); + return { ...state, - availableListTypes: action.listTypes, - endpointList: action.endpointList, - detectionsList: action.detectionsList, - selectedListId: - state.selectedListType === ToggleId.ENDPOINT - ? action.endpointList.id - : action.detectionsList.id, - selectedListNamespaceType: - state.selectedListType === ToggleId.ENDPOINT - ? action.endpointList.namespaceType - : action.detectionsList.namespaceType, + endpointList: state.filterOptions.showEndpointList + ? endpointList[0] ?? null + : state.endpointList, + detectionsList: state.filterOptions.showDetectionsList + ? detectionsList[0] ?? null + : state.detectionsList, + pagination: { + ...state.pagination, + pageIndex: action.pagination.page - 1, + pageSize: action.pagination.perPage, + totalItemCount: action.pagination.total, + }, + exceptions: action.exceptions, + isLoading: false, }; } - case 'updateSelectedListType': { - if (action.listType === ToggleId.ENDPOINT) { - return { - ...state, - selectedListType: action.listType, - selectedListId: state.endpointList.id, - selectedListNamespaceType: state.endpointList.namespaceType, - }; - } else { - return { - ...state, - selectedListType: action.listType, - selectedListId: state.detectionsList.id, - selectedListNamespaceType: state.detectionsList.namespaceType, - }; - } - } case 'updateFilterOptions': { - return { + const returnState = { ...state, filterOptions: { ...state.filterOptions, ...action.filterOptions, }, + pagination: { + ...state.pagination, + ...action.pagination, + }, + isLoading: true, }; + + if (action.filterOptions.showEndpointList) { + const exceptions = state.exceptions.filter((t) => t.type === 'endpoint'); + + return { + ...returnState, + exceptions, + }; + } else if (action.filterOptions.showDetectionsList) { + const exceptions = state.exceptions.filter((t) => t.type === 'detection'); + + return { + ...returnState, + exceptions, + }; + } else { + return { + ...returnState, + }; + } } - case 'updateExceptionToDelete': { + case 'updateLoadingItemIds': { return { ...state, - exceptionToDelete: action.id, + loadingItemIds: [...state.loadingItemIds, ...action.items], }; } case 'updateExceptionToEdit': { diff --git a/x-pack/plugins/security_solution/public/lists_plugin_deps.ts b/x-pack/plugins/security_solution/public/lists_plugin_deps.ts index 3acdf42d27fd0..113bfaa860f00 100644 --- a/x-pack/plugins/security_solution/public/lists_plugin_deps.ts +++ b/x-pack/plugins/security_solution/public/lists_plugin_deps.ts @@ -5,11 +5,18 @@ */ export { + useApi, useExceptionList, usePersistExceptionItem, usePersistExceptionList, - deleteExceptionListItemById, + ExceptionIdentifiers, + ExceptionList, mockNewExceptionItem, mockNewExceptionList, } from '../../lists/public'; -export { ExceptionListItemSchema, Entries, NamespaceType } from '../../lists/common/schemas'; +export { + ExceptionListSchema, + ExceptionListItemSchema, + Entries, + NamespaceType, +} from '../../lists/common/schemas'; From aea3b1646fc8d46beea45bcfcd062deef9258adf Mon Sep 17 00:00:00 2001 From: Yara Tercero Date: Mon, 8 Jun 2020 15:50:30 -0400 Subject: [PATCH 25/32] temp disabled complexity linter for rules/details/index, this file is due to be refactored but dont want to make this PR bigger --- .../detection_engine/rules/details/index.tsx | 15 +++------------ 1 file changed, 3 insertions(+), 12 deletions(-) diff --git a/x-pack/plugins/security_solution/public/alerts/pages/detection_engine/rules/details/index.tsx b/x-pack/plugins/security_solution/public/alerts/pages/detection_engine/rules/details/index.tsx index e34c80f0a29dd..0e527bf4dfc72 100644 --- a/x-pack/plugins/security_solution/public/alerts/pages/detection_engine/rules/details/index.tsx +++ b/x-pack/plugins/security_solution/public/alerts/pages/detection_engine/rules/details/index.tsx @@ -5,6 +5,7 @@ */ /* eslint-disable react-hooks/rules-of-hooks */ +/* eslint-disable complexity */ import { EuiButton, @@ -403,20 +404,10 @@ export const RuleDetailsPageComponent: FC = ({ ExceptionListType.ENDPOINT, ]} commentsAccordionId={'ruleDetailsTabExceptions'} - exceptionListsMeta={[ - { - id: '5b543420-a6c3-11ea-989f-53aa81611022', - type: 'endpoint', - namespaceType: 'single', - }, - { - id: '98440bc0-a750-11ea-989f-53aa81611022', - type: 'detection', - namespaceType: 'single', - }, - ]} + exceptionListsMeta={[]} /> )} + {ruleDetailTab === RuleDetailTabs.failures && } )} From 854892a7af871ae59ca6c67f6d1f52e06bb26987 Mon Sep 17 00:00:00 2001 From: Yara Tercero Date: Mon, 8 Jun 2020 17:15:33 -0400 Subject: [PATCH 26/32] cleanup --- .../lists/public/exceptions/hooks/use_api.tsx | 4 +-- .../exceptions/hooks/use_exception_list.tsx | 2 +- .../components/exceptions/translations.ts | 2 +- .../viewer/exceptions_viewer_header.tsx | 2 +- .../components/exceptions/viewer/index.tsx | 36 ++++++------------- .../components/exceptions/viewer/reducer.ts | 25 +++++++------ 6 files changed, 28 insertions(+), 43 deletions(-) diff --git a/x-pack/plugins/lists/public/exceptions/hooks/use_api.tsx b/x-pack/plugins/lists/public/exceptions/hooks/use_api.tsx index dec00747c9e91..45e180d9d617c 100644 --- a/x-pack/plugins/lists/public/exceptions/hooks/use_api.tsx +++ b/x-pack/plugins/lists/public/exceptions/hooks/use_api.tsx @@ -11,7 +11,7 @@ import { HttpStart } from '../../../../../../src/core/public'; import { ExceptionListItemSchema, ExceptionListSchema } from '../../../common/schemas'; import { ApiCallMemoProps } from '../types'; -interface ExceptionsApi { +export interface ExceptionsApi { deleteExceptionItem: (arg: ApiCallMemoProps) => Promise; deleteExceptionList: (arg: ApiCallMemoProps) => Promise; getExceptionItem: ( @@ -24,7 +24,7 @@ interface ExceptionsApi { export const useApi = (http: HttpStart): ExceptionsApi => { return useMemo( - () => ({ + (): ExceptionsApi => ({ async deleteExceptionItem({ id, namespaceType, diff --git a/x-pack/plugins/lists/public/exceptions/hooks/use_exception_list.tsx b/x-pack/plugins/lists/public/exceptions/hooks/use_exception_list.tsx index 9d80dd367efc1..c26d556fe8f25 100644 --- a/x-pack/plugins/lists/public/exceptions/hooks/use_exception_list.tsx +++ b/x-pack/plugins/lists/public/exceptions/hooks/use_exception_list.tsx @@ -35,7 +35,7 @@ export const useExceptionList = ({ lists, pagination = { page: 1, - perPage: 5, + perPage: 20, total: 0, }, filterOptions = { diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/translations.ts b/x-pack/plugins/security_solution/public/common/components/exceptions/translations.ts index 4e6092af3882b..23e9f64caf695 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/translations.ts +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/translations.ts @@ -62,7 +62,7 @@ export const OPERATING_SYSTEM = i18n.translate( export const SEARCH_DEFAULT = i18n.translate( 'xpack.securitySolution.exceptions.viewer.searchDefaultPlaceholder', { - defaultMessage: 'Search field (default)', + defaultMessage: 'Search field (ex: host.name)', } ); diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exceptions_viewer_header.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exceptions_viewer_header.tsx index a819539fc5d94..92a8830310b51 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exceptions_viewer_header.tsx +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exceptions_viewer_header.tsx @@ -51,7 +51,7 @@ const ExceptionsViewerHeaderComponent = ({ filter: { filter, showDetectionsList, showEndpointList, tags }, pagination: {}, }); - }, [filter, tags, showDetectionsList, showEndpointList]); + }, [filter, tags, showDetectionsList, showEndpointList, onFilterChange]); const onAddExceptionDropdownClick = useCallback( (): void => setAddExceptionMenuOpen(!isAddExceptionMenuOpen), diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/index.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/index.tsx index 9ae694b49a936..31cff134d2dc4 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/index.tsx +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/index.tsx @@ -9,7 +9,6 @@ import { EuiEmptyPrompt, EuiText, EuiLink, - EuiLoadingContent, EuiOverlayMask, EuiModal, EuiModalBody, @@ -71,10 +70,10 @@ const initialState: State = { }, endpointList: null, detectionsList: null, + allExceptions: [], exceptions: [], exceptionToEdit: null, loadingItemIds: [], - isLoading: false, isModalOpen: false, }; @@ -118,7 +117,6 @@ const ExceptionsViewerComponent = ({ const { deleteExceptionItem } = useApi(services.http); const [ { - isLoading, endpointList, detectionsList, exceptions, @@ -184,10 +182,9 @@ const ExceptionsViewerComponent = ({ type: 'updateFilterOptions', filterOptions: filter, pagination: pag, - ruleExceptionLists: exceptionListsMeta, }); }, - [dispatch, exceptionListsMeta] + [dispatch] ); const onAddException = useCallback( @@ -212,7 +209,7 @@ const ExceptionsViewerComponent = ({ ); const onCloseExceptionModal = useCallback( - ({ actionType, listId, listNamespaceType }): void => { + ({ actionType, listId }): void => { setIsModalOpen(false); // TODO: This callback along with fetchList can probably get @@ -257,14 +254,7 @@ const ExceptionsViewerComponent = ({ }, }); }, - [ - dispatch, - setLoadingItemIds, - deleteExceptionItem, - loadingItemIds, - onFetchList, - onDispatchToaster, - ] + [setLoadingItemIds, deleteExceptionItem, loadingItemIds, onFetchList, onDispatchToaster] ); // Logic for initial render @@ -321,8 +311,8 @@ const ExceptionsViewerComponent = ({ }, [filterOptions.showEndpointList, filterOptions.showDetectionsList, ruleSettingsUrl]); const showEmpty = useMemo((): boolean => { - return !initLoading && !isLoading && exceptions.length === 0; - }, [initLoading, exceptions.length, isLoading]); + return !initLoading && exceptions.length === 0; + }, [initLoading, exceptions.length]); return ( <> @@ -338,10 +328,8 @@ const ExceptionsViewerComponent = ({ )} - - {initLoading && ( - - )} + + {initLoading && } - - {(filterOptions.showEndpointList || filterOptions.showDetectionsList) && ( <> + {exceptionsSubtext} )} + + @@ -379,8 +368,6 @@ const ExceptionsViewerComponent = ({ - {isLoading && } - {showEmpty && ( {!initLoading && - !isLoading && exceptions.length > 0 && exceptions.map((exception, index) => ( diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/reducer.ts b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/reducer.ts index 142f750f383fc..121a33741534c 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/reducer.ts +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/reducer.ts @@ -10,18 +10,18 @@ import { ExceptionListItemSchema, Pagination, } from '../types'; -import { ExceptionList, ExceptionIdentifiers } from '../../../../../public/lists_plugin_deps'; +import { ExceptionList } from '../../../../../public/lists_plugin_deps'; export interface State { filterOptions: FilterOptions; pagination: ExceptionsPagination; endpointList: ExceptionList | null; detectionsList: ExceptionList | null; + allExceptions: ExceptionListItemSchema[]; exceptions: ExceptionListItemSchema[]; exceptionToEdit: ExceptionListItemSchema | null; loadingItemIds: ApiProps[]; isModalOpen: boolean; - isLoading: boolean; } export type Action = @@ -35,7 +35,6 @@ export type Action = type: 'updateFilterOptions'; filterOptions: Partial; pagination: Partial; - ruleExceptionLists: ExceptionIdentifiers[]; } | { type: 'updateModalOpen'; isOpen: boolean } | { type: 'updateExceptionToEdit'; exception: ExceptionListItemSchema } @@ -49,20 +48,20 @@ export const allExceptionItemsReducer = () => (state: State, action: Action): St return { ...state, - endpointList: state.filterOptions.showEndpointList - ? endpointList[0] ?? null - : state.endpointList, - detectionsList: state.filterOptions.showDetectionsList - ? detectionsList[0] ?? null - : state.detectionsList, + endpointList: state.filterOptions.showDetectionsList + ? state.endpointList + : endpointList[0] ?? null, + detectionsList: state.filterOptions.showEndpointList + ? state.detectionsList + : detectionsList[0] ?? null, pagination: { ...state.pagination, pageIndex: action.pagination.page - 1, pageSize: action.pagination.perPage, totalItemCount: action.pagination.total, }, + allExceptions: action.exceptions, exceptions: action.exceptions, - isLoading: false, }; } case 'updateFilterOptions': { @@ -76,18 +75,17 @@ export const allExceptionItemsReducer = () => (state: State, action: Action): St ...state.pagination, ...action.pagination, }, - isLoading: true, }; if (action.filterOptions.showEndpointList) { - const exceptions = state.exceptions.filter((t) => t.type === 'endpoint'); + const exceptions = state.allExceptions.filter((t) => t._tags.includes('endpoint')); return { ...returnState, exceptions, }; } else if (action.filterOptions.showDetectionsList) { - const exceptions = state.exceptions.filter((t) => t.type === 'detection'); + const exceptions = state.allExceptions.filter((t) => t._tags.includes('detection')); return { ...returnState, @@ -96,6 +94,7 @@ export const allExceptionItemsReducer = () => (state: State, action: Action): St } else { return { ...returnState, + exceptions: state.allExceptions, }; } } From 5303cc95eb037e65b682d9fe6c13b64b66914480 Mon Sep 17 00:00:00 2001 From: Yara Tercero Date: Mon, 8 Jun 2020 17:50:55 -0400 Subject: [PATCH 27/32] updated hook tests and clean up --- .../hooks/use_exception_list.test.tsx | 69 ++++++++++--------- .../exceptions/hooks/use_exception_list.tsx | 14 ++-- .../viewer/exceptions_pagination.tsx | 6 +- .../components/exceptions/viewer/index.tsx | 4 +- 4 files changed, 50 insertions(+), 43 deletions(-) diff --git a/x-pack/plugins/lists/public/exceptions/hooks/use_exception_list.test.tsx b/x-pack/plugins/lists/public/exceptions/hooks/use_exception_list.test.tsx index 26ebb7ff5d359..fbd43787a822e 100644 --- a/x-pack/plugins/lists/public/exceptions/hooks/use_exception_list.test.tsx +++ b/x-pack/plugins/lists/public/exceptions/hooks/use_exception_list.test.tsx @@ -10,8 +10,8 @@ import * as api from '../api'; import { createKibanaCoreStartMock } from '../../common/mocks/kibana_core'; import { getExceptionListSchemaMock } from '../../../common/schemas/response/exception_list_schema.mock'; import { getExceptionListItemSchemaMock } from '../../../common/schemas/response/exception_list_item_schema.mock'; -import { ExceptionListSchema } from '../../../common/schemas'; -import { ExceptionItemsAndPagination, UseExceptionListProps } from '../types'; +import { ExceptionListItemSchema } from '../../../common/schemas'; +import { ExceptionList, UseExceptionListProps } from '../types'; import { ReturnExceptionListAndItems, useExceptionList } from './use_exception_list'; @@ -35,14 +35,23 @@ describe('useExceptionList', () => { >(() => useExceptionList({ http: mockKibanaHttpService, - id: 'myListId', - namespaceType: 'single', + lists: [{ id: 'myListId', namespaceType: 'single' }], onError: onErrorMock, }) ); await waitForNextUpdate(); - expect(result.current).toEqual([true, null, null, null]); + expect(result.current).toEqual([ + true, + [], + [], + { + page: 1, + perPage: 20, + total: 0, + }, + null, + ]); }); }); @@ -54,30 +63,31 @@ describe('useExceptionList', () => { >(() => useExceptionList({ http: mockKibanaHttpService, - id: 'myListId', - namespaceType: 'single', + lists: [{ id: 'myListId', namespaceType: 'single' }], onError: onErrorMock, }) ); await waitForNextUpdate(); await waitForNextUpdate(); - const expectedListResult: ExceptionListSchema = getExceptionListSchemaMock(); + const expectedListResult: ExceptionList[] = [ + { ...getExceptionListSchemaMock(), totalItems: 1 }, + ]; - const expectedListItemsResult: ExceptionItemsAndPagination = { - items: [getExceptionListItemSchemaMock()], - pagination: { - page: 1, - perPage: 20, - total: 1, - }, - }; + const expectedListItemsResult: ExceptionListItemSchema[] = [ + { ...getExceptionListItemSchemaMock() }, + ]; expect(result.current).toEqual([ false, expectedListResult, expectedListItemsResult, - result.current[3], + { + page: 1, + perPage: 20, + total: 1, + }, + result.current[4], ]); }); }); @@ -90,13 +100,12 @@ describe('useExceptionList', () => { UseExceptionListProps, ReturnExceptionListAndItems >( - ({ filterOptions, http, id, namespaceType, pagination, onError }) => - useExceptionList({ filterOptions, http, id, namespaceType, onError, pagination }), + ({ filterOptions, http, lists, pagination, onError }) => + useExceptionList({ filterOptions, http, lists, onError, pagination }), { initialProps: { http: mockKibanaHttpService, - id: 'myListId', - namespaceType: 'single', + lists: [{ id: 'myListId', namespaceType: 'single' }], onError: onErrorMock, }, } @@ -104,8 +113,7 @@ describe('useExceptionList', () => { await waitForNextUpdate(); rerender({ http: mockKibanaHttpService, - id: 'newListId', - namespaceType: 'single', + lists: [{ id: 'newListId', namespaceType: 'single' }], onError: onErrorMock, }); await waitForNextUpdate(); @@ -125,18 +133,17 @@ describe('useExceptionList', () => { >(() => useExceptionList({ http: mockKibanaHttpService, - id: 'myListId', - namespaceType: 'single', + lists: [{ id: 'myListId', namespaceType: 'single' }], onError: onErrorMock, }) ); await waitForNextUpdate(); await waitForNextUpdate(); - expect(typeof result.current[3]).toEqual('function'); + expect(typeof result.current[4]).toEqual('function'); - if (result.current[3] != null) { - result.current[3]({ listId: 'myListId', listNamespaceType: 'single' }); + if (result.current[4] != null) { + result.current[4](); } await waitForNextUpdate(); @@ -157,8 +164,7 @@ describe('useExceptionList', () => { () => useExceptionList({ http: mockKibanaHttpService, - id: 'myListId', - namespaceType: 'single', + lists: [{ id: 'myListId', namespaceType: 'single' }], onError: onErrorMock, }) ); @@ -180,8 +186,7 @@ describe('useExceptionList', () => { () => useExceptionList({ http: mockKibanaHttpService, - id: 'myListId', - namespaceType: 'single', + lists: [{ id: 'myListId', namespaceType: 'single' }], onError: onErrorMock, }) ); diff --git a/x-pack/plugins/lists/public/exceptions/hooks/use_exception_list.tsx b/x-pack/plugins/lists/public/exceptions/hooks/use_exception_list.tsx index c26d556fe8f25..1d7a63ba880bf 100644 --- a/x-pack/plugins/lists/public/exceptions/hooks/use_exception_list.tsx +++ b/x-pack/plugins/lists/public/exceptions/hooks/use_exception_list.tsx @@ -8,7 +8,7 @@ import { useEffect, useMemo, useRef, useState } from 'react'; import { fetchExceptionListById, fetchExceptionListItemsByListId } from '../api'; import { ExceptionIdentifiers, ExceptionList, Pagination, UseExceptionListProps } from '../types'; -import { ExceptionListItemSchema, ExceptionListSchema } from '../../../common/schemas'; +import { ExceptionListItemSchema } from '../../../common/schemas'; type Func = () => void; export type ReturnExceptionListAndItems = [ @@ -45,9 +45,7 @@ export const useExceptionList = ({ onError, dispatchListsInReducer, }: UseExceptionListProps): ReturnExceptionListAndItems => { - const [exceptionLists, setExceptionLists] = useState< - Array - >([]); + const [exceptionLists, setExceptionLists] = useState([]); const [exceptionItems, setExceptionListItems] = useState([]); const [paginationInfo, setPagination] = useState(pagination); const fetchExceptionList = useRef(null); @@ -142,10 +140,6 @@ export const useExceptionList = ({ onError(error); } } - - if (isSubscribed) { - setLoading(false); - } }; // TODO: Workaround for now. Once api updated, we can pass in array of lists to fetch @@ -155,6 +149,10 @@ export const useExceptionList = ({ fetchData({ id, namespaceType }) ) ); + + if (isSubscribed) { + setLoading(false); + } }; fetchLists(); diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exceptions_pagination.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exceptions_pagination.tsx index 48d15dd6ae333..fdbee42c4eea8 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exceptions_pagination.tsx +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exceptions_pagination.tsx @@ -71,7 +71,11 @@ const ExceptionsViewerPaginationComponent = ({ }, [pagination, onPaginationChange]); const totalPages = useMemo((): number => { - return Math.ceil(pagination.totalItemCount / pagination.pageSize); + if (pagination.totalItemCount > 0) { + return Math.ceil(pagination.totalItemCount / pagination.pageSize); + } else { + return 1; + } }, [pagination]); return ( diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/index.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/index.tsx index 31cff134d2dc4..946a98b19decd 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/index.tsx +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/index.tsx @@ -311,8 +311,8 @@ const ExceptionsViewerComponent = ({ }, [filterOptions.showEndpointList, filterOptions.showDetectionsList, ruleSettingsUrl]); const showEmpty = useMemo((): boolean => { - return !initLoading && exceptions.length === 0; - }, [initLoading, exceptions.length]); + return !initLoading && !loadingList && exceptions.length === 0; + }, [initLoading, exceptions.length, loadingList]); return ( <> From 6027cbb84a2e2ea1a98f41d1b4a056fb7920c328 Mon Sep 17 00:00:00 2001 From: Yara Tercero Date: Mon, 8 Jun 2020 22:44:35 -0400 Subject: [PATCH 28/32] updated and added more tests, cleaned up linter issues and per page selection bug --- .../__examples__/exception_item.stories.tsx | 11 +- .../exceptions_search.stories.tsx | 21 +-- .../common/components/exceptions/mocks.ts | 19 +++ .../common/components/exceptions/types.ts | 2 +- .../exception_item/exception_entries.test.tsx | 6 + .../viewer/exceptions_pagination.test.tsx | 158 ++++++++++++++++++ .../viewer/exceptions_pagination.tsx | 18 +- .../exceptions/viewer/index.test.tsx | 128 ++++++++++++++ .../components/exceptions/viewer/index.tsx | 3 +- .../components/exceptions/viewer/reducer.ts | 2 +- 10 files changed, 343 insertions(+), 25 deletions(-) create mode 100644 x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exceptions_pagination.test.tsx create mode 100644 x-pack/plugins/security_solution/public/common/components/exceptions/viewer/index.test.tsx diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/__examples__/exception_item.stories.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/__examples__/exception_item.stories.tsx index af3b20d14e690..8942832798a5e 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/__examples__/exception_item.stories.tsx +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/__examples__/exception_item.stories.tsx @@ -16,7 +16,7 @@ storiesOf('ExceptionItem', module) .add('with os', () => { const payload = getExceptionItemMock(); payload.description = ''; - payload.comments = []; + payload.comment = []; payload.entries = [ { field: 'actingProcess.file.signer', @@ -29,6 +29,7 @@ storiesOf('ExceptionItem', module) return ( ({ eui: euiLightVars, darkMode: false })}> {}} @@ -40,7 +41,7 @@ storiesOf('ExceptionItem', module) .add('with description', () => { const payload = getExceptionItemMock(); payload._tags = []; - payload.comments = []; + payload.comment = []; payload.entries = [ { field: 'actingProcess.file.signer', @@ -53,6 +54,7 @@ storiesOf('ExceptionItem', module) return ( ({ eui: euiLightVars, darkMode: false })}> {}} @@ -77,6 +79,7 @@ storiesOf('ExceptionItem', module) return ( ({ eui: euiLightVars, darkMode: false })}> {}} @@ -89,11 +92,12 @@ storiesOf('ExceptionItem', module) const payload = getExceptionItemMock(); payload._tags = []; payload.description = ''; - payload.comments = []; + payload.comment = []; return ( ({ eui: euiLightVars, darkMode: false })}> {}} @@ -108,6 +112,7 @@ storiesOf('ExceptionItem', module) return ( ({ eui: euiLightVars, darkMode: false })}> {}} diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/__examples__/exceptions_search.stories.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/__examples__/exceptions_search.stories.tsx index e9f93930c5919..29cded8f69165 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/__examples__/exceptions_search.stories.tsx +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/__examples__/exceptions_search.stories.tsx @@ -9,6 +9,7 @@ import { ThemeProvider } from 'styled-components'; import euiLightVars from '@elastic/eui/dist/eui_theme_light.json'; import { ExceptionsViewerHeader } from '../viewer/exceptions_viewer_header'; +import { ExceptionListType } from '../types'; storiesOf('ExceptionsViewerHeader', module) .add('loading', () => { @@ -18,10 +19,9 @@ storiesOf('ExceptionsViewerHeader', module) isInitLoading={true} detectionsListItems={5} endpointListItems={2000} - supportedListTypes={['a', 'b']} + supportedListTypes={[ExceptionListType.DETECTION_ENGINE, ExceptionListType.ENDPOINT]} onFilterChange={() => {}} - onAddEndpointExceptionClick={() => {}} - onAddDetectionsExceptionClick={() => {}} + onAddExceptionClick={() => {}} /> ); @@ -33,10 +33,9 @@ storiesOf('ExceptionsViewerHeader', module) isInitLoading={false} detectionsListItems={5} endpointListItems={2000} - supportedListTypes={['a', 'b']} + supportedListTypes={[ExceptionListType.DETECTION_ENGINE, ExceptionListType.ENDPOINT]} onFilterChange={() => {}} - onAddEndpointExceptionClick={() => {}} - onAddDetectionsExceptionClick={() => {}} + onAddExceptionClick={() => {}} /> ); @@ -48,10 +47,9 @@ storiesOf('ExceptionsViewerHeader', module) isInitLoading={false} detectionsListItems={0} endpointListItems={2000} - supportedListTypes={['a']} + supportedListTypes={[ExceptionListType.DETECTION_ENGINE]} onFilterChange={() => {}} - onAddEndpointExceptionClick={() => {}} - onAddDetectionsExceptionClick={() => {}} + onAddExceptionClick={() => {}} /> ); @@ -63,10 +61,9 @@ storiesOf('ExceptionsViewerHeader', module) isInitLoading={false} detectionsListItems={5} endpointListItems={0} - supportedListTypes={['a']} + supportedListTypes={[ExceptionListType.DETECTION_ENGINE]} onFilterChange={() => {}} - onAddEndpointExceptionClick={() => {}} - onAddDetectionsExceptionClick={() => {}} + onAddExceptionClick={() => {}} /> ); diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/mocks.ts b/x-pack/plugins/security_solution/public/common/components/exceptions/mocks.ts index 5b28cdd491beb..0dba3fd26c487 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/mocks.ts +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/mocks.ts @@ -11,6 +11,25 @@ import { NestedExceptionEntry, FormattedEntry, } from './types'; +import { ExceptionList } from '../../../lists_plugin_deps'; + +export const getExceptionListMock = (): ExceptionList => ({ + id: '5b543420', + created_at: '2020-04-23T00:19:13.289Z', + created_by: 'user_name', + list_id: 'test-exception', + tie_breaker_id: '77fd1909-6786-428a-a671-30229a719c1f', + updated_at: '2020-04-23T00:19:13.289Z', + updated_by: 'user_name', + namespace_type: 'single', + name: '', + description: 'This is a description', + _tags: ['os:windows'], + tags: [], + type: 'endpoint', + meta: {}, + totalItems: 0, +}); export const getExceptionItemEntryMock = (): ExceptionEntry => ({ field: 'actingProcess.file.signer', diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/types.ts b/x-pack/plugins/security_solution/public/common/components/exceptions/types.ts index 8364df81a6d8f..b56364bd7b952 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/types.ts +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/types.ts @@ -72,7 +72,7 @@ export interface FilterOptions { export interface Filter { filter: Partial; - pagination: Partial; + pagination: Partial; } export interface SetExceptionsProps { diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/exception_entries.test.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/exception_entries.test.tsx index 3d0e5a97f6d05..10f11231ace01 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/exception_entries.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/exception_entries.test.tsx @@ -18,6 +18,7 @@ describe('ExceptionEntries', () => { const wrapper = mount( ({ eui: euiLightVars, darkMode: false })}> { const wrapper = mount( ({ eui: euiLightVars, darkMode: false })}> { const wrapper = mount( ({ eui: euiLightVars, darkMode: false })}> { const wrapper = mount( ({ eui: euiLightVars, darkMode: false })}> { const wrapper = mount( ({ eui: euiLightVars, darkMode: false })}> { const wrapper = mount( ({ eui: euiLightVars, darkMode: false })}> { + it('it renders passed in "pageSize" as selected option', () => { + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + + expect(wrapper.find('[data-test-subj="exceptionsPerPageBtn"]').at(0).text()).toEqual( + 'Items per page: 50' + ); + }); + + it('it renders all passed in page size options when per page button clicked', () => { + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + + wrapper.find('[data-test-subj="exceptionsPerPageBtn"] button').simulate('click'); + + expect(wrapper.find('button[data-test-subj="exceptionsPerPageItem"]').at(0).text()).toEqual( + '20 items' + ); + expect(wrapper.find('button[data-test-subj="exceptionsPerPageItem"]').at(1).text()).toEqual( + '50 items' + ); + expect(wrapper.find('button[data-test-subj="exceptionsPerPageItem"]').at(2).text()).toEqual( + '100 items' + ); + }); + + it('it invokes "onPaginationChange" when per page item is clicked', () => { + const mockOnPaginationChange = jest.fn(); + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + + wrapper.find('[data-test-subj="exceptionsPerPageBtn"] button').simulate('click'); + wrapper.find('button[data-test-subj="exceptionsPerPageItem"]').at(0).simulate('click'); + + expect(mockOnPaginationChange).toHaveBeenCalledWith({ + filter: {}, + pagination: { pageIndex: 0, pageSize: 20, totalItemCount: 1 }, + }); + }); + + it('it renders correct total page count', () => { + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + + expect(wrapper.find('[data-test-subj="exceptionsPagination"]').at(0).prop('pageCount')).toEqual( + 4 + ); + expect( + wrapper.find('[data-test-subj="exceptionsPagination"]').at(0).prop('activePage') + ).toEqual(0); + }); + + it('it invokes "onPaginationChange" when next clicked', () => { + const mockOnPaginationChange = jest.fn(); + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + + wrapper.find('[data-test-subj="pagination-button-next"]').at(1).simulate('click'); + + expect(mockOnPaginationChange).toHaveBeenCalledWith({ + filter: {}, + pagination: { pageIndex: 2, pageSize: 50, totalItemCount: 160 }, + }); + }); + + it('it invokes "onPaginationChange" when page clicked', () => { + const mockOnPaginationChange = jest.fn(); + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + + wrapper.find('button[data-test-subj="pagination-button-3"]').simulate('click'); + + expect(mockOnPaginationChange).toHaveBeenCalledWith({ + filter: {}, + pagination: { pageIndex: 4, pageSize: 50, totalItemCount: 160 }, + }); + }); +}); diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exceptions_pagination.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exceptions_pagination.tsx index fdbee42c4eea8..0953a5c666c5d 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exceptions_pagination.tsx +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exceptions_pagination.tsx @@ -40,9 +40,9 @@ const ExceptionsViewerPaginationComponent = ({ onPaginationChange({ filter: {}, pagination: { - page: pageIndex + 1, - perPage: pagination.pageSize, - total: pagination.totalItemCount, + pageIndex: pageIndex + 1, + pageSize: pagination.pageSize, + totalItemCount: pagination.totalItemCount, }, }); }, @@ -58,17 +58,19 @@ const ExceptionsViewerPaginationComponent = ({ onPaginationChange({ filter: {}, pagination: { - page: pagination.pageIndex, - perPage: rows, - total: pagination.totalItemCount, + pageIndex: pagination.pageIndex, + pageSize: rows, + totalItemCount: pagination.totalItemCount, }, }); + closePerPageMenu(); }} + data-test-subj="exceptionsPerPageItem" > {i18n.NUMBER_OF_ITEMS(rows)}
)); - }, [pagination, onPaginationChange]); + }, [pagination, onPaginationChange, closePerPageMenu]); const totalPages = useMemo((): number => { if (pagination.totalItemCount > 0) { @@ -89,6 +91,7 @@ const ExceptionsViewerPaginationComponent = ({ iconType="arrowDown" iconSide="right" onClick={onPerPageMenuClick} + data-test-subj="exceptionsPerPageBtn" > {i18n.ITEMS_PER_PAGE(pagination.pageSize)} @@ -106,6 +109,7 @@ const ExceptionsViewerPaginationComponent = ({ pageCount={totalPages} activePage={pagination.pageIndex} onPageClick={onPageClick} + data-test-subj="exceptionsPagination" />
diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/index.test.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/index.test.tsx new file mode 100644 index 0000000000000..cc8e8111064bc --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/index.test.tsx @@ -0,0 +1,128 @@ +/* + * 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 React from 'react'; +import { ThemeProvider } from 'styled-components'; +import { mount } from 'enzyme'; +import euiLightVars from '@elastic/eui/dist/eui_theme_light.json'; + +import { ExceptionsViewer } from './'; +import { ExceptionListType } from '../types'; +import { useKibana } from '../../../../common/lib/kibana'; +import { useExceptionList, useApi } from '../../../../../public/lists_plugin_deps'; +import { getExceptionListMock } from '../mocks'; + +jest.mock('../../../../common/lib/kibana'); +jest.mock('../../../../../public/lists_plugin_deps'); + +describe('ExceptionsViewer', () => { + beforeEach(() => { + (useKibana as jest.Mock).mockReturnValue({ + services: { + http: {}, + application: { + getUrlForApp: () => 'some/url', + }, + }, + }); + + (useApi as jest.Mock).mockReturnValue({ + deleteExceptionItem: jest.fn().mockResolvedValue(true), + }); + + (useExceptionList as jest.Mock).mockReturnValue([ + false, + [], + [], + { + page: 1, + perPage: 20, + total: 0, + }, + jest.fn(), + ]); + }); + + it('it renders loader if "initLoading" is true', () => { + (useExceptionList as jest.Mock).mockReturnValue([ + true, + [], + [], + { + page: 1, + perPage: 20, + total: 0, + }, + jest.fn(), + ]); + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + + expect(wrapper.find('[data-test-subj="loadingPanelAllRulesTable"]').exists()).toBeTruthy(); + }); + + it('it renders empty prompt if no "exceptionListMeta" passed in', () => { + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + + expect(wrapper.find('[data-test-subj="exceptionsEmptyPrompt"]').exists()).toBeTruthy(); + }); + + it('it renders empty prompt if no exception items exist', () => { + (useExceptionList as jest.Mock).mockReturnValue([ + false, + [getExceptionListMock()], + [], + { + page: 1, + perPage: 20, + total: 0, + }, + jest.fn(), + ]); + + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + + expect(wrapper.find('[data-test-subj="exceptionsEmptyPrompt"]').exists()).toBeTruthy(); + }); +}); diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/index.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/index.tsx index 946a98b19decd..4a7e5772d4b2d 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/index.tsx +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/index.tsx @@ -259,7 +259,7 @@ const ExceptionsViewerComponent = ({ // Logic for initial render useEffect((): void => { - if (initLoading && (exceptions.length === 0 || exceptions != null)) { + if (initLoading && !loadingList && (exceptions.length === 0 || exceptions != null)) { setInitLoading(false); } }, [initLoading, exceptions, loadingList]); @@ -373,6 +373,7 @@ const ExceptionsViewerComponent = ({ iconType="advancedSettingsApp" title={

{i18n.EXCEPTION_EMPTY_PROMPT_TITLE}

} body={

{i18n.EXCEPTION_EMPTY_PROMPT_BODY}

} + data-test-subj="exceptionsEmptyPrompt" /> )} diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/reducer.ts b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/reducer.ts index 121a33741534c..40d5bb5f0a297 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/reducer.ts +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/reducer.ts @@ -34,7 +34,7 @@ export type Action = | { type: 'updateFilterOptions'; filterOptions: Partial; - pagination: Partial; + pagination: Partial; } | { type: 'updateModalOpen'; isOpen: boolean } | { type: 'updateExceptionToEdit'; exception: ExceptionListItemSchema } From d25ccdf0f2c4838dd1e420e43f1de7fb3e798184 Mon Sep 17 00:00:00 2001 From: Yara Tercero Date: Tue, 9 Jun 2020 16:03:17 -0400 Subject: [PATCH 29/32] updating viewer ux per feedback --- .../detection_engine/rules/details/index.tsx | 14 +- .../common/components/exceptions/types.ts | 8 +- .../viewer/exceptions_viewer_header.tsx | 5 +- .../components/exceptions/viewer/index.tsx | 164 +++++++++++------- .../components/exceptions/viewer/reducer.ts | 24 ++- 5 files changed, 139 insertions(+), 76 deletions(-) diff --git a/x-pack/plugins/security_solution/public/alerts/pages/detection_engine/rules/details/index.tsx b/x-pack/plugins/security_solution/public/alerts/pages/detection_engine/rules/details/index.tsx index 0e527bf4dfc72..591902d12f59b 100644 --- a/x-pack/plugins/security_solution/public/alerts/pages/detection_engine/rules/details/index.tsx +++ b/x-pack/plugins/security_solution/public/alerts/pages/detection_engine/rules/details/index.tsx @@ -6,6 +6,7 @@ /* eslint-disable react-hooks/rules-of-hooks */ /* eslint-disable complexity */ +// TODO: Disabling complexity is temporary till this component is refactored as part of lists UI integration import { EuiButton, @@ -404,7 +405,18 @@ export const RuleDetailsPageComponent: FC = ({ ExceptionListType.ENDPOINT, ]} commentsAccordionId={'ruleDetailsTabExceptions'} - exceptionListsMeta={[]} + exceptionListsMeta={[ + { + id: '5b543420-a6c3-11ea-989f-53aa81611022', + type: 'endpoint', + namespaceType: 'single', + }, + { + id: '98440bc0-a750-11ea-989f-53aa81611022', + type: 'detection', + namespaceType: 'single', + }, + ]} /> )} {ruleDetailTab === RuleDetailTabs.failures && } diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/types.ts b/x-pack/plugins/security_solution/public/common/components/exceptions/types.ts index b56364bd7b952..d60d1ef71e502 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/types.ts +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/types.ts @@ -5,7 +5,11 @@ */ import { ReactNode } from 'react'; -import { NamespaceType, ExceptionList } from '../../../lists_plugin_deps'; +import { + NamespaceType, + ExceptionList, + ExceptionListItemSchema as ExceptionItem, +} from '../../../lists_plugin_deps'; export interface OperatorOption { message: string; @@ -77,7 +81,7 @@ export interface Filter { export interface SetExceptionsProps { lists: ExceptionList[]; - exceptions: ExceptionListItemSchema[]; + exceptions: ExceptionItem[]; pagination: Pagination; } diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exceptions_viewer_header.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exceptions_viewer_header.tsx index 92a8830310b51..0a630414e3267 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exceptions_viewer_header.tsx +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exceptions_viewer_header.tsx @@ -69,8 +69,7 @@ const ExceptionsViewerHeaderComponent = ({ }, [showEndpointList, setShowEndpointList, setShowDetectionsList]); const handleOnSearch = useCallback( - (event: React.ChangeEvent): void => { - const searchValue = event.target.value; + (searchValue: string): void => { const tagsRegex = /(tags:[^\s]*)/i; const tagsMatch = searchValue.match(tagsRegex); const foundTags: string = tagsMatch != null ? tagsMatch[0].split(':')[1] : ''; @@ -121,7 +120,7 @@ const ExceptionsViewerHeaderComponent = ({ data-test-subj="exceptionsHeaderSearch" aria-label={i18n.SEARCH_DEFAULT} placeholder={i18n.SEARCH_DEFAULT} - onChange={handleOnSearch} + onSearch={handleOnSearch} disabled={isInitLoading} incremental={false} fullWidth diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/index.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/index.tsx index 4a7e5772d4b2d..97d42f07c5086 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/index.tsx +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/index.tsx @@ -55,7 +55,19 @@ const StyledText = styled(EuiText)` font-style: italic; `; -const MyExceptionsContainer = styled.div` +const MyFlexItem = styled(EuiFlexItem)` + margin: ${({ theme }) => `${theme.eui.euiSize} 0`}; + + &:first-child { + margin: ${({ theme }) => `${theme.eui.euiSizeXS} 0 ${theme.eui.euiSize}`}; + } +`; + +const MyUtilities = styled(EuiFlexGroup)` + height: 50px; +`; + +const MyExceptionsContainer = styled(EuiFlexGroup)` height: 600px; overflow: hidden; `; @@ -73,7 +85,9 @@ const initialState: State = { allExceptions: [], exceptions: [], exceptionToEdit: null, + loadingLists: [], loadingItemIds: [], + isLoading: false, isModalOpen: false, }; @@ -122,11 +136,13 @@ const ExceptionsViewerComponent = ({ exceptions, filterOptions, pagination, + loadingLists, loadingItemIds, + isLoading, isModalOpen, }, dispatch, - ] = useReducer(allExceptionItemsReducer(), initialState); + ] = useReducer(allExceptionItemsReducer(), { ...initialState, loadingLists: exceptionListsMeta }); const setExceptions = useCallback( ({ @@ -137,7 +153,7 @@ const ExceptionsViewerComponent = ({ dispatch({ type: 'setExceptions', lists: newLists, - exceptions: newExceptions, + exceptions: (newExceptions as unknown) as ExceptionListItemSchema[], pagination: newPagination, }); }, @@ -145,7 +161,7 @@ const ExceptionsViewerComponent = ({ ); const [loadingList, , , , fetchList] = useExceptionList({ http: services.http, - lists: exceptionListsMeta, + lists: loadingLists, filterOptions, pagination: { page: pagination.pageIndex + 1, @@ -160,6 +176,16 @@ const ExceptionsViewerComponent = ({ }), }); + const setIsLoading = useCallback( + (loading: boolean): void => { + dispatch({ + type: 'updateIsLoading', + isLoading: loading, + }); + }, + [dispatch] + ); + const setIsModalOpen = useCallback( (isOpen: boolean): void => { dispatch({ @@ -172,9 +198,10 @@ const ExceptionsViewerComponent = ({ const onFetchList = useCallback((): void => { if (fetchList != null) { + setIsLoading(true); fetchList(); } - }, [fetchList]); + }, [fetchList, setIsLoading]); const onFiltersChange = useCallback( ({ filter, pagination: pag }: Filter): void => { @@ -182,9 +209,10 @@ const ExceptionsViewerComponent = ({ type: 'updateFilterOptions', filterOptions: filter, pagination: pag, + allLists: exceptionListsMeta, }); }, - [dispatch] + [dispatch, exceptionListsMeta] ); const onAddException = useCallback( @@ -329,7 +357,9 @@ const ExceptionsViewerComponent = ({ )} - {initLoading && } + {(initLoading || isLoading) && ( + + )} - {(filterOptions.showEndpointList || filterOptions.showDetectionsList) && ( - <> - - {exceptionsSubtext} - - )} - - - - - - {i18n.SHOWING_EXCEPTIONS(pagination.totalItemCount ?? 0)} - - - - - - {i18n.REFRESH} - - - - - - - - - {showEmpty && ( - {i18n.EXCEPTION_EMPTY_PROMPT_TITLE}} - body={

{i18n.EXCEPTION_EMPTY_PROMPT_BODY}

} - data-test-subj="exceptionsEmptyPrompt" - /> + + + + + + + {i18n.SHOWING_EXCEPTIONS(pagination.totalItemCount ?? 0)} + + + + + + {i18n.REFRESH} + + + + + + + {exceptionsSubtext} + + + + + {showEmpty ? ( + + {i18n.EXCEPTION_EMPTY_PROMPT_TITLE}} + body={

{i18n.EXCEPTION_EMPTY_PROMPT_BODY}

} + data-test-subj="exceptionsEmptyPrompt" + /> +
+ ) : ( + + + {!initLoading && + exceptions.length > 0 && + exceptions.map((exception, index) => ( + + {index !== 0 ? ( + <> + + + + ) : ( + + )} + + + ))} + + )} - - - - - {!initLoading && - exceptions.length > 0 && - exceptions.map((exception, index) => ( - - {index !== 0 && ( - <> - - - - )} - - - ))} -
diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/reducer.ts b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/reducer.ts index 40d5bb5f0a297..436d5a6f2944d 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/reducer.ts +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/reducer.ts @@ -10,7 +10,7 @@ import { ExceptionListItemSchema, Pagination, } from '../types'; -import { ExceptionList } from '../../../../../public/lists_plugin_deps'; +import { ExceptionList, ExceptionIdentifiers } from '../../../../../public/lists_plugin_deps'; export interface State { filterOptions: FilterOptions; @@ -20,7 +20,9 @@ export interface State { allExceptions: ExceptionListItemSchema[]; exceptions: ExceptionListItemSchema[]; exceptionToEdit: ExceptionListItemSchema | null; + loadingLists: ExceptionIdentifiers[]; loadingItemIds: ApiProps[]; + isLoading: boolean; isModalOpen: boolean; } @@ -35,7 +37,9 @@ export type Action = type: 'updateFilterOptions'; filterOptions: Partial; pagination: Partial; + allLists: ExceptionIdentifiers[]; } + | { type: 'updateIsLoading'; isLoading: boolean } | { type: 'updateModalOpen'; isOpen: boolean } | { type: 'updateExceptionToEdit'; exception: ExceptionListItemSchema } | { type: 'updateLoadingItemIds'; items: ApiProps[] }; @@ -62,6 +66,7 @@ export const allExceptionItemsReducer = () => (state: State, action: Action): St }, allExceptions: action.exceptions, exceptions: action.exceptions, + isLoading: false, }; } case 'updateFilterOptions': { @@ -75,29 +80,36 @@ export const allExceptionItemsReducer = () => (state: State, action: Action): St ...state.pagination, ...action.pagination, }, + isLoading: true, }; if (action.filterOptions.showEndpointList) { - const exceptions = state.allExceptions.filter((t) => t._tags.includes('endpoint')); + const list = action.allLists.filter((t) => t.type === 'endpoint'); return { ...returnState, - exceptions, + loadingLists: list, }; } else if (action.filterOptions.showDetectionsList) { - const exceptions = state.allExceptions.filter((t) => t._tags.includes('detection')); + const list = action.allLists.filter((t) => t.type === 'detection'); return { ...returnState, - exceptions, + loadingLists: list, }; } else { return { ...returnState, - exceptions: state.allExceptions, + loadingLists: action.allLists, }; } } + case 'updateIsLoading': { + return { + ...state, + isLoading: action.isLoading, + }; + } case 'updateLoadingItemIds': { return { ...state, From 700e6bfbd59232d89706dd1deced7b36ed597614 Mon Sep 17 00:00:00 2001 From: Yara Tercero Date: Tue, 9 Jun 2020 21:36:06 -0400 Subject: [PATCH 30/32] added tests and cleaned up --- .../lists/public/exceptions/__mocks__/api.ts | 15 + .../public/exceptions/hooks/use_api.test.tsx | 257 ++++++++++++++++++ .../hooks/use_exception_list.test.tsx | 16 +- .../exceptions/hooks/use_exception_list.tsx | 10 +- .../plugins/lists/public/exceptions/types.ts | 16 +- .../exceptions/viewer/exeptions_utility.tsx | 106 ++++++++ .../components/exceptions/viewer/index.tsx | 89 +----- 7 files changed, 411 insertions(+), 98 deletions(-) create mode 100644 x-pack/plugins/lists/public/exceptions/hooks/use_api.test.tsx create mode 100644 x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exeptions_utility.tsx diff --git a/x-pack/plugins/lists/public/exceptions/__mocks__/api.ts b/x-pack/plugins/lists/public/exceptions/__mocks__/api.ts index ecc771279b3ab..9651be0d04e8c 100644 --- a/x-pack/plugins/lists/public/exceptions/__mocks__/api.ts +++ b/x-pack/plugins/lists/public/exceptions/__mocks__/api.ts @@ -54,3 +54,18 @@ export const fetchExceptionListItemById = async ({ signal, }: ApiCallByIdProps): Promise => Promise.resolve(getExceptionListItemSchemaMock()); + +export const deleteExceptionListById = async ({ + http, + id, + namespaceType, + signal, +}: ApiCallByIdProps): Promise => Promise.resolve(getExceptionListSchemaMock()); + +export const deleteExceptionListItemById = async ({ + http, + id, + namespaceType, + signal, +}: ApiCallByIdProps): Promise => + Promise.resolve(getExceptionListItemSchemaMock()); diff --git a/x-pack/plugins/lists/public/exceptions/hooks/use_api.test.tsx b/x-pack/plugins/lists/public/exceptions/hooks/use_api.test.tsx new file mode 100644 index 0000000000000..edf65839c07cf --- /dev/null +++ b/x-pack/plugins/lists/public/exceptions/hooks/use_api.test.tsx @@ -0,0 +1,257 @@ +/* + * 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 { act, renderHook } from '@testing-library/react-hooks'; + +import * as api from '../api'; +import { createKibanaCoreStartMock } from '../../common/mocks/kibana_core'; +import { getExceptionListSchemaMock } from '../../../common/schemas/response/exception_list_schema.mock'; +import { getExceptionListItemSchemaMock } from '../../../common/schemas/response/exception_list_item_schema.mock'; +import { HttpStart } from '../../../../../../src/core/public'; +import { ApiCallByIdProps } from '../types'; + +import { ExceptionsApi, useApi } from './use_api'; + +jest.mock('../api'); + +const mockKibanaHttpService = createKibanaCoreStartMock().http; + +describe('useApi', () => { + const onErrorMock = jest.fn(); + + afterEach(() => { + onErrorMock.mockClear(); + jest.clearAllMocks(); + }); + + test('it invokes "deleteExceptionListItemById" when "deleteExceptionItem" used', async () => { + const payload = getExceptionListItemSchemaMock(); + const onSuccessMock = jest.fn(); + const spyOnDeleteExceptionListItemById = jest + .spyOn(api, 'deleteExceptionListItemById') + .mockResolvedValue(payload); + + await act(async () => { + const { result, waitForNextUpdate } = renderHook(() => + useApi(mockKibanaHttpService) + ); + await waitForNextUpdate(); + + const { id, namespace_type: namespaceType } = payload; + + await result.current.deleteExceptionItem({ + id, + namespaceType, + onError: jest.fn(), + onSuccess: onSuccessMock, + }); + + const expected: ApiCallByIdProps = { + http: mockKibanaHttpService, + id, + namespaceType, + signal: new AbortController().signal, + }; + + expect(spyOnDeleteExceptionListItemById).toHaveBeenCalledWith(expected); + expect(onSuccessMock).toHaveBeenCalled(); + }); + }); + + test('invokes "onError" callback if "deleteExceptionListItemById" fails', async () => { + const mockError = new Error('failed to delete item'); + jest.spyOn(api, 'deleteExceptionListItemById').mockRejectedValue(mockError); + + await act(async () => { + const { result, waitForNextUpdate } = renderHook(() => + useApi(mockKibanaHttpService) + ); + await waitForNextUpdate(); + + const { id, namespace_type: namespaceType } = getExceptionListItemSchemaMock(); + + await result.current.deleteExceptionItem({ + id, + namespaceType, + onError: onErrorMock, + onSuccess: jest.fn(), + }); + + expect(onErrorMock).toHaveBeenCalledWith(mockError); + }); + }); + + test('it invokes "deleteExceptionListById" when "deleteExceptionList" used', async () => { + const payload = getExceptionListSchemaMock(); + const onSuccessMock = jest.fn(); + const spyOnDeleteExceptionListById = jest + .spyOn(api, 'deleteExceptionListById') + .mockResolvedValue(payload); + + await act(async () => { + const { result, waitForNextUpdate } = renderHook(() => + useApi(mockKibanaHttpService) + ); + await waitForNextUpdate(); + + const { id, namespace_type: namespaceType } = payload; + + await result.current.deleteExceptionList({ + id, + namespaceType, + onError: jest.fn(), + onSuccess: onSuccessMock, + }); + + const expected: ApiCallByIdProps = { + http: mockKibanaHttpService, + id, + namespaceType, + signal: new AbortController().signal, + }; + + expect(spyOnDeleteExceptionListById).toHaveBeenCalledWith(expected); + expect(onSuccessMock).toHaveBeenCalled(); + }); + }); + + test('invokes "onError" callback if "deleteExceptionListById" fails', async () => { + const mockError = new Error('failed to delete item'); + jest.spyOn(api, 'deleteExceptionListById').mockRejectedValue(mockError); + + await act(async () => { + const { result, waitForNextUpdate } = renderHook(() => + useApi(mockKibanaHttpService) + ); + await waitForNextUpdate(); + + const { id, namespace_type: namespaceType } = getExceptionListSchemaMock(); + + await result.current.deleteExceptionList({ + id, + namespaceType, + onError: onErrorMock, + onSuccess: jest.fn(), + }); + + expect(onErrorMock).toHaveBeenCalledWith(mockError); + }); + }); + + test('it invokes "fetchExceptionListItemById" when "getExceptionItem" used', async () => { + const payload = getExceptionListItemSchemaMock(); + const onSuccessMock = jest.fn(); + const spyOnFetchExceptionListItemById = jest + .spyOn(api, 'fetchExceptionListItemById') + .mockResolvedValue(payload); + + await act(async () => { + const { result, waitForNextUpdate } = renderHook(() => + useApi(mockKibanaHttpService) + ); + await waitForNextUpdate(); + + const { id, namespace_type: namespaceType } = payload; + + await result.current.getExceptionItem({ + id, + namespaceType, + onError: jest.fn(), + onSuccess: onSuccessMock, + }); + + const expected: ApiCallByIdProps = { + http: mockKibanaHttpService, + id, + namespaceType, + signal: new AbortController().signal, + }; + + expect(spyOnFetchExceptionListItemById).toHaveBeenCalledWith(expected); + expect(onSuccessMock).toHaveBeenCalled(); + }); + }); + + test('invokes "onError" callback if "fetchExceptionListItemById" fails', async () => { + const mockError = new Error('failed to delete item'); + jest.spyOn(api, 'fetchExceptionListItemById').mockRejectedValue(mockError); + + await act(async () => { + const { result, waitForNextUpdate } = renderHook(() => + useApi(mockKibanaHttpService) + ); + await waitForNextUpdate(); + + const { id, namespace_type: namespaceType } = getExceptionListSchemaMock(); + + await result.current.getExceptionItem({ + id, + namespaceType, + onError: onErrorMock, + onSuccess: jest.fn(), + }); + + expect(onErrorMock).toHaveBeenCalledWith(mockError); + }); + }); + + test('it invokes "fetchExceptionListById" when "getExceptionList" used', async () => { + const payload = getExceptionListSchemaMock(); + const onSuccessMock = jest.fn(); + const spyOnFetchExceptionListById = jest + .spyOn(api, 'fetchExceptionListById') + .mockResolvedValue(payload); + + await act(async () => { + const { result, waitForNextUpdate } = renderHook(() => + useApi(mockKibanaHttpService) + ); + await waitForNextUpdate(); + + const { id, namespace_type: namespaceType } = payload; + + await result.current.getExceptionList({ + id, + namespaceType, + onError: jest.fn(), + onSuccess: onSuccessMock, + }); + + const expected: ApiCallByIdProps = { + http: mockKibanaHttpService, + id, + namespaceType, + signal: new AbortController().signal, + }; + + expect(spyOnFetchExceptionListById).toHaveBeenCalledWith(expected); + expect(onSuccessMock).toHaveBeenCalled(); + }); + }); + + test('invokes "onError" callback if "fetchExceptionListById" fails', async () => { + const mockError = new Error('failed to delete item'); + jest.spyOn(api, 'fetchExceptionListById').mockRejectedValue(mockError); + + await act(async () => { + const { result, waitForNextUpdate } = renderHook(() => + useApi(mockKibanaHttpService) + ); + await waitForNextUpdate(); + + const { id, namespace_type: namespaceType } = getExceptionListSchemaMock(); + + await result.current.getExceptionList({ + id, + namespaceType, + onError: onErrorMock, + onSuccess: jest.fn(), + }); + + expect(onErrorMock).toHaveBeenCalledWith(mockError); + }); + }); +}); diff --git a/x-pack/plugins/lists/public/exceptions/hooks/use_exception_list.test.tsx b/x-pack/plugins/lists/public/exceptions/hooks/use_exception_list.test.tsx index fbd43787a822e..eeb3ac63ee318 100644 --- a/x-pack/plugins/lists/public/exceptions/hooks/use_exception_list.test.tsx +++ b/x-pack/plugins/lists/public/exceptions/hooks/use_exception_list.test.tsx @@ -11,7 +11,7 @@ import { createKibanaCoreStartMock } from '../../common/mocks/kibana_core'; import { getExceptionListSchemaMock } from '../../../common/schemas/response/exception_list_schema.mock'; import { getExceptionListItemSchemaMock } from '../../../common/schemas/response/exception_list_item_schema.mock'; import { ExceptionListItemSchema } from '../../../common/schemas'; -import { ExceptionList, UseExceptionListProps } from '../types'; +import { ExceptionList, UseExceptionListProps, UseExceptionListSuccess } from '../types'; import { ReturnExceptionListAndItems, useExceptionList } from './use_exception_list'; @@ -57,6 +57,7 @@ describe('useExceptionList', () => { test('fetch exception list and items', async () => { await act(async () => { + const onSuccessMock = jest.fn(); const { result, waitForNextUpdate } = renderHook< UseExceptionListProps, ReturnExceptionListAndItems @@ -65,6 +66,7 @@ describe('useExceptionList', () => { http: mockKibanaHttpService, lists: [{ id: 'myListId', namespaceType: 'single' }], onError: onErrorMock, + onSuccess: onSuccessMock, }) ); await waitForNextUpdate(); @@ -78,6 +80,12 @@ describe('useExceptionList', () => { { ...getExceptionListItemSchemaMock() }, ]; + const expectedResult: UseExceptionListSuccess = { + exceptions: expectedListItemsResult, + lists: expectedListResult, + pagination: { page: 1, perPage: 20, total: 1 }, + }; + expect(result.current).toEqual([ false, expectedListResult, @@ -89,6 +97,7 @@ describe('useExceptionList', () => { }, result.current[4], ]); + expect(onSuccessMock).toHaveBeenCalledWith(expectedResult); }); }); @@ -100,13 +109,14 @@ describe('useExceptionList', () => { UseExceptionListProps, ReturnExceptionListAndItems >( - ({ filterOptions, http, lists, pagination, onError }) => - useExceptionList({ filterOptions, http, lists, onError, pagination }), + ({ filterOptions, http, lists, pagination, onError, onSuccess }) => + useExceptionList({ filterOptions, http, lists, onError, onSuccess, pagination }), { initialProps: { http: mockKibanaHttpService, lists: [{ id: 'myListId', namespaceType: 'single' }], onError: onErrorMock, + onSuccess: jest.fn(), }, } ); diff --git a/x-pack/plugins/lists/public/exceptions/hooks/use_exception_list.tsx b/x-pack/plugins/lists/public/exceptions/hooks/use_exception_list.tsx index 1d7a63ba880bf..9595cb7b7558e 100644 --- a/x-pack/plugins/lists/public/exceptions/hooks/use_exception_list.tsx +++ b/x-pack/plugins/lists/public/exceptions/hooks/use_exception_list.tsx @@ -23,9 +23,9 @@ export type ReturnExceptionListAndItems = [ * Hook for using to get an ExceptionList and it's ExceptionListItems * * @param http Kibana http service - * @param id desired ExceptionList ID (not list_id) - * @param namespaceType list namespaceType determines list space + * @param lists array of ExceptionIdentifiers for all lists to fetch * @param onError error callback + * @param onSuccess callback when all lists fetched successfully * @param filterOptions optional - filter by fields or tags * @param pagination optional * @@ -43,7 +43,7 @@ export const useExceptionList = ({ tags: [], }, onError, - dispatchListsInReducer, + onSuccess, }: UseExceptionListProps): ReturnExceptionListAndItems => { const [exceptionLists, setExceptionLists] = useState([]); const [exceptionItems, setExceptionListItems] = useState([]); @@ -116,8 +116,8 @@ export const useExceptionList = ({ exceptions = [...exceptions, ...fetchListItemsResult.data]; setExceptionListItems(exceptions); - if (dispatchListsInReducer != null) { - dispatchListsInReducer({ + if (onSuccess != null) { + onSuccess({ exceptions, lists: exceptionListsReturned, pagination: { diff --git a/x-pack/plugins/lists/public/exceptions/types.ts b/x-pack/plugins/lists/public/exceptions/types.ts index 286eb0570ebb8..013788cddc076 100644 --- a/x-pack/plugins/lists/public/exceptions/types.ts +++ b/x-pack/plugins/lists/public/exceptions/types.ts @@ -37,21 +37,19 @@ export interface ExceptionList extends ExceptionListSchema { totalItems: number; } +export interface UseExceptionListSuccess { + lists: ExceptionList[]; + exceptions: ExceptionListItemSchema[]; + pagination: Pagination; +} + export interface UseExceptionListProps { http: HttpStart; lists: ExceptionIdentifiers[]; onError: (arg: Error) => void; filterOptions?: FilterExceptionsOptions; pagination?: Pagination; - dispatchListsInReducer?: ({ - lists, - exceptions, - pagination, - }: { - lists: ExceptionList[]; - exceptions: ExceptionListItemSchema[]; - pagination: Pagination; - }) => void; + onSuccess?: (arg: UseExceptionListSuccess) => void; } export interface ExceptionIdentifiers { diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exeptions_utility.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exeptions_utility.tsx new file mode 100644 index 0000000000000..2051c1eead1f9 --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exeptions_utility.tsx @@ -0,0 +1,106 @@ +/* + * 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 React from 'react'; +import { EuiText, EuiLink, EuiFlexGroup, EuiFlexItem } from '@elastic/eui'; +import { FormattedMessage } from 'react-intl'; +import styled from 'styled-components'; + +import * as i18n from '../translations'; +import { ExceptionsPagination, FilterOptions } from '../types'; +import { + UtilityBar, + UtilityBarSection, + UtilityBarGroup, + UtilityBarText, + UtilityBarAction, +} from '../../utility_bar'; + +const StyledText = styled(EuiText)` + font-style: italic; +`; + +const MyUtilities = styled(EuiFlexGroup)` + height: 50px; +`; + +interface ExceptionsViewerUtilityProps { + pagination: ExceptionsPagination; + filterOptions: FilterOptions; + ruleSettingsUrl: string; + onRefreshClick: () => void; +} + +const ExceptionsViewerUtilityComponent = ({ + pagination, + filterOptions, + ruleSettingsUrl, + onRefreshClick, +}: ExceptionsViewerUtilityProps): JSX.Element => { + return ( + + + + + + + {i18n.SHOWING_EXCEPTIONS(pagination.totalItemCount ?? 0)} + + + + + + {i18n.REFRESH} + + + + + + + + {filterOptions.showEndpointList && ( + + + + ), + }} + /> + )} + {filterOptions.showDetectionsList && ( + + + + ), + }} + /> + )} + + + + ); +}; + +ExceptionsViewerUtilityComponent.displayName = 'ExceptionsViewerUtilityComponent'; + +export const ExceptionsViewerUtility = React.memo(ExceptionsViewerUtilityComponent); + +ExceptionsViewerUtility.displayName = 'ExceptionsViewerUtility'; diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/index.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/index.tsx index 97d42f07c5086..3d1528ce77094 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/index.tsx +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/index.tsx @@ -7,8 +7,6 @@ import React, { useCallback, useState, useMemo, useEffect, useReducer } from 'react'; import { EuiEmptyPrompt, - EuiText, - EuiLink, EuiOverlayMask, EuiModal, EuiModalBody, @@ -17,7 +15,6 @@ import { EuiFlexItem, EuiSpacer, } from '@elastic/eui'; -import { FormattedMessage } from 'react-intl'; import styled from 'styled-components'; import uuid from 'uuid'; @@ -43,17 +40,7 @@ import { import { ExceptionItem } from './exception_item'; import { AndOrBadge } from '../../and_or_badge'; import { ExceptionsViewerPagination } from './exceptions_pagination'; -import { - UtilityBar, - UtilityBarSection, - UtilityBarGroup, - UtilityBarText, - UtilityBarAction, -} from '../../utility_bar'; - -const StyledText = styled(EuiText)` - font-style: italic; -`; +import { ExceptionsViewerUtility } from './exeptions_utility'; const MyFlexItem = styled(EuiFlexItem)` margin: ${({ theme }) => `${theme.eui.euiSize} 0`}; @@ -63,10 +50,6 @@ const MyFlexItem = styled(EuiFlexItem)` } `; -const MyUtilities = styled(EuiFlexGroup)` - height: 50px; -`; - const MyExceptionsContainer = styled(EuiFlexGroup)` height: 600px; overflow: hidden; @@ -168,7 +151,7 @@ const ExceptionsViewerComponent = ({ perPage: pagination.pageSize, total: pagination.totalItemCount, }, - dispatchListsInReducer: setExceptions, + onSuccess: setExceptions, onError: onDispatchToaster({ color: 'danger', title: i18n.FETCH_LIST_ERROR, @@ -298,46 +281,6 @@ const ExceptionsViewerComponent = ({ ); }, [ruleId, services.application]); - const exceptionsSubtext = useMemo((): JSX.Element => { - if (filterOptions.showEndpointList) { - return ( - - - - ), - }} - /> - ); - } else if (filterOptions.showDetectionsList) { - return ( - - - - ), - }} - /> - ); - } else { - return <>; - } - }, [filterOptions.showEndpointList, filterOptions.showDetectionsList, ruleSettingsUrl]); - const showEmpty = useMemo((): boolean => { return !initLoading && !loadingList && exceptions.length === 0; }, [initLoading, exceptions.length, loadingList]); @@ -372,28 +315,12 @@ const ExceptionsViewerComponent = ({ - - - - - - - {i18n.SHOWING_EXCEPTIONS(pagination.totalItemCount ?? 0)} - - - - - - {i18n.REFRESH} - - - - - - - {exceptionsSubtext} - - + Date: Wed, 10 Jun 2020 00:45:53 -0400 Subject: [PATCH 31/32] cleaned up viewer index component --- .../detection_engine/rules/details/index.tsx | 13 +- .../viewer/exceptions_viewer_items.tsx | 92 ++++++++++++++ .../components/exceptions/viewer/index.tsx | 120 ++++-------------- .../components/exceptions/viewer/reducer.ts | 10 +- 4 files changed, 136 insertions(+), 99 deletions(-) create mode 100644 x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exceptions_viewer_items.tsx diff --git a/x-pack/plugins/security_solution/public/alerts/pages/detection_engine/rules/details/index.tsx b/x-pack/plugins/security_solution/public/alerts/pages/detection_engine/rules/details/index.tsx index 0021cd2f20a4b..591902d12f59b 100644 --- a/x-pack/plugins/security_solution/public/alerts/pages/detection_engine/rules/details/index.tsx +++ b/x-pack/plugins/security_solution/public/alerts/pages/detection_engine/rules/details/index.tsx @@ -405,7 +405,18 @@ export const RuleDetailsPageComponent: FC = ({ ExceptionListType.ENDPOINT, ]} commentsAccordionId={'ruleDetailsTabExceptions'} - exceptionListsMeta={[]} + exceptionListsMeta={[ + { + id: '5b543420-a6c3-11ea-989f-53aa81611022', + type: 'endpoint', + namespaceType: 'single', + }, + { + id: '98440bc0-a750-11ea-989f-53aa81611022', + type: 'detection', + namespaceType: 'single', + }, + ]} /> )} {ruleDetailTab === RuleDetailTabs.failures && } diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exceptions_viewer_items.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exceptions_viewer_items.tsx new file mode 100644 index 0000000000000..7ef32c0ec73d7 --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exceptions_viewer_items.tsx @@ -0,0 +1,92 @@ +/* + * 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 React from 'react'; +import { EuiEmptyPrompt, EuiFlexGroup, EuiFlexItem, EuiSpacer } from '@elastic/eui'; +import styled from 'styled-components'; + +import * as i18n from '../translations'; +import { ExceptionListItemSchema, ApiProps } from '../types'; +import { ExceptionItem } from './exception_item'; +import { AndOrBadge } from '../../and_or_badge'; + +const MyFlexItem = styled(EuiFlexItem)` + margin: ${({ theme }) => `${theme.eui.euiSize} 0`}; + + &:first-child { + margin: ${({ theme }) => `${theme.eui.euiSizeXS} 0 ${theme.eui.euiSize}`}; + } +`; + +const MyExceptionsContainer = styled(EuiFlexGroup)` + height: 600px; + overflow: hidden; +`; + +const MyExceptionItemContainer = styled(EuiFlexGroup)` + margin: ${({ theme }) => `0 ${theme.eui.euiSize} ${theme.eui.euiSize} 0`}; +`; + +interface ExceptionsViewerItemsProps { + showEmpty: boolean; + isInitLoading: boolean; + exceptions: ExceptionListItemSchema[]; + loadingItemIds: ApiProps[]; + commentsAccordionId: string; + onDeleteException: (arg: ApiProps) => void; + onEditExceptionItem: (item: ExceptionListItemSchema) => void; +} + +export const ExceptionsViewerItems: React.FC = ({ + showEmpty, + isInitLoading, + exceptions, + loadingItemIds, + commentsAccordionId, + onDeleteException, + onEditExceptionItem, +}) => ( + + {showEmpty ? ( + + {i18n.EXCEPTION_EMPTY_PROMPT_TITLE}} + body={

{i18n.EXCEPTION_EMPTY_PROMPT_BODY}

} + data-test-subj="exceptionsEmptyPrompt" + /> +
+ ) : ( + + + {!isInitLoading && + exceptions.length > 0 && + exceptions.map((exception, index) => ( + + {index !== 0 ? ( + <> + + + + ) : ( + + )} + + + ))} + + + )} +
+); + +ExceptionsViewerItems.displayName = 'ExceptionsViewerItems'; diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/index.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/index.tsx index 3d1528ce77094..1318359945155 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/index.tsx +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/index.tsx @@ -4,18 +4,8 @@ * you may not use this file except in compliance with the Elastic License. */ -import React, { useCallback, useState, useMemo, useEffect, useReducer } from 'react'; -import { - EuiEmptyPrompt, - EuiOverlayMask, - EuiModal, - EuiModalBody, - EuiCodeBlock, - EuiFlexGroup, - EuiFlexItem, - EuiSpacer, -} from '@elastic/eui'; -import styled from 'styled-components'; +import React, { useCallback, useMemo, useEffect, useReducer } from 'react'; +import { EuiOverlayMask, EuiModal, EuiModalBody, EuiCodeBlock, EuiSpacer } from '@elastic/eui'; import uuid from 'uuid'; import * as i18n from '../translations'; @@ -37,23 +27,9 @@ import { ExceptionIdentifiers, useApi, } from '../../../../../public/lists_plugin_deps'; -import { ExceptionItem } from './exception_item'; -import { AndOrBadge } from '../../and_or_badge'; import { ExceptionsViewerPagination } from './exceptions_pagination'; import { ExceptionsViewerUtility } from './exeptions_utility'; - -const MyFlexItem = styled(EuiFlexItem)` - margin: ${({ theme }) => `${theme.eui.euiSize} 0`}; - - &:first-child { - margin: ${({ theme }) => `${theme.eui.euiSizeXS} 0 ${theme.eui.euiSize}`}; - } -`; - -const MyExceptionsContainer = styled(EuiFlexGroup)` - height: 600px; - overflow: hidden; -`; +import { ExceptionsViewerItems } from './exceptions_viewer_items'; const initialState: State = { filterOptions: { filter: '', showEndpointList: false, showDetectionsList: false, tags: [] }, @@ -70,7 +46,7 @@ const initialState: State = { exceptionToEdit: null, loadingLists: [], loadingItemIds: [], - isLoading: false, + isInitLoading: true, isModalOpen: false, }; @@ -96,7 +72,6 @@ const ExceptionsViewerComponent = ({ }: ExceptionsViewerProps): JSX.Element => { const { services } = useKibana(); const [, dispatchToaster] = useStateToaster(); - const [initLoading, setInitLoading] = useState(true); const onDispatchToaster = useCallback( ({ title, color, iconType }) => (): void => { dispatchToaster({ @@ -121,7 +96,7 @@ const ExceptionsViewerComponent = ({ pagination, loadingLists, loadingItemIds, - isLoading, + isInitLoading, isModalOpen, }, dispatch, @@ -159,16 +134,6 @@ const ExceptionsViewerComponent = ({ }), }); - const setIsLoading = useCallback( - (loading: boolean): void => { - dispatch({ - type: 'updateIsLoading', - isLoading: loading, - }); - }, - [dispatch] - ); - const setIsModalOpen = useCallback( (isOpen: boolean): void => { dispatch({ @@ -181,10 +146,9 @@ const ExceptionsViewerComponent = ({ const onFetchList = useCallback((): void => { if (fetchList != null) { - setIsLoading(true); fetchList(); } - }, [fetchList, setIsLoading]); + }, [fetchList]); const onFiltersChange = useCallback( ({ filter, pagination: pag }: Filter): void => { @@ -270,11 +234,15 @@ const ExceptionsViewerComponent = ({ // Logic for initial render useEffect((): void => { - if (initLoading && !loadingList && (exceptions.length === 0 || exceptions != null)) { - setInitLoading(false); + if (isInitLoading && !loadingList && (exceptions.length === 0 || exceptions != null)) { + dispatch({ + type: 'updateIsInitLoading', + loading: false, + }); } - }, [initLoading, exceptions, loadingList]); + }, [isInitLoading, exceptions, loadingList, dispatch]); + // Used in utility bar info text const ruleSettingsUrl = useMemo((): string => { return services.application.getUrlForApp( `security#/detections/rules/id/${encodeURI(ruleId)}/edit` @@ -282,8 +250,8 @@ const ExceptionsViewerComponent = ({ }, [ruleId, services.application]); const showEmpty = useMemo((): boolean => { - return !initLoading && !loadingList && exceptions.length === 0; - }, [initLoading, exceptions.length, loadingList]); + return !isInitLoading && !loadingList && exceptions.length === 0; + }, [isInitLoading, exceptions.length, loadingList]); return ( <> @@ -299,13 +267,13 @@ const ExceptionsViewerComponent = ({ )} - - {(initLoading || isLoading) && ( + + {(isInitLoading || loadingList) && ( )} - - {showEmpty ? ( - - {i18n.EXCEPTION_EMPTY_PROMPT_TITLE}} - body={

{i18n.EXCEPTION_EMPTY_PROMPT_BODY}

} - data-test-subj="exceptionsEmptyPrompt" - /> -
- ) : ( - - - {!initLoading && - exceptions.length > 0 && - exceptions.map((exception, index) => ( - - {index !== 0 ? ( - <> - - - - ) : ( - - )} - - - ))} - - - )} -
+ +
diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/reducer.ts b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/reducer.ts index 436d5a6f2944d..32cb4fe46e310 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/reducer.ts +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/reducer.ts @@ -22,7 +22,7 @@ export interface State { exceptionToEdit: ExceptionListItemSchema | null; loadingLists: ExceptionIdentifiers[]; loadingItemIds: ApiProps[]; - isLoading: boolean; + isInitLoading: boolean; isModalOpen: boolean; } @@ -39,7 +39,7 @@ export type Action = pagination: Partial; allLists: ExceptionIdentifiers[]; } - | { type: 'updateIsLoading'; isLoading: boolean } + | { type: 'updateIsInitLoading'; loading: boolean } | { type: 'updateModalOpen'; isOpen: boolean } | { type: 'updateExceptionToEdit'; exception: ExceptionListItemSchema } | { type: 'updateLoadingItemIds'; items: ApiProps[] }; @@ -66,7 +66,6 @@ export const allExceptionItemsReducer = () => (state: State, action: Action): St }, allExceptions: action.exceptions, exceptions: action.exceptions, - isLoading: false, }; } case 'updateFilterOptions': { @@ -80,7 +79,6 @@ export const allExceptionItemsReducer = () => (state: State, action: Action): St ...state.pagination, ...action.pagination, }, - isLoading: true, }; if (action.filterOptions.showEndpointList) { @@ -104,10 +102,10 @@ export const allExceptionItemsReducer = () => (state: State, action: Action): St }; } } - case 'updateIsLoading': { + case 'updateIsInitLoading': { return { ...state, - isLoading: action.isLoading, + isInitLoading: action.loading, }; } case 'updateLoadingItemIds': { From 5cde9371b774bcaad5e2343a5318118cd962dce3 Mon Sep 17 00:00:00 2001 From: Yara Tercero Date: Wed, 10 Jun 2020 13:40:41 -0400 Subject: [PATCH 32/32] updated stories and unit tests --- .../detection_engine/rules/details/index.tsx | 13 +- .../exceptions_search.stories.tsx | 70 ------- .../components/exceptions/translations.ts | 2 +- .../exception_item/exception_details.tsx | 6 +- .../exception_item/exception_entries.test.tsx | 35 +++- .../exception_item/exception_entries.tsx | 24 +-- .../exception_item/index.stories.tsx} | 53 ++++-- .../viewer/exception_item/index.test.tsx | 7 +- .../viewer/exceptions_pagination.tsx | 21 ++- .../viewer/exceptions_utility.test.tsx | 174 ++++++++++++++++++ .../exceptions/viewer/exceptions_utility.tsx | 111 +++++++++++ .../exceptions_viewer_header.stories.tsx | 67 +++++++ .../viewer/exceptions_viewer_header.test.tsx | 54 +----- .../viewer/exceptions_viewer_item.test.tsx | 147 +++++++++++++++ .../viewer/exceptions_viewer_items.tsx | 24 ++- .../exceptions/viewer/exeptions_utility.tsx | 106 ----------- .../exceptions/viewer/index.test.tsx | 2 +- .../components/exceptions/viewer/index.tsx | 31 ++-- .../components/exceptions/viewer/reducer.ts | 2 + 19 files changed, 642 insertions(+), 307 deletions(-) delete mode 100644 x-pack/plugins/security_solution/public/common/components/exceptions/__examples__/exceptions_search.stories.tsx rename x-pack/plugins/security_solution/public/common/components/exceptions/{__examples__/exception_item.stories.tsx => viewer/exception_item/index.stories.tsx} (66%) create mode 100644 x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exceptions_utility.test.tsx create mode 100644 x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exceptions_utility.tsx create mode 100644 x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exceptions_viewer_header.stories.tsx create mode 100644 x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exceptions_viewer_item.test.tsx delete mode 100644 x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exeptions_utility.tsx diff --git a/x-pack/plugins/security_solution/public/alerts/pages/detection_engine/rules/details/index.tsx b/x-pack/plugins/security_solution/public/alerts/pages/detection_engine/rules/details/index.tsx index 591902d12f59b..0021cd2f20a4b 100644 --- a/x-pack/plugins/security_solution/public/alerts/pages/detection_engine/rules/details/index.tsx +++ b/x-pack/plugins/security_solution/public/alerts/pages/detection_engine/rules/details/index.tsx @@ -405,18 +405,7 @@ export const RuleDetailsPageComponent: FC = ({ ExceptionListType.ENDPOINT, ]} commentsAccordionId={'ruleDetailsTabExceptions'} - exceptionListsMeta={[ - { - id: '5b543420-a6c3-11ea-989f-53aa81611022', - type: 'endpoint', - namespaceType: 'single', - }, - { - id: '98440bc0-a750-11ea-989f-53aa81611022', - type: 'detection', - namespaceType: 'single', - }, - ]} + exceptionListsMeta={[]} /> )} {ruleDetailTab === RuleDetailTabs.failures && } diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/__examples__/exceptions_search.stories.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/__examples__/exceptions_search.stories.tsx deleted file mode 100644 index 29cded8f69165..0000000000000 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/__examples__/exceptions_search.stories.tsx +++ /dev/null @@ -1,70 +0,0 @@ -/* - * 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 { storiesOf } from '@storybook/react'; -import React from 'react'; -import { ThemeProvider } from 'styled-components'; -import euiLightVars from '@elastic/eui/dist/eui_theme_light.json'; - -import { ExceptionsViewerHeader } from '../viewer/exceptions_viewer_header'; -import { ExceptionListType } from '../types'; - -storiesOf('ExceptionsViewerHeader', module) - .add('loading', () => { - return ( - ({ eui: euiLightVars, darkMode: false })}> - {}} - onAddExceptionClick={() => {}} - /> - - ); - }) - .add('all lists', () => { - return ( - ({ eui: euiLightVars, darkMode: false })}> - {}} - onAddExceptionClick={() => {}} - /> - - ); - }) - .add('endpoint only', () => { - return ( - ({ eui: euiLightVars, darkMode: false })}> - {}} - onAddExceptionClick={() => {}} - /> - - ); - }) - .add('detections only', () => { - return ( - ({ eui: euiLightVars, darkMode: false })}> - {}} - onAddExceptionClick={() => {}} - /> - - ); - }); diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/translations.ts b/x-pack/plugins/security_solution/public/common/components/exceptions/translations.ts index 23e9f64caf695..27dab7cf9db29 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/translations.ts +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/translations.ts @@ -135,5 +135,5 @@ export const REFRESH = i18n.translate('xpack.securitySolution.exceptions.utility export const SHOWING_EXCEPTIONS = (items: number) => i18n.translate('xpack.securitySolution.exceptions.utilityNumberExceptionsLabel', { values: { items }, - defaultMessage: 'Showing {items} exceptions', + defaultMessage: 'Showing {items} {items, plural, =1 {exception} other {exceptions}}', }); diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/exception_details.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/exception_details.tsx index 12287f7cd0fa9..ce7d1d499de6e 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/exception_details.tsx +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/exception_details.tsx @@ -19,7 +19,7 @@ import { DescriptionListItem, ExceptionListItemSchema } from '../../types'; import { getDescriptionListContent } from '../../helpers'; import * as i18n from '../../translations'; -const StyledExceptionDetails = styled(EuiFlexItem)` +const MyExceptionDetails = styled(EuiFlexItem)` ${({ theme }) => css` background-color: ${theme.eui.euiColorLightestShade}; padding: ${theme.eui.euiSize}; @@ -68,7 +68,7 @@ const ExceptionDetailsComponent = ({ }, [showComments, onCommentsClick, exceptionItem]); return ( - + @@ -82,7 +82,7 @@ const ExceptionDetailsComponent = ({ {commentsSection} - + ); }; diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/exception_entries.test.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/exception_entries.test.tsx index b2408a654b1c6..2d022591d9980 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/exception_entries.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/exception_entries.test.tsx @@ -44,7 +44,7 @@ describe('ExceptionEntries', () => { expect(wrapper.find('[data-test-subj="exceptionsViewerAndBadge"]')).toHaveLength(1); }); - test('it invokes "handlEdit" when edit button clicked', () => { + test('it invokes "onEdit" when edit button clicked', () => { const mockOnEdit = jest.fn(); const wrapper = mount( ({ eui: euiLightVars, darkMode: false })}> @@ -80,6 +80,39 @@ describe('ExceptionEntries', () => { expect(mockOnDelete).toHaveBeenCalledTimes(1); }); + test('it renders edit button disabled if "disableDelete" is "true"', () => { + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + const editBtn = wrapper.find('[data-test-subj="exceptionsViewerEditBtn"] button').at(0); + + expect(editBtn.prop('disabled')).toBeTruthy(); + }); + + test('it renders delete button in loading state if "disableDelete" is "true"', () => { + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + const deleteBtn = wrapper.find('[data-test-subj="exceptionsViewerDeleteBtn"] button').at(0); + + expect(deleteBtn.prop('disabled')).toBeTruthy(); + expect(deleteBtn.find('.euiLoadingSpinner')).toBeTruthy(); + }); + test('it renders nested entry', () => { const parentEntry = getFormattedEntryMock(); parentEntry.operator = null; diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/exception_entries.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/exception_entries.tsx index 8c758e3b84f42..58667f1f78b0d 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/exception_entries.tsx +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/exception_entries.tsx @@ -22,11 +22,11 @@ import { getEmptyValue } from '../../../empty_value'; import * as i18n from '../../translations'; import { FormattedEntry } from '../../types'; -const EntriesDetails = styled(EuiFlexItem)` +const MyEntriesDetails = styled(EuiFlexItem)` padding: ${({ theme }) => theme.eui.euiSize}; `; -const StyledEditButton = styled(EuiButton)` +const MyEditButton = styled(EuiButton)` ${({ theme }) => css` background-color: ${transparentize(0.9, theme.eui.euiColorPrimary)}; border: none; @@ -34,7 +34,7 @@ const StyledEditButton = styled(EuiButton)` `} `; -const StyledRemoveButton = styled(EuiButton)` +const MyRemoveButton = styled(EuiButton)` ${({ theme }) => css` background-color: ${transparentize(0.9, theme.eui.euiColorDanger)}; border: none; @@ -42,7 +42,7 @@ const StyledRemoveButton = styled(EuiButton)` `} `; -const AndOrBadgeContainer = styled(EuiFlexItem)` +const MyAndOrBadgeContainer = styled(EuiFlexItem)` padding-top: ${({ theme }) => theme.eui.euiSizeXL}; `; @@ -118,19 +118,19 @@ const ExceptionEntriesComponent = ({ ); return ( - + {entries.length > 1 && ( - + - + )} @@ -147,7 +147,7 @@ const ExceptionEntriesComponent = ({ - {i18n.EDIT} - + - {i18n.REMOVE} - + - + ); }; diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/__examples__/exception_item.stories.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/index.stories.tsx similarity index 66% rename from x-pack/plugins/security_solution/public/common/components/exceptions/__examples__/exception_item.stories.tsx rename to x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/index.stories.tsx index 5f2b0b93e9df0..de214b098d4ea 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/__examples__/exception_item.stories.tsx +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/index.stories.tsx @@ -3,22 +3,22 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -import { storiesOf } from '@storybook/react'; -import React, { ReactNode } from 'react'; +import { storiesOf, addDecorator } from '@storybook/react'; +import { action } from '@storybook/addon-actions'; +import React from 'react'; import { ThemeProvider } from 'styled-components'; import euiLightVars from '@elastic/eui/dist/eui_theme_light.json'; -import { ExceptionItem } from '../viewer/exception_item'; -import { Operator } from '../types'; -import { getExceptionItemMock } from '../mocks'; +import { ExceptionItem } from './'; +import { Operator } from '../../types'; +import { getExceptionItemMock } from '../../mocks'; -const withTheme = (storyFn: () => ReactNode) => ( +addDecorator((storyFn) => ( ({ eui: euiLightVars, darkMode: false })}>{storyFn()} -); +)); -storiesOf('ExceptionItem', module) - .addDecorator(withTheme) - .add('ExceptionItem/with os', () => { +storiesOf('Components|ExceptionItem', module) + .add('with os', () => { const payload = getExceptionItemMock(); payload.description = ''; payload.comment = []; @@ -36,8 +36,8 @@ storiesOf('ExceptionItem', module) loadingItemIds={[]} commentsAccordionId={'accordion--comments'} exceptionItem={payload} - onDeleteException={() => {}} - onEditException={() => {}} + onDeleteException={action('onClick')} + onEditException={action('onClick')} /> ); }) @@ -59,8 +59,8 @@ storiesOf('ExceptionItem', module) loadingItemIds={[]} commentsAccordionId={'accordion--comments'} exceptionItem={payload} - onDeleteException={() => {}} - onEditException={() => {}} + onDeleteException={action('onClick')} + onEditException={action('onClick')} /> ); }) @@ -82,8 +82,8 @@ storiesOf('ExceptionItem', module) loadingItemIds={[]} commentsAccordionId={'accordion--comments'} exceptionItem={payload} - onDeleteException={() => {}} - onEditException={() => {}} + onDeleteException={action('onClick')} + onEditException={action('onClick')} /> ); }) @@ -98,8 +98,8 @@ storiesOf('ExceptionItem', module) loadingItemIds={[]} commentsAccordionId={'accordion--comments'} exceptionItem={payload} - onDeleteException={() => {}} - onEditException={() => {}} + onDeleteException={action('onClick')} + onEditException={action('onClick')} /> ); }) @@ -111,8 +111,21 @@ storiesOf('ExceptionItem', module) loadingItemIds={[]} commentsAccordionId={'accordion--comments'} exceptionItem={payload} - onDeleteException={() => {}} - onEditException={() => {}} + onDeleteException={action('onClick')} + onEditException={action('onClick')} + /> + ); + }) + .add('with loadingItemIds', () => { + const { id, namespace_type, ...rest } = getExceptionItemMock(); + + return ( + ); }); diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/index.test.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/index.test.tsx index dca3afe4f9069..b4de3639944b1 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/index.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/index.test.tsx @@ -51,7 +51,7 @@ describe('ExceptionItem', () => { const editBtn = wrapper.find('[data-test-subj="exceptionsViewerEditBtn"] button').at(0); editBtn.simulate('click'); - expect(mockOnEditException).toHaveBeenCalledTimes(1); + expect(mockOnEditException).toHaveBeenCalledWith(getExceptionItemMock()); }); it('it invokes "onDeleteException" when delete button clicked', () => { @@ -73,7 +73,10 @@ describe('ExceptionItem', () => { const editBtn = wrapper.find('[data-test-subj="exceptionsViewerDeleteBtn"] button').at(0); editBtn.simulate('click'); - expect(mockOnDeleteException).toHaveBeenCalledTimes(1); + expect(mockOnDeleteException).toHaveBeenCalledWith({ + id: 'uuid_here', + namespaceType: 'single', + }); }); it('it renders comment accordion closed to begin with', () => { diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exceptions_pagination.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exceptions_pagination.tsx index 0953a5c666c5d..2920f1a85eee7 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exceptions_pagination.tsx +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exceptions_pagination.tsx @@ -29,13 +29,14 @@ const ExceptionsViewerPaginationComponent = ({ }: ExceptionsViewerPaginationProps): JSX.Element => { const [isOpen, setIsOpen] = useState(false); - const closePerPageMenu = useCallback((): void => setIsOpen(false), [setIsOpen]); + const handleClosePerPageMenu = useCallback((): void => setIsOpen(false), [setIsOpen]); - const onPerPageMenuClick = useCallback((): void => setIsOpen((isPopoverOpen) => !isPopoverOpen), [ - setIsOpen, - ]); + const handlePerPageMenuClick = useCallback( + (): void => setIsOpen((isPopoverOpen) => !isPopoverOpen), + [setIsOpen] + ); - const onPageClick = useCallback( + const handlePageClick = useCallback( (pageIndex: number): void => { onPaginationChange({ filter: {}, @@ -63,14 +64,14 @@ const ExceptionsViewerPaginationComponent = ({ totalItemCount: pagination.totalItemCount, }, }); - closePerPageMenu(); + handleClosePerPageMenu(); }} data-test-subj="exceptionsPerPageItem" > {i18n.NUMBER_OF_ITEMS(rows)} )); - }, [pagination, onPaginationChange, closePerPageMenu]); + }, [pagination, onPaginationChange, handleClosePerPageMenu]); const totalPages = useMemo((): number => { if (pagination.totalItemCount > 0) { @@ -90,14 +91,14 @@ const ExceptionsViewerPaginationComponent = ({ color="text" iconType="arrowDown" iconSide="right" - onClick={onPerPageMenuClick} + onClick={handlePerPageMenuClick} data-test-subj="exceptionsPerPageBtn" > {i18n.ITEMS_PER_PAGE(pagination.pageSize)} } isOpen={isOpen} - closePopover={closePerPageMenu} + closePopover={handleClosePerPageMenu} panelPaddingSize="none" > @@ -108,7 +109,7 @@ const ExceptionsViewerPaginationComponent = ({ diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exceptions_utility.test.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exceptions_utility.test.tsx new file mode 100644 index 0000000000000..d697023b2ced4 --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exceptions_utility.test.tsx @@ -0,0 +1,174 @@ +/* + * 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 React from 'react'; +import { ThemeProvider } from 'styled-components'; +import { mountWithIntl } from 'test_utils/enzyme_helpers'; +import euiLightVars from '@elastic/eui/dist/eui_theme_light.json'; + +import { ExceptionsViewerUtility } from './exceptions_utility'; + +describe('ExceptionsViewerUtility', () => { + it('it renders correct pluralized text when more than one exception exists', () => { + const wrapper = mountWithIntl( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + + expect(wrapper.find('[data-test-subj="exceptionsShowing"]').at(0).text()).toEqual( + 'Showing 2 exceptions' + ); + }); + + it('it renders correct singular text when less than two exceptions exists', () => { + const wrapper = mountWithIntl( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + + expect(wrapper.find('[data-test-subj="exceptionsShowing"]').at(0).text()).toEqual( + 'Showing 1 exception' + ); + }); + + it('it invokes "onRefreshClick" when refresh button clicked', () => { + const mockOnRefreshClick = jest.fn(); + const wrapper = mountWithIntl( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + + wrapper.find('[data-test-subj="exceptionsRefresh"] button').simulate('click'); + + expect(mockOnRefreshClick).toHaveBeenCalledTimes(1); + }); + + it('it does not render any messages when "showEndpointList" and "showDetectionsList" are "false"', () => { + const wrapper = mountWithIntl( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + + expect(wrapper.find('[data-test-subj="exceptionsEndpointMessage"]').exists()).toBeFalsy(); + expect(wrapper.find('[data-test-subj="exceptionsDetectionsMessage"]').exists()).toBeFalsy(); + }); + + it('it does render detections messages when "showDetectionsList" is "true"', () => { + const wrapper = mountWithIntl( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + + expect(wrapper.find('[data-test-subj="exceptionsEndpointMessage"]').exists()).toBeFalsy(); + expect(wrapper.find('[data-test-subj="exceptionsDetectionsMessage"]').exists()).toBeTruthy(); + }); + + it('it does render endpoint messages when "showEndpointList" is "true"', () => { + const wrapper = mountWithIntl( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + + expect(wrapper.find('[data-test-subj="exceptionsEndpointMessage"]').exists()).toBeTruthy(); + expect(wrapper.find('[data-test-subj="exceptionsDetectionsMessage"]').exists()).toBeFalsy(); + }); +}); diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exceptions_utility.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exceptions_utility.tsx new file mode 100644 index 0000000000000..9ab4e170f4090 --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exceptions_utility.tsx @@ -0,0 +1,111 @@ +/* + * 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 React from 'react'; +import { EuiText, EuiLink, EuiFlexGroup, EuiFlexItem } from '@elastic/eui'; +import { FormattedMessage } from 'react-intl'; +import styled from 'styled-components'; + +import * as i18n from '../translations'; +import { ExceptionsPagination, FilterOptions } from '../types'; +import { + UtilityBar, + UtilityBarSection, + UtilityBarGroup, + UtilityBarText, + UtilityBarAction, +} from '../../utility_bar'; + +const StyledText = styled(EuiText)` + font-style: italic; +`; + +const MyUtilities = styled(EuiFlexGroup)` + height: 50px; +`; + +interface ExceptionsViewerUtilityProps { + pagination: ExceptionsPagination; + filterOptions: FilterOptions; + ruleSettingsUrl: string; + onRefreshClick: () => void; +} + +const ExceptionsViewerUtilityComponent: React.FC = ({ + pagination, + filterOptions, + ruleSettingsUrl, + onRefreshClick, +}): JSX.Element => ( + + + + + + + {i18n.SHOWING_EXCEPTIONS(pagination.totalItemCount ?? 0)} + + + + + + {i18n.REFRESH} + + + + + + + + {filterOptions.showEndpointList && ( + + + + ), + }} + /> + )} + {filterOptions.showDetectionsList && ( + + + + ), + }} + /> + )} + + + +); + +ExceptionsViewerUtilityComponent.displayName = 'ExceptionsViewerUtilityComponent'; + +export const ExceptionsViewerUtility = React.memo(ExceptionsViewerUtilityComponent); + +ExceptionsViewerUtility.displayName = 'ExceptionsViewerUtility'; diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exceptions_viewer_header.stories.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exceptions_viewer_header.stories.tsx new file mode 100644 index 0000000000000..796af7cd760e2 --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exceptions_viewer_header.stories.tsx @@ -0,0 +1,67 @@ +/* + * 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 { storiesOf, addDecorator } from '@storybook/react'; +import { action } from '@storybook/addon-actions'; +import React from 'react'; +import { ThemeProvider } from 'styled-components'; +import euiLightVars from '@elastic/eui/dist/eui_theme_light.json'; + +import { ExceptionsViewerHeader } from './exceptions_viewer_header'; +import { ExceptionListType } from '../types'; + +addDecorator((storyFn) => ( + ({ eui: euiLightVars, darkMode: false })}>{storyFn()} +)); + +storiesOf('Components|ExceptionsViewerHeader', module) + .add('loading', () => { + return ( + + ); + }) + .add('all lists', () => { + return ( + + ); + }) + .add('endpoint only', () => { + return ( + + ); + }) + .add('detections only', () => { + return ( + + ); + }); diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exceptions_viewer_header.test.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exceptions_viewer_header.test.tsx index bdc99370a6293..c609a2296b83d 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exceptions_viewer_header.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exceptions_viewer_header.test.tsx @@ -269,7 +269,7 @@ describe('ExceptionsViewerHeader', () => { expect(mockOnAddExceptionClick).toHaveBeenCalledTimes(1); }); - it('it invokes "onFilterChange" with filter value when search used', () => { + it('it invokes "onFilterChange" when search used and "Enter" pressed', () => { const mockOnFilterChange = jest.fn(); const wrapper = mount( ({ eui: euiLightVars, darkMode: false })}> @@ -284,54 +284,12 @@ describe('ExceptionsViewerHeader', () => { ); - wrapper - .find('input[data-test-subj="exceptionsHeaderSearch"]') - .at(0) - .simulate('change', { - target: { value: 'host' }, - }); - - expect(mockOnFilterChange).toHaveBeenCalledWith({ - filter: { - filter: 'host', - showDetectionsList: false, - showEndpointList: false, - tags: [], - }, - pagination: {}, + wrapper.find('EuiFieldSearch').at(0).simulate('keyup', { + charCode: 13, + code: 'Enter', + key: 'Enter', }); - }); - - it('it invokes "onFilterChange" with tags values when search value includes "tags:..."', () => { - const mockOnFilterChange = jest.fn(); - const wrapper = mount( - ({ eui: euiLightVars, darkMode: false })}> - - - ); - - wrapper - .find('input[data-test-subj="exceptionsHeaderSearch"]') - .at(0) - .simulate('change', { - target: { value: 'tags:malware' }, - }); - expect(mockOnFilterChange).toHaveBeenCalledWith({ - filter: { - filter: '', - showDetectionsList: false, - showEndpointList: false, - tags: ['malware'], - }, - pagination: {}, - }); + expect(mockOnFilterChange).toHaveBeenCalled(); }); }); diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exceptions_viewer_item.test.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exceptions_viewer_item.test.tsx new file mode 100644 index 0000000000000..dbcae20eb1385 --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exceptions_viewer_item.test.tsx @@ -0,0 +1,147 @@ +/* + * 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 React from 'react'; +import { ThemeProvider } from 'styled-components'; +import { mount } from 'enzyme'; +import euiLightVars from '@elastic/eui/dist/eui_theme_light.json'; + +import { getExceptionItemMock } from '../mocks'; +import { ExceptionsViewerItems } from './exceptions_viewer_items'; + +describe('ExceptionsViewerItems', () => { + it('it renders empty prompt if "showEmpty" is "true"', () => { + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + + expect(wrapper.find('[data-test-subj="exceptionsEmptyPrompt"]').exists()).toBeTruthy(); + expect(wrapper.find('[data-test-subj="exceptionsContainer"]').exists()).toBeFalsy(); + }); + + it('it renders exceptions if "showEmpty" and "isInitLoading" is "false", and exceptions exist', () => { + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + + expect(wrapper.find('[data-test-subj="exceptionsContainer"]').exists()).toBeTruthy(); + expect(wrapper.find('[data-test-subj="exceptionsEmptyPrompt"]').exists()).toBeFalsy(); + }); + + it('it does not render exceptions if "isInitLoading" is "true"', () => { + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + + expect(wrapper.find('[data-test-subj="exceptionsContainer"]').exists()).toBeFalsy(); + expect(wrapper.find('[data-test-subj="exceptionsEmptyPrompt"]').exists()).toBeTruthy(); + }); + + it('it does not render or badge for first exception displayed', () => { + const exception1 = getExceptionItemMock(); + const exception2 = getExceptionItemMock(); + exception2.id = 'newId'; + + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + + const firstExceptionItem = wrapper.find('[data-test-subj="exceptionItemContainer"]').at(0); + + expect(firstExceptionItem.find('[data-test-subj="exceptionItemOrBadge"]').exists()).toBeFalsy(); + }); + + it('it does render or badge with exception displayed', () => { + const exception1 = getExceptionItemMock(); + const exception2 = getExceptionItemMock(); + exception2.id = 'newId'; + + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + + const notFirstExceptionItem = wrapper.find('[data-test-subj="exceptionItemContainer"]').at(1); + + expect( + notFirstExceptionItem.find('[data-test-subj="exceptionItemOrBadge"]').exists() + ).toBeFalsy(); + }); + + it('it invokes "onDeleteException" when delete button is clicked', () => { + const mockOnDeleteException = jest.fn(); + + const wrapper = mount( + ({ eui: euiLightVars, darkMode: false })}> + + + ); + + wrapper.find('[data-test-subj="exceptionsViewerDeleteBtn"] button').at(0).simulate('click'); + + expect(mockOnDeleteException).toHaveBeenCalledWith({ + id: 'uuid_here', + namespaceType: 'single', + }); + }); +}); diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exceptions_viewer_items.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exceptions_viewer_items.tsx index 7ef32c0ec73d7..e1ef3c10188b3 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exceptions_viewer_items.tsx +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exceptions_viewer_items.tsx @@ -40,7 +40,7 @@ interface ExceptionsViewerItemsProps { onEditExceptionItem: (item: ExceptionListItemSchema) => void; } -export const ExceptionsViewerItems: React.FC = ({ +const ExceptionsViewerItemsComponent: React.FC = ({ showEmpty, isInitLoading, exceptions, @@ -48,9 +48,9 @@ export const ExceptionsViewerItems: React.FC = ({ commentsAccordionId, onDeleteException, onEditExceptionItem, -}) => ( +}): JSX.Element => ( - {showEmpty ? ( + {showEmpty || isInitLoading ? ( = ({ ) : ( - + {!isInitLoading && exceptions.length > 0 && exceptions.map((exception, index) => ( - + {index !== 0 ? ( <> - + ) : ( @@ -78,8 +82,8 @@ export const ExceptionsViewerItems: React.FC = ({ loadingItemIds={loadingItemIds} commentsAccordionId={commentsAccordionId} exceptionItem={exception} - handleDelete={onDeleteException} - handleEdit={onEditExceptionItem} + onDeleteException={onDeleteException} + onEditException={onEditExceptionItem} /> ))} @@ -89,4 +93,8 @@ export const ExceptionsViewerItems: React.FC = ({ ); +ExceptionsViewerItemsComponent.displayName = 'ExceptionsViewerItemsComponent'; + +export const ExceptionsViewerItems = React.memo(ExceptionsViewerItemsComponent); + ExceptionsViewerItems.displayName = 'ExceptionsViewerItems'; diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exeptions_utility.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exeptions_utility.tsx deleted file mode 100644 index 2051c1eead1f9..0000000000000 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exeptions_utility.tsx +++ /dev/null @@ -1,106 +0,0 @@ -/* - * 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 React from 'react'; -import { EuiText, EuiLink, EuiFlexGroup, EuiFlexItem } from '@elastic/eui'; -import { FormattedMessage } from 'react-intl'; -import styled from 'styled-components'; - -import * as i18n from '../translations'; -import { ExceptionsPagination, FilterOptions } from '../types'; -import { - UtilityBar, - UtilityBarSection, - UtilityBarGroup, - UtilityBarText, - UtilityBarAction, -} from '../../utility_bar'; - -const StyledText = styled(EuiText)` - font-style: italic; -`; - -const MyUtilities = styled(EuiFlexGroup)` - height: 50px; -`; - -interface ExceptionsViewerUtilityProps { - pagination: ExceptionsPagination; - filterOptions: FilterOptions; - ruleSettingsUrl: string; - onRefreshClick: () => void; -} - -const ExceptionsViewerUtilityComponent = ({ - pagination, - filterOptions, - ruleSettingsUrl, - onRefreshClick, -}: ExceptionsViewerUtilityProps): JSX.Element => { - return ( - - - - - - - {i18n.SHOWING_EXCEPTIONS(pagination.totalItemCount ?? 0)} - - - - - - {i18n.REFRESH} - - - - - - - - {filterOptions.showEndpointList && ( - - - - ), - }} - /> - )} - {filterOptions.showDetectionsList && ( - - - - ), - }} - /> - )} - - - - ); -}; - -ExceptionsViewerUtilityComponent.displayName = 'ExceptionsViewerUtilityComponent'; - -export const ExceptionsViewerUtility = React.memo(ExceptionsViewerUtilityComponent); - -ExceptionsViewerUtility.displayName = 'ExceptionsViewerUtility'; diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/index.test.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/index.test.tsx index cc8e8111064bc..b77b8380c39f1 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/index.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/index.test.tsx @@ -46,7 +46,7 @@ describe('ExceptionsViewer', () => { ]); }); - it('it renders loader if "initLoading" is true', () => { + it('it renders loader if "loadingList" is true', () => { (useExceptionList as jest.Mock).mockReturnValue([ true, [], diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/index.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/index.tsx index a35bfc449da89..1051962852219 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/index.tsx +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/index.tsx @@ -28,7 +28,7 @@ import { useApi, } from '../../../../../public/lists_plugin_deps'; import { ExceptionsViewerPagination } from './exceptions_pagination'; -import { ExceptionsViewerUtility } from './exeptions_utility'; +import { ExceptionsViewerUtility } from './exceptions_utility'; import { ExceptionsViewerItems } from './exceptions_viewer_items'; const initialState: State = { @@ -86,7 +86,6 @@ const ExceptionsViewerComponent = ({ }, [dispatchToaster] ); - const { deleteExceptionItem } = useApi(services.http); const [ { endpointList, @@ -101,6 +100,7 @@ const ExceptionsViewerComponent = ({ }, dispatch, ] = useReducer(allExceptionItemsReducer(), { ...initialState, loadingLists: exceptionListsMeta }); + const { deleteExceptionItem } = useApi(services.http); const setExceptions = useCallback( ({ @@ -144,13 +144,13 @@ const ExceptionsViewerComponent = ({ [dispatch] ); - const onFetchList = useCallback((): void => { + const handleFetchList = useCallback((): void => { if (fetchList != null) { fetchList(); } }, [fetchList]); - const onFiltersChange = useCallback( + const handleFilterChange = useCallback( ({ filter, pagination: pag }: Filter): void => { dispatch({ type: 'updateFilterOptions', @@ -162,7 +162,7 @@ const ExceptionsViewerComponent = ({ [dispatch, exceptionListsMeta] ); - const onAddException = useCallback( + const handleAddException = useCallback( (type: ExceptionListType): void => { setIsModalOpen(true); }, @@ -193,9 +193,9 @@ const ExceptionsViewerComponent = ({ onAssociateList(listId); } - onFetchList(); + handleFetchList(); }, - [setIsModalOpen, onFetchList, onAssociateList] + [setIsModalOpen, handleFetchList, onAssociateList] ); const setLoadingItemIds = useCallback( @@ -210,12 +210,14 @@ const ExceptionsViewerComponent = ({ const handleDeleteException = useCallback( ({ id, namespaceType }: ApiProps) => { + setLoadingItemIds([{ id, namespaceType }]); + deleteExceptionItem({ id, namespaceType, onSuccess: () => { setLoadingItemIds(loadingItemIds.filter((t) => t.id !== id)); - onFetchList(); + handleFetchList(); }, onError: () => { const dispatchToasterError = onDispatchToaster({ @@ -229,7 +231,7 @@ const ExceptionsViewerComponent = ({ }, }); }, - [setLoadingItemIds, deleteExceptionItem, loadingItemIds, onFetchList, onDispatchToaster] + [setLoadingItemIds, deleteExceptionItem, loadingItemIds, handleFetchList, onDispatchToaster] ); // Logic for initial render @@ -277,8 +279,8 @@ const ExceptionsViewerComponent = ({ supportedListTypes={availableListTypes} detectionsListItems={detectionsList != null ? detectionsList.totalItems : 0} endpointListItems={endpointList != null ? endpointList.totalItems : 0} - onFilterChange={onFiltersChange} - onAddExceptionClick={onAddException} + onFilterChange={handleFilterChange} + onAddExceptionClick={handleAddException} /> @@ -286,7 +288,7 @@ const ExceptionsViewerComponent = ({ @@ -300,7 +302,10 @@ const ExceptionsViewerComponent = ({ onEditExceptionItem={handleEditException} /> - +
); diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/reducer.ts b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/reducer.ts index 32cb4fe46e310..538207458f0ed 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/reducer.ts +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/reducer.ts @@ -87,6 +87,7 @@ export const allExceptionItemsReducer = () => (state: State, action: Action): St return { ...returnState, loadingLists: list, + exceptions: list.length === 0 ? [] : [...state.exceptions], }; } else if (action.filterOptions.showDetectionsList) { const list = action.allLists.filter((t) => t.type === 'detection'); @@ -94,6 +95,7 @@ export const allExceptionItemsReducer = () => (state: State, action: Action): St return { ...returnState, loadingLists: list, + exceptions: list.length === 0 ? [] : [...state.exceptions], }; } else { return {