[SIEM][Exceptions] - Part 1 of ExceptionViewer UI (#68027)

### Summary

The ExceptionViewer is a component that displays all of a user's exception list items. It will allow them to delete, edit, search and add exception items.

This is part 1 of the UI for the ExceptionViewer. Trying to keep PRs relatively small and found this was one way to split it up. This first part accomplishes the following:

- adds helper functions that will be used in the ExceptionBuilder as well and offer ways to format and access the new exception list item structure
- creates ExceptionItem component, this is the component that displays the exception item information
- moves the and_or_badge component into the common folder
- adds stories for the ExceptionItem to easily test changes (Note that the color of some things like the and_or_badge is a bit off, as the light gray color used for it isn't picked up in the mock eui theme)
This commit is contained in:
Yara Tercero 2020-06-04 12:04:34 -04:00 committed by GitHub
parent 1f3379a0e2
commit c5e9ad513e
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
24 changed files with 2129 additions and 65 deletions

View file

@ -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', () => (
<ThemeProvider theme={() => ({ eui: euiLightVars, darkMode: true })}>
<AndOrBadge type="and" />
</ThemeProvider>
))
.add('or', () => (
<ThemeProvider theme={() => ({ eui: euiLightVars, darkMode: true })}>
<AndOrBadge type="or" />
</ThemeProvider>
))
.add('antennas', () => (
<ThemeProvider theme={() => ({ eui: euiLightVars, darkMode: true })}>
<EuiFlexGroup>
<EuiFlexItem grow={false}>
<AndOrBadge type="and" includeAntennas />
</EuiFlexItem>
<EuiFlexItem>
<p>{sampleText}</p>
</EuiFlexItem>
</EuiFlexGroup>
</ThemeProvider>
));

View file

@ -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(
<ThemeProvider theme={() => ({ eui: euiLightVars, darkMode: false })}>
<AndOrBadge includeAntennas type="and" />
</ThemeProvider>
);
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(
<ThemeProvider theme={() => ({ eui: euiLightVars, darkMode: false })}>
<AndOrBadge type="and" />
</ThemeProvider>
);
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(
<ThemeProvider theme={() => ({ eui: euiLightVars, darkMode: false })}>
<AndOrBadge type="or" />
</ThemeProvider>
);
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);
});
});

View file

@ -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 = () => (
<RoundedBadge data-test-subj="and-or-badge" color="hollow">
{type === 'and' ? i18n.AND : i18n.OR}
</RoundedBadge>
);
const getBadgeWithAntennas = () => (
<EuiFlexGroup
className="andBadgeContainer"
gutterSize="none"
direction="column"
alignItems="center"
>
<AndOrBadgeAntenna
className="topAndOrBadgeAntenna"
data-test-subj="andOrBadgeBarTop"
grow={1}
/>
<EuiFlexItemWrapper grow={false}>{getBadge()}</EuiFlexItemWrapper>
<AndOrBadgeAntenna
className="bottomAndOrBadgeAntenna"
data-test-subj="andOrBadgeBarBottom"
grow={1}
/>
</EuiFlexGroup>
);
return includeAntennas ? getBadgeWithAntennas() : getBadge();
}
);
AndOrBadge.displayName = 'AndOrBadge';

View file

@ -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 (
<ThemeProvider theme={() => ({ eui: euiLightVars, darkMode: false })}>
<ExceptionItem
commentsAccordionId={'accordion--comments'}
exceptionItem={payload}
handleDelete={() => {}}
handleEdit={() => {}}
/>
</ThemeProvider>
);
})
.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 (
<ThemeProvider theme={() => ({ eui: euiLightVars, darkMode: false })}>
<ExceptionItem
commentsAccordionId={'accordion--comments'}
exceptionItem={payload}
handleDelete={() => {}}
handleEdit={() => {}}
/>
</ThemeProvider>
);
})
.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 (
<ThemeProvider theme={() => ({ eui: euiLightVars, darkMode: false })}>
<ExceptionItem
commentsAccordionId={'accordion--comments'}
exceptionItem={payload}
handleDelete={() => {}}
handleEdit={() => {}}
/>
</ThemeProvider>
);
})
.add('ExceptionItem/with nested entries', () => {
const payload = getExceptionItemMock();
payload._tags = [];
payload.description = '';
payload.comments = [];
return (
<ThemeProvider theme={() => ({ eui: euiLightVars, darkMode: false })}>
<ExceptionItem
commentsAccordionId={'accordion--comments'}
exceptionItem={payload}
handleDelete={() => {}}
handleEdit={() => {}}
/>
</ThemeProvider>
);
})
.add('ExceptionItem/with everything', () => {
const payload = getExceptionItemMock();
return (
<ThemeProvider theme={() => ({ eui: euiLightVars, darkMode: false })}>
<ExceptionItem
commentsAccordionId={'accordion--comments'}
exceptionItem={payload}
handleDelete={() => {}}
handleEdit={() => {}}
/>
</ThemeProvider>
);
});

View file

@ -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<React.ReactElement>(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<React.ReactElement>(result[0].children as React.ReactElement);
expect(wrapper.text()).toEqual('Comment goes here');
});
});
});

View file

@ -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<ExceptionEntry | NestedExceptionEntry>
): FormattedEntry[] => {
const formattedEntries = entries.map((entry) => {
if (determineIfIsNested(entry)) {
const parent = { fieldName: entry.field, operator: null, value: null, isNested: false };
return entry.entries.reduce<FormattedEntry[]>(
(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<DescriptionListItem[]>((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: <EuiAvatar size="l" name={comment.user.toUpperCase()} />,
children: <EuiText size="s">{comment.comment}</EuiText>,
}));

View file

@ -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',
},
],
},
],
});

View file

@ -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,
];

View file

@ -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',
}
);

View file

@ -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<ReactNode>;
description: NonNullable<ReactNode>;
}
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<ExceptionEntry | NestedExceptionEntry>;
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;
}

View file

@ -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(
<ThemeProvider theme={() => ({ eui: euiLightVars, darkMode: false })}>
<ExceptionDetails
showComments={false}
onCommentsClick={jest.fn()}
exceptionItem={exceptionItem}
/>
</ThemeProvider>
);
expect(wrapper.find('[data-test-subj="exceptionsViewerItemCommentsBtn"]')).toHaveLength(0);
});
test('it renders comments button if comments exist', () => {
const exceptionItem = getExceptionItemMock();
const wrapper = mount(
<ThemeProvider theme={() => ({ eui: euiLightVars, darkMode: false })}>
<ExceptionDetails
showComments={false}
onCommentsClick={jest.fn()}
exceptionItem={exceptionItem}
/>
</ThemeProvider>
);
expect(
wrapper.find('.euiButtonEmpty[data-test-subj="exceptionsViewerItemCommentsBtn"]')
).toHaveLength(1);
});
test('it renders correct number of comments', () => {
const exceptionItem = getExceptionItemMock();
const wrapper = mount(
<ThemeProvider theme={() => ({ eui: euiLightVars, darkMode: false })}>
<ExceptionDetails
showComments={false}
onCommentsClick={jest.fn()}
exceptionItem={exceptionItem}
/>
</ThemeProvider>
);
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(
<ThemeProvider theme={() => ({ eui: euiLightVars, darkMode: false })}>
<ExceptionDetails
showComments={false}
onCommentsClick={jest.fn()}
exceptionItem={exceptionItem}
/>
</ThemeProvider>
);
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(
<ThemeProvider theme={() => ({ eui: euiLightVars, darkMode: false })}>
<ExceptionDetails
showComments={false}
onCommentsClick={jest.fn()}
exceptionItem={exceptionItem}
/>
</ThemeProvider>
);
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(
<ThemeProvider theme={() => ({ eui: euiLightVars, darkMode: false })}>
<ExceptionDetails
showComments={true}
onCommentsClick={jest.fn()}
exceptionItem={exceptionItem}
/>
</ThemeProvider>
);
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(
<ThemeProvider theme={() => ({ eui: euiLightVars, darkMode: false })}>
<ExceptionDetails
showComments={true}
onCommentsClick={mockOnCommentsClick}
exceptionItem={exceptionItem}
/>
</ThemeProvider>
);
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(
<ThemeProvider theme={() => ({ eui: euiLightVars, darkMode: false })}>
<ExceptionDetails
showComments={true}
onCommentsClick={jest.fn()}
exceptionItem={exceptionItem}
/>
</ThemeProvider>
);
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(
<ThemeProvider theme={() => ({ eui: euiLightVars, darkMode: false })}>
<ExceptionDetails
showComments={true}
onCommentsClick={jest.fn()}
exceptionItem={exceptionItem}
/>
</ThemeProvider>
);
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(
<ThemeProvider theme={() => ({ eui: euiLightVars, darkMode: false })}>
<ExceptionDetails
showComments={true}
onCommentsClick={jest.fn()}
exceptionItem={exceptionItem}
/>
</ThemeProvider>
);
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(
<ThemeProvider theme={() => ({ eui: euiLightVars, darkMode: false })}>
<ExceptionDetails
showComments={true}
onCommentsClick={jest.fn()}
exceptionItem={exceptionItem}
/>
</ThemeProvider>
);
expect(wrapper.find('EuiDescriptionListTitle').at(3).text()).toEqual('Comment');
expect(wrapper.find('EuiDescriptionListDescription').at(3).text()).toEqual(
'This is a description'
);
});
});

View file

@ -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 (
<EuiButtonEmpty
onClick={onCommentsClick}
flush="left"
size="xs"
data-test-subj="exceptionsViewerItemCommentsBtn"
>
{!showComments
? i18n.COMMENTS_SHOW(comments.length)
: i18n.COMMENTS_HIDE(comments.length)}
</EuiButtonEmpty>
);
} else {
return <></>;
}
}, [showComments, onCommentsClick, exceptionItem]);
return (
<StyledExceptionDetails grow={2}>
<EuiFlexGroup direction="column" alignItems="flexStart">
<EuiFlexItem grow={1}>
<EuiDescriptionList
compressed
type="column"
listItems={descriptionList}
titleProps={{ className: 'listTitle--width' }}
descriptionProps={{ className: 'listDescription--width' }}
data-test-subj="exceptionsViewerItemDetails"
/>
</EuiFlexItem>
<EuiFlexItem grow={false}>{commentsSection}</EuiFlexItem>
</EuiFlexGroup>
</StyledExceptionDetails>
);
};
ExceptionDetailsComponent.displayName = 'ExceptionDetailsComponent';
export const ExceptionDetails = React.memo(ExceptionDetailsComponent);
ExceptionDetails.displayName = 'ExceptionDetails';

View file

@ -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(
<ThemeProvider theme={() => ({ eui: euiLightVars, darkMode: false })}>
<ExceptionEntries
entries={[getFormattedEntryMock()]}
handleDelete={jest.fn()}
handleEdit={jest.fn()}
/>
</ThemeProvider>
);
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(
<ThemeProvider theme={() => ({ eui: euiLightVars, darkMode: false })}>
<ExceptionEntries
entries={[getFormattedEntryMock(), getFormattedEntryMock()]}
handleDelete={jest.fn()}
handleEdit={jest.fn()}
/>
</ThemeProvider>
);
expect(wrapper.find('[data-test-subj="exceptionsViewerAndBadge"]')).toHaveLength(1);
});
test('it invokes "handlEdit" when edit button clicked', () => {
const mockHandleEdit = jest.fn();
const wrapper = mount(
<ThemeProvider theme={() => ({ eui: euiLightVars, darkMode: false })}>
<ExceptionEntries
entries={[getFormattedEntryMock()]}
handleDelete={jest.fn()}
handleEdit={mockHandleEdit}
/>
</ThemeProvider>
);
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(
<ThemeProvider theme={() => ({ eui: euiLightVars, darkMode: false })}>
<ExceptionEntries
entries={[getFormattedEntryMock()]}
handleDelete={mockHandleDelete}
handleEdit={jest.fn()}
/>
</ThemeProvider>
);
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(
<ThemeProvider theme={() => ({ eui: euiLightVars, darkMode: false })}>
<ExceptionEntries
entries={[parentEntry, getFormattedEntryMock(true)]}
handleDelete={jest.fn()}
handleEdit={jest.fn()}
/>
</ThemeProvider>
);
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(
<ThemeProvider theme={() => ({ eui: euiLightVars, darkMode: false })}>
<ExceptionEntries
entries={[getFormattedEntryMock()]}
handleDelete={jest.fn()}
handleEdit={jest.fn()}
/>
</ThemeProvider>
);
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');
});
});

View file

@ -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<EuiTableFieldDataColumnType<FormattedEntry>> => [
{
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 (
<>
<EuiIconTip type="grabHorizontal" size="m" />
{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 (
<EuiFlexGroup direction="row">
{values.map((value) => {
return <EuiFlexItem grow={1}>{value}</EuiFlexItem>;
})}
</EuiFlexGroup>
);
} else {
return values ?? getEmptyValue();
}
},
},
],
[entries]
);
return (
<EntriesDetails grow={5}>
<EuiFlexGroup direction="column" gutterSize="m">
<EuiFlexItem>
<EuiFlexGroup direction="row" gutterSize="none">
{entries.length > 1 && (
<AndOrBadgeContainer grow={false}>
<AndOrBadge type="and" includeAntennas data-test-subj="exceptionsViewerAndBadge" />
</AndOrBadgeContainer>
)}
<EuiFlexItem grow={1}>
<EuiBasicTable
isSelectable={false}
itemId="id"
columns={columns}
items={entries}
responsive
/>
</EuiFlexItem>
</EuiFlexGroup>
</EuiFlexItem>
<EuiFlexItem>
<EuiFlexGroup gutterSize="s" justifyContent="flexEnd">
<EuiFlexItem grow={false}>
<StyledEditButton
size="s"
color="primary"
onClick={handleEdit}
data-test-subj="exceptionsViewerEditBtn"
>
{i18n.EDIT}
</StyledEditButton>
</EuiFlexItem>
<EuiFlexItem grow={false}>
<StyledRemoveButton
size="s"
color="danger"
onClick={handleDelete}
data-test-subj="exceptionsViewerDeleteBtn"
>
{i18n.REMOVE}
</StyledRemoveButton>
</EuiFlexItem>
</EuiFlexGroup>
</EuiFlexItem>
</EuiFlexGroup>
</EntriesDetails>
);
};
ExceptionEntriesComponent.displayName = 'ExceptionEntriesComponent';
export const ExceptionEntries = React.memo(ExceptionEntriesComponent);
ExceptionEntries.displayName = 'ExceptionEntries';

View file

@ -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(
<ThemeProvider theme={() => ({ eui: euiLightVars, darkMode: false })}>
<ExceptionItem
commentsAccordionId={'accordion--comments'}
handleDelete={jest.fn()}
handleEdit={jest.fn()}
exceptionItem={exceptionItem}
/>
</ThemeProvider>
);
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(
<ThemeProvider theme={() => ({ eui: euiLightVars, darkMode: false })}>
<ExceptionItem
commentsAccordionId={'accordion--comments'}
handleDelete={jest.fn()}
handleEdit={mockHandleEdit}
exceptionItem={exceptionItem}
/>
</ThemeProvider>
);
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(
<ThemeProvider theme={() => ({ eui: euiLightVars, darkMode: false })}>
<ExceptionItem
commentsAccordionId={'accordion--comments'}
handleDelete={mockHandleDelete}
handleEdit={jest.fn()}
exceptionItem={exceptionItem}
/>
</ThemeProvider>
);
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(
<ThemeProvider theme={() => ({ eui: euiLightVars, darkMode: false })}>
<ExceptionItem
commentsAccordionId={'accordion--comments'}
handleDelete={mockHandleDelete}
handleEdit={jest.fn()}
exceptionItem={exceptionItem}
/>
</ThemeProvider>
);
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(
<ThemeProvider theme={() => ({ eui: euiLightVars, darkMode: false })}>
<ExceptionItem
commentsAccordionId={'accordion--comments'}
handleDelete={mockHandleDelete}
handleEdit={jest.fn()}
exceptionItem={exceptionItem}
/>
</ThemeProvider>
);
const commentsBtn = wrapper
.find('.euiButtonEmpty[data-test-subj="exceptionsViewerItemCommentsBtn"]')
.at(0);
commentsBtn.simulate('click');
expect(wrapper.find('.euiAccordion-isOpen')).toHaveLength(1);
});
});

View file

@ -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<FormattedEntry[]>([]);
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 (
<EuiPanel paddingSize="none">
<EuiFlexGroup direction="column" gutterSize="none">
<EuiFlexItem>
<EuiFlexGroup direction="row">
<ExceptionDetails
showComments={showComments}
exceptionItem={exceptionItem}
onCommentsClick={onCommentsClick}
/>
<ExceptionEntries entries={entryItems} handleDelete={onDelete} handleEdit={onEdit} />
</EuiFlexGroup>
</EuiFlexItem>
<MyFlexItem className={showComments ? 'comments--show' : ''}>
<EuiAccordion
id={commentsAccordionId}
arrowDisplay="none"
forceState={showComments ? 'open' : 'closed'}
data-test-subj="exceptionsViewerCommentAccordion"
>
<EuiCommentList comments={formattedComments} />
</EuiAccordion>
</MyFlexItem>
</EuiFlexGroup>
</EuiPanel>
);
};
ExceptionItemComponent.displayName = 'ExceptionItemComponent';
export const ExceptionItem = React.memo(ExceptionItemComponent);
ExceptionItem.displayName = 'ExceptionItem';

View file

@ -11,3 +11,4 @@ export {
mockNewExceptionItem,
mockNewExceptionList,
} from '../../lists/public';
export { ExceptionListItemSchema, Entries } from '../../lists/common/schemas';

View file

@ -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', () => <AndOrBadge type="and" />)
.add('or', () => <AndOrBadge type="or" />);

View file

@ -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 (
<RoundedBadge data-test-subj="and-or-badge" color="hollow">
{type === 'and' ? i18n.AND : i18n.OR}
</RoundedBadge>
);
});
AndOrBadge.displayName = 'AndOrBadge';

View file

@ -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';

View file

@ -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,

View file

@ -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';

View file

@ -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')],
});