Skip to content

Commit

Permalink
[Security Solution] Security Assistant: fixes linter issues (#13)
Browse files Browse the repository at this point in the history
- fixes linter issues remaining from ON week
  • Loading branch information
andrew-goldstein authored May 23, 2023
1 parent c1ca34f commit e055574
Show file tree
Hide file tree
Showing 12 changed files with 104 additions and 46 deletions.
34 changes: 9 additions & 25 deletions x-pack/packages/kbn-elastic-assistant/impl/assistant/api.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,7 @@ import axios from 'axios';

import type { Message } from '../assistant_context/types';

export const fetchOpenAlerts = async () => {
try {
// TODO: Fetch alerts via alerts API if need be
return [];
} catch (error) {
console.error('Error fetching open alerts:', error);
throw error;
}
};
export const fetchOpenAlerts = async () => []; // TODO: fetch alerts via alerts API

export interface FetchVirusTotalAnalysisProps {
analysisId: string;
Expand All @@ -37,7 +29,6 @@ export const fetchVirusTotalAnalysis = async ({
});
return response.data;
} catch (error) {
console.error('Error while fetching analysis from VirusTotal:', error);
return null;
}
};
Expand All @@ -57,18 +48,14 @@ export const sendFileToVirusTotal = async ({
const formData = new FormData();
formData.append('file', file); // Append the file to the FormData object

try {
const response = await axios.post(url, formData, {
headers: {
'x-apikey': apiKey,
'Content-Type': 'multipart/form-data',
},
});
return response.data;
} catch (error) {
console.error('Error while uploading file to VirusTotal:', error);
throw error;
}
const response = await axios.post(url, formData, {
headers: {
'x-apikey': apiKey,
'Content-Type': 'multipart/form-data',
},
});

return response.data;
};

export interface FetchChatCompletionProps {
Expand Down Expand Up @@ -108,19 +95,16 @@ export const fetchChatCompletion = async ({

const data = await response.json();
if (!response.ok) {
console.error('Error in ChatGPT API response:', data);
return 'An error occurred while processing your request.';
}

if (data.choices && data.choices.length > 0 && data.choices[0].message.content) {
const result = data.choices[0].message.content.trim();
return result;
} else {
console.error('Unexpected API response format:', data);
return 'An error occurred while processing your request.';
}
} catch (error) {
console.error('Error while sending message to ChatGPT:', error);
return 'An error occurred while processing your request.';
}
};
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import React, { useCallback, useEffect, useState } from 'react';
import { EuiModal } from '@elastic/eui';

import useEvent from 'react-use/lib/useEvent';
// eslint-disable-next-line @kbn/eslint/module_migration
import styled from 'styled-components';
import { ShowAssistantOverlayProps, useAssistantContext } from '../../assistant_context';
import { Assistant } from '..';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
*/

import { EuiButton, EuiFlexGroup, EuiFlexItem, EuiToolTip } from '@elastic/eui';
// eslint-disable-next-line @kbn/eslint/module_migration
import styled from 'styled-components';

import { sortBy } from 'lodash/fp';
Expand Down
104 changes: 86 additions & 18 deletions x-pack/packages/kbn-elastic-assistant/impl/assistant/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,32 @@ export async function fetchVirusTotalReport({
}: {
hash: string;
settings: AssistantUiSettings;
}): Promise<unknown> {
}): Promise<{
attributes: {
last_analysis_stats: {
malicious: number | string;
suspicious: number | string;
undetected: number | string;
timeout: number | string;
};
magic: string;
meaningful_name: string;
sha256: string;
};
data: {
attributes: {
last_analysis_stats: {
malicious: number | string;
suspicious: number | string;
undetected: number | string;
timeout: number | string;
};
magic: string;
meaningful_name: string;
sha256: string;
};
};
}> {
const url = `${virusTotal.baseUrl}/files/${hash}`;

const response = await fetch(url, {
Expand Down Expand Up @@ -79,9 +104,7 @@ export const handleOpenAlerts = async ({ chatHistory, setChatHistory }: HandleOp
const dateTimeString = new Date().toLocaleString();
try {
if (response) {
console.log('Response from Open Alerts API:', response);
const formattedResponseComponent = formatOpenAlertsResponse(response);
console.log('Response from formatting', formattedResponseComponent);
setChatHistory([
...chatHistory,
{
Expand All @@ -90,11 +113,8 @@ export const handleOpenAlerts = async ({ chatHistory, setChatHistory }: HandleOp
timestamp: dateTimeString,
},
]);
} else {
console.error('Error: Response from Open Alerts API is empty or undefined.');
}
} catch (error) {
console.error('Error while fetching Open Alerts:', error);
setChatHistory([
...chatHistory,
{
Expand Down Expand Up @@ -122,15 +142,13 @@ export const handleFileHash = async ({
const dateTimeString = new Date().toLocaleString();
try {
const result = await fetchVirusTotalReport({ hash, settings: { virusTotal, openAI } });
console.log('VirusTotal response:', result);
const markdownReport = formatVirusTotalResponse(result);
setChatHistory([
...chatHistory,
{ role: 'assistant', content: markdownReport, timestamp: dateTimeString },
]);
// setLastResponse(markdownReport);
} catch (error) {
console.error('Error while fetching VirusTotal report:', error);
setChatHistory([
...chatHistory,
{
Expand All @@ -142,7 +160,21 @@ export const handleFileHash = async ({
}
};

export const formatVirusTotalResponse = (response: any) => {
export const formatVirusTotalResponse = (response: {
data: {
attributes: {
last_analysis_stats: {
malicious: number | string;
suspicious: number | string;
undetected: number | string;
timeout: number | string;
};
magic: string;
meaningful_name: string;
sha256: string;
};
};
}) => {
const { data } = response;
const { attributes } = data;

Expand All @@ -165,9 +197,27 @@ export const formatVirusTotalResponse = (response: any) => {
return mdResponse;
};

export const formatOpenAlertsResponse = (response: any): string => {
console.log('Open alerts response:', response);

export const formatOpenAlertsResponse = (
response:
| Array<{
_source: {
host?: {
risk?: {
calculated_level?: string | number | undefined;
};
};
'kibana.alert.rule.name': string | undefined;
'kibana.alert.reason': string | undefined;
'kibana.alert.severity': string | number | undefined;
user?: {
risk?: {
calculated_level?: string | number | undefined;
};
};
};
}>
| undefined
): string => {
// Check if the response object has the hits property and if it has any elements.
if (!response || response.length === 0) {
return 'An error occurred while formatting alerts.';
Expand All @@ -179,7 +229,7 @@ export const formatOpenAlertsResponse = (response: any): string => {
'| # | Alert Name | Severity | Event Reason | User Risk Score | Host Risk Score |\n';
formattedAlerts += '|---|------------|----------|----------|----------|----------|\n';

response.forEach((alert: any, index: any) => {
response.forEach((alert, index: number) => {
const { _source } = alert;

const alertName = _source['kibana.alert.rule.name'];
Expand All @@ -199,9 +249,9 @@ export const formatOpenAlertsResponse = (response: any): string => {
};

export interface HandleFileUploadProps {
files: FileList | null;
virusTotal: AssistantUiSettings['virusTotal'];
chatHistory: Message[];
files: File[] | undefined;
setChatHistory: (value: Message[]) => void;
setFilePickerKey: React.Dispatch<React.SetStateAction<number>>;
}
Expand Down Expand Up @@ -279,15 +329,34 @@ export const handleFileUpload = async ({
},
]);
setFilePickerKey((prevKey) => prevKey + 1);
} else {
console.error('Error: Response from VirusTotal API is empty or undefined.');
}
}
};
fileReader.readAsArrayBuffer(file);
};

export const formatFileVirusTotalResponse = (response: any, sha256Hash: any) => {
export const formatFileVirusTotalResponse = (
response: {
data: {
attributes: {
results: {
Elastic: {
category: string;
engine_version: string;
result: string;
};
};
stats: {
malicious: number | string;
suspicious: number | string;
undetected: number | string;
timeout: number | string;
};
};
};
},
sha256Hash: string
) => {
if (!response || !response.data) {
return 'An error occurred while processing your request.';
}
Expand All @@ -296,7 +365,6 @@ export const formatFileVirusTotalResponse = (response: any, sha256Hash: any) =>
const { attributes } = data;
const { results } = attributes;

console.log(response);
const stats = response.data.attributes.stats;
// const links = response.data.attributes.links;
const result =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import {
EuiSplitPanel,
} from '@elastic/eui';

// eslint-disable-next-line @kbn/eslint/module_migration
import styled from 'styled-components';
import { createPortal } from 'react-dom';
import { css } from '@emotion/react';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

import { EuiAvatar, EuiCommentList, EuiText } from '@elastic/eui';
import React, { useMemo } from 'react';
// eslint-disable-next-line @kbn/eslint/module_migration
import styled from 'styled-components';

import type { PromptContext } from '../prompt_context/types';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import {
} from '@elastic/eui';
import { isEmpty } from 'lodash/fp';
import React, { useCallback, useEffect, useMemo, useState } from 'react';
// eslint-disable-next-line @kbn/eslint/module_migration
import styled from 'styled-components';

import { SYSTEM_PROMPT_CONTEXT_NON_I18N } from '../../../content/prompts/system/translations';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import { EuiText, EuiToolTip } from '@elastic/eui';
import type { EuiSuperSelectOption } from '@elastic/eui';
import React from 'react';
// eslint-disable-next-line @kbn/eslint/module_migration
import styled from 'styled-components';

import { css } from '@emotion/react';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import {
EuiToolTip,
} from '@elastic/eui';
import React, { useCallback, useMemo } from 'react';
// eslint-disable-next-line @kbn/eslint/module_migration
import styled from 'styled-components';

import { getPromptById } from '../helpers';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import { EuiTextArea } from '@elastic/eui';
import React, { useCallback, useEffect, forwardRef } from 'react';

// eslint-disable-next-line @kbn/eslint/module_migration
import styled from 'styled-components';
import * as i18n from './translations';

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

import React from 'react';
import { EuiFlexGroup, EuiFlexItem, EuiBadge } from '@elastic/eui';
// eslint-disable-next-line @kbn/eslint/module_migration
import styled from 'styled-components';
import { css } from '@emotion/react';

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,6 @@ export const useSendMessages = (): UseSendMessages => {
// baseUrl: apiConfig.openAI.baseUrl,
// apiKey: apiConfig.openAI.apiKey,
// });
} catch (e) {
console.error(e);
throw e;
} finally {
setIsLoading(false);
}
Expand Down

0 comments on commit e055574

Please sign in to comment.