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] Adds enable on install UI workflow to prebuilt rules page #191529

Merged
merged 9 commits into from
Sep 18, 2024
Merged
Show file tree
Hide file tree
Changes from 5 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 @@ -16,20 +16,27 @@ import { useInvalidateFindRulesQuery } from '../use_find_rules_query';
import { useInvalidateFetchRuleManagementFiltersQuery } from '../use_fetch_rule_management_filters_query';
import { useInvalidateFetchRulesSnoozeSettingsQuery } from '../use_fetch_rules_snooze_settings_query';
import { useInvalidateFetchPrebuiltRulesInstallReviewQuery } from './use_fetch_prebuilt_rules_install_review_query';
import type { BulkAction } from '../../api';
import { performInstallSpecificRules } from '../../api';
import { useInvalidateFetchCoverageOverviewQuery } from '../use_fetch_coverage_overview_query';
import { useBulkActionMutation } from '../use_bulk_action_mutation';

export const PERFORM_SPECIFIC_RULES_INSTALLATION_KEY = [
'POST',
'SPECIFIC_RULES',
PERFORM_RULE_INSTALLATION_URL,
];

export interface UsePerformSpecificRulesInstallParams {
rules: InstallSpecificRulesRequest['rules'];
enableOnInstall?: boolean;
}

export const usePerformSpecificRulesInstallMutation = (
options?: UseMutationOptions<
PerformRuleInstallationResponseBody,
Error,
InstallSpecificRulesRequest['rules']
UsePerformSpecificRulesInstallParams
>
) => {
const invalidateFindRulesQuery = useInvalidateFindRulesQuery();
Expand All @@ -40,14 +47,15 @@ export const usePerformSpecificRulesInstallMutation = (
useInvalidateFetchPrebuiltRulesInstallReviewQuery();
const invalidateRuleStatus = useInvalidateFetchPrebuiltRulesStatusQuery();
const invalidateFetchCoverageOverviewQuery = useInvalidateFetchCoverageOverviewQuery();
const { mutateAsync } = useBulkActionMutation();

return useMutation<
PerformRuleInstallationResponseBody,
Error,
InstallSpecificRulesRequest['rules']
UsePerformSpecificRulesInstallParams
>(
(rulesToInstall: InstallSpecificRulesRequest['rules']) => {
return performInstallSpecificRules(rulesToInstall);
(rulesToInstall: UsePerformSpecificRulesInstallParams) => {
return performInstallSpecificRules(rulesToInstall.rules);
dplumlee marked this conversation as resolved.
Show resolved Hide resolved
},
{
...options,
Expand All @@ -62,6 +70,14 @@ export const usePerformSpecificRulesInstallMutation = (
invalidateRuleStatus();
invalidateFetchCoverageOverviewQuery();

const [response, , { enableOnInstall }] = args;

if (response && enableOnInstall) {
const idMap = response.results.created.map((rule) => rule.id);
const bulkAction: BulkAction = { type: 'enable', ids: idMap };
mutateAsync({ bulkAction });
dplumlee marked this conversation as resolved.
Show resolved Hide resolved
}

if (options?.onSettled) {
options.onSettled(...args);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,17 @@
* 2.0.
*/

import { EuiButton, EuiFlexGroup, EuiFlexItem, EuiLoadingSpinner } from '@elastic/eui';
import React from 'react';
import {
EuiButton,
EuiButtonIcon,
EuiContextMenuItem,
EuiContextMenuPanel,
EuiFlexGroup,
EuiFlexItem,
EuiLoadingSpinner,
EuiPopover,
} from '@elastic/eui';
import React, { useState } from 'react';
import { useUserData } from '../../../../../detections/components/user_info';
import { useAddPrebuiltRulesTableContext } from './add_prebuilt_rules_table_context';
import * as i18n from './translations';
Expand All @@ -26,19 +35,62 @@ export const AddPrebuiltRulesHeaderButtons = () => {
const isRuleInstalling = loadingRules.length > 0;
const isRequestInProgress = isRuleInstalling || isRefetching || isUpgradingSecurityPackages;

const [isOverflowPopoverOpen, setOverflowPopover] = useState(false);
dplumlee marked this conversation as resolved.
Show resolved Hide resolved

const onButtonClick = () => {
setOverflowPopover(!isOverflowPopoverOpen);
};

const closeOverflowPopover = () => {
setOverflowPopover(false);
};

const enableOnClick = () => {
installSelectedRules(true);
closeOverflowPopover();
};

const overflowItems = [
dplumlee marked this conversation as resolved.
Show resolved Hide resolved
<EuiContextMenuItem key="copy" icon={'play'} onClick={enableOnClick}>
{i18n.INSTALL_AND_ENABLE_BUTTON_LABEL}
</EuiContextMenuItem>,
];

return (
<EuiFlexGroup alignItems="center" gutterSize="s" responsive={false} wrap={true}>
{shouldDisplayInstallSelectedRulesButton ? (
<EuiFlexItem grow={false}>
<EuiButton
onClick={installSelectedRules}
disabled={!canUserEditRules || isRequestInProgress}
data-test-subj="installSelectedRulesButton"
>
{i18n.INSTALL_SELECTED_RULES(numberOfSelectedRules)}
{isRuleInstalling ? <EuiLoadingSpinner size="s" /> : undefined}
</EuiButton>
</EuiFlexItem>
<>
<EuiFlexItem grow={false}>
<EuiButton
onClick={() => installSelectedRules()}
dplumlee marked this conversation as resolved.
Show resolved Hide resolved
disabled={!canUserEditRules || isRequestInProgress}
data-test-subj="installSelectedRulesButton"
>
{i18n.INSTALL_SELECTED_RULES(numberOfSelectedRules)}
{isRuleInstalling ? <EuiLoadingSpinner size="s" /> : undefined}
dplumlee marked this conversation as resolved.
Show resolved Hide resolved
</EuiButton>
</EuiFlexItem>
<EuiFlexItem grow={false}>
<EuiPopover
button={
<EuiButtonIcon
display="base"
size="m"
iconType="boxesVertical"
aria-label={i18n.INSTALL_RULES_OVERFLOW_BUTTON_ARIA_LABEL}
onClick={onButtonClick}
disabled={!canUserEditRules || isRequestInProgress}
/>
}
isOpen={isOverflowPopoverOpen}
closePopover={closeOverflowPopover}
panelPaddingSize="s"
anchorPosition="downRight"
>
<EuiContextMenuPanel size="s" items={overflowItems} />
</EuiPopover>
</EuiFlexItem>
</>
) : null}
<EuiFlexItem grow={false}>
<EuiButton
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
/*
* 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 {
EuiButtonEmpty,
EuiButtonIcon,
EuiContextMenuItem,
EuiContextMenuPanel,
EuiFlexGroup,
EuiFlexItem,
EuiLoadingSpinner,
EuiPopover,
} from '@elastic/eui';
import React, { useState } from 'react';
import type { Rule } from '../../../../rule_management/logic';
import type { RuleSignatureId } from '../../../../../../common/api/detection_engine';
import type { AddPrebuiltRulesTableActions } from './add_prebuilt_rules_table_context';
import * as i18n from './translations';

export const PrebuiltRulesInstallButton = ({
ruleId,
record,
installOneRule,
loadingRules,
isDisabled,
}: {
ruleId: RuleSignatureId;
record: Rule;
installOneRule: AddPrebuiltRulesTableActions['installOneRule'];
loadingRules: RuleSignatureId[];
isDisabled: boolean;
}) => {
dplumlee marked this conversation as resolved.
Show resolved Hide resolved
const isRuleInstalling = loadingRules.includes(ruleId);
const isInstallButtonDisabled = isRuleInstalling || isDisabled;
const [isPopoverOpen, setPopover] = useState(false);

const onOverflowButtonClick = () => {
setPopover(!isPopoverOpen);
};

const closeOverflowPopover = () => {
setPopover(false);
};

const enableOnClick = () => {
installOneRule(ruleId, true);
closeOverflowPopover();
};
dplumlee marked this conversation as resolved.
Show resolved Hide resolved

const overflowItems = [
dplumlee marked this conversation as resolved.
Show resolved Hide resolved
<EuiContextMenuItem key="copy" icon={'play'} onClick={enableOnClick}>
{i18n.INSTALL_AND_ENABLE_BUTTON_LABEL}
</EuiContextMenuItem>,
];

return (
<>
{isRuleInstalling ? (
dplumlee marked this conversation as resolved.
Show resolved Hide resolved
<EuiLoadingSpinner
size="s"
data-test-subj={`installSinglePrebuiltRuleButton-loadingSpinner-${ruleId}`}
/>
) : (
<EuiFlexGroup responsive={false} gutterSize="xs" alignItems="center">
<EuiFlexItem grow={false}>
<EuiButtonEmpty
size="s"
disabled={isInstallButtonDisabled}
onClick={() => installOneRule(ruleId)}
dplumlee marked this conversation as resolved.
Show resolved Hide resolved
data-test-subj={`installSinglePrebuiltRuleButton-${ruleId}`}
aria-label={i18n.INSTALL_RULE_BUTTON_ARIA_LABEL(record.name)}
>
{i18n.INSTALL_BUTTON_LABEL}
</EuiButtonEmpty>
</EuiFlexItem>
<EuiFlexItem grow={false}>
<EuiPopover
button={
<EuiButtonIcon
dplumlee marked this conversation as resolved.
Show resolved Hide resolved
display="empty"
size="s"
iconType="boxesVertical"
aria-label={i18n.INSTALL_RULES_OVERFLOW_BUTTON_ARIA_LABEL}
onClick={onOverflowButtonClick}
disabled={isInstallButtonDisabled}
/>
}
isOpen={isPopoverOpen}
closePopover={closeOverflowPopover}
panelPaddingSize="s"
anchorPosition="downRight"
>
<EuiContextMenuPanel size="s" items={overflowItems} />
</EuiPopover>
</EuiFlexItem>
</EuiFlexGroup>
)}
</>
);
};
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

import type { Dispatch, SetStateAction } from 'react';
import React, { createContext, useCallback, useContext, useMemo, useState } from 'react';
import { EuiButton } from '@elastic/eui';
import { EuiButton, EuiFlexGroup, EuiFlexItem } from '@elastic/eui';
import { useUserData } from '../../../../../detections/components/user_info';
import { useFetchPrebuiltRulesStatusQuery } from '../../../../rule_management/api/hooks/prebuilt_rules/use_fetch_prebuilt_rules_status_query';
import { useIsUpgradingSecurityPackages } from '../../../../rule_management/logic/use_upgrade_security_packages';
Expand Down Expand Up @@ -76,9 +76,9 @@ export interface AddPrebuiltRulesTableState {

export interface AddPrebuiltRulesTableActions {
reFetchRules: () => void;
installOneRule: (ruleId: RuleSignatureId) => void;
installOneRule: (ruleId: RuleSignatureId, enableOnInstall?: boolean) => void;
dplumlee marked this conversation as resolved.
Show resolved Hide resolved
installAllRules: () => void;
installSelectedRules: () => void;
installSelectedRules: (enableOnInstall?: boolean) => void;
setFilterOptions: Dispatch<SetStateAction<AddPrebuiltRulesTableFilterOptions>>;
selectRules: (rules: RuleResponse[]) => void;
openRulePreview: (ruleId: RuleSignatureId) => void;
Expand Down Expand Up @@ -148,33 +148,41 @@ export const AddPrebuiltRulesTableContextProvider = ({
!(isPreviewRuleLoading || isRefetching || isUpgradingSecurityPackages);

const installOneRule = useCallback(
async (ruleId: RuleSignatureId) => {
async (ruleId: RuleSignatureId, enableOnInstall?: boolean) => {
const rule = rules.find((r) => r.rule_id === ruleId);
invariant(rule, `Rule with id ${ruleId} not found`);

setLoadingRules((prev) => [...prev, ruleId]);
try {
await installSpecificRulesRequest([{ rule_id: ruleId, version: rule.version }]);
await installSpecificRulesRequest({
rules: [{ rule_id: ruleId, version: rule.version }],
enableOnInstall,
});
} finally {
setLoadingRules((prev) => prev.filter((id) => id !== ruleId));
}
},
[installSpecificRulesRequest, rules]
);

const installSelectedRules = useCallback(async () => {
const rulesToUpgrade = selectedRules.map((rule) => ({
rule_id: rule.rule_id,
version: rule.version,
}));
setLoadingRules((prev) => [...prev, ...rulesToUpgrade.map((r) => r.rule_id)]);
try {
await installSpecificRulesRequest(rulesToUpgrade);
} finally {
setLoadingRules((prev) => prev.filter((id) => !rulesToUpgrade.some((r) => r.rule_id === id)));
setSelectedRules([]);
}
}, [installSpecificRulesRequest, selectedRules]);
const installSelectedRules = useCallback(
async (enableOnInstall?: boolean) => {
const rulesToUpgrade = selectedRules.map((rule) => ({
rule_id: rule.rule_id,
version: rule.version,
}));
setLoadingRules((prev) => [...prev, ...rulesToUpgrade.map((r) => r.rule_id)]);
try {
await installSpecificRulesRequest({ rules: rulesToUpgrade, enableOnInstall });
} finally {
setLoadingRules((prev) =>
prev.filter((id) => !rulesToUpgrade.some((r) => r.rule_id === id))
);
setSelectedRules([]);
}
},
[installSpecificRulesRequest, selectedRules]
);

const installAllRules = useCallback(async () => {
// Unselect all rules so that the table doesn't show the "bulk actions" bar
Expand Down Expand Up @@ -242,17 +250,33 @@ export const AddPrebuiltRulesTableContextProvider = ({
dataTestSubj="installPrebuiltRulePreview"
closeFlyout={closeRulePreview}
ruleActions={
<EuiButton
disabled={!canPreviewedRuleBeInstalled}
onClick={() => {
installOneRule(previewedRule.rule_id ?? '');
closeRulePreview();
}}
fill
data-test-subj="installPrebuiltRuleFromFlyoutButton"
>
{i18n.INSTALL_BUTTON_LABEL}
</EuiButton>
<EuiFlexGroup>
<EuiFlexItem>
<EuiButton
disabled={!canPreviewedRuleBeInstalled}
onClick={() => {
Copy link
Contributor

Choose a reason for hiding this comment

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

nit: onClick handlers could be extracted in useCallback.

installOneRule(previewedRule.rule_id ?? '');
closeRulePreview();
}}
data-test-subj="installPrebuiltRuleFromFlyoutButton"
>
{i18n.INSTALL_WITHOUT_ENABLING_BUTTON_LABEL}
</EuiButton>
</EuiFlexItem>
<EuiFlexItem>
<EuiButton
disabled={!canPreviewedRuleBeInstalled}
onClick={() => {
installOneRule(previewedRule.rule_id ?? '', true);
closeRulePreview();
}}
fill
data-test-subj="installPrebuiltRuleFromFlyoutButton"
>
{i18n.INSTALL_AND_ENABLE_BUTTON_LABEL}
</EuiButton>
</EuiFlexItem>
</EuiFlexGroup>
}
/>
)}
Expand Down
Loading