Skip to content

Commit

Permalink
alert preview
Browse files Browse the repository at this point in the history
  • Loading branch information
christineweng committed Jun 26, 2024
1 parent 3c78092 commit e08302d
Show file tree
Hide file tree
Showing 35 changed files with 623 additions and 168 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -140,8 +140,9 @@ export const PreviewSection: React.FC<PreviewSectionProps> = ({
css={css`
margin: ${euiTheme.size.xs};
box-shadow: 0 0 4px 4px ${euiTheme.colors.darkShade};
height: 90%;
`}
className="eui-yScroll"
className="eui-fullHeight"
data-test-subj={PREVIEW_SECTION_TEST_ID}
>
{isPreviewBanner(banner) && (
Expand All @@ -168,7 +169,7 @@ export const PreviewSection: React.FC<PreviewSectionProps> = ({
>
{header}
</EuiSplitPanel.Inner>
<EuiSplitPanel.Inner paddingSize="none">{component}</EuiSplitPanel.Inner>
{component}
</EuiSplitPanel.Outer>
</div>
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,11 @@ export const allowedExperimentalValues = Object.freeze({
*/
securitySolutionNotesEnabled: false,

/**
* Enables entity and alert previews
*/
entityAlertPreviewEnabled: false,

/**
* Enables the Assistant Model Evaluation advanced setting and API endpoint, introduced in `8.11.0`.
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,24 +8,49 @@
import React from 'react';
import { render } from '@testing-library/react';
import { TestProviders } from '../../../../common/mock';
import { EuiBasicTable } from '@elastic/eui';
import { CorrelationsDetailsAlertsTable, columns } from './correlations_details_alerts_table';
import { useExpandableFlyoutApi } from '@kbn/expandable-flyout';
import { CorrelationsDetailsAlertsTable } from './correlations_details_alerts_table';
import { usePaginatedAlerts } from '../hooks/use_paginated_alerts';
import { CORRELATIONS_DETAILS_ALERT_LINK_TEST_ID } from './test_ids';
import { useIsExperimentalFeatureEnabled } from '../../../../common/hooks/use_experimental_features';
import { mockFlyoutApi } from '../../shared/mocks/mock_flyout_context';
import { mockContextValue } from '../../shared/mocks/mock_context';
import { DocumentDetailsPreviewPanelKey } from '../../shared/constants/panel_keys';
import { ALERT_PREVIEW_BANNER } from '../../preview';
import { DocumentDetailsContext } from '../../shared/context';

jest.mock('../hooks/use_paginated_alerts');
jest.mock('@elastic/eui', () => ({
...jest.requireActual('@elastic/eui'),
EuiBasicTable: jest.fn(() => <div data-testid="mock-euibasictable" />),
jest.mock('../../../../common/hooks/use_experimental_features');
const mockUseIsExperimentalFeatureEnabled = useIsExperimentalFeatureEnabled as jest.Mock;

jest.mock('@kbn/expandable-flyout', () => ({
useExpandableFlyoutApi: jest.fn(),
ExpandableFlyoutProvider: ({ children }: React.PropsWithChildren<{}>) => <>{children}</>,
}));

const TEST_ID = 'TEST';
const scopeId = 'scopeId';
const eventId = 'eventId';
const alertIds = ['id1', 'id2', 'id3'];

describe('CorrelationsDetailsAlertsTable', () => {
const alertIds = ['id1', 'id2', 'id3'];
const renderCorrelationsTable = (panelContext: DocumentDetailsContext) =>
render(
<TestProviders>
<DocumentDetailsContext.Provider value={panelContext}>
<CorrelationsDetailsAlertsTable
title={<p>{'title'}</p>}
loading={false}
alertIds={alertIds}
scopeId={mockContextValue.scopeId}
eventId={mockContextValue.eventId}
data-test-subj={TEST_ID}
/>
</DocumentDetailsContext.Provider>
</TestProviders>
);

describe('CorrelationsDetailsAlertsTable', () => {
beforeEach(() => {
jest.mocked(useExpandableFlyoutApi).mockReturnValue(mockFlyoutApi);
mockUseIsExperimentalFeatureEnabled.mockReturnValue(false);
jest.mocked(usePaginatedAlerts).mockReturnValue({
setPagination: jest.fn(),
setSorting: jest.fn(),
Expand Down Expand Up @@ -64,44 +89,43 @@ describe('CorrelationsDetailsAlertsTable', () => {
});

it('renders EuiBasicTable with correct props', () => {
const { getByTestId } = render(
<TestProviders>
<CorrelationsDetailsAlertsTable
title={<p>{'title'}</p>}
loading={false}
alertIds={alertIds}
scopeId={scopeId}
eventId={eventId}
data-test-subj={TEST_ID}
/>
</TestProviders>
);
const { getByTestId, queryByTestId, queryAllByRole } =
renderCorrelationsTable(mockContextValue);

expect(getByTestId(`${TEST_ID}InvestigateInTimeline`)).toBeInTheDocument();
expect(getByTestId(`${TEST_ID}Table`)).toBeInTheDocument();
expect(queryByTestId(CORRELATIONS_DETAILS_ALERT_LINK_TEST_ID)).not.toBeInTheDocument();

expect(jest.mocked(usePaginatedAlerts)).toHaveBeenCalled();

expect(jest.mocked(EuiBasicTable)).toHaveBeenCalledWith(
expect.objectContaining({
loading: false,
items: [
{
'@timestamp': '2022-01-01',
'kibana.alert.rule.name': 'Rule1',
'kibana.alert.reason': 'Reason1',
'kibana.alert.severity': 'Severity1',
},
{
'@timestamp': '2022-01-02',
'kibana.alert.rule.name': 'Rule2',
'kibana.alert.reason': 'Reason2',
'kibana.alert.severity': 'Severity2',
},
],
columns,
pagination: { pageIndex: 0, pageSize: 5, totalItemCount: 10, pageSizeOptions: [5, 10, 20] },
sorting: { sort: { field: '@timestamp', direction: 'asc' }, enableAllColumns: true },
}),
expect.anything()
);
expect(queryAllByRole('columnheader').length).toBe(4);
expect(queryAllByRole('row').length).toBe(3); // 1 header row and 2 data rows
expect(queryAllByRole('row')[1].textContent).toContain('Jan 1, 2022 @ 00:00:00.000');
expect(queryAllByRole('row')[1].textContent).toContain('Reason1');
expect(queryAllByRole('row')[1].textContent).toContain('Rule1');
expect(queryAllByRole('row')[1].textContent).toContain('Severity1');
});

it('renders alert preview link when feature flag is on', () => {
mockUseIsExperimentalFeatureEnabled.mockReturnValue(true);
const { getByTestId, getAllByTestId } = renderCorrelationsTable({
...mockContextValue,
isPreviewMode: true,
});

expect(getByTestId(`${TEST_ID}InvestigateInTimeline`)).toBeInTheDocument();
expect(getAllByTestId(CORRELATIONS_DETAILS_ALERT_LINK_TEST_ID).length).toBe(2);

getAllByTestId(CORRELATIONS_DETAILS_ALERT_LINK_TEST_ID)[0].click();
expect(mockFlyoutApi.openPreviewPanel).toHaveBeenCalledWith({
id: DocumentDetailsPreviewPanelKey,
params: {
id: '1',
indexName: 'index',
scopeId: mockContextValue.scopeId,
banner: ALERT_PREVIEW_BANNER,
isPreviewMode: true,
},
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,17 @@

import type { ReactElement, ReactNode } from 'react';
import React, { type FC, useMemo, useCallback } from 'react';
import { type Criteria, EuiBasicTable, formatDate } from '@elastic/eui';
import { type Criteria, EuiBasicTable, formatDate, EuiLink } from '@elastic/eui';
import { Severity } from '@kbn/securitysolution-io-ts-alerting-types';
import type { Filter } from '@kbn/es-query';
import { isRight } from 'fp-ts/lib/Either';
import { useExpandableFlyoutApi } from '@kbn/expandable-flyout';
import { ALERT_REASON, ALERT_RULE_NAME } from '@kbn/rule-data-utils';
import { FormattedMessage } from '@kbn/i18n-react';
import { i18n } from '@kbn/i18n';
import { useIsExperimentalFeatureEnabled } from '../../../../common/hooks/use_experimental_features';
import { useDocumentDetailsContext } from '../../shared/context';
import { CORRELATIONS_DETAILS_ALERT_LINK_TEST_ID } from './test_ids';
import { CellTooltipWrapper } from '../../shared/components/cell_tooltip_wrapper';
import type { DataProvider } from '../../../../../common/types';
import { SeverityBadge } from '../../../../common/components/severity_badge';
Expand All @@ -22,10 +26,56 @@ import { ExpandablePanel } from '../../../shared/components/expandable_panel';
import { InvestigateInTimelineButton } from '../../../../common/components/event_details/table/investigate_in_timeline_button';
import { ACTION_INVESTIGATE_IN_TIMELINE } from '../../../../detections/components/alerts_table/translations';
import { getDataProvider } from '../../../../common/components/event_details/table/use_action_cell_data_provider';
import { DocumentDetailsPreviewPanelKey } from '../../shared/constants/panel_keys';
import { ALERT_PREVIEW_BANNER } from '../../preview';

export const TIMESTAMP_DATE_FORMAT = 'MMM D, YYYY @ HH:mm:ss.SSS';
const dataProviderLimit = 5;

interface RuleLinkProps {
/**
* Rule name of the alert
*/
ruleName: string;
/**
* Id of the document
*/
id: string;
/**
* Name of the index used in the parent's page
*/
indexName: string;
}

const RuleLink: FC<RuleLinkProps> = ({ ruleName, id, indexName }) => {
const { openPreviewPanel } = useExpandableFlyoutApi();
const { scopeId } = useDocumentDetailsContext();
const isPreviewEnabled = useIsExperimentalFeatureEnabled('entityAlertPreviewEnabled');

const openAlertPreview = useCallback(
() =>
openPreviewPanel({
id: DocumentDetailsPreviewPanelKey,
params: {
id,
indexName,
scopeId,
isPreviewMode: true,
banner: ALERT_PREVIEW_BANNER,
},
}),
[openPreviewPanel, id, indexName, scopeId]
);

return isPreviewEnabled ? (
<EuiLink data-test-subj={CORRELATIONS_DETAILS_ALERT_LINK_TEST_ID} onClick={openAlertPreview}>
{ruleName}
</EuiLink>
) : (
<span>{ruleName}</span>
);
};

export const columns = [
{
field: '@timestamp',
Expand All @@ -47,19 +97,21 @@ export const columns = [
},
},
{
field: ALERT_RULE_NAME,
name: (
<FormattedMessage
id="xpack.securitySolution.flyout.left.insights.correlations.ruleColumnLabel"
defaultMessage="Rule"
defaultMessage="Alert"
/>
),
truncateText: true,
render: (value: string) => (
<CellTooltipWrapper tooltip={value}>
<span>{value}</span>
</CellTooltipWrapper>
),
render: (data: Record<string, unknown>) => {
const ruleName = data[ALERT_RULE_NAME] as string;
return (
<CellTooltipWrapper tooltip={ruleName}>
<RuleLink ruleName={ruleName} id={data.id as string} indexName={data.index as string} />
</CellTooltipWrapper>
);
},
},
{
field: ALERT_REASON,
Expand Down Expand Up @@ -166,13 +218,19 @@ export const CorrelationsDetailsAlertsTable: FC<CorrelationsDetailsAlertsTablePr

const mappedData = useMemo(() => {
return data
.map((hit) => hit.fields)
.map((fields = {}) =>
Object.keys(fields).reduce((result, fieldName) => {
result[fieldName] = fields?.[fieldName]?.[0] || fields?.[fieldName];
.map((hit) => {
return { fields: hit.fields ?? {}, id: hit._id, index: hit._index };
})
.map((dataWithMeta) => {
const res = Object.keys(dataWithMeta.fields).reduce((result, fieldName) => {
result[fieldName] =
dataWithMeta.fields?.[fieldName]?.[0] || dataWithMeta.fields?.[fieldName];
return result;
}, {} as Record<string, unknown>)
);
}, {} as Record<string, unknown>);
res.id = dataWithMeta.id;
res.index = dataWithMeta.index;
return res;
});
}, [data]);

const shouldUseFilters = Boolean(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
import React from 'react';
import { render } from '@testing-library/react';
import { TestProviders } from '../../../../common/mock';
import { DocumentDetailsContext } from '../../shared/context';
import { mockContextValue } from '../../shared/mocks/mock_context';
import {
CORRELATIONS_DETAILS_BY_ANCESTRY_SECTION_TABLE_TEST_ID,
CORRELATIONS_DETAILS_BY_ANCESTRY_SECTION_TEST_ID,
Expand Down Expand Up @@ -41,7 +43,9 @@ const TITLE_TEXT = EXPANDABLE_PANEL_HEADER_TITLE_TEXT_TEST_ID(
const renderRelatedAlertsByAncestry = () =>
render(
<TestProviders>
<RelatedAlertsByAncestry documentId={documentId} indices={indices} scopeId={scopeId} />
<DocumentDetailsContext.Provider value={mockContextValue}>
<RelatedAlertsByAncestry documentId={documentId} indices={indices} scopeId={scopeId} />
</DocumentDetailsContext.Provider>
</TestProviders>
);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
import React from 'react';
import { render } from '@testing-library/react';
import { TestProviders } from '../../../../common/mock';
import { DocumentDetailsContext } from '../../shared/context';
import { mockContextValue } from '../../shared/mocks/mock_context';
import {
CORRELATIONS_DETAILS_BY_SOURCE_SECTION_TEST_ID,
CORRELATIONS_DETAILS_BY_SOURCE_SECTION_TABLE_TEST_ID,
Expand Down Expand Up @@ -41,11 +43,13 @@ const TITLE_TEXT = EXPANDABLE_PANEL_HEADER_TITLE_TEXT_TEST_ID(
const renderRelatedAlertsBySameSourceEvent = () =>
render(
<TestProviders>
<RelatedAlertsBySameSourceEvent
originalEventId={originalEventId}
scopeId={scopeId}
eventId={eventId}
/>
<DocumentDetailsContext.Provider value={mockContextValue}>
<RelatedAlertsBySameSourceEvent
originalEventId={originalEventId}
scopeId={scopeId}
eventId={eventId}
/>
</DocumentDetailsContext.Provider>
</TestProviders>
);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
import React from 'react';
import { render } from '@testing-library/react';
import { TestProviders } from '../../../../common/mock';
import { DocumentDetailsContext } from '../../shared/context';
import { mockContextValue } from '../../shared/mocks/mock_context';
import {
CORRELATIONS_DETAILS_BY_SESSION_SECTION_TABLE_TEST_ID,
CORRELATIONS_DETAILS_BY_SESSION_SECTION_TEST_ID,
Expand Down Expand Up @@ -41,7 +43,9 @@ const TITLE_TEXT = EXPANDABLE_PANEL_HEADER_TITLE_TEXT_TEST_ID(
const renderRelatedAlertsBySession = () =>
render(
<TestProviders>
<RelatedAlertsBySession entityId={entityId} scopeId={scopeId} eventId={eventId} />
<DocumentDetailsContext.Provider value={mockContextValue}>
<RelatedAlertsBySession entityId={entityId} scopeId={scopeId} eventId={eventId} />
</DocumentDetailsContext.Provider>
</TestProviders>
);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,9 @@ export const THREAT_INTELLIGENCE_DETAILS_LOADING_TEST_ID =

export const CORRELATIONS_DETAILS_TEST_ID = `${PREFIX}CorrelationsDetails` as const;

export const CORRELATIONS_DETAILS_ALERT_LINK_TEST_ID =
`${CORRELATIONS_DETAILS_TEST_ID}AlertLink` as const;

export const CORRELATIONS_DETAILS_BY_ANCESTRY_SECTION_TEST_ID =
`${CORRELATIONS_DETAILS_TEST_ID}AlertsByAncestrySection` as const;
export const CORRELATIONS_DETAILS_BY_ANCESTRY_SECTION_TABLE_TEST_ID =
Expand Down
Loading

0 comments on commit e08302d

Please sign in to comment.