Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[SIEM] Threat hunting enhancements: Filter for/out value, Show top field, Copy to Clipboard, Draggable chart legends #61207

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions x-pack/legacy/plugins/siem/common/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,3 +111,20 @@ export const NOTIFICATION_SUPPORTED_ACTION_TYPES_IDS = [
];
export const NOTIFICATION_THROTTLE_NO_ACTIONS = 'no_actions';
export const NOTIFICATION_THROTTLE_RULE = 'rule';

/**
* Histograms for fields named in this list should be displayed with an
* "All others" bucket, to count events that don't specify a value for
* the field being counted
*/
export const showAllOthersBucket: string[] = [
'destination.ip',
'event.action',
'event.category',
'event.dataset',
'event.module',
'signal.rule.threat.tactic.name',
'source.ip',
'destination.ip',
'user.name',
];
116 changes: 114 additions & 2 deletions x-pack/legacy/plugins/siem/public/components/charts/barchart.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,29 @@
* you may not use this file except in compliance with the Elastic License.
*/

import { shallow, ShallowWrapper } from 'enzyme';
import { Chart, BarSeries, Axis, ScaleType } from '@elastic/charts';
import euiDarkVars from '@elastic/eui/dist/eui_theme_dark.json';
import { mount, ReactWrapper, shallow, ShallowWrapper } from 'enzyme';
import React from 'react';
import { ThemeProvider } from 'styled-components';

import { escapeDataProviderId } from '../drag_and_drop/helpers';
import { TestProviders } from '../../mock';

import { BarChartBaseComponent, BarChartComponent } from './barchart';
import { ChartSeriesData } from './common';
import { Chart, BarSeries, Axis, ScaleType } from '@elastic/charts';

jest.mock('../../lib/kibana');

jest.mock('uuid', () => {
return {
v1: jest.fn(() => 'uuid.v1()'),
v4: jest.fn(() => 'uuid.v4()'),
};
});

const theme = () => ({ eui: euiDarkVars, darkMode: true });

const customHeight = '100px';
const customWidth = '120px';
const chartDataSets = [
Expand Down Expand Up @@ -116,6 +130,19 @@ const mockConfig = {
customHeight: 324,
};

// Suppress warnings about "react-beautiful-dnd"
/* eslint-disable no-console */
const originalError = console.error;
const originalWarn = console.warn;
beforeAll(() => {
console.warn = jest.fn();
console.error = jest.fn();
});
afterAll(() => {
console.error = originalError;
console.warn = originalWarn;
});

describe('BarChartBaseComponent', () => {
let shallowWrapper: ShallowWrapper;
const mockBarChartData: ChartSeriesData[] = [
Expand Down Expand Up @@ -280,6 +307,91 @@ describe.each(chartDataSets)('BarChart with valid data [%o]', data => {
expect(shallowWrapper.find('BarChartBase')).toHaveLength(1);
expect(shallowWrapper.find('ChartPlaceHolder')).toHaveLength(0);
});

it('it does NOT render a draggable legend because stackByField is not provided', () => {
expect(shallowWrapper.find('[data-test-subj="draggable-legend"]').exists()).toBe(false);
});
});

describe.each(chartDataSets)('BarChart with stackByField', () => {
let wrapper: ReactWrapper;

const data = [
{
key: 'python.exe',
value: [
{
x: 1586754900000,
y: 9675,
g: 'python.exe',
},
],
},
{
key: 'kernel',
value: [
{
x: 1586754900000,
y: 8708,
g: 'kernel',
},
{
x: 1586757600000,
y: 9282,
g: 'kernel',
},
],
},
{
key: 'sshd',
value: [
{
x: 1586754900000,
y: 5907,
g: 'sshd',
},
],
},
];

const expectedColors = ['#1EA593', '#2B70F7', '#CE0060'];

const stackByField = 'process.name';

beforeAll(() => {
wrapper = mount(
<ThemeProvider theme={theme}>
<TestProviders>
<BarChartComponent configs={mockConfig} barChart={data} stackByField={stackByField} />
</TestProviders>
</ThemeProvider>
);
});

it('it renders a draggable legend', () => {
expect(wrapper.find('[data-test-subj="draggable-legend"]').exists()).toBe(true);
});

expectedColors.forEach((color, i) => {
test(`it renders the expected legend color ${color} for legend item ${i}`, () => {
expect(wrapper.find(`div [color="${color}"]`).exists()).toBe(true);
});
});

data.forEach(datum => {
test(`it renders the expected draggable legend text for datum ${datum.key}`, () => {
const dataProviderId = `draggableId.content.draggable-legend-item-uuid_v4()-${escapeDataProviderId(
stackByField
)}-${escapeDataProviderId(datum.key)}`;

expect(
wrapper
.find(`div [data-rbd-draggable-id="${dataProviderId}"]`)
.first()
.text()
).toEqual(datum.key);
});
});
});

describe.each(chartHolderDataSets)('BarChart with invalid data [%o]', data => {
Expand Down
65 changes: 57 additions & 8 deletions x-pack/legacy/plugins/siem/public/components/charts/barchart.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,19 @@
* you may not use this file except in compliance with the Elastic License.
*/

import React from 'react';
import { EuiFlexGroup, EuiFlexItem } from '@elastic/eui';
import React, { useMemo } from 'react';
import { Chart, BarSeries, Axis, Position, ScaleType, Settings } from '@elastic/charts';
import { getOr, get, isNumber } from 'lodash/fp';
import deepmerge from 'deepmerge';
import uuid from 'uuid';
import styled from 'styled-components';

import { useThrottledResizeObserver } from '../utils';
import { escapeDataProviderId } from '../drag_and_drop/helpers';
import { useTimeZone } from '../../lib/kibana';
import { defaultLegendColors } from '../matrix_histogram/utils';
import { useThrottledResizeObserver } from '../utils';

import { ChartPlaceHolder } from './chart_place_holder';
import {
chartDefaultSettings,
Expand All @@ -22,6 +28,12 @@ import {
WrappedByAutoSizer,
useTheme,
} from './common';
import { DraggableLegend } from './draggable_legend';
import { LegendItem } from './draggable_legend_item';

const LegendFlexItem = styled(EuiFlexItem)`
overview: hidden;
`;

const checkIfAllTheDataInTheSeriesAreValid = (series: ChartSeriesData): series is ChartSeriesData =>
series != null &&
Expand All @@ -38,12 +50,14 @@ const checkIfAnyValidSeriesExist = (
// Bar chart rotation: https://ela.st/chart-rotations
export const BarChartBaseComponent = ({
data,
forceHiddenLegend = false,
...chartConfigs
}: {
data: ChartSeriesData[];
width: string | null | undefined;
height: string | null | undefined;
configs?: ChartSeriesConfigs | undefined;
forceHiddenLegend?: boolean;
}) => {
const theme = useTheme();
const timeZone = useTimeZone();
Expand All @@ -59,10 +73,10 @@ export const BarChartBaseComponent = ({

return chartConfigs.width && chartConfigs.height ? (
<Chart>
<Settings {...settings} />
<Settings {...settings} showLegend={settings.showLegend && !forceHiddenLegend} />
{data.map(series => {
const barSeriesKey = series.key;
return checkIfAllTheDataInTheSeriesAreValid ? (
return checkIfAllTheDataInTheSeriesAreValid(series) ? (
<BarSeries
id={barSeriesKey}
key={barSeriesKey}
Expand Down Expand Up @@ -102,19 +116,54 @@ BarChartBase.displayName = 'BarChartBase';
interface BarChartComponentProps {
barChart: ChartSeriesData[] | null | undefined;
configs?: ChartSeriesConfigs | undefined;
stackByField?: string;
}

export const BarChartComponent: React.FC<BarChartComponentProps> = ({ barChart, configs }) => {
const NO_LEGEND_DATA: LegendItem[] = [];

export const BarChartComponent: React.FC<BarChartComponentProps> = ({
barChart,
configs,
stackByField,
}) => {
const { ref: measureRef, width, height } = useThrottledResizeObserver();
const legendItems: LegendItem[] = useMemo(
() =>
barChart != null && stackByField != null
? barChart.map((d, i) => ({
color: d.color ?? i < defaultLegendColors.length ? defaultLegendColors[i] : undefined,
dataProviderId: escapeDataProviderId(
`draggable-legend-item-${uuid.v4()}-${stackByField}-${d.key}`
),
field: stackByField,
value: d.key,
}))
: NO_LEGEND_DATA,
[barChart, stackByField]
);

const customHeight = get('customHeight', configs);
const customWidth = get('customWidth', configs);
const chartHeight = getChartHeight(customHeight, height);
const chartWidth = getChartWidth(customWidth, width);

return checkIfAnyValidSeriesExist(barChart) ? (
<WrappedByAutoSizer ref={measureRef} height={chartHeight}>
<BarChartBase height={chartHeight} width={chartHeight} data={barChart} configs={configs} />
</WrappedByAutoSizer>
<EuiFlexGroup gutterSize="none">
<EuiFlexItem grow={true}>
<WrappedByAutoSizer ref={measureRef} height={chartHeight}>
<BarChartBase
configs={configs}
data={barChart}
forceHiddenLegend={stackByField != null}
height={chartHeight}
width={chartHeight}
/>
</WrappedByAutoSizer>
</EuiFlexItem>
<LegendFlexItem grow={false}>
<DraggableLegend legendItems={legendItems} height={height} />
</LegendFlexItem>
</EuiFlexGroup>
) : (
<ChartPlaceHolder height={chartHeight} width={chartWidth} data={barChart} />
);
Expand Down
Loading