Skip to content

Commit

Permalink
[EDR Workflows] Endpoint Insights UI (elastic#202209)
Browse files Browse the repository at this point in the history
## Description  
This PR introduces the **Endpoint Insights generation functionality**.
It covers the happy path, providing a complete MVP flow of the feature.

Please make sure to enable feature flag(`defendInsights`) when testing
locally as well as enable defendInsights
[here](https://github.com/szwarckonrad/kibana/blob/efc0568e014105637332533e37491f074ec8fe2b/x-pack/packages/kbn-elastic-assistant-common/impl/capabilities/index.ts#L23).

### Flow Overview  
- **Initial Load**:  
  - Fetches already generated insights and ongoing scans on page load.  
  - If ongoing scans are detected:  
    - Polls periodically until no active scans remain.  
- Refetches insights to account for those generated during the scans.
  - Enables the **Scan** button once the above steps complete.  

- **Scan Trigger**:  
  - On clicking the **Scan** button:  
    - Calls an API to trigger new insight generation.  
- Repeats the polling and refetching process until no active scans are
running.

- **Insights Rendering**:  
  - Displays generated insights as panels.  
- Clicking a panel redirects the user to the **Trusted Apps** page with
a prefilled modal.
  - On successful creation of a trusted app entry:  
    - Redirects the user back to the **Endpoint Details** page.  


https://github.com/user-attachments/assets/72cb62a0-a66f-4a89-bbef-c41c53cdc3a2

---------

Co-authored-by: Joey F. Poon <joey.poon@elastic.co>
Co-authored-by: kibanamachine <42973632+kibanamachine@users.noreply.github.com>
  • Loading branch information
3 people authored Dec 13, 2024
1 parent 85a0273 commit d12d079
Show file tree
Hide file tree
Showing 24 changed files with 1,088 additions and 238 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@ import {
import type { EuiFlyoutSize } from '@elastic/eui/src/components/flyout/flyout';
import type { IHttpFetchError } from '@kbn/core-http-browser';
import { useIsMounted } from '@kbn/securitysolution-hook-utils';
import { useLocation } from 'react-router-dom';
import { useMarkInsightAsRemediated } from '../hooks/use_mark_workflow_insight_as_remediated';
import type { WorkflowInsightRouteState } from '../../../pages/endpoint_hosts/types';
import { useUrlParams } from '../../../hooks/use_url_params';
import { useIsFlyoutOpened } from '../hooks/use_is_flyout_opened';
import { useTestIdGenerator } from '../../../hooks/use_test_id_generator';
Expand Down Expand Up @@ -197,6 +200,11 @@ export const ArtifactFlyout = memo<ArtifactFlyoutProps>(
links: { securitySolution },
},
} = useKibana().services;

const location = useLocation<WorkflowInsightRouteState>();
const [sourceInsight, setSourceInsight] = useState<{ id: string; back_url: string } | null>(
null
);
const getTestId = useTestIdGenerator(dataTestSubj);
const toasts = useToasts();
const isFlyoutOpened = useIsFlyoutOpened();
Expand Down Expand Up @@ -225,6 +233,10 @@ export const ArtifactFlyout = memo<ArtifactFlyoutProps>(
error: internalSubmitError,
} = useWithArtifactSubmitData(apiClient, formMode);

const { mutateAsync: markInsightAsRemediated } = useMarkInsightAsRemediated(
sourceInsight?.back_url
);

const isSubmittingData = useMemo(() => {
return submitHandler ? externalIsSubmittingData : internalIsSubmittingData;
}, [externalIsSubmittingData, internalIsSubmittingData, submitHandler]);
Expand Down Expand Up @@ -286,13 +298,23 @@ export const ArtifactFlyout = memo<ArtifactFlyoutProps>(
);

const handleSuccess = useCallback(
(result: ExceptionListItemSchema) => {
async (result: ExceptionListItemSchema) => {
toasts.addSuccess(
isEditFlow
? labels.flyoutEditSubmitSuccess(result)
: labels.flyoutCreateSubmitSuccess(result)
);

// Check if this artifact creation was opened from an endpoint insight
try {
if (sourceInsight?.id) {
await markInsightAsRemediated({ insightId: sourceInsight.id });
return;
}
} catch {
setSourceInsight(null);
}

if (isMounted()) {
// Close the flyout
// `undefined` will cause params to be dropped from url
Expand All @@ -301,7 +323,17 @@ export const ArtifactFlyout = memo<ArtifactFlyoutProps>(
onSuccess();
}
},
[isEditFlow, isMounted, labels, onSuccess, setUrlParams, toasts, urlParams]
[
isEditFlow,
isMounted,
labels,
markInsightAsRemediated,
onSuccess,
setUrlParams,
sourceInsight,
toasts,
urlParams,
]
);

const handleSubmitClick = useCallback(() => {
Expand Down Expand Up @@ -357,6 +389,19 @@ export const ArtifactFlyout = memo<ArtifactFlyoutProps>(
}
}, [formState, confirmModalOnSuccess]);

// If this form was opened from an endpoint insight, prepopulate the form with the insight data
useEffect(() => {
if (location.state?.insight?.id && location.state?.insight?.item) {
setSourceInsight({
id: location.state.insight.id,
back_url: location.state.insight.back_url,
});
setFormState({ isValid: true, item: location.state.insight.item });

location.state.insight = undefined;
}
}, [apiClient.listId, location.state, location.state?.insight]);

// If we don't have the actual Artifact data yet for edit (in initialization phase - ex. came in with an
// ID in the url that was not in the list), then retrieve it now
useEffect(() => {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/*
* 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 { useMutation } from '@tanstack/react-query';
import { WORKFLOW_INSIGHTS } from '../../../pages/endpoint_hosts/view/translations';
import type { SecurityWorkflowInsight } from '../../../../../common/endpoint/types/workflow_insights';
import { ActionType } from '../../../../../common/endpoint/types/workflow_insights';
import { resolvePathVariables } from '../../../../common/utils/resolve_path_variables';
import { WORKFLOW_INSIGHTS_UPDATE_ROUTE } from '../../../../../common/endpoint/constants';
import { useKibana, useToasts } from '../../../../common/lib/kibana';

export const useMarkInsightAsRemediated = (backUrl?: string) => {
const toasts = useToasts();
const {
application: { navigateToUrl },
http,
} = useKibana().services;
return useMutation<SecurityWorkflowInsight, Error, { insightId: string }>(
({ insightId }: { insightId: string }) =>
http.put<SecurityWorkflowInsight>(
resolvePathVariables(WORKFLOW_INSIGHTS_UPDATE_ROUTE, { insightId }),
{
version: '1',
body: JSON.stringify({
action: {
type: ActionType.Remediated,
},
}),
}
),
{
onError: (err) => {
toasts.addDanger({
title: WORKFLOW_INSIGHTS.toasts.updateInsightError,
text: err?.message,
});
},
onSuccess: () => {
if (backUrl) return navigateToUrl(backUrl);
},
}
);
};
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

import type { DataViewBase } from '@kbn/es-query';
import type { GetInfoResponse } from '@kbn/fleet-plugin/common';
import type { CreateExceptionListItemSchema } from '@kbn/securitysolution-io-ts-list-types';
import type {
AppLocation,
EndpointPendingActions,
Expand Down Expand Up @@ -155,3 +156,11 @@ export interface TransformStatsResponse {
count: number;
transforms: TransformStats[];
}

export interface WorkflowInsightRouteState {
insight?: {
back_url: string;
id: string;
item: CreateExceptionListItemSchema;
};
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,31 +6,83 @@
*/

import { EuiHorizontalRule, EuiAccordion, EuiSpacer, EuiText } from '@elastic/eui';
import React from 'react';
import React, { useState, useEffect, useCallback, useMemo } from 'react';
import moment from 'moment';
import { useFetchInsights } from '../../../hooks/insights/use_fetch_insights';
import { useTriggerScan } from '../../../hooks/insights/use_trigger_scan';
import { useFetchOngoingScans } from '../../../hooks/insights/use_fetch_ongoing_tasks';
import { WorkflowInsightsResults } from './workflow_insights_results';
import { WorkflowInsightsScanSection } from './workflow_insights_scan';
import { useIsExperimentalFeatureEnabled } from '../../../../../../../common/hooks/use_experimental_features';
import { WORKFLOW_INSIGHTS } from '../../../translations';

export const WorkflowInsights = () => {
const isWorkflowInsightsEnabled = useIsExperimentalFeatureEnabled('defendInsights');
interface WorkflowInsightsProps {
endpointId: string;
}

if (!isWorkflowInsightsEnabled) {
return null;
}
export const WorkflowInsights = React.memo(({ endpointId }: WorkflowInsightsProps) => {
const [isScanButtonDisabled, setIsScanButtonDisabled] = useState(true);
const [scanCompleted, setIsScanCompleted] = useState(false);
const [userTriggeredScan, setUserTriggeredScan] = useState(false);

const results = null;
const disableScanButton = () => {
setIsScanButtonDisabled(true);
};

const [setScanOngoing, setScanCompleted] = [
() => setIsScanCompleted(false),
() => setIsScanCompleted(true),
];

const { data: insights, refetch: refetchInsights } = useFetchInsights({
endpointId,
onSuccess: setScanCompleted,
});

const {
data: ongoingScans,
isLoading: isLoadingOngoingScans,
refetch: refetchOngoingScans,
} = useFetchOngoingScans({
endpointId,
isPolling: isScanButtonDisabled,
onSuccess: refetchInsights,
});

const { mutate: triggerScan } = useTriggerScan({
onSuccess: refetchOngoingScans,
onMutate: disableScanButton,
});

useEffect(() => {
setIsScanButtonDisabled(!!ongoingScans?.length || isLoadingOngoingScans);
}, [ongoingScans, isLoadingOngoingScans]);

const renderLastResultsCaption = () => {
if (!results) {
const lastResultCaption = useMemo(() => {
if (!insights?.length) {
return null;
}

const latestTimestamp = insights
.map((insight) => moment.utc(insight['@timestamp']))
.sort((a, b) => b.diff(a))[0];

return (
<EuiText color={'subdued'} size={'xs'}>
{WORKFLOW_INSIGHTS.titleRight}
{`${WORKFLOW_INSIGHTS.titleRight} ${latestTimestamp.local().fromNow()}`}
</EuiText>
);
};
}, [insights]);

const onScanButtonClick = useCallback(
({ actionTypeId, connectorId }: { actionTypeId: string; connectorId: string }) => {
setScanOngoing();
if (!userTriggeredScan) {
setUserTriggeredScan(true);
}
triggerScan({ endpointId, actionTypeId, connectorId });
},
[setScanOngoing, userTriggeredScan, triggerScan, endpointId]
);

return (
<>
Expand All @@ -42,16 +94,25 @@ export const WorkflowInsights = () => {
</EuiText>
}
initialIsOpen
extraAction={renderLastResultsCaption()}
extraAction={lastResultCaption}
paddingSize={'none'}
>
<EuiSpacer size={'m'} />
<WorkflowInsightsScanSection />
<WorkflowInsightsScanSection
isScanButtonDisabled={isScanButtonDisabled}
onScanButtonClick={onScanButtonClick}
/>
<EuiSpacer size={'m'} />
<WorkflowInsightsResults results={true} />
<WorkflowInsightsResults
results={insights}
scanCompleted={scanCompleted && userTriggeredScan}
endpointId={endpointId}
/>
<EuiHorizontalRule />
</EuiAccordion>
<EuiSpacer size="l" />
</>
);
};
});

WorkflowInsights.displayName = 'WorkflowInsights';
Loading

0 comments on commit d12d079

Please sign in to comment.