diff --git a/x-pack/plugins/security_solution/public/common/components/and_or_badge/__examples__/index.stories.tsx b/x-pack/plugins/security_solution/public/common/components/and_or_badge/__examples__/index.stories.tsx new file mode 100644 index 00000000000000..f939cf81d1bd3d --- /dev/null +++ b/x-pack/plugins/security_solution/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/security_solution/public/common/components/and_or_badge/index.test.tsx b/x-pack/plugins/security_solution/public/common/components/and_or_badge/index.test.tsx new file mode 100644 index 00000000000000..ed918a59a514a0 --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/and_or_badge/index.test.tsx @@ -0,0 +1,48 @@ +/* + * 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 "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="andOrBadgeBarTop"]')).toHaveLength(1); + expect(wrapper.find('EuiFlexItem[data-test-subj="andOrBadgeBarBottom"]')).toHaveLength(1); + }); + + 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/security_solution/public/common/components/and_or_badge/index.tsx b/x-pack/plugins/security_solution/public/common/components/and_or_badge/index.tsx new file mode 100644 index 00000000000000..ba3f880d9757eb --- /dev/null +++ b/x-pack/plugins/security_solution/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 AndOrBadgeAntenna = 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; includeAntennas?: boolean }>( + ({ type, includeAntennas = false }) => { + const getBadge = () => ( + + {type === 'and' ? i18n.AND : i18n.OR} + + ); + + const getBadgeWithAntennas = () => ( + + + {getBadge()} + + + ); + + return includeAntennas ? getBadgeWithAntennas() : getBadge(); + } +); + +AndOrBadge.displayName = 'AndOrBadge'; diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/and_or_badge/translations.ts b/x-pack/plugins/security_solution/public/common/components/and_or_badge/translations.ts similarity index 100% rename from x-pack/plugins/security_solution/public/timelines/components/timeline/and_or_badge/translations.ts rename to x-pack/plugins/security_solution/public/common/components/and_or_badge/translations.ts 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 new file mode 100644 index 00000000000000..b6620ed103bc84 --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/__examples__/index.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'; +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 new file mode 100644 index 00000000000000..223eabb0ea4eeb --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/helpers.test.tsx @@ -0,0 +1,467 @@ +/* + * 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 moment from 'moment-timezone'; + +import { + getOperatorType, + getExceptionOperatorSelect, + determineIfIsNested, + getFormattedEntries, + formatEntry, + getOperatingSystems, + getTagsInclude, + getDescriptionListContent, + getFormattedComments, +} from './helpers'; +import { + OperatorType, + Operator, + NestedExceptionEntry, + FormattedEntry, + DescriptionListItem, +} from './types'; +import { + isOperator, + isNotOperator, + isOneOfOperator, + isNotOneOfOperator, + isInListOperator, + isNotInListOperator, + existsOperator, + doesNotExistOperator, +} from './operators'; +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(); + 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: 'actingProcess.file.signer', + 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: 'actingProcess.file.signer', + 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: 'actingProcess.file.signer', + 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: 'actingProcess.file.signer', + isNested: false, + operator: 'is', + value: 'Elastic, N.V.', + }; + + 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.actingProcess.file.signer', + isNested: true, + operator: 'is', + value: 'Elastic, N.V.', + }; + + 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).toEqual(''); + }); + + test('it returns null if operating system tag malformed', () => { + const result = getOperatingSystems(['some tag', 'jibberos:mac,windows', 'some other tag']); + + expect(result).toEqual(''); + }); + + 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'); + }); + + 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'); + }); + }); + + 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(); + payload.description = ''; + const result = getDescriptionListContent(payload); + const expected: DescriptionListItem[] = [ + { + description: 'Windows', + title: 'OS', + }, + { + description: 'April 23rd 2020 @ 00: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 23rd 2020 @ 00: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 23rd 2020 @ 00: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 23rd 2020 @ 00: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/security_solution/public/common/components/exceptions/helpers.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/helpers.tsx new file mode 100644 index 00000000000000..bd22de636bf6c8 --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/helpers.tsx @@ -0,0 +1,192 @@ +/* + * 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 { capitalize } from 'lodash'; +import moment from 'moment'; + +import * as i18n from './translations'; +import { + FormattedEntry, + OperatorType, + OperatorOption, + ExceptionEntry, + NestedExceptionEntry, + DescriptionListItem, + Comment, + ExceptionListItemSchema, +} from './types'; +import { EXCEPTION_OPERATORS, isOperator } from './operators'; + +/** + * 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 formattedEntries.flat(); +}; + +/** + * Helper method for `getFormattedEntries` + */ +export const formatEntry = ({ + isNested, + parent, + item, +}: { + isNested: boolean; + parent?: string; + item: ExceptionEntry; +}): FormattedEntry => { + 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 => { + const osMatches = tags + .filter((tag) => tag.startsWith('os:')) + .map((os) => capitalize(os.substring(3).trim())) + .join(', '); + + return osMatches; +}; + +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: i18n.OPERATING_SYSTEM, + value: getOperatingSystems(exceptionItem._tags), + }, + { + title: i18n.DATE_CREATED, + value: moment(exceptionItem.created_at).format('MMMM Do YYYY @ HH:mm:ss'), + }, + { + title: i18n.CREATED_BY, + value: exceptionItem.created_by, + }, + { + title: i18n.COMMENT, + value: exceptionItem.description, + }, + ]; + + return details.reduce((acc, { value, title }) => { + if (value != null && value.trim() !== '') { + 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: i18n.COMMENT_EVENT, + timelineIcon: , + children: {comment.comment}, + })); 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 new file mode 100644 index 00000000000000..15aec3533b325d --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/mocks.ts @@ -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 { + 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', + 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/security_solution/public/common/components/exceptions/operators.ts b/x-pack/plugins/security_solution/public/common/components/exceptions/operators.ts new file mode 100644 index 00000000000000..19c726893e6827 --- /dev/null +++ b/x-pack/plugins/security_solution/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.securitySolution.exceptions.isOperatorLabel', { + defaultMessage: 'is', + }), + value: 'is', + type: OperatorType.PHRASE, + operator: Operator.INCLUSION, +}; + +export const isNotOperator: OperatorOption = { + message: i18n.translate('xpack.securitySolution.exceptions.isNotOperatorLabel', { + defaultMessage: 'is not', + }), + value: 'is_not', + type: OperatorType.PHRASE, + operator: Operator.EXCLUSION, +}; + +export const isOneOfOperator: OperatorOption = { + message: i18n.translate('xpack.securitySolution.exceptions.isOneOfOperatorLabel', { + defaultMessage: 'is one of', + }), + value: 'is_one_of', + type: OperatorType.PHRASES, + operator: Operator.INCLUSION, +}; + +export const isNotOneOfOperator: OperatorOption = { + message: i18n.translate('xpack.securitySolution.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.securitySolution.exceptions.existsOperatorLabel', { + defaultMessage: 'exists', + }), + value: 'exists', + type: OperatorType.EXISTS, + operator: Operator.INCLUSION, +}; + +export const doesNotExistOperator: OperatorOption = { + message: i18n.translate('xpack.securitySolution.exceptions.doesNotExistOperatorLabel', { + defaultMessage: 'does not exist', + }), + value: 'does_not_exist', + type: OperatorType.EXISTS, + operator: Operator.EXCLUSION, +}; + +export const isInListOperator: OperatorOption = { + message: i18n.translate('xpack.securitySolution.exceptions.isInListOperatorLabel', { + defaultMessage: 'is in list', + }), + value: 'is_in_list', + type: OperatorType.LIST, + operator: Operator.INCLUSION, +}; + +export const isNotInListOperator: OperatorOption = { + message: i18n.translate('xpack.securitySolution.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/security_solution/public/common/components/exceptions/translations.ts b/x-pack/plugins/security_solution/public/common/components/exceptions/translations.ts new file mode 100644 index 00000000000000..704849430daf91 --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/translations.ts @@ -0,0 +1,49 @@ +/* + * 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.securitySolution.exceptions.editButtonLabel', { + defaultMessage: 'Edit', +}); + +export const REMOVE = i18n.translate('xpack.securitySolution.exceptions.removeButtonLabel', { + defaultMessage: 'Remove', +}); + +export const COMMENTS_SHOW = (comments: number) => + 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.securitySolution.exceptions.hideCommentsLabel', { + values: { comments }, + defaultMessage: 'Hide ({comments}) {comments, plural, =1 {Comment} other {Comments}}', + }); + +export const DATE_CREATED = i18n.translate('xpack.securitySolution.exceptions.dateCreatedLabel', { + defaultMessage: 'Date created', +}); + +export const CREATED_BY = i18n.translate('xpack.securitySolution.exceptions.createdByLabel', { + defaultMessage: 'Created by', +}); + +export const COMMENT = i18n.translate('xpack.securitySolution.exceptions.commentLabel', { + defaultMessage: 'Comment', +}); + +export const COMMENT_EVENT = i18n.translate('xpack.securitySolution.exceptions.commentEventLabel', { + defaultMessage: 'added a comment', +}); + +export const OPERATING_SYSTEM = i18n.translate( + 'xpack.securitySolution.exceptions.operatingSystemLabel', + { + defaultMessage: 'OS', + } +); 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 new file mode 100644 index 00000000000000..e8393610e459d5 --- /dev/null +++ b/x-pack/plugins/security_solution/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/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 new file mode 100644 index 00000000000000..536d005c57b6e9 --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/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_details.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_details.tsx new file mode 100644 index 00000000000000..8745e80a215486 --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/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_entries.test.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_entries.test.tsx new file mode 100644 index 00000000000000..e0c62f51d032ad --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/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_entries.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_entries.tsx new file mode 100644 index 00000000000000..d0236adc27c6c1 --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/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/index.test.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/index.test.tsx new file mode 100644 index 00000000000000..7d3b7195def80e --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/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/index.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/index.tsx new file mode 100644 index 00000000000000..f4cdce62f56b38 --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/viewer/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'; 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 d2ee5ae56b7d9c..350b53ef52f4eb 100644 --- a/x-pack/plugins/security_solution/public/lists_plugin_deps.ts +++ b/x-pack/plugins/security_solution/public/lists_plugin_deps.ts @@ -11,3 +11,4 @@ export { mockNewExceptionItem, mockNewExceptionList, } from '../../lists/public'; +export { ExceptionListItemSchema, Entries } from '../../lists/common/schemas'; diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/and_or_badge/__examples__/index.stories.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/and_or_badge/__examples__/index.stories.tsx deleted file mode 100644 index f34e9ee214537d..00000000000000 --- a/x-pack/plugins/security_solution/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/security_solution/public/timelines/components/timeline/and_or_badge/index.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/and_or_badge/index.tsx deleted file mode 100644 index 28355372df1463..00000000000000 --- a/x-pack/plugins/security_solution/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/security_solution/public/timelines/components/timeline/data_providers/empty.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/data_providers/empty.tsx index 240b336f4eccee..691c919029261b 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/data_providers/empty.tsx +++ b/x-pack/plugins/security_solution/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/security_solution/public/timelines/components/timeline/data_providers/providers.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/data_providers/providers.tsx index bdd5e25eb3a9f7..b5d44cf8544588 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/data_providers/providers.tsx +++ b/x-pack/plugins/security_solution/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/security_solution/public/timelines/components/timeline/search_or_filter/helpers.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/search_or_filter/helpers.tsx index 77257e367c6f58..beadc138113952 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/search_or_filter/helpers.tsx +++ b/x-pack/plugins/security_solution/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'; diff --git a/x-pack/plugins/security_solution/scripts/storybook.js b/x-pack/plugins/security_solution/scripts/storybook.js index 65662367049363..5f06f2a4ebb12b 100644 --- a/x-pack/plugins/security_solution/scripts/storybook.js +++ b/x-pack/plugins/security_solution/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')], });