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

[TIP] Investigate in timeline #140496

Merged
merged 16 commits into from
Sep 19, 2022
Merged
Show file tree
Hide file tree
Changes from 12 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
2 changes: 1 addition & 1 deletion packages/kbn-optimizer/limits.yml
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ pageLoadAssetSize:
synthetics: 40958
telemetry: 51957
telemetryManagementSection: 38586
threatIntelligence: 29195
threatIntelligence: 44299
timelines: 327300
transform: 41007
triggersActionsUi: 119000
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@ import { TrackApplicationView } from '@kbn/usage-collection-plugin/public';
import type { SecuritySolutionPluginContext } from '@kbn/threat-intelligence-plugin/public';
import { THREAT_INTELLIGENCE_BASE_PATH } from '@kbn/threat-intelligence-plugin/public';
import type { SourcererDataView } from '@kbn/threat-intelligence-plugin/public/types';
import type { Store } from 'redux';
import { useInvestigateInTimeline } from './use_investigate_in_timeline';
import { getStore } from '../common/store';
import { useKibana } from '../common/lib/kibana';
import { FiltersGlobal } from '../common/components/filters_global';
import { SpyRoute } from '../common/utils/route/spy_routes';
Expand All @@ -32,11 +35,15 @@ const ThreatIntelligence = memo(() => {
return <Redirect to="/" />;
}

const securitySolutionStore = getStore() as Store;

const securitySolutionContext: SecuritySolutionPluginContext = {
getFiltersGlobalComponent: () => FiltersGlobal,
getPageWrapper: () => SecuritySolutionPageWrapper,
licenseService,
sourcererDataView: sourcererDataView as unknown as SourcererDataView,
getSecuritySolutionStore: securitySolutionStore,
getUseInvestigateInTimeline: useInvestigateInTimeline,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎉

};

return (
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

import { i18n } from '@kbn/i18n';

export const ACTION_INVESTIGATE_IN_TIMELINE = i18n.translate(
'xpack.securitySolution.threatIntelligence.investigateInTimelineTitle',
{
defaultMessage: 'Investigate in timeline',
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I remember talking with UX writer they mentioned that they always use Timeline capitalized and it's the only feature that behaves this way, let's change to Investigate in Timeline

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Though I don't see where this defaultMeassage appears, I'd expect it to show up as a tooltip on the action icon, but it's not there. Btw about tooltips, I see that our expand icon has a tooltip "View Details", but Investigate in Timeline icon doesn't have a tooltip. I think we should add it, but it can be in a separate PR if it's not a one-lines somewhere

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

good point. I've added the tooltip here as well as in every other places in the plugin I could find

}
);
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

import { useCallback, useMemo } from 'react';
import { useDispatch } from 'react-redux';
import { timelineDefaults } from '../timelines/store/timeline/defaults';
import { APP_UI_ID } from '../../common/constants';
import type { DataProvider } from '../../common/types';
import { TimelineId, TimelineType } from '../../common/types';
import { useDeepEqualSelector } from '../common/hooks/use_selector';
import { useKibana } from '../common/lib/kibana';
import { useStartTransaction } from '../common/lib/apm/use_start_transaction';
import { timelineActions, timelineSelectors } from '../timelines/store/timeline';
import { useCreateTimeline } from '../timelines/components/timeline/properties/use_create_timeline';
import type { CreateTimelineProps } from '../detections/components/alerts_table/types';
import { dispatchUpdateTimeline } from '../timelines/components/open_timeline/helpers';

interface UseInvestigateInTimelineActionProps {
/**
* Created when the user clicks on the Investigate in Timeline button.
* DataProvider contain the field(s) and value(s) displayed in the timeline.
*/
dataProviders: DataProvider[];
/**
* Start date used in the createTimeline method.
*/
from: string;
/**
* End date used in the createTimeline method.
*/
to: string;
}

/**
* Hook passed down to the Threat Intelligence plugin, via context.
* This code is closely duplicated from here: https://github.com/elastic/kibana/blob/main/x-pack/plugins/security_solution/public/detections/components/alerts_table/timeline_actions/use_investigate_in_timeline.tsx,
* the main changes being:
* - no exceptions are handled at the moment
* - we use dataProviders, from and to directly instead of consuming ecsData
*/
export const useInvestigateInTimeline = ({
dataProviders,
from,
to,
}: UseInvestigateInTimelineActionProps) => {
const {
data: { query },
} = useKibana().services;
const dispatch = useDispatch();
const { startTransaction } = useStartTransaction();

const filterManagerBackup = useMemo(() => query.filterManager, [query.filterManager]);
const getManageTimeline = useMemo(() => timelineSelectors.getManageTimelineById(), []);
const { filterManager: activeFilterManager } = useDeepEqualSelector((state) =>
getManageTimeline(state, TimelineId.active ?? '')
);
const filterManager = useMemo(
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

out of curiosity what this filterManager does and what is the logic behind filterManagerBackup?

() => activeFilterManager ?? filterManagerBackup,
[activeFilterManager, filterManagerBackup]
);

const updateTimelineIsLoading = useCallback(
(payload) => dispatch(timelineActions.updateIsLoading(payload)),
[dispatch]
);

const clearActiveTimeline = useCreateTimeline({
timelineId: TimelineId.active,
timelineType: TimelineType.default,
});

const createTimeline = useCallback(
({ from: fromTimeline, timeline, to: toTimeline, ruleNote }: CreateTimelineProps) => {
clearActiveTimeline();
updateTimelineIsLoading({ id: TimelineId.active, isLoading: false });
dispatchUpdateTimeline(dispatch)({
duplicate: true,
from: fromTimeline,
id: TimelineId.active,
notes: [],
timeline: {
...timeline,
filterManager,
indexNames: timeline.indexNames ?? [],
show: true,
},
to: toTimeline,
ruleNote,
})();
},
[dispatch, filterManager, updateTimelineIsLoading, clearActiveTimeline]
);

const investigateInTimelineClick = useCallback(async () => {
startTransaction({ name: `${APP_UI_ID} threat indicator investigateInTimeline` });
await createTimeline({
from,
notes: null,
timeline: {
...timelineDefaults,
dataProviders,
id: TimelineId.active,
indexNames: [],
dateRange: {
start: from,
end: to,
},
eventType: 'all',
filters: [],
kqlQuery: {
filterQuery: {
kuery: {
kind: 'kuery',
expression: '',
},
serializedQuery: '',
},
},
},
to,
ruleNote: '',
});
}, [startTransaction, createTimeline, dataProviders, from, to]);

return investigateInTimelineClick;
};
20 changes: 19 additions & 1 deletion x-pack/plugins/threat_intelligence/common/types/indicator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,10 @@ export enum RawIndicatorFieldId {
FileImphash = 'threat.indicator.file.imphash',
FilePehash = 'threat.indicator.file.pehash',
FileVhash = 'threat.indicator.file.vhash',
FileTelfhash = 'threat.indicator.file.elf.telfhash',
X509Serial = 'threat.indicator.x509.serial_number',
WindowsRegistryKey = 'threat.indicator.registry.key',
WindowsRegistryPath = 'threat.indicator.registry.path',
AutonomousSystemNumber = 'threat.indicator.as.number',
MacAddress = 'threat.indicator.mac',
TimeStamp = '@timestamp',
Expand All @@ -49,6 +51,22 @@ export enum RawIndicatorFieldId {
NameOrigin = 'threat.indicator.name_origin',
}

/**
* Threat indicator field map to Enriched Event.
* (reverse of https://github.com/elastic/kibana/blob/main/x-pack/plugins/security_solution/common/cti/constants.ts#L35)
*/
export const IndicatorFieldEventEnrichmentMap: { [id: string]: string[] } = {
[RawIndicatorFieldId.FileMd5]: ['file.hash.md5'],
[RawIndicatorFieldId.FileSha1]: ['file.hash.sha1'],
[RawIndicatorFieldId.FileSha256]: ['file.hash.sha256'],
[RawIndicatorFieldId.FileImphash]: ['file.pe.imphash'],
[RawIndicatorFieldId.FileTelfhash]: ['file.elf.telfhash'],
[RawIndicatorFieldId.FileSSDeep]: ['file.hash.ssdeep'],
[RawIndicatorFieldId.Ip]: ['source.ip', 'destination.ip'],
[RawIndicatorFieldId.UrlFull]: ['url.full'],
[RawIndicatorFieldId.WindowsRegistryPath]: ['registry.path'],
};

/**
* Threat Intelligence Indicator interface.
*/
Expand Down Expand Up @@ -93,7 +111,7 @@ export const generateMockUrlIndicator = (): Indicator => {
indicator.fields['threat.indicator.url.full'] = ['https://0.0.0.0/test'];
indicator.fields['threat.indicator.url.original'] = ['https://0.0.0.0/test'];
indicator.fields['threat.indicator.name'] = ['https://0.0.0.0/test'];
indicator.fields['threat.indicator.name_origin'] = ['threat.indicator.url.original'];
indicator.fields['threat.indicator.name_origin'] = ['threat.indicator.url.full'];

return indicator;
};
Expand Down
16 changes: 16 additions & 0 deletions x-pack/plugins/threat_intelligence/cypress/e2e/timeline.cy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ import {
UNTITLED_TIMELINE_BUTTON,
FLYOUT_OVERVIEW_TAB_BLOCKS_TIMELINE_BUTTON,
FLYOUT_OVERVIEW_TAB_BLOCKS_ITEM,
INDICATORS_TABLE_INVESTIGATE_IN_TIMELINE_BUTTON_ICON,
INDICATOR_FLYOUT_INVESTIGATE_IN_TIMELINE_BUTTON,
} from '../screens/indicators';
import { esArchiverLoad, esArchiverUnload } from '../tasks/es_archiver';
import { login } from '../tasks/login';
Expand Down Expand Up @@ -88,5 +90,19 @@ describe('Indicators', () => {
cy.get(UNTITLED_TIMELINE_BUTTON).should('exist').first().click();
cy.get(TIMELINE_DRAGGABLE_ITEM).should('exist');
});

it('should investigate in timeline when clicking in an indicator table action row', () => {
cy.get(INDICATORS_TABLE_INVESTIGATE_IN_TIMELINE_BUTTON_ICON).should('exist').first().click();
cy.get(UNTITLED_TIMELINE_BUTTON).should('exist').first().click();
cy.get(TIMELINE_DRAGGABLE_ITEM).should('exist');
});

it('should investigate in timeline when clicking in an indicator flyout', () => {
cy.get(TOGGLE_FLYOUT_BUTTON).first().click({ force: true });
cy.get(INDICATOR_FLYOUT_INVESTIGATE_IN_TIMELINE_BUTTON).should('exist').first().click();
cy.get(FLYOUT_CLOSE_BUTTON).should('exist').click();
cy.get(UNTITLED_TIMELINE_BUTTON).should('exist').first().click();
cy.get(TIMELINE_DRAGGABLE_ITEM).should('exist');
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -101,3 +101,9 @@ export const UNTITLED_TIMELINE_BUTTON = '[data-test-subj="flyoutOverlay"]';
export const TIMELINE_DRAGGABLE_ITEM = '[data-test-subj="providerContainer"]';

export const KQL_FILTER = '[id="popoverFor_filter0"]';

export const INDICATORS_TABLE_INVESTIGATE_IN_TIMELINE_BUTTON_ICON =
'[data-test-subj="tiIndicatorTableInvestigateInTimelineButtonIcon"]';

export const INDICATOR_FLYOUT_INVESTIGATE_IN_TIMELINE_BUTTON =
'[data-test-subj="tiIndicatorFlyoutInvestigateInTimelineButton"]';
Original file line number Diff line number Diff line change
Expand Up @@ -28,4 +28,12 @@ export const getSecuritySolutionContextMock = (): SecuritySolutionPluginContext
indexPattern: { fields: [], title: '' },
loading: false,
},
getSecuritySolutionStore: {
// @ts-ignore
dispatch: () => jest.fn(),
},
getUseInvestigateInTimeline:
({ dataProviders, from, to }) =>
() =>
new Promise((resolve) => window.alert('investigate in timeline')),
});
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,11 @@

import React, { useMemo, useState, VFC } from 'react';
import {
EuiFlexGroup,
EuiFlexItem,
EuiFlyout,
EuiFlyoutBody,
EuiFlyoutFooter,
EuiFlyoutHeader,
EuiSpacer,
EuiTab,
Expand All @@ -18,6 +21,7 @@ import {
useGeneratedHtmlId,
} from '@elastic/eui';
import { FormattedMessage } from '@kbn/i18n-react';
import { InvestigateInTimelineButton } from '../../../timeline/components/investigate_in_timeline_button';
import { DateFormatter } from '../../../../components/date_formatter/date_formatter';
import { Indicator, RawIndicatorFieldId } from '../../../../../common/types/indicator';
import { IndicatorsFlyoutJson } from './tabs/indicators_flyout_json/indicators_flyout_json';
Expand All @@ -28,6 +32,7 @@ import { IndicatorsFlyoutOverview } from './tabs/indicators_flyout_overview';
export const TITLE_TEST_ID = 'tiIndicatorFlyoutTitle';
export const SUBTITLE_TEST_ID = 'tiIndicatorFlyoutSubtitle';
export const TABS_TEST_ID = 'tiIndicatorFlyoutTabs';
export const INVESTIGATE_IN_TIMELINE_BUTTON_ID = 'tiIndicatorFlyoutInvestigateInTimelineButton';

const enum TAB_IDS {
overview,
Expand Down Expand Up @@ -142,6 +147,16 @@ export const IndicatorsFlyout: VFC<IndicatorsFlyoutProps> = ({ indicator, closeF
</EuiTabs>
</EuiFlyoutHeader>
<EuiFlyoutBody>{selectedTabContent}</EuiFlyoutBody>
<EuiFlyoutFooter>
<EuiFlexGroup justifyContent="flexEnd">
<EuiFlexItem grow={false}>
<InvestigateInTimelineButton
data={indicator}
data-test-subj={INVESTIGATE_IN_TIMELINE_BUTTON_ID}
/>
</EuiFlexItem>
</EuiFlexGroup>
</EuiFlyoutFooter>
</EuiFlyout>
);
};
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,17 @@
*/

import React, { useContext, VFC } from 'react';
import { InvestigateInTimelineButtonIcon } from '../../../timeline/components/investigate_in_timeline_button_icon';
import { Indicator } from '../../../../../common/types/indicator';
import { OpenIndicatorFlyoutButton } from '../open_indicator_flyout_button/open_indicator_flyout_button';
import { IndicatorsTableContext } from './context';
import { useStyles } from './styles';

const INVESTIGATE_TEST_ID = 'tiIndicatorTableInvestigateInTimelineButtonIcon';

export const ActionsRowCell: VFC<{ indicator: Indicator }> = ({ indicator }) => {
const styles = useStyles();

const indicatorTableContext = useContext(IndicatorsTableContext);

if (!indicatorTableContext) {
Expand All @@ -20,10 +26,13 @@ export const ActionsRowCell: VFC<{ indicator: Indicator }> = ({ indicator }) =>
const { setExpanded, expanded } = indicatorTableContext;

return (
<OpenIndicatorFlyoutButton
indicator={indicator}
onOpen={setExpanded}
isOpen={Boolean(expanded && expanded._id === indicator._id)}
/>
<div css={styles.rowActionsDiv}>
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can EUI flex components be used here, eg EuiFlexGroup?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yup done, good cleanup I could delete the styles.ts file entirely

<OpenIndicatorFlyoutButton
indicator={indicator}
onOpen={setExpanded}
isOpen={Boolean(expanded && expanded._id === indicator._id)}
/>
<InvestigateInTimelineButtonIcon data={indicator} data-test-subj={INVESTIGATE_TEST_ID} />
</div>
);
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

import { CSSObject } from '@emotion/react';

export const useStyles = () => {
const rowActionsDiv: CSSObject = {
display: 'flex',
};

return {
rowActionsDiv,
};
};
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ describe('display name generation', () => {
if (doc['threat.indicator.file.pehash'].value!=null) { return emit(doc['threat.indicator.file.pehash'].value) }
if (doc['threat.indicator.file.vhash'].value!=null) { return emit(doc['threat.indicator.file.vhash'].value) } }

if (doc['threat.indicator.type'].value != null && doc['threat.indicator.type'].value.toLowerCase()=='url') { if (doc['threat.indicator.url.original'].value!=null) { return emit(doc['threat.indicator.url.original'].value) } }
if (doc['threat.indicator.type'].value != null && doc['threat.indicator.type'].value.toLowerCase()=='url') { if (doc['threat.indicator.url.full'].value!=null) { return emit(doc['threat.indicator.url.full'].value) } }

if (doc['threat.indicator.type'].value != null && doc['threat.indicator.type'].value.toLowerCase()=='domain') { if (doc['threat.indicator.url.domain'].value!=null) { return emit(doc['threat.indicator.url.domain'].value) } }
if (doc['threat.indicator.type'].value != null && doc['threat.indicator.type'].value.toLowerCase()=='domain-name') { if (doc['threat.indicator.url.domain'].value!=null) { return emit(doc['threat.indicator.url.domain'].value) } }
Expand Down Expand Up @@ -83,7 +83,7 @@ describe('display name generation', () => {
if (doc['threat.indicator.file.pehash'].value!=null) { return emit('threat.indicator.file.pehash') }
if (doc['threat.indicator.file.vhash'].value!=null) { return emit('threat.indicator.file.vhash') } }

if (doc['threat.indicator.type'].value != null && doc['threat.indicator.type'].value.toLowerCase()=='url') { if (doc['threat.indicator.url.original'].value!=null) { return emit('threat.indicator.url.original') } }
if (doc['threat.indicator.type'].value != null && doc['threat.indicator.type'].value.toLowerCase()=='url') { if (doc['threat.indicator.url.full'].value!=null) { return emit('threat.indicator.url.full') } }

if (doc['threat.indicator.type'].value != null && doc['threat.indicator.type'].value.toLowerCase()=='domain') { if (doc['threat.indicator.url.domain'].value!=null) { return emit('threat.indicator.url.domain') } }
if (doc['threat.indicator.type'].value != null && doc['threat.indicator.type'].value.toLowerCase()=='domain-name') { if (doc['threat.indicator.url.domain'].value!=null) { return emit('threat.indicator.url.domain') } }
Expand Down
Loading