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

[Security Solution] Security Assistant: Add note to Timeline #9

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
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,12 @@
* 2.0.
*/

import React, { useCallback, useEffect, useMemo } from 'react';
import React, { useMemo } from 'react';

import type { TimelineEventsDetailsItem } from '../../../../common/search_strategy';
import type { BrowserFields } from '../../../../common/search_strategy/index_fields';
import { getSummaryRows } from './get_alert_summary_rows';
import { EXPLAIN_THEN_SUMMARIZE_SUGGEST_INVESTIGATION_GUIDE } from '../../../security_assistant/content/prompts/user/translations';
import { useSecurityAssistantContext } from '../../../security_assistant/security_assistant_context';
import { SummaryView } from './summary_view';
import * as i18n from './translations';
import { getPromptContextFromEventDetailsItem } from '../../../security_assistant/prompt_context/helpers';
import { getUniquePromptContextId } from '../../../security_assistant/security_assistant_context/helpers';

const AlertSummaryViewComponent: React.FC<{
browserFields: BrowserFields;
Expand All @@ -32,35 +27,8 @@ const AlertSummaryViewComponent: React.FC<{
[browserFields, data, eventId, isDraggable, scopeId, isReadOnly]
);

const { registerPromptContext, unRegisterPromptContext } = useSecurityAssistantContext();
const promptContextId = useMemo(() => getUniquePromptContextId(), []);

const getPromptContext = useCallback(
async () => getPromptContextFromEventDetailsItem(data),
[data]
);

useEffect(() => {
registerPromptContext({
category: 'alert',
description: i18n.ALERT_SUMMARY_VIEW_CONTEXT_DESCRIPTION,
id: promptContextId,
getPromptContext,
suggestedUserPrompt: EXPLAIN_THEN_SUMMARIZE_SUGGEST_INVESTIGATION_GUIDE,
tooltip: i18n.ALERT_SUMMARY_VIEW_CONTEXT_TOOLTIP,
});

return () => unRegisterPromptContext(promptContextId);
}, [getPromptContext, promptContextId, registerPromptContext, unRegisterPromptContext]);

return (
<SummaryView
goToTable={goToTable}
isReadOnly={isReadOnly}
promptContextId={promptContextId}
rows={summaryRows}
title={title}
/>
<SummaryView goToTable={goToTable} isReadOnly={isReadOnly} rows={summaryRows} title={title} />
);
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,6 @@ const enrichedHostIpData: AlertSummaryRow['description'] = {
};

const mockCount = 90019001;
const promptContextId = 'abcd';

jest.mock('../../containers/alerts/use_alert_prevalence', () => ({
useAlertPrevalence: () => ({
Expand All @@ -68,12 +67,7 @@ describe('Summary View', () => {
test('should show an empty table', () => {
render(
<TestProviders>
<SummaryView
goToTable={jest.fn()}
title="Test Summary View"
promptContextId={promptContextId}
rows={[]}
/>
<SummaryView goToTable={jest.fn()} title="Test Summary View" rows={[]} />
</TestProviders>
);
expect(screen.getByText('No items found')).toBeInTheDocument();
Expand All @@ -91,12 +85,7 @@ describe('Summary View', () => {

render(
<TestProviders>
<SummaryView
goToTable={jest.fn()}
title="Test Summary View"
promptContextId={promptContextId}
rows={sampleRows}
/>
<SummaryView goToTable={jest.fn()} title="Test Summary View" rows={sampleRows} />
</TestProviders>
);
// Shows the field name
Expand Down Expand Up @@ -127,7 +116,6 @@ describe('Summary View', () => {
<SummaryView
goToTable={jest.fn()}
title="Test Summary View"
promptContextId={promptContextId}
rows={sampleRows}
isReadOnly={true}
/>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ import {
import React from 'react';

import type { AlertSummaryRow } from './helpers';
import { NewChat } from '../../../security_assistant/new_chat';
import * as i18n from './translations';
import { VIEW_ALL_FIELDS } from './translations';
import { SummaryTable } from './table/summary_table';
Expand Down Expand Up @@ -70,15 +69,13 @@ const rowProps = {
const SummaryViewComponent: React.FC<{
goToTable: () => void;
title: string;
promptContextId: string;
rows: AlertSummaryRow[];
isReadOnly?: boolean;
}> = ({ goToTable, promptContextId, rows, title, isReadOnly }) => {
}> = ({ goToTable, rows, title, isReadOnly }) => {
const columns = isReadOnly ? baseColumns : allColumns;

return (
<div>
<NewChat promptContextId={promptContextId} />
<EuiFlexGroup>
<EuiFlexItem>
<EuiTitle size="xxxs">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -147,16 +147,36 @@ export const VIEW_ALL_FIELDS = i18n.translate('xpack.securitySolution.eventDetai
defaultMessage: 'View all fields in table',
});

export const ALERT_SUMMARY_VIEW_CONTEXT_DESCRIPTION = i18n.translate(
'xpack.securitySolution.alertSummaryView.contextDescription',
export const SUMMARY_VIEW = i18n.translate('xpack.securitySolution.eventDetails.summaryView', {
defaultMessage: 'summary',
});

export const TIMELINE_VIEW = i18n.translate('xpack.securitySolution.eventDetails.timelineView', {
defaultMessage: 'Timeline',
});

export const ALERT_SUMMARY_CONTEXT_DESCRIPTION = (view: string) =>
i18n.translate('xpack.securitySolution.alertSummaryView.alertSummaryViewContextDescription', {
defaultMessage: 'Alert (from {view})',
values: { view },
});

export const ALERT_SUMMARY_VIEW_CONTEXT_TOOLTIP = i18n.translate(
'xpack.securitySolution.alertSummaryView.alertSummaryViewContextTooltip',
{
defaultMessage: 'Alert (summary view)',
defaultMessage: 'Use this alert for context',
}
);

export const ALERT_SUMMARY_VIEW_CONTEXT_TOOLTIP = i18n.translate(
'xpack.securitySolution.alertSummaryView.contextTooltip',
export const EVENT_SUMMARY_CONTEXT_DESCRIPTION = (view: string) =>
i18n.translate('xpack.securitySolution.alertSummaryView.eventSummaryViewContextDescription', {
defaultMessage: 'Event (from {view})',
values: { view },
});

export const EVENT_SUMMARY_VIEW_CONTEXT_TOOLTIP = i18n.translate(
'xpack.securitySolution.alertSummaryView.eventSummaryViewContextTooltip',
{
defaultMessage: 'Use this alert for context',
defaultMessage: 'Use this event for context',
}
);
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,17 @@
*/

import { EuiButton, EuiFlexGroup, EuiFlexItem, EuiToolTip } from '@elastic/eui';
import styled from 'styled-components';

import { sortBy } from 'lodash/fp';
import React, { useCallback, useMemo } from 'react';

import type { PromptContext } from '../prompt_context/types';

const PillButton = styled(EuiButton)`
margin-right: ${({ theme }) => theme.eui.euiSizeXS};
`;

interface Props {
promptContexts: Record<string, PromptContext>;
selectedPromptContextIds: string[];
Expand Down Expand Up @@ -42,14 +47,14 @@ const ContextPillsComponent: React.FC<Props> = ({
{sortedPromptContexts.map(({ description, id, getPromptContext, tooltip }) => (
<EuiFlexItem grow={false} key={id}>
<EuiToolTip content={tooltip}>
<EuiButton
<PillButton
disabled={selectedPromptContextIds.includes(id)}
iconSide="left"
iconType="plus"
onClick={() => selectPromptContext(id)}
>
{description}
</EuiButton>
</PillButton>
</EuiToolTip>
</EuiFlexItem>
))}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,38 +12,16 @@ export interface QueryField {
values: string;
}

export const getQueryFields = (data: TimelineEventsDetailsItem[]): QueryField[] => [
...data
?.filter((x) => x.field === 'kibana.alert.rule.description')
?.map((x) => ({
field: 'kibana.alert.rule.description',
values: x.values?.join(',\n') ?? '',
})),
...data
?.filter((x) => x.field === 'event.category')
?.map((x) => ({ field: 'event.category', values: x.values?.join(',\n') ?? '' })),
...data
?.filter((x) => x.field === 'event.action')
?.map((x) => ({ field: 'event.action', values: x.values?.join(',\n') ?? '' })),
...data
?.filter((x) => x.field === 'host.name')
?.map((x) => ({ field: 'host.name', values: x.values?.join(',\n') ?? '' })),
...data
?.filter((x) => x.field === 'kibana.alert.reason')
?.map((x) => ({ field: 'kibana.alert.reason', values: x.values?.join(',\n') ?? '' })),
...data
?.filter((x) => x.field === 'destination.ip')
?.map((x) => ({ field: 'destination.ip', values: x.values?.join(',\n') ?? '' })),
...data
?.filter((x) => x.field === 'user.name')
?.map((x) => ({ field: 'user.name', values: x.values?.join(',\n') ?? '' })),
];
export const getAllFields = (data: TimelineEventsDetailsItem[]): QueryField[] =>
data
.filter(({ field }) => !field.startsWith('signal.'))
.map(({ field, values }) => ({ field, values: values?.join(',') ?? '' }));

export const getFieldsAsCsv = (queryFields: QueryField[]): string =>
queryFields.map(({ field, values }) => `${field},${values}`).join('\n');

export const getPromptContextFromEventDetailsItem = (data: TimelineEventsDetailsItem[]): string => {
const queryFields = getQueryFields(data);
const allFields = getAllFields(data);

return getFieldsAsCsv(queryFields);
return getFieldsAsCsv(allFields);
};
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,10 @@ import { CommentType } from '@kbn/cases-plugin/common';
import styled from 'styled-components';
import { createPortal } from 'react-dom';
import { css } from '@emotion/react';
import { useDispatch } from 'react-redux';
import * as i18n from './translations';

import { useKibana } from '../common/lib/kibana';
import { useKibana, useToasts } from '../common/lib/kibana';
import { getCombinedMessage, getMessageFromRawResponse, isFileHash } from './helpers';

import { SettingsPopover } from './settings_popover';
Expand All @@ -46,6 +47,11 @@ import type { Prompt } from './types';
import { getPromptById } from './prompt_editor/helpers';
import { augmentMessageCodeBlocks } from './use_conversation/helpers';
import { QuickPrompts } from './quick_prompts/quick_prompts';
import { updateAndAssociateNode } from '../timelines/components/notes/helpers';
import { timelineActions } from '../timelines/store/timeline';
import { appActions } from '../common/store/actions';
import { TimelineId } from '../../common/types';
import type { Note } from '../common/lib/note';

const CommentsContainer = styled.div`
max-height: 600px;
Expand Down Expand Up @@ -148,6 +154,34 @@ export const SecurityAssistant: React.FC<SecurityAssistantProps> =
);
////

const dispatch = useDispatch();
const toasts = useToasts();

const associateNote = useCallback(
(noteId: string) => dispatch(timelineActions.addNote({ id: TimelineId.active, noteId })),
[dispatch]
);

const updateNote = useCallback(
(note: Note) => dispatch(appActions.updateNote({ note })),
[dispatch]
);

const handleAddNoteToTimelineClick = useCallback(
(messageContents: string) => {
updateAndAssociateNode({
associateNote,
newNote: messageContents,
updateNewNote: () => {},
updateNote,
user: '', // TODO: attribute assistant messages
});

toasts.addSuccess(i18n.ADDED_NOTE_TO_TIMELINE);
},
[associateNote, toasts, updateNote]
);

// Handles sending latest user prompt to API
const handleSendMessage = useCallback(
async (promptText) => {
Expand Down Expand Up @@ -200,11 +234,14 @@ export const SecurityAssistant: React.FC<SecurityAssistantProps> =
conversationId: selectedConversationId,
message,
});

// Reset prompt context selection and preview before sending:
setSelectedPromptContextIds([]);
setPromptTextPreview('');

const rawResponse = await sendMessages(updatedMessages);
const responseMessage: Message = getMessageFromRawResponse(rawResponse);
appendMessage({ conversationId: selectedConversationId, message: responseMessage });
setSelectedPromptContextIds([]);
setPromptTextPreview('');
}
},
[
Expand Down Expand Up @@ -319,7 +356,7 @@ export const SecurityAssistant: React.FC<SecurityAssistantProps> =
<>
<EuiToolTip position="top" content={'Add to timeline note'}>
<EuiButtonIcon
onClick={() => handleAddToExistingCaseClick(message.content)}
onClick={() => handleAddNoteToTimelineClick(message.content)}
iconType="editorComment"
color="primary"
aria-label="Add message content as a timeline note"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,20 @@

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

export const ADDED_NOTE_TO_TIMELINE = i18n.translate(
'xpack.securitySolution.securityAssistant.addedNoteToTimeline',
{
defaultMessage: 'Added note to timeline',
}
);

export const SECURITY_ASSISTANT_TITLE = i18n.translate(
'xpack.securitySolution.securityAssistant.title',
{
defaultMessage: 'Elastic Security Assistant',
}
);

export const PROMPT_PLACEHOLDER = i18n.translate(
'xpack.securitySolution.securityAssistant.promptPlaceholder',
{
Expand Down
Loading