Skip to content

Commit

Permalink
[Security Solution] Fix success bulk edit toast message (#144497)
Browse files Browse the repository at this point in the history
**Resolves:** #139897

## Summary

Fixes bulk edit success toast's message. Displays `You've successfully updated X rules. If you did not select to apply changes to rules using Kibana data views, those rules were not updated and will continue using data views.` when rule's index patterns were edited and `You've successfully updated X rules.` in the other cases.

*Before:*

https://user-images.githubusercontent.com/3775283/199676233-d3287d97-8e66-4938-bc80-7c643ca0e0ad.mov

*After:*

https://user-images.githubusercontent.com/3775283/199676250-0814ea26-a9bb-4402-a8db-8c2f0e394563.mov


### Checklist


- [x] Any text added follows [EUI's writing guidelines](https://elastic.github.io/eui/#/guidelines/writing), uses sentence case text and includes [i18n support](https://github.com/elastic/kibana/blob/main/packages/kbn-i18n/README.md)
- [x] [Unit or functional tests](https://www.elastic.co/guide/en/kibana/master/development-tests.html) were updated or added to match the most common scenarios
  • Loading branch information
maximpn authored Nov 3, 2022
1 parent 4233713 commit 190354a
Show file tree
Hide file tree
Showing 12 changed files with 215 additions and 102 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -289,6 +289,32 @@ describe('Detection rules, bulk edit', () => {
checkTagsInTagsFilter(resultingTagsInFilter);
});

it('Display success toast after adding tags', () => {
const tagsToBeAdded = ['tag-to-add-1', 'tag-to-add-2'];

// check if only pre-populated tags exist in the tags filter
checkTagsInTagsFilter(prePopulatedTags);

cy.get(EUI_FILTER_SELECT_ITEM)
.should('have.length', prePopulatedTags.length)
.each(($el, index) => {
cy.wrap($el).should('have.text', prePopulatedTags[index]);
});

selectNumberOfRules(expectedNumberOfCustomRulesToBeEdited);

// open add tags form and add 2 new tags
openBulkEditAddTagsForm();
typeTags(tagsToBeAdded);
submitBulkEditForm();
waitForBulkEditActionToFinish({ rulesCount: expectedNumberOfCustomRulesToBeEdited });

cy.get(TOASTER_BODY).should(
'have.text',
`You've successfully updated ${expectedNumberOfCustomRulesToBeEdited} rules`
);
});

it('Overwrite tags in custom rules', () => {
const tagsToOverwrite = ['overwrite-tag-1'];

Expand Down Expand Up @@ -392,6 +418,25 @@ describe('Detection rules, bulk edit', () => {
hasIndexPatterns(resultingIndexPatterns.join(''));
});

it('Display success toast after editing the index pattern', () => {
const indexPattersToBeAdded = ['index-to-add-1-*', 'index-to-add-2-*'];

// select only rules that are not ML
selectNumberOfRules(expectedNumberOfCustomRulesToBeEdited);
unselectRuleByName(getMachineLearningRule().name);

openBulkEditAddIndexPatternsForm();
typeIndexPatterns(indexPattersToBeAdded);
submitBulkEditForm();

waitForBulkEditActionToFinish({ rulesCount: expectedNumberOfNotMLRules });

cy.get(TOASTER_BODY).should(
'have.text',
`You've successfully updated ${expectedNumberOfNotMLRules} rules. If you did not select to apply changes to rules using Kibana data views, those rules were not updated and will continue using data views.`
);
});

it('Overwrite index patterns in custom rules', () => {
const indexPattersToWrite = ['index-to-write-1-*', 'index-to-write-2-*'];

Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,11 @@
*/

import type { HTTPError } from '../../../../../common/detection_engine/types';
import { BulkActionType } from '../../../../../common/detection_engine/rule_management/api/rules/bulk_actions/request_schema';
import type { BulkActionEditPayload } from '../../../../../common/detection_engine/rule_management/api/rules/bulk_actions/request_schema';
import {
BulkActionEditType,
BulkActionType,
} from '../../../../../common/detection_engine/rule_management/api/rules/bulk_actions/request_schema';
import * as i18n from '../../../../detections/pages/detection_engine/rules/translations';
import type { BulkActionResponse, BulkActionSummary } from '../../api/api';

Expand All @@ -32,7 +36,10 @@ export function summarizeBulkSuccess(action: BulkActionType): string {
}
}

export function explainBulkSuccess(action: BulkActionType, summary: BulkActionSummary): string {
export function explainBulkSuccess(
action: Exclude<BulkActionType, BulkActionType.edit>,
summary: BulkActionSummary
): string {
switch (action) {
case BulkActionType.export:
return getExportSuccessToastMessage(summary.succeeded, summary.total);
Expand All @@ -48,10 +55,27 @@ export function explainBulkSuccess(action: BulkActionType, summary: BulkActionSu

case BulkActionType.disable:
return i18n.RULES_BULK_DISABLE_SUCCESS_DESCRIPTION(summary.succeeded);
}
}

case BulkActionType.edit:
return i18n.RULES_BULK_EDIT_SUCCESS_DESCRIPTION(summary.succeeded);
export function explainBulkEditSuccess(
editPayload: BulkActionEditPayload[],
summary: BulkActionSummary
): string {
if (
editPayload.some(
(x) =>
x.type === BulkActionEditType.add_index_patterns ||
x.type === BulkActionEditType.set_index_patterns ||
x.type === BulkActionEditType.delete_index_patterns
)
) {
return `${i18n.RULES_BULK_EDIT_SUCCESS_DESCRIPTION(summary.succeeded)}. ${
i18n.RULES_BULK_EDIT_SUCCESS_INDEX_EDIT_DESCRIPTION
}`;
}

return i18n.RULES_BULK_EDIT_SUCCESS_DESCRIPTION(summary.succeeded);
}

export function summarizeBulkError(action: BulkActionType): string {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,21 +7,15 @@

import { useCallback } from 'react';
import { BulkActionType } from '../../../../../common/detection_engine/rule_management/api/rules/bulk_actions/request_schema';
import type { UseAppToasts } from '../../../../common/hooks/use_app_toasts';
import { useAppToasts } from '../../../../common/hooks/use_app_toasts';
import { downloadBlob } from '../../../../common/utils/download_blob';
import * as i18n from '../../../../detections/pages/detection_engine/rules/translations';
import { useRulesTableContextOptional } from '../../../rule_management_ui/components/rules_table/rules_table/rules_table_context';
import { getExportedRulesCounts } from '../../../rule_management_ui/components/rules_table/helpers';
import { useBulkExportMutation } from '../../api/hooks/use_bulk_export_mutation';
import { showBulkErrorToast } from './show_bulk_error_toast';
import { showBulkSuccessToast } from './show_bulk_success_toast';
import { useShowBulkErrorToast } from './use_show_bulk_error_toast';
import type { QueryOrIds } from '../../api/api';
import { useGuessRuleIdsForBulkAction } from './use_guess_rule_ids_for_bulk_action';

export function useBulkExport() {
const toasts = useAppToasts();
const { mutateAsync } = useBulkExportMutation();
const showBulkErrorToast = useShowBulkErrorToast();
const guessRuleIdsForBulkAction = useGuessRuleIdsForBulkAction();
const rulesTableContext = useRulesTableContextOptional();
const setLoadingRules = rulesTableContext?.actions.setLoadingRules;
Expand All @@ -35,35 +29,13 @@ export function useBulkExport() {
});
return await mutateAsync(queryOrIds);
} catch (error) {
showBulkErrorToast(toasts, BulkActionType.export, error);
showBulkErrorToast({ actionType: BulkActionType.export, error });
} finally {
setLoadingRules?.({ ids: [], action: null });
}
},
[guessRuleIdsForBulkAction, setLoadingRules, mutateAsync, toasts]
[guessRuleIdsForBulkAction, setLoadingRules, mutateAsync, showBulkErrorToast]
);

return { bulkExport };
}

/**
* downloads exported rules, received from export action
* @param params.response - Blob results with exported rules
* @param params.toasts - {@link UseAppToasts} toasts service
* @param params.onSuccess - {@link OnActionSuccessCallback} optional toast to display when action successful
* @param params.onError - {@link OnActionErrorCallback} optional toast to display when action failed
*/
export async function downloadExportedRules({
response,
toasts,
}: {
response: Blob;
toasts: UseAppToasts;
}) {
try {
downloadBlob(response, `${i18n.EXPORT_FILENAME}.ndjson`);
showBulkSuccessToast(toasts, BulkActionType.export, await getExportedRulesCounts(response));
} catch (error) {
showBulkErrorToast(toasts, BulkActionType.export, error);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/*
* 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 } from 'react';
import { BulkActionType } from '../../../../../common/detection_engine/rule_management/api/rules/bulk_actions/request_schema';
import { downloadBlob } from '../../../../common/utils/download_blob';
import * as i18n from '../../../../detections/pages/detection_engine/rules/translations';
import { getExportedRulesCounts } from '../../../rule_management_ui/components/rules_table/helpers';
import { useShowBulkErrorToast } from './use_show_bulk_error_toast';
import { useShowBulkSuccessToast } from './use_show_bulk_success_toast';

const DEFAULT_EXPORT_FILENAME = `${i18n.EXPORT_FILENAME}.ndjson`;

/**
* downloads exported rules, received from export action
*/
export function useDownloadExportedRules() {
const showBulkSuccessToast = useShowBulkSuccessToast();
const showBulkErrorToast = useShowBulkErrorToast();

return useCallback(
async (response: Blob) => {
try {
downloadBlob(response, DEFAULT_EXPORT_FILENAME);
showBulkSuccessToast({
actionType: BulkActionType.export,
summary: await getExportedRulesCounts(response),
});
} catch (error) {
showBulkErrorToast({ actionType: BulkActionType.export, error });
}
},
[showBulkSuccessToast, showBulkErrorToast]
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,12 @@ import { APP_UI_ID } from '../../../../../common/constants';
import { BulkActionType } from '../../../../../common/detection_engine/rule_management/api/rules/bulk_actions/request_schema';
import { SecurityPageName } from '../../../../app/types';
import { getEditRuleUrl } from '../../../../common/components/link_to/redirect_to_detection_engine';
import { useAppToasts } from '../../../../common/hooks/use_app_toasts';
import { METRIC_TYPE, TELEMETRY_EVENT, track } from '../../../../common/lib/telemetry';
import { useRulesTableContextOptional } from '../../../rule_management_ui/components/rules_table/rules_table/rules_table_context';
import type { BulkAction } from '../../api/api';
import { useBulkActionMutation } from '../../api/hooks/use_bulk_action_mutation';
import { showBulkErrorToast } from './show_bulk_error_toast';
import { showBulkSuccessToast } from './show_bulk_success_toast';
import { useShowBulkErrorToast } from './use_show_bulk_error_toast';
import { useShowBulkSuccessToast } from './use_show_bulk_success_toast';
import { useGuessRuleIdsForBulkAction } from './use_guess_rule_ids_for_bulk_action';

export const goToRuleEditPage = (
Expand All @@ -36,8 +35,9 @@ interface UseExecuteBulkActionOptions {
}

export const useExecuteBulkAction = (options?: UseExecuteBulkActionOptions) => {
const toasts = useAppToasts();
const { mutateAsync } = useBulkActionMutation();
const showBulkSuccessToast = useShowBulkSuccessToast();
const showBulkErrorToast = useShowBulkErrorToast();
const guessRuleIdsForBulkAction = useGuessRuleIdsForBulkAction();
const rulesTableContext = useRulesTableContextOptional();
const setLoadingRules = rulesTableContext?.actions.setLoadingRules;
Expand All @@ -54,17 +54,29 @@ export const useExecuteBulkAction = (options?: UseExecuteBulkActionOptions) => {
sendTelemetry(bulkAction.type, response);

if (!options?.suppressSuccessToast) {
showBulkSuccessToast(toasts, bulkAction.type, response.attributes.summary);
showBulkSuccessToast({
actionType: bulkAction.type,
summary: response.attributes.summary,
editPayload:
bulkAction.type === BulkActionType.edit ? bulkAction.editPayload : undefined,
});
}

return response;
} catch (error) {
showBulkErrorToast(toasts, bulkAction.type, error);
showBulkErrorToast({ actionType: bulkAction.type, error });
} finally {
setLoadingRules?.({ ids: [], action: null });
}
},
[options?.suppressSuccessToast, guessRuleIdsForBulkAction, setLoadingRules, mutateAsync, toasts]
[
options?.suppressSuccessToast,
guessRuleIdsForBulkAction,
setLoadingRules,
mutateAsync,
showBulkSuccessToast,
showBulkErrorToast,
]
);

return { executeBulkAction };
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,29 @@
* 2.0.
*/

import { useCallback } from 'react';
import type { HTTPError } from '../../../../../common/detection_engine/types';
import type { UseAppToasts } from '../../../../common/hooks/use_app_toasts';
import { useAppToasts } from '../../../../common/hooks/use_app_toasts';
import type { BulkActionType } from '../../../../../common/detection_engine/rule_management/api/rules/bulk_actions/request_schema';
import { explainBulkError, summarizeBulkError } from './translations';

export function showBulkErrorToast(
toasts: UseAppToasts,
action: BulkActionType,
error: HTTPError
): void {
toasts.addError(populateErrorStack(error), {
title: summarizeBulkError(action),
toastMessage: explainBulkError(action, error),
});
interface ShowBulkErrorToastProps {
actionType: BulkActionType;
error: HTTPError;
}

export function useShowBulkErrorToast() {
const toasts = useAppToasts();

return useCallback(
({ actionType, error }: ShowBulkErrorToastProps) => {
toasts.addError(populateErrorStack(error), {
title: summarizeBulkError(actionType),
toastMessage: explainBulkError(actionType, error),
});
},
[toasts]
);
}

function populateErrorStack(error: HTTPError): HTTPError {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/*
* 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 } from 'react';
import type { BulkActionSummary } from '..';
import { useAppToasts } from '../../../../common/hooks/use_app_toasts';
import type { BulkActionEditPayload } from '../../../../../common/detection_engine/rule_management/api/rules/bulk_actions/request_schema';
import { BulkActionType } from '../../../../../common/detection_engine/rule_management/api/rules/bulk_actions/request_schema';
import { explainBulkEditSuccess, explainBulkSuccess, summarizeBulkSuccess } from './translations';

interface ShowBulkSuccessToastProps {
actionType: BulkActionType;
summary: BulkActionSummary;
editPayload?: BulkActionEditPayload[];
}

export function useShowBulkSuccessToast() {
const toasts = useAppToasts();

return useCallback(
({ actionType, summary, editPayload }: ShowBulkSuccessToastProps) => {
const text =
actionType === BulkActionType.edit
? explainBulkEditSuccess(editPayload ?? [], summary)
: explainBulkSuccess(actionType, summary);

toasts.addSuccess({
title: summarizeBulkSuccess(actionType),
text,
});
},
[toasts]
);
}
Loading

0 comments on commit 190354a

Please sign in to comment.