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] Fix success bulk edit toast message #144497

Merged
merged 4 commits into from
Nov 3, 2022
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 @@ -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
}`;
Comment on lines +65 to +75
Copy link
Contributor

Choose a reason for hiding this comment

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

Will modify this logic in #144461 so that the warning that explains that rules with data views were skipped will only show when rules were actually skipped, along with the detail of how many rules were skipped.

}

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