Skip to content

Commit 8f7fb59

Browse files
committed
[Security Solution][Detections] Better toast errors (#72205)
* Add new hook to wrap the toasts service When receiving error responses from our APIs, this gives us better toast messages. * Replace useToasts with useAppToasts in trivial case * WIP: prevent infinite polling when server is unresponsive The crux of this issue was that we had no steady state when the server returned a non-API error (!isApiError), as it would if the server was throwing 500s or just generally misbehaving. The solution, then, is to addresse these non-API errors in our underlying useListsIndex and useListsPrivileges hooks. This also refactors those hooks to: * collapse multiple error states into one (that's all we currently need) * use useAppToasts for better UI TODO: I don't think I need the changes in useListsConfig's useEffect. * Slightly more legible variables The only task in this hook is our readPrivileges task right now, so I'm shortening the variable until we have a need to disambiguate it further. * Remove unnecessary conditions around creating our index If the index hook has an error needsIndex will not be true. * Better toast errors for Kibana API errors Our isApiError predicate does not work for errors coming back from Kibana platform itself, e.g. for a request payload error. I've added a separate predicate for that case, isKibanaError, and then a wrapping isAppError predicate since most of our use cases just care about error.body.message, which is common to both. * Use new toasts hook on our exceptions modals This fixes two issues: * toast appears above modal overlay * Error message from response is now presented in the toast * Fix bug with toasts dependencies Because of the way some of the exception modal's hooks are written, a change to one of its callbacks means that the request will be canceled. Because the toasts service exports instance methods, the context within the function (and thus the function itself) can change leading to a mutable ref. Because we don't want/need this behavior, we store our exported functions in refs to 'freeze' them for react. With our bound functions, we should now be able to declare e.g. `toast.addError` as a dependency, however react cannot determine that it is bound (and thus that toast.addError() is equivalent to addError()), and so we must destructure our functions in order to use them as dependencies. * Alert clipboard toasts through new Toasts service This fixes the z-index issue between modals and toasts. * Fix type errors * Mock external dependency These tests now call out to the Notifications service (in a context) instead of our redux implementation.
1 parent dcf745b commit 8f7fb59

14 files changed

Lines changed: 211 additions & 101 deletions

File tree

x-pack/plugins/security_solution/public/common/components/exceptions/add_exception_modal/index.tsx

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -29,8 +29,8 @@ import {
2929
} from '../../../../../public/lists_plugin_deps';
3030
import * as i18n from './translations';
3131
import { TimelineNonEcsData, Ecs } from '../../../../graphql/types';
32+
import { useAppToasts } from '../../../hooks/use_app_toasts';
3233
import { useKibana } from '../../../lib/kibana';
33-
import { errorToToaster, displaySuccessToast, useStateToaster } from '../../toasters';
3434
import { ExceptionBuilder } from '../builder';
3535
import { Loader } from '../../loader';
3636
import { useAddOrUpdateException } from '../use_add_exception';
@@ -115,7 +115,7 @@ export const AddExceptionModal = memo(function AddExceptionModal({
115115
Array<ExceptionListItemSchema | CreateExceptionListItemSchema>
116116
>([]);
117117
const [fetchOrCreateListError, setFetchOrCreateListError] = useState(false);
118-
const [, dispatchToaster] = useStateToaster();
118+
const { addError, addSuccess } = useAppToasts();
119119
const { loading: isSignalIndexLoading, signalIndexName } = useSignalIndex();
120120

121121
const [{ isLoading: indexPatternLoading, indexPatterns }] = useFetchIndexPatterns(
@@ -124,15 +124,15 @@ export const AddExceptionModal = memo(function AddExceptionModal({
124124

125125
const onError = useCallback(
126126
(error: Error) => {
127-
errorToToaster({ title: i18n.ADD_EXCEPTION_ERROR, error, dispatchToaster });
127+
addError(error, { title: i18n.ADD_EXCEPTION_ERROR });
128128
onCancel();
129129
},
130-
[dispatchToaster, onCancel]
130+
[addError, onCancel]
131131
);
132132
const onSuccess = useCallback(() => {
133-
displaySuccessToast(i18n.ADD_EXCEPTION_SUCCESS, dispatchToaster);
133+
addSuccess(i18n.ADD_EXCEPTION_SUCCESS);
134134
onConfirm(shouldCloseAlert);
135-
}, [dispatchToaster, onConfirm, shouldCloseAlert]);
135+
}, [addSuccess, onConfirm, shouldCloseAlert]);
136136

137137
const [{ isLoading: addExceptionIsLoading }, addOrUpdateExceptionItems] = useAddOrUpdateException(
138138
{

x-pack/plugins/security_solution/public/common/components/exceptions/edit_exception_modal/index.tsx

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ import {
3030
} from '../../../../../public/lists_plugin_deps';
3131
import * as i18n from './translations';
3232
import { useKibana } from '../../../lib/kibana';
33-
import { errorToToaster, displaySuccessToast, useStateToaster } from '../../toasters';
33+
import { useAppToasts } from '../../../hooks/use_app_toasts';
3434
import { ExceptionBuilder } from '../builder';
3535
import { useAddOrUpdateException } from '../use_add_exception';
3636
import { AddExceptionComments } from '../add_exception_comments';
@@ -93,7 +93,7 @@ export const EditExceptionModal = memo(function EditExceptionModal({
9393
const [exceptionItemsToAdd, setExceptionItemsToAdd] = useState<
9494
Array<ExceptionListItemSchema | CreateExceptionListItemSchema>
9595
>([]);
96-
const [, dispatchToaster] = useStateToaster();
96+
const { addError, addSuccess } = useAppToasts();
9797
const { loading: isSignalIndexLoading, signalIndexName } = useSignalIndex();
9898

9999
const [{ isLoading: indexPatternLoading, indexPatterns }] = useFetchIndexPatterns(
@@ -102,15 +102,15 @@ export const EditExceptionModal = memo(function EditExceptionModal({
102102

103103
const onError = useCallback(
104104
(error) => {
105-
errorToToaster({ title: i18n.EDIT_EXCEPTION_ERROR, error, dispatchToaster });
105+
addError(error, { title: i18n.EDIT_EXCEPTION_ERROR });
106106
onCancel();
107107
},
108-
[dispatchToaster, onCancel]
108+
[addError, onCancel]
109109
);
110110
const onSuccess = useCallback(() => {
111-
displaySuccessToast(i18n.EDIT_EXCEPTION_SUCCESS, dispatchToaster);
111+
addSuccess(i18n.EDIT_EXCEPTION_SUCCESS);
112112
onConfirm();
113-
}, [dispatchToaster, onConfirm]);
113+
}, [addSuccess, onConfirm]);
114114

115115
const [{ isLoading: addExceptionIsLoading }, addOrUpdateExceptionItems] = useAddOrUpdateException(
116116
{

x-pack/plugins/security_solution/public/common/components/exceptions/viewer/exception_item/index.test.tsx

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@ import { ExceptionItem } from './';
1313
import { getExceptionListItemSchemaMock } from '../../../../../../../lists/common/schemas/response/exception_list_item_schema.mock';
1414
import { getCommentsArrayMock } from '../../../../../../../lists/common/schemas/types/comments.mock';
1515

16+
jest.mock('../../../../lib/kibana');
17+
1618
describe('ExceptionItem', () => {
1719
it('it renders ExceptionDetails and ExceptionEntries', () => {
1820
const exceptionItem = getExceptionListItemSchemaMock();

x-pack/plugins/security_solution/public/common/components/toasters/utils.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ import { isError } from 'lodash/fp';
99

1010
import { AppToast, ActionToaster } from './';
1111
import { isToasterError } from './errors';
12-
import { isApiError } from '../../utils/api';
12+
import { isAppError } from '../../utils/api';
1313

1414
/**
1515
* Displays an error toast for the provided title and message
@@ -114,7 +114,7 @@ export const errorToToaster = ({
114114
iconType,
115115
errors: error.messages,
116116
};
117-
} else if (isApiError(error)) {
117+
} else if (isAppError(error)) {
118118
toast = {
119119
id,
120120
title,
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
/*
2+
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
3+
* or more contributor license agreements. Licensed under the Elastic License;
4+
* you may not use this file except in compliance with the Elastic License.
5+
*/
6+
7+
import { renderHook } from '@testing-library/react-hooks';
8+
9+
import { useToasts } from '../lib/kibana';
10+
import { useAppToasts } from './use_app_toasts';
11+
12+
jest.mock('../lib/kibana');
13+
14+
describe('useDeleteList', () => {
15+
let addErrorMock: jest.Mock;
16+
let addSuccessMock: jest.Mock;
17+
18+
beforeEach(() => {
19+
addErrorMock = jest.fn();
20+
addSuccessMock = jest.fn();
21+
(useToasts as jest.Mock).mockImplementation(() => ({
22+
addError: addErrorMock,
23+
addSuccess: addSuccessMock,
24+
}));
25+
});
26+
27+
it('works normally with a regular error', async () => {
28+
const error = new Error('regular error');
29+
const { result } = renderHook(() => useAppToasts());
30+
31+
result.current.addError(error, { title: 'title' });
32+
33+
expect(addErrorMock).toHaveBeenCalledWith(error, { title: 'title' });
34+
});
35+
36+
it("uses a AppError's body.message as the toastMessage", async () => {
37+
const kibanaApiError = {
38+
message: 'Not Found',
39+
body: { status_code: 404, message: 'Detailed Message' },
40+
};
41+
42+
const { result } = renderHook(() => useAppToasts());
43+
44+
result.current.addError(kibanaApiError, { title: 'title' });
45+
46+
expect(addErrorMock).toHaveBeenCalledWith(kibanaApiError, {
47+
title: 'title',
48+
toastMessage: 'Detailed Message',
49+
});
50+
});
51+
52+
it('converts an unknown error to an Error', () => {
53+
const unknownError = undefined;
54+
55+
const { result } = renderHook(() => useAppToasts());
56+
57+
result.current.addError(unknownError, { title: 'title' });
58+
59+
expect(addErrorMock).toHaveBeenCalledWith(Error(`${undefined}`), {
60+
title: 'title',
61+
});
62+
});
63+
});
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
/*
2+
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
3+
* or more contributor license agreements. Licensed under the Elastic License;
4+
* you may not use this file except in compliance with the Elastic License.
5+
*/
6+
7+
import { useCallback, useRef } from 'react';
8+
9+
import { ErrorToastOptions, ToastsStart, Toast } from '../../../../../../src/core/public';
10+
import { useToasts } from '../lib/kibana';
11+
import { isAppError, AppError } from '../utils/api';
12+
13+
export type UseAppToasts = Pick<ToastsStart, 'addSuccess'> & {
14+
api: ToastsStart;
15+
addError: (error: unknown, options: ErrorToastOptions) => Toast;
16+
};
17+
18+
export const useAppToasts = (): UseAppToasts => {
19+
const toasts = useToasts();
20+
const addError = useRef(toasts.addError.bind(toasts)).current;
21+
const addSuccess = useRef(toasts.addSuccess.bind(toasts)).current;
22+
23+
const addAppError = useCallback(
24+
(error: AppError, options: ErrorToastOptions) =>
25+
addError(error, {
26+
...options,
27+
toastMessage: error.body.message,
28+
}),
29+
[addError]
30+
);
31+
32+
const _addError = useCallback(
33+
(error: unknown, options: ErrorToastOptions) => {
34+
if (isAppError(error)) {
35+
return addAppError(error, options);
36+
} else {
37+
if (error instanceof Error) {
38+
return addError(error, options);
39+
} else {
40+
return addError(new Error(String(error)), options);
41+
}
42+
}
43+
},
44+
[addAppError, addError]
45+
);
46+
47+
return { api: toasts, addError: _addError, addSuccess };
48+
};

x-pack/plugins/security_solution/public/common/lib/clipboard/clipboard.tsx

Lines changed: 4 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,12 @@
44
* you may not use this file except in compliance with the Elastic License.
55
*/
66

7-
import { EuiGlobalToastListToast as Toast, EuiButtonIcon } from '@elastic/eui';
7+
import { EuiButtonIcon } from '@elastic/eui';
88
import copy from 'copy-to-clipboard';
99
import React from 'react';
10-
import uuid from 'uuid';
1110

1211
import * as i18n from './translations';
13-
import { useStateToaster } from '../../components/toasters';
12+
import { useAppToasts } from '../../hooks/use_app_toasts';
1413

1514
export type OnCopy = ({
1615
content,
@@ -20,17 +19,6 @@ export type OnCopy = ({
2019
isSuccess: boolean;
2120
}) => void;
2221

23-
interface GetSuccessToastParams {
24-
titleSummary?: string;
25-
}
26-
27-
const getSuccessToast = ({ titleSummary }: GetSuccessToastParams): Toast => ({
28-
id: `copy-success-${uuid.v4()}`,
29-
color: 'success',
30-
iconType: 'copyClipboard',
31-
title: `${i18n.COPIED} ${titleSummary} ${i18n.TO_THE_CLIPBOARD}`,
32-
});
33-
3422
interface Props {
3523
children?: JSX.Element;
3624
content: string | number;
@@ -40,7 +28,7 @@ interface Props {
4028
}
4129

4230
export const Clipboard = ({ children, content, onCopy, titleSummary, toastLifeTimeMs }: Props) => {
43-
const dispatchToaster = useStateToaster()[1];
31+
const { addSuccess } = useAppToasts();
4432
const onClick = (event: React.MouseEvent<HTMLButtonElement>) => {
4533
event.preventDefault();
4634
event.stopPropagation();
@@ -52,10 +40,7 @@ export const Clipboard = ({ children, content, onCopy, titleSummary, toastLifeTi
5240
}
5341

5442
if (isSuccess) {
55-
dispatchToaster({
56-
type: 'addToaster',
57-
toast: { toastLifeTimeMs, ...getSuccessToast({ titleSummary }) },
58-
});
43+
addSuccess(`${i18n.COPIED} ${titleSummary} ${i18n.TO_THE_CLIPBOARD}`, { toastLifeTimeMs });
5944
}
6045
};
6146

x-pack/plugins/security_solution/public/common/lib/kibana/__mocks__/index.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
* you may not use this file except in compliance with the Elastic License.
55
*/
66

7+
import { notificationServiceMock } from '../../../../../../../../src/core/public/mocks';
78
import {
89
createKibanaContextProviderMock,
910
createUseUiSettingMock,
@@ -19,6 +20,7 @@ export const useUiSetting$ = jest.fn(createUseUiSetting$Mock());
1920
export const useTimeZone = jest.fn();
2021
export const useDateFormat = jest.fn();
2122
export const useBasePath = jest.fn(() => '/test/base/path');
23+
export const useToasts = jest.fn(() => notificationServiceMock.createStartContract().toasts);
2224
export const useCurrentUser = jest.fn();
2325
export const withKibana = jest.fn(createWithKibanaMock());
2426
export const KibanaContextProvider = jest.fn(createKibanaContextProviderMock());

x-pack/plugins/security_solution/public/common/utils/api/index.ts

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,14 +6,33 @@
66

77
import { has } from 'lodash/fp';
88

9-
export interface KibanaApiError {
9+
export interface AppError {
1010
name: string;
1111
message: string;
12+
body: {
13+
message: string;
14+
};
15+
}
16+
17+
export interface KibanaError extends AppError {
18+
body: {
19+
message: string;
20+
statusCode: number;
21+
};
22+
}
23+
24+
export interface SecurityAppError extends AppError {
1225
body: {
1326
message: string;
1427
status_code: number;
1528
};
1629
}
1730

18-
export const isApiError = (error: unknown): error is KibanaApiError =>
31+
export const isKibanaError = (error: unknown): error is KibanaError =>
32+
has('message', error) && has('body.message', error) && has('body.statusCode', error);
33+
34+
export const isSecurityAppError = (error: unknown): error is SecurityAppError =>
1935
has('message', error) && has('body.message', error) && has('body.status_code', error);
36+
37+
export const isAppError = (error: unknown): error is AppError =>
38+
isKibanaError(error) || isSecurityAppError(error);

x-pack/plugins/security_solution/public/detections/components/value_lists_management_modal/modal.tsx

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,8 @@ import {
2323
useDeleteList,
2424
useCursor,
2525
} from '../../../shared_imports';
26-
import { useToasts, useKibana } from '../../../common/lib/kibana';
26+
import { useKibana } from '../../../common/lib/kibana';
27+
import { useAppToasts } from '../../../common/hooks/use_app_toasts';
2728
import { GenericDownloader } from '../../../common/components/generic_downloader';
2829
import * as i18n from './translations';
2930
import { ValueListsTable } from './table';
@@ -45,7 +46,7 @@ export const ValueListsModalComponent: React.FC<ValueListsModalProps> = ({
4546
const { start: findLists, ...lists } = useFindLists();
4647
const { start: deleteList, result: deleteResult } = useDeleteList();
4748
const [exportListId, setExportListId] = useState<string>();
48-
const toasts = useToasts();
49+
const { addError, addSuccess } = useAppToasts();
4950

5051
const fetchLists = useCallback(() => {
5152
findLists({ cursor, http, pageIndex: pageIndex + 1, pageSize });
@@ -82,21 +83,21 @@ export const ValueListsModalComponent: React.FC<ValueListsModalProps> = ({
8283
const handleUploadError = useCallback(
8384
(error: Error) => {
8485
if (error.name !== 'AbortError') {
85-
toasts.addError(error, { title: i18n.UPLOAD_ERROR });
86+
addError(error, { title: i18n.UPLOAD_ERROR });
8687
}
8788
},
88-
[toasts]
89+
[addError]
8990
);
9091
const handleUploadSuccess = useCallback(
9192
(response: ListSchema) => {
92-
toasts.addSuccess({
93+
addSuccess({
9394
text: i18n.uploadSuccessMessage(response.name),
9495
title: i18n.UPLOAD_SUCCESS_TITLE,
9596
});
9697
fetchLists();
9798
},
9899
// eslint-disable-next-line react-hooks/exhaustive-deps
99-
[toasts]
100+
[addSuccess]
100101
);
101102

102103
useEffect(() => {

0 commit comments

Comments
 (0)