[Security Solution] Indicator Matches Rendering Performance in Event Rendered View. (#154821)

## Summary

Handles :  https://github.com/elastic/kibana/issues/150982

When encountered with large number of threat indicator matches, there
was a lag in rendering of Event Rendered View because of sheer size of
DOM that needed to be rendered.

This PR defers the rendering of all indicator matches to a modal which
user can open/close on demand. Currently, MAX_RENDERED matches are `2`
at a time but it can be changed.

This number has been set so as to provide user with optimal performance
event when 100 Rows are displayed. Demo below:


https://user-images.githubusercontent.com/7485038/231473548-e18b3999-ea13-4a72-a78b-feff8eec99a9.mov

### Checklist

Delete any items that are not applicable to this PR.

- [x] Any text added follows [EUI's writing
guidelines](https://elastic.github.io/eui/#/guidelines/writing), uses
sentence case text and includes [i18n
support](https://github.com/elastic/kibana/blob/main/packages/kbn-i18n/README.md)
- [x]
[Documentation](https://www.elastic.co/guide/en/kibana/master/development-documentation.html)
was added for features that require explanation or tutorials
- [x] [Unit or functional
tests](https://www.elastic.co/guide/en/kibana/master/development-tests.html)
were updated or added to match the most common scenarios
- [x] Any UI touched in this PR is usable by keyboard only (learn more
about [keyboard accessibility](https://webaim.org/techniques/keyboard/))
- [x] Any UI touched in this PR does not create any new axe failures
(run axe in browser:
[FF](https://addons.mozilla.org/en-US/firefox/addon/axe-devtools/),
[Chrome](https://chrome.google.com/webstore/detail/axe-web-accessibility-tes/lhdoppojpmngadmnindnejefpokejbdd?hl=en-US))
- [x] If a plugin configuration key changed, check if it needs to be
allowlisted in the cloud and added to the [docker
list](https://github.com/elastic/kibana/blob/main/src/dev/build/tasks/os_packages/docker_generator/resources/base/bin/kibana-docker)
- [x] This renders correctly on smaller devices using a responsive
layout. (You can test this [in your
browser](https://www.browserstack.com/guide/responsive-testing-on-local-server))
- [x] This was checked for [cross-browser
compatibility](https://www.elastic.co/support/matrix#matrix_browsers)


### Risk Matrix

Delete this section if it is not applicable to this PR.

Before closing this PR, invite QA, stakeholders, and other developers to
identify risks that should be tested prior to the change/feature
release.

When forming the risk matrix, consider some of the following examples
and how they may potentially impact the change:

| Risk | Probability | Severity | Mitigation/Notes |

|---------------------------|-------------|----------|-------------------------|
| Multiple Spaces—unexpected behavior in non-default Kibana Space.
| Low | High | Integration tests will verify that all features are still
supported in non-default Kibana Space and when user switches between
spaces. |
| Multiple nodes—Elasticsearch polling might have race conditions
when multiple Kibana nodes are polling for the same tasks. | High | Low
| Tasks are idempotent, so executing them multiple times will not result
in logical error, but will degrade performance. To test for this case we
add plenty of unit tests around this logic and document manual testing
procedure. |
| Code should gracefully handle cases when feature X or plugin Y are
disabled. | Medium | High | Unit tests will verify that any feature flag
or plugin combination still results in our service operational. |
| [See more potential risk
examples](https://github.com/elastic/kibana/blob/main/RISK_MATRIX.mdx) |


### For maintainers

- [ ] This was checked for breaking API changes and was [labeled
appropriately](https://www.elastic.co/guide/en/kibana/master/contributing.html#kibana-release-notes-process)
This commit is contained in:
Jatin Kathuria 2023-04-20 14:43:17 +02:00 committed by GitHub
parent 20532c8051
commit eb9c868779
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
5 changed files with 177 additions and 24 deletions

View file

@ -6,14 +6,18 @@
*/
import { TimelineId } from '../../../../../../../common/types';
import { render } from '@testing-library/react';
import { render, fireEvent } from '@testing-library/react';
import React from 'react';
import { get } from 'lodash';
import { getThreatMatchDetectionAlert, TestProviders } from '../../../../../../common/mock';
import type { Fields } from '../../../../../../../common/search_strategy';
import { threatMatchRowRenderer } from './threat_match_row_renderer';
import { useKibana } from '../../../../../../common/lib/kibana';
import { mockTimelines } from '../../../../../../common/mock/mock_timelines_plugin';
import { ENRICHMENT_DESTINATION_PATH } from '../../../../../../../common/constants';
import type { ThreatEnrichmentEcs } from '@kbn/securitysolution-ecs/src/threat';
jest.mock('../../../../../../common/lib/kibana');
describe('threatMatchRowRenderer', () => {
@ -73,5 +77,36 @@ describe('threatMatchRowRenderer', () => {
expect(getByTestId('threat-match-details')).toBeInTheDocument();
});
it('rendered when indicator matches are more than MAX rendered', async () => {
const NO_OF_MATCHES = 20;
const largeNoOfIndicatorMatches = new Array(NO_OF_MATCHES)
.fill({})
.map(() => get(threatMatchData, ENRICHMENT_DESTINATION_PATH)[0] as Fields);
const modThreatMatchData: typeof threatMatchData = {
...threatMatchData,
threat: {
enrichments: largeNoOfIndicatorMatches as ThreatEnrichmentEcs[],
},
};
const children = threatMatchRowRenderer.renderRow({
data: modThreatMatchData,
isDraggable: true,
scopeId: TimelineId.test,
});
const { getByTestId, queryAllByTestId, findAllByTestId, findByTestId } = render(
<TestProviders>{children}</TestProviders>
);
expect(getByTestId('threat-match-row-show-all')).toBeVisible();
expect(queryAllByTestId('threat-match-row').length).toBe(2);
fireEvent.click(getByTestId('threat-match-row-show-all'));
expect(await findByTestId('threat-match-row-modal')).toBeVisible();
expect((await findAllByTestId('threat-match-row')).length).toBe(NO_OF_MATCHES + 2);
});
});
});

View file

@ -8,10 +8,10 @@
import type { RowRenderer } from '../../../../../../../common/types/timeline';
import { RowRendererId } from '../../../../../../../common/types/timeline';
import { hasThreatMatchValue } from './helpers';
import { ThreatMatchRows } from './threat_match_rows';
import { renderThreatMatchRows } from './threat_match_rows';
export const threatMatchRowRenderer: RowRenderer = {
id: RowRendererId.threat_match,
isInstance: hasThreatMatchValue,
renderRow: ThreatMatchRows,
renderRow: renderThreatMatchRows,
};

View file

@ -5,44 +5,140 @@
* 2.0.
*/
import { EuiHorizontalRule } from '@elastic/eui';
import {
EuiButton,
EuiButtonEmpty,
EuiFlexGroup,
EuiFlexItem,
EuiHorizontalRule,
EuiModal,
EuiModalBody,
EuiModalFooter,
EuiModalHeader,
EuiModalHeaderTitle,
} from '@elastic/eui';
import { get } from 'lodash';
import React, { Fragment } from 'react';
import type { FC, ReactElement } from 'react';
import React, { Fragment, useState, useCallback } from 'react';
import styled from 'styled-components';
import type { EcsSecurityExtension } from '@kbn/securitysolution-ecs';
import { ENRICHMENT_DESTINATION_PATH } from '../../../../../../../common/constants';
import type { RowRenderer } from '../../../../../../../common/types';
import type { Fields } from '../../../../../../../common/search_strategy';
import { ID_FIELD_NAME } from '../../../../../../common/components/event_details/event_id';
import { RowRendererContainer } from '../row_renderer';
import { ThreatMatchRow } from './threat_match_row';
import {
ALL_INDICATOR_MATCHES_MODAL_CLOSE,
ALL_INDICATOR_MATCHES_MODAL_HEADER,
SHOW_ALL_INDICATOR_MATCHES,
} from '../translations';
const SpacedContainer = styled.div`
margin: ${({ theme }) => theme.eui.euiSizeS} 0;
`;
export const ThreatMatchRows: RowRenderer['renderRow'] = ({ data, isDraggable, scopeId }) => {
export const renderThreatMatchRows: RowRenderer['renderRow'] = ({ data, isDraggable, scopeId }) => {
return <ThreatMatchRowWrapper data={data} isDraggable={isDraggable} scopeId={scopeId} />;
};
interface ThreatMatchRowProps {
data: EcsSecurityExtension;
isDraggable: boolean;
scopeId: string;
}
const MAX_INDICATOR_VISIBLE = 2;
const ThreatMatchRowWrapper: FC<ThreatMatchRowProps> = ({ data, isDraggable, scopeId }) => {
const indicators = get(data, ENRICHMENT_DESTINATION_PATH) as Fields[];
const eventId = get(data, ID_FIELD_NAME);
const getThreatMatchRows = useCallback(
(mode: 'max' | 'all' = 'max') => {
const allIndicators =
mode === 'max' ? indicators.slice(0, MAX_INDICATOR_VISIBLE) : indicators;
return (
<RowRendererContainer data-test-subj="threat-match-row-renderer">
<SpacedContainer>
{allIndicators.map((indicator, index) => {
const contextId = `threat-match-row-${scopeId}-${eventId}-${index}`;
return (
<Fragment key={contextId}>
<ThreatMatchRow
contextId={contextId}
data={indicator}
eventId={eventId}
isDraggable={isDraggable}
/>
{index < indicators.length - 1 && <EuiHorizontalRule margin="s" />}
</Fragment>
);
})}
</SpacedContainer>
</RowRendererContainer>
);
},
[indicators, eventId, isDraggable, scopeId]
);
const renderModalChildren = useCallback(() => getThreatMatchRows('all'), [getThreatMatchRows]);
return (
<RowRendererContainer data-test-subj="threat-match-row-renderer">
<SpacedContainer>
{indicators.map((indicator, index) => {
const contextId = `threat-match-row-${scopeId}-${eventId}-${index}`;
return (
<Fragment key={contextId}>
<ThreatMatchRow
contextId={contextId}
data={indicator}
eventId={eventId}
isDraggable={isDraggable}
/>
{index < indicators.length - 1 && <EuiHorizontalRule margin="s" />}
</Fragment>
);
})}
</SpacedContainer>
</RowRendererContainer>
<EuiFlexGroup direction="column" justifyContent="center" alignItems="center" gutterSize="none">
<EuiFlexItem>{getThreatMatchRows()}</EuiFlexItem>
{indicators.length > MAX_INDICATOR_VISIBLE && (
<EuiFlexItem>
<ThreatMatchRowModal
title={SHOW_ALL_INDICATOR_MATCHES(indicators.length)}
renderChildren={renderModalChildren}
/>
</EuiFlexItem>
)}
</EuiFlexGroup>
);
};
interface ThreatMatchRowModalProps {
title: string;
renderChildren: () => ReactElement;
}
const ThreatMatchRowModal: FC<ThreatMatchRowModalProps> = ({ title, renderChildren }) => {
const [isModalVisible, setShowModal] = useState(false);
const closeModal = () => setShowModal(false);
const showModal = () => setShowModal(true);
let modal;
if (isModalVisible) {
modal = (
<EuiModal onClose={closeModal}>
<EuiModalHeader data-test-subj="threat-match-row-modal">
<EuiModalHeaderTitle>{ALL_INDICATOR_MATCHES_MODAL_HEADER}</EuiModalHeaderTitle>
</EuiModalHeader>
<EuiModalBody>{renderChildren()}</EuiModalBody>
<EuiModalFooter>
<EuiButton onClick={closeModal} fill>
{ALL_INDICATOR_MATCHES_MODAL_CLOSE}
</EuiButton>
</EuiModalFooter>
</EuiModal>
);
}
return (
<div>
<EuiButtonEmpty
data-test-subj="threat-match-row-show-all"
iconType="popout"
color="primary"
onClick={showModal}
>
{title}
</EuiButtonEmpty>
{modal}
</div>
);
};

View file

@ -40,3 +40,23 @@ export const LINK_ELASTIC_ENDPOINT_SECURITY = i18n.translate(
defaultMessage: 'Open in Endpoint Security',
}
);
export const SHOW_ALL_INDICATOR_MATCHES = (count: number) =>
i18n.translate('xpack.securitySolution.event.summary.threat_indicator.showMatches', {
values: { count },
defaultMessage: 'Show all {count} indicator match alerts',
});
export const ALL_INDICATOR_MATCHES_MODAL_HEADER = i18n.translate(
'xpack.securitySolution.event.summary.threat_indicator.modal.allMatches',
{
defaultMessage: 'All Indicator Matches',
}
);
export const ALL_INDICATOR_MATCHES_MODAL_CLOSE = i18n.translate(
'xpack.securitySolution.event.summary.threat_indicator.modal.close',
{
defaultMessage: 'Close',
}
);

View file

@ -16,6 +16,8 @@ import { getLinkColumnDefinition } from '../../../../common/lib/cell_actions/hel
const StyledContent = styled.div<{ $isDetails: boolean }>`
padding: ${({ $isDetails }) => ($isDetails ? '0 8px' : undefined)};
width: 100%;
margin: 0 auto;
`;
export const DefaultCellRenderer: React.FC<CellValueElementProps> = ({