From 24ed91f5a3d9f14ad9b6952162d148faf241891b Mon Sep 17 00:00:00 2001 From: Yara Tercero Date: Tue, 2 Jun 2020 17:14:00 -0400 Subject: [PATCH 01/29] 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 00000000000000..27ca4644044452 --- /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 00000000000000..9df865193a791b --- /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 00000000000000..095a151a5c2832 --- /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 00000000000000..58bcb5130a5292 --- /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/29] 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 f34e9ee214537d..00000000000000 --- 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 28355372df1463..00000000000000 --- 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 58bcb5130a5292..00000000000000 --- 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 240b336f4eccee..691c919029261b 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 641f6fba112fcb..d6122fef915112 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 77257e367c6f58..beadc138113952 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/29] 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 00000000000000..9f3ba4341c5ebd --- /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 00000000000000..f07f3a959b40d6 --- /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 00000000000000..b94c15e8ac1536 --- /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 00000000000000..9b553c5af9bd50 --- /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 00000000000000..8c69de5b2a371a --- /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 00000000000000..e8393610e459d5 --- /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 00000000000000..c3edccba5a6603 --- /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 00000000000000..373ecedc95441c --- /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 00000000000000..a35ec3521e84c1 --- /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 d2ee5ae56b7d9c..350b53ef52f4eb 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/29] 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 65662367049363..5f06f2a4ebb12b 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/29] 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 b94c15e8ac1536..2182b6cf799250 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 8c69de5b2a371a..5f7f5b2811921c 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/29] 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 f07f3a959b40d6..4b74b47d8e433a 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 00000000000000..4135840e63d100 --- /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 00000000000000..b104e7806f9fc5 --- /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 c3edccba5a6603..15b6425956c349 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/29] 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 4b74b47d8e433a..85221b9da0803a 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 4135840e63d100..15aec3533b325d 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 5f7f5b2811921c..b60b87d98de026 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 00000000000000..05d31d99c90cf0 --- /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 373ecedc95441c..896d27088df7e3 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 00000000000000..43c326f6c5314e --- /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 a35ec3521e84c1..0599d5dd93b7f1 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 eae3887ec0636d..628d56ebb647cc 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/29] 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 85221b9da0803a..2b59b758b43ade 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/29] 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 00000000000000..e468a5330c2860 --- /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/29] 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 e468a5330c2860..00000000000000 --- 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/29] 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 b104e7806f9fc5..02a8e5c96de6ff 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/29] 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 27ca4644044452..f939cf81d1bd3d 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 9df865193a791b..3c92e06810c8e6 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 095a151a5c2832..bed1412dda28b0 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 9f3ba4341c5ebd..b6620ed103bc84 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 2b59b758b43ade..223eabb0ea4eeb 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 2182b6cf799250..41d9ed39a326c9 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 02a8e5c96de6ff..536d005c57b6e9 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 15b6425956c349..bcaa1abb237273 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 896d27088df7e3..63bba06a03ccfe 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 43c326f6c5314e..7d3b7195def80e 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 0599d5dd93b7f1..ab22cb364c5393 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/29] 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 41d9ed39a326c9..bd22de636bf6c8 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 bcaa1abb237273..8745e80a215486 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 63bba06a03ccfe..d0236adc27c6c1 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 ab22cb364c5393..f4cdce62f56b38 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/29] 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 3c92e06810c8e6..ed918a59a514a0 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 bed1412dda28b0..ba3f880d9757eb 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/29] 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 9b553c5af9bd50..19c726893e6827 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 b60b87d98de026..704849430daf91 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/29] 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 a6a25ab4d4e9d8..26ebb7ff5d3599 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 116233cd893481..881e9facd8d3b7 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 cf6b6c3ec1c598..e3daf7c28fc88f 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 fb4d5de06ae54d..10f87c407df511 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/29] 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 00000000000000..fee9c4165972db --- /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 00000000000000..596ef996a4571d --- /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 00000000000000..3d0e5a97f6d05e --- /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 00000000000000..74d0020c6c77e8 --- /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 00000000000000..ebfa9b7b9998a2 --- /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 00000000000000..16dd67c9071fdc --- /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/29] 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 704849430daf91..956f65de645b42 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 e8393610e459d5..f4707efa76a0fc 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 536d005c57b6e9..00000000000000 --- 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 8745e80a215486..00000000000000 --- 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 e0c62f51d032ad..00000000000000 --- 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 d0236adc27c6c1..00000000000000 --- 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 00000000000000..2b0d7d9384aa27 --- /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 00000000000000..251048b6322753 --- /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/29] 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 7d3b7195def80e..00000000000000 --- 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 f4cdce62f56b38..ac75bc3a8c2f44 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 00000000000000..899a403ff07853 --- /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 350b53ef52f4eb..3acdf42d27fd01 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/29] 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 536d005c57b6e9..00000000000000 --- 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 8745e80a215486..00000000000000 --- 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 e0c62f51d032ad..00000000000000 --- 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 d0236adc27c6c1..00000000000000 --- 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 7d3b7195def80e..00000000000000 --- 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/29] 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 ebd6ed118f937d..a38a56555c7a90 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 9cf510f4a9b5d0..94dfdc3e9daa02 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 596ef996a4571d..6f418808b239a6 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 16dd67c9071fdc..98c6f62dd8a3de 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 ac75bc3a8c2f44..21cea588e907a4 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/29] 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 00000000000000..306195f4226e39 --- /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 d68a26eb8ffe23..c89c7a8f080cf6 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 00000000000000..3fe4458a737693 --- /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/29] 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 00000000000000..dec00747c9e918 --- /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 00000000000000..af3b20d14e690c --- /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 00000000000000..e9f93930c5919f --- /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 00000000000000..73ebd4df627b23 --- /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 fee9c4165972db..c5d2ffc7ac2bf0 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 74d0020c6c77e8..73774f2f3c8f8a 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 ebfa9b7b9998a2..784fc4336a5ff0 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 00000000000000..8d72afe3d47de5 --- /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/29] 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 881e9facd8d3b7..9d80dd367efc14 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 e3daf7c28fc88f..286eb0570ebb82 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 10f87c407df511..1e25275a0d38ba 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 a38a56555c7a90..a7c9332c55daf1 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 b6620ed103bc84..00000000000000 --- 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 223eabb0ea4eeb..7698605588e768 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 15aec3533b325d..5b28cdd491beb2 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 956f65de645b42..4e6092af3882b9 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 f4707efa76a0fc..8364df81a6d8f4 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 73ebd4df627b23..00000000000000 --- 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 8d72afe3d47de5..48d15dd6ae3330 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 2b0d7d9384aa27..bdc99370a6293e 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 251048b6322753..a819539fc5d94d 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 21cea588e907a4..9ae694b49a936d 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 899a403ff07853..142f750f383fca 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 3acdf42d27fd01..113bfaa860f000 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/29] 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 e34c80f0a29ddc..0e527bf4dfc72c 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/29] 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 dec00747c9e918..45e180d9d617c6 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 9d80dd367efc14..c26d556fe8f258 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 4e6092af3882b9..23e9f64caf695a 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 a819539fc5d94d..92a8830310b516 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 9ae694b49a936d..31cff134d2dc4b 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 142f750f383fca..121a33741534cd 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/29] 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 26ebb7ff5d3599..fbd43787a822ea 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 c26d556fe8f258..1d7a63ba880bfb 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 48d15dd6ae3330..fdbee42c4eea82 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 31cff134d2dc4b..946a98b19decd5 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/29] 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 af3b20d14e690c..8942832798a5e5 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 e9f93930c5919f..29cded8f691650 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 5b28cdd491beb2..0dba3fd26c487b 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 8364df81a6d8f4..b56364bd7b9528 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 3d0e5a97f6d05e..10f11231ace017 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 fdbee42c4eea82..0953a5c666c5da 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 00000000000000..cc8e8111064bc0 --- /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 946a98b19decd5..4a7e5772d4b2d6 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 121a33741534cd..40d5bb5f0a2978 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 2f8eb185983f07a72cb73beaa8983f044dd63d80 Mon Sep 17 00:00:00 2001 From: Yara Tercero Date: Tue, 9 Jun 2020 16:19:54 -0400 Subject: [PATCH 29/29] update typing --- .../public/common/components/exceptions/types.ts | 8 ++++++-- .../common/components/exceptions/viewer/index.tsx | 11 ++++++----- 2 files changed, 12 insertions(+), 7 deletions(-) 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 b56364bd7b9528..d60d1ef71e502e 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/index.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/index.tsx index 4a7e5772d4b2d6..ff52e395c3b1e8 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 @@ -128,6 +128,7 @@ const ExceptionsViewerComponent = ({ dispatch, ] = useReducer(allExceptionItemsReducer(), initialState); + // TODO: Update icky typing once api updated const setExceptions = useCallback( ({ lists: newLists, @@ -137,7 +138,7 @@ const ExceptionsViewerComponent = ({ dispatch({ type: 'setExceptions', lists: newLists, - exceptions: newExceptions, + exceptions: (newExceptions as unknown) as ExceptionListItemSchema[], pagination: newPagination, }); }, @@ -274,13 +275,13 @@ const ExceptionsViewerComponent = ({ if (filterOptions.showEndpointList) { return ( @@ -291,13 +292,13 @@ const ExceptionsViewerComponent = ({ } else if (filterOptions.showDetectionsList) { return (