diff --git a/src/core/server/elasticsearch/elasticsearch_service.mock.ts b/src/core/server/elasticsearch/elasticsearch_service.mock.ts index fdfc48fa9f754b..f524781de4c7ed 100644 --- a/src/core/server/elasticsearch/elasticsearch_service.mock.ts +++ b/src/core/server/elasticsearch/elasticsearch_service.mock.ts @@ -18,37 +18,14 @@ */ import { BehaviorSubject } from 'rxjs'; -import { Client } from 'elasticsearch'; -import { - ILegacyClusterClient, - ILegacyCustomClusterClient, - ILegacyScopedClusterClient, -} from './legacy'; +import { ILegacyClusterClient, ILegacyCustomClusterClient } from './legacy'; +import { legacyClientMock } from './legacy/mocks'; import { ElasticsearchConfig } from './elasticsearch_config'; import { ElasticsearchService } from './elasticsearch_service'; import { InternalElasticsearchServiceSetup, ElasticsearchStatusMeta } from './types'; import { NodesVersionCompatibility } from './version_check/ensure_es_version'; import { ServiceStatus, ServiceStatusLevels } from '../status'; -const createScopedClusterClientMock = (): jest.Mocked => ({ - callAsInternalUser: jest.fn(), - callAsCurrentUser: jest.fn(), -}); - -const createCustomClusterClientMock = (): jest.Mocked => ({ - ...createClusterClientMock(), - close: jest.fn(), -}); - -function createClusterClientMock() { - const client: jest.Mocked = { - callAsInternalUser: jest.fn(), - asScoped: jest.fn(), - }; - client.asScoped.mockReturnValue(createScopedClusterClientMock()); - return client; -} - interface MockedElasticSearchServiceSetup { legacy: { createClient: jest.Mock; @@ -60,11 +37,13 @@ const createSetupContractMock = () => { const setupContract: MockedElasticSearchServiceSetup = { legacy: { createClient: jest.fn(), - client: createClusterClientMock(), + client: legacyClientMock.createClusterClient(), }, }; - setupContract.legacy.createClient.mockReturnValue(createCustomClusterClientMock()); - setupContract.legacy.client.asScoped.mockReturnValue(createScopedClusterClientMock()); + setupContract.legacy.createClient.mockReturnValue(legacyClientMock.createCustomClusterClient()); + setupContract.legacy.client.asScoped.mockReturnValue( + legacyClientMock.createScopedClusterClient() + ); return setupContract; }; @@ -74,11 +53,14 @@ const createStartContractMock = () => { const startContract: MockedElasticSearchServiceStart = { legacy: { createClient: jest.fn(), - client: createClusterClientMock(), + client: legacyClientMock.createClusterClient(), }, }; - startContract.legacy.createClient.mockReturnValue(createCustomClusterClientMock()); - startContract.legacy.client.asScoped.mockReturnValue(createScopedClusterClientMock()); + startContract.legacy.createClient.mockReturnValue(legacyClientMock.createCustomClusterClient()); + startContract.legacy.client.asScoped.mockReturnValue( + legacyClientMock.createScopedClusterClient() + ); + return startContract; }; @@ -104,7 +86,9 @@ const createInternalSetupContractMock = () => { ...createSetupContractMock().legacy, }, }; - setupContract.legacy.client.asScoped.mockReturnValue(createScopedClusterClientMock()); + setupContract.legacy.client.asScoped.mockReturnValue( + legacyClientMock.createScopedClusterClient() + ); return setupContract; }; @@ -121,62 +105,13 @@ const createMock = () => { return mocked; }; -const createElasticsearchClientMock = () => { - const mocked: jest.Mocked = { - cat: {} as any, - cluster: {} as any, - indices: {} as any, - ingest: {} as any, - nodes: {} as any, - snapshot: {} as any, - tasks: {} as any, - bulk: jest.fn(), - clearScroll: jest.fn(), - count: jest.fn(), - create: jest.fn(), - delete: jest.fn(), - deleteByQuery: jest.fn(), - deleteScript: jest.fn(), - deleteTemplate: jest.fn(), - exists: jest.fn(), - explain: jest.fn(), - fieldStats: jest.fn(), - get: jest.fn(), - getScript: jest.fn(), - getSource: jest.fn(), - getTemplate: jest.fn(), - index: jest.fn(), - info: jest.fn(), - mget: jest.fn(), - msearch: jest.fn(), - msearchTemplate: jest.fn(), - mtermvectors: jest.fn(), - ping: jest.fn(), - putScript: jest.fn(), - putTemplate: jest.fn(), - reindex: jest.fn(), - reindexRethrottle: jest.fn(), - renderSearchTemplate: jest.fn(), - scroll: jest.fn(), - search: jest.fn(), - searchShards: jest.fn(), - searchTemplate: jest.fn(), - suggest: jest.fn(), - termvectors: jest.fn(), - update: jest.fn(), - updateByQuery: jest.fn(), - close: jest.fn(), - }; - return mocked; -}; - export const elasticsearchServiceMock = { create: createMock, createInternalSetup: createInternalSetupContractMock, createSetup: createSetupContractMock, createStart: createStartContractMock, - createClusterClient: createClusterClientMock, - createCustomClusterClient: createCustomClusterClientMock, - createScopedClusterClient: createScopedClusterClientMock, - createElasticsearchClient: createElasticsearchClientMock, + createLegacyClusterClient: legacyClientMock.createClusterClient, + createLegacyCustomClusterClient: legacyClientMock.createCustomClusterClient, + createLegacyScopedClusterClient: legacyClientMock.createScopedClusterClient, + createLegacyElasticsearchClient: legacyClientMock.createElasticsearchClient, }; diff --git a/src/core/server/elasticsearch/elasticsearch_service.test.ts b/src/core/server/elasticsearch/elasticsearch_service.test.ts index 0a7068903e15c2..99d12b8662577a 100644 --- a/src/core/server/elasticsearch/elasticsearch_service.test.ts +++ b/src/core/server/elasticsearch/elasticsearch_service.test.ts @@ -75,7 +75,7 @@ describe('#setup', () => { }); it('returns elasticsearch client as a part of the contract', async () => { - const mockClusterClientInstance = elasticsearchServiceMock.createClusterClient(); + const mockClusterClientInstance = elasticsearchServiceMock.createLegacyClusterClient(); MockClusterClient.mockImplementationOnce(() => mockClusterClientInstance); const setupContract = await elasticsearchService.setup(deps); @@ -209,7 +209,7 @@ describe('#setup', () => { }); it('esNodeVersionCompatibility$ only starts polling when subscribed to', async (done) => { - const clusterClientInstance = elasticsearchServiceMock.createClusterClient(); + const clusterClientInstance = elasticsearchServiceMock.createLegacyClusterClient(); MockClusterClient.mockImplementationOnce(() => clusterClientInstance); clusterClientInstance.callAsInternalUser.mockRejectedValue(new Error()); @@ -225,7 +225,7 @@ describe('#setup', () => { }); it('esNodeVersionCompatibility$ stops polling when unsubscribed from', async (done) => { - const mockClusterClientInstance = elasticsearchServiceMock.createClusterClient(); + const mockClusterClientInstance = elasticsearchServiceMock.createLegacyClusterClient(); MockClusterClient.mockImplementationOnce(() => mockClusterClientInstance); mockClusterClientInstance.callAsInternalUser.mockRejectedValue(new Error()); @@ -255,7 +255,7 @@ describe('#stop', () => { it('stops pollEsNodeVersions even if there are active subscriptions', async (done) => { expect.assertions(2); - const mockClusterClientInstance = elasticsearchServiceMock.createCustomClusterClient(); + const mockClusterClientInstance = elasticsearchServiceMock.createLegacyCustomClusterClient(); MockClusterClient.mockImplementationOnce(() => mockClusterClientInstance); diff --git a/src/core/server/elasticsearch/legacy/mocks.ts b/src/core/server/elasticsearch/legacy/mocks.ts new file mode 100644 index 00000000000000..7714e7032940a5 --- /dev/null +++ b/src/core/server/elasticsearch/legacy/mocks.ts @@ -0,0 +1,97 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { Client } from 'elasticsearch'; +import { ILegacyScopedClusterClient } from './scoped_cluster_client'; +import { ILegacyClusterClient, ILegacyCustomClusterClient } from './cluster_client'; + +const createScopedClusterClientMock = (): jest.Mocked => ({ + callAsInternalUser: jest.fn(), + callAsCurrentUser: jest.fn(), +}); + +const createCustomClusterClientMock = (): jest.Mocked => ({ + ...createClusterClientMock(), + close: jest.fn(), +}); + +function createClusterClientMock() { + const client: jest.Mocked = { + callAsInternalUser: jest.fn(), + asScoped: jest.fn(), + }; + client.asScoped.mockReturnValue(createScopedClusterClientMock()); + return client; +} + +const createElasticsearchClientMock = () => { + const mocked: jest.Mocked = { + cat: {} as any, + cluster: {} as any, + indices: {} as any, + ingest: {} as any, + nodes: {} as any, + snapshot: {} as any, + tasks: {} as any, + bulk: jest.fn(), + clearScroll: jest.fn(), + count: jest.fn(), + create: jest.fn(), + delete: jest.fn(), + deleteByQuery: jest.fn(), + deleteScript: jest.fn(), + deleteTemplate: jest.fn(), + exists: jest.fn(), + explain: jest.fn(), + fieldStats: jest.fn(), + get: jest.fn(), + getScript: jest.fn(), + getSource: jest.fn(), + getTemplate: jest.fn(), + index: jest.fn(), + info: jest.fn(), + mget: jest.fn(), + msearch: jest.fn(), + msearchTemplate: jest.fn(), + mtermvectors: jest.fn(), + ping: jest.fn(), + putScript: jest.fn(), + putTemplate: jest.fn(), + reindex: jest.fn(), + reindexRethrottle: jest.fn(), + renderSearchTemplate: jest.fn(), + scroll: jest.fn(), + search: jest.fn(), + searchShards: jest.fn(), + searchTemplate: jest.fn(), + suggest: jest.fn(), + termvectors: jest.fn(), + update: jest.fn(), + updateByQuery: jest.fn(), + close: jest.fn(), + }; + return mocked; +}; + +export const legacyClientMock = { + createScopedClusterClient: createScopedClusterClientMock, + createCustomClusterClient: createCustomClusterClientMock, + createClusterClient: createClusterClientMock, + createElasticsearchClient: createElasticsearchClientMock, +}; diff --git a/src/core/server/http/integration_tests/core_service.test.mocks.ts b/src/core/server/http/integration_tests/core_service.test.mocks.ts index 6f9b4b96eae9d6..f7ebd18b9c4883 100644 --- a/src/core/server/http/integration_tests/core_service.test.mocks.ts +++ b/src/core/server/http/integration_tests/core_service.test.mocks.ts @@ -21,7 +21,7 @@ import { elasticsearchServiceMock } from '../../elasticsearch/elasticsearch_serv export const clusterClientMock = jest.fn(); jest.doMock('../../elasticsearch/legacy/scoped_cluster_client', () => ({ LegacyScopedClusterClient: clusterClientMock.mockImplementation(function () { - return elasticsearchServiceMock.createScopedClusterClient(); + return elasticsearchServiceMock.createLegacyScopedClusterClient(); }), })); @@ -31,7 +31,7 @@ jest.doMock('elasticsearch', () => { ...realES, // eslint-disable-next-line object-shorthand Client: function () { - return elasticsearchServiceMock.createElasticsearchClient(); + return elasticsearchServiceMock.createLegacyElasticsearchClient(); }, }; }); diff --git a/src/core/server/mocks.ts b/src/core/server/mocks.ts index 4491942951c505..73d8e79069ce31 100644 --- a/src/core/server/mocks.ts +++ b/src/core/server/mocks.ts @@ -190,7 +190,7 @@ function createCoreRequestHandlerContextMock() { }, elasticsearch: { legacy: { - client: elasticsearchServiceMock.createScopedClusterClient(), + client: elasticsearchServiceMock.createLegacyScopedClusterClient(), }, }, uiSettings: { diff --git a/src/legacy/core_plugins/kibana/server/ui_setting_defaults.js b/src/legacy/core_plugins/kibana/server/ui_setting_defaults.js index b7af6a73e1bc18..e1dadb0a24de15 100644 --- a/src/legacy/core_plugins/kibana/server/ui_setting_defaults.js +++ b/src/legacy/core_plugins/kibana/server/ui_setting_defaults.js @@ -101,7 +101,14 @@ export function getUiSettingDefaults() { }, }), type: 'select', - options: ['Browser', ...moment.tz.names()], + options: [ + 'Browser', + ...moment.tz + .names() + // We need to filter out some time zones, that moment.js knows about, but Elasticsearch + // does not understand and would fail thus with a 400 bad request when using them. + .filter((tz) => !['America/Nuuk', 'EST', 'HST', 'ROC', 'MST'].includes(tz)), + ], requiresPageReload: true, }, 'dateFormat:scaled': { diff --git a/test/functional/apps/dashboard/time_zones.js b/test/functional/apps/dashboard/time_zones.js index 4e95a14efb4d60..800bedb1329788 100644 --- a/test/functional/apps/dashboard/time_zones.js +++ b/test/functional/apps/dashboard/time_zones.js @@ -65,7 +65,7 @@ export default function ({ getService, getPageObjects }) { it('Changing timezone changes dashboard timestamp and shows the same data', async () => { await PageObjects.settings.navigateTo(); await PageObjects.settings.clickKibanaSettings(); - await PageObjects.settings.setAdvancedSettingsSelect('dateFormat:tz', 'EST'); + await PageObjects.settings.setAdvancedSettingsSelect('dateFormat:tz', 'Etc/GMT+5'); await PageObjects.common.navigateToApp('dashboard'); await PageObjects.dashboard.loadSavedDashboard('time zone test'); const time = await PageObjects.timePicker.getTimeConfigAsAbsoluteTimes(); diff --git a/x-pack/plugins/actions/server/actions_client.test.ts b/x-pack/plugins/actions/server/actions_client.test.ts index 1b40e4458b77f4..09dd42dc91dd5c 100644 --- a/x-pack/plugins/actions/server/actions_client.test.ts +++ b/x-pack/plugins/actions/server/actions_client.test.ts @@ -27,7 +27,7 @@ import { actionsAuthorizationMock } from './authorization/actions_authorization. const defaultKibanaIndex = '.kibana'; const savedObjectsClient = savedObjectsClientMock.create(); -const scopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); +const scopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); const actionExecutor = actionExecutorMock.create(); const authorization = actionsAuthorizationMock.create(); const executionEnqueuer = jest.fn(); diff --git a/x-pack/plugins/actions/server/mocks.ts b/x-pack/plugins/actions/server/mocks.ts index 1763d275c6fb07..87aa571ce6b8a0 100644 --- a/x-pack/plugins/actions/server/mocks.ts +++ b/x-pack/plugins/actions/server/mocks.ts @@ -37,7 +37,7 @@ const createServicesMock = () => { savedObjectsClient: ReturnType; } > = { - callCluster: elasticsearchServiceMock.createScopedClusterClient().callAsCurrentUser, + callCluster: elasticsearchServiceMock.createLegacyScopedClusterClient().callAsCurrentUser, getScopedCallCluster: jest.fn(), savedObjectsClient: savedObjectsClientMock.create(), }; diff --git a/x-pack/plugins/alerts/server/mocks.ts b/x-pack/plugins/alerts/server/mocks.ts index c94a7aba46cfa3..84f79d53f218cb 100644 --- a/x-pack/plugins/alerts/server/mocks.ts +++ b/x-pack/plugins/alerts/server/mocks.ts @@ -58,7 +58,7 @@ const createAlertServicesMock = () => { alertInstanceFactory: jest .fn, [string]>() .mockReturnValue(alertInstanceFactoryMock), - callCluster: elasticsearchServiceMock.createScopedClusterClient().callAsCurrentUser, + callCluster: elasticsearchServiceMock.createLegacyScopedClusterClient().callAsCurrentUser, getScopedCallCluster: jest.fn(), savedObjectsClient: savedObjectsClientMock.create(), }; diff --git a/x-pack/plugins/alerts/server/routes/_mock_handler_arguments.ts b/x-pack/plugins/alerts/server/routes/_mock_handler_arguments.ts index 7d86d4fde7e61b..548495866ec210 100644 --- a/x-pack/plugins/alerts/server/routes/_mock_handler_arguments.ts +++ b/x-pack/plugins/alerts/server/routes/_mock_handler_arguments.ts @@ -20,7 +20,7 @@ export function mockHandlerArguments( { alertsClient = alertsClientMock.create(), listTypes: listTypesRes = [], - esClient = elasticsearchServiceMock.createClusterClient(), + esClient = elasticsearchServiceMock.createLegacyClusterClient(), }: { alertsClient?: AlertsClientMock; listTypes?: AlertType[]; diff --git a/x-pack/plugins/alerts/server/routes/health.test.ts b/x-pack/plugins/alerts/server/routes/health.test.ts index b3f41e03ebdc98..ce782dbd631a5a 100644 --- a/x-pack/plugins/alerts/server/routes/health.test.ts +++ b/x-pack/plugins/alerts/server/routes/health.test.ts @@ -43,7 +43,7 @@ describe('healthRoute', () => { healthRoute(router, licenseState, encryptedSavedObjects); const [, handler] = router.get.mock.calls[0]; - const esClient = elasticsearchServiceMock.createClusterClient(); + const esClient = elasticsearchServiceMock.createLegacyClusterClient(); esClient.callAsInternalUser.mockReturnValue(Promise.resolve({})); const [context, req, res] = mockHandlerArguments({ esClient }, {}, ['ok']); @@ -72,7 +72,7 @@ describe('healthRoute', () => { healthRoute(router, licenseState, encryptedSavedObjects); const [, handler] = router.get.mock.calls[0]; - const esClient = elasticsearchServiceMock.createClusterClient(); + const esClient = elasticsearchServiceMock.createLegacyClusterClient(); esClient.callAsInternalUser.mockReturnValue(Promise.resolve({})); const [context, req, res] = mockHandlerArguments({ esClient }, {}, ['ok']); @@ -96,7 +96,7 @@ describe('healthRoute', () => { healthRoute(router, licenseState, encryptedSavedObjects); const [, handler] = router.get.mock.calls[0]; - const esClient = elasticsearchServiceMock.createClusterClient(); + const esClient = elasticsearchServiceMock.createLegacyClusterClient(); esClient.callAsInternalUser.mockReturnValue(Promise.resolve({})); const [context, req, res] = mockHandlerArguments({ esClient }, {}, ['ok']); @@ -120,7 +120,7 @@ describe('healthRoute', () => { healthRoute(router, licenseState, encryptedSavedObjects); const [, handler] = router.get.mock.calls[0]; - const esClient = elasticsearchServiceMock.createClusterClient(); + const esClient = elasticsearchServiceMock.createLegacyClusterClient(); esClient.callAsInternalUser.mockReturnValue(Promise.resolve({ security: {} })); const [context, req, res] = mockHandlerArguments({ esClient }, {}, ['ok']); @@ -144,7 +144,7 @@ describe('healthRoute', () => { healthRoute(router, licenseState, encryptedSavedObjects); const [, handler] = router.get.mock.calls[0]; - const esClient = elasticsearchServiceMock.createClusterClient(); + const esClient = elasticsearchServiceMock.createLegacyClusterClient(); esClient.callAsInternalUser.mockReturnValue(Promise.resolve({ security: { enabled: true } })); const [context, req, res] = mockHandlerArguments({ esClient }, {}, ['ok']); @@ -168,7 +168,7 @@ describe('healthRoute', () => { healthRoute(router, licenseState, encryptedSavedObjects); const [, handler] = router.get.mock.calls[0]; - const esClient = elasticsearchServiceMock.createClusterClient(); + const esClient = elasticsearchServiceMock.createLegacyClusterClient(); esClient.callAsInternalUser.mockReturnValue( Promise.resolve({ security: { enabled: true, ssl: {} } }) ); @@ -194,7 +194,7 @@ describe('healthRoute', () => { healthRoute(router, licenseState, encryptedSavedObjects); const [, handler] = router.get.mock.calls[0]; - const esClient = elasticsearchServiceMock.createClusterClient(); + const esClient = elasticsearchServiceMock.createLegacyClusterClient(); esClient.callAsInternalUser.mockReturnValue( Promise.resolve({ security: { enabled: true, ssl: { http: { enabled: true } } } }) ); diff --git a/x-pack/plugins/apm/public/components/app/Main/route_config/index.tsx b/x-pack/plugins/apm/public/components/app/Main/route_config/index.tsx index 1625fb4c1409ef..8379def2a7d9aa 100644 --- a/x-pack/plugins/apm/public/components/app/Main/route_config/index.tsx +++ b/x-pack/plugins/apm/public/components/app/Main/route_config/index.tsx @@ -23,6 +23,7 @@ import { resolveUrlParams } from '../../../../context/UrlParamsContext/resolveUr import { UNIDENTIFIED_SERVICE_NODES_LABEL } from '../../../../../common/i18n'; import { TraceLink } from '../../TraceLink'; import { CustomizeUI } from '../../Settings/CustomizeUI'; +import { AnomalyDetection } from '../../Settings/anomaly_detection'; import { EditAgentConfigurationRouteHandler, CreateAgentConfigurationRouteHandler, @@ -268,4 +269,20 @@ export const routes: BreadcrumbRoute[] = [ }), name: RouteName.RUM_OVERVIEW, }, + { + exact: true, + path: '/settings/anomaly-detection', + component: () => ( + + + + ), + breadcrumb: i18n.translate( + 'xpack.apm.breadcrumb.settings.anomalyDetection', + { + defaultMessage: 'Anomaly detection', + } + ), + name: RouteName.ANOMALY_DETECTION, + }, ]; diff --git a/x-pack/plugins/apm/public/components/app/Main/route_config/route_names.tsx b/x-pack/plugins/apm/public/components/app/Main/route_config/route_names.tsx index 4965aa9db87602..37d96e74d8ee6e 100644 --- a/x-pack/plugins/apm/public/components/app/Main/route_config/route_names.tsx +++ b/x-pack/plugins/apm/public/components/app/Main/route_config/route_names.tsx @@ -27,4 +27,5 @@ export enum RouteName { LINK_TO_TRACE = 'link_to_trace', CUSTOMIZE_UI = 'customize_ui', RUM_OVERVIEW = 'rum_overview', + ANOMALY_DETECTION = 'anomaly_detection', } diff --git a/x-pack/plugins/apm/public/components/app/Settings/anomaly_detection/add_environments.tsx b/x-pack/plugins/apm/public/components/app/Settings/anomaly_detection/add_environments.tsx new file mode 100644 index 00000000000000..2da3c125631043 --- /dev/null +++ b/x-pack/plugins/apm/public/components/app/Settings/anomaly_detection/add_environments.tsx @@ -0,0 +1,164 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import React, { useState } from 'react'; +import { + EuiPanel, + EuiTitle, + EuiText, + EuiSpacer, + EuiButton, + EuiButtonEmpty, + EuiComboBox, + EuiComboBoxOptionOption, + EuiFlexGroup, + EuiFlexItem, + EuiFormRow, +} from '@elastic/eui'; +import { i18n } from '@kbn/i18n'; +import { useFetcher, FETCH_STATUS } from '../../../../hooks/useFetcher'; +import { useApmPluginContext } from '../../../../hooks/useApmPluginContext'; +import { createJobs } from './create_jobs'; +import { ENVIRONMENT_NOT_DEFINED } from '../../../../../common/environment_filter_values'; + +interface Props { + currentEnvironments: string[]; + onCreateJobSuccess: () => void; + onCancel: () => void; +} +export const AddEnvironments = ({ + currentEnvironments, + onCreateJobSuccess, + onCancel, +}: Props) => { + const { toasts } = useApmPluginContext().core.notifications; + const { data = [], status } = useFetcher( + (callApmApi) => + callApmApi({ + pathname: `/api/apm/settings/anomaly-detection/environments`, + }), + [], + { preservePreviousData: false } + ); + + const environmentOptions = data.map((env) => ({ + label: env === ENVIRONMENT_NOT_DEFINED ? NOT_DEFINED_OPTION_LABEL : env, + value: env, + disabled: currentEnvironments.includes(env), + })); + + const [selectedOptions, setSelected] = useState< + Array> + >([]); + + const isLoading = + status === FETCH_STATUS.PENDING || status === FETCH_STATUS.LOADING; + return ( + + +

+ {i18n.translate( + 'xpack.apm.settings.anomalyDetection.addEnvironments.titleText', + { + defaultMessage: 'Select environments', + } + )} +

+
+ + + {i18n.translate( + 'xpack.apm.settings.anomalyDetection.addEnvironments.descriptionText', + { + defaultMessage: + 'Select the service environments that you want to enable anomaly detection in. Anomalies will surface for all services and transaction types within the selected environments.', + } + )} + + + + { + setSelected(nextSelectedOptions); + }} + onCreateOption={(searchValue) => { + if (currentEnvironments.includes(searchValue)) { + return; + } + const newOption = { + label: searchValue, + value: searchValue, + }; + setSelected([...selectedOptions, newOption]); + }} + isClearable={true} + /> + + + + + {i18n.translate( + 'xpack.apm.settings.anomalyDetection.addEnvironments.cancelButtonText', + { + defaultMessage: 'Cancel', + } + )} + + + + { + const selectedEnvironments = selectedOptions.map( + ({ value }) => value as string + ); + const success = await createJobs({ + environments: selectedEnvironments, + toasts, + }); + if (success) { + onCreateJobSuccess(); + } + }} + > + {i18n.translate( + 'xpack.apm.settings.anomalyDetection.addEnvironments.createJobsButtonText', + { + defaultMessage: 'Create Jobs', + } + )} + + + + +
+ ); +}; + +const NOT_DEFINED_OPTION_LABEL = i18n.translate( + 'xpack.apm.filter.environment.notDefinedLabel', + { + defaultMessage: 'Not defined', + } +); diff --git a/x-pack/plugins/apm/public/components/app/Settings/anomaly_detection/create_jobs.ts b/x-pack/plugins/apm/public/components/app/Settings/anomaly_detection/create_jobs.ts new file mode 100644 index 00000000000000..614632a5a3b092 --- /dev/null +++ b/x-pack/plugins/apm/public/components/app/Settings/anomaly_detection/create_jobs.ts @@ -0,0 +1,64 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { i18n } from '@kbn/i18n'; +import { NotificationsStart } from 'kibana/public'; +import { callApmApi } from '../../../../services/rest/createCallApmApi'; + +export async function createJobs({ + environments, + toasts, +}: { + environments: string[]; + toasts: NotificationsStart['toasts']; +}) { + try { + await callApmApi({ + pathname: '/api/apm/settings/anomaly-detection/jobs', + method: 'POST', + params: { + body: { environments }, + }, + }); + + toasts.addSuccess({ + title: i18n.translate( + 'xpack.apm.anomalyDetection.createJobs.succeeded.title', + { defaultMessage: 'Anomaly detection jobs created' } + ), + text: i18n.translate( + 'xpack.apm.anomalyDetection.createJobs.succeeded.text', + { + defaultMessage: + 'Anomaly detection jobs successfully created for APM service environments [{environments}]. It will take some time for machine learning to start analyzing traffic for anomalies.', + values: { environments: environments.join(', ') }, + } + ), + }); + return true; + } catch (error) { + toasts.addDanger({ + title: i18n.translate( + 'xpack.apm.anomalyDetection.createJobs.failed.title', + { + defaultMessage: 'Anomaly detection jobs could not be created', + } + ), + text: i18n.translate( + 'xpack.apm.anomalyDetection.createJobs.failed.text', + { + defaultMessage: + 'Something went wrong when creating one ore more anomaly detection jobs for APM service environments [{environments}]. Error: "{errorMessage}"', + values: { + environments: environments.join(', '), + errorMessage: error.message, + }, + } + ), + }); + return false; + } +} diff --git a/x-pack/plugins/apm/public/components/app/Settings/anomaly_detection/index.tsx b/x-pack/plugins/apm/public/components/app/Settings/anomaly_detection/index.tsx new file mode 100644 index 00000000000000..0b720242237014 --- /dev/null +++ b/x-pack/plugins/apm/public/components/app/Settings/anomaly_detection/index.tsx @@ -0,0 +1,68 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import React, { useState } from 'react'; +import { EuiTitle, EuiSpacer, EuiText } from '@elastic/eui'; +import { i18n } from '@kbn/i18n'; +import { JobsList } from './jobs_list'; +import { AddEnvironments } from './add_environments'; +import { useFetcher, FETCH_STATUS } from '../../../../hooks/useFetcher'; + +export const AnomalyDetection = () => { + const [viewAddEnvironments, setViewAddEnvironments] = useState(false); + + const { refetch, data = [], status } = useFetcher( + (callApmApi) => + callApmApi({ pathname: `/api/apm/settings/anomaly-detection` }), + [], + { preservePreviousData: false } + ); + + const isLoading = + status === FETCH_STATUS.PENDING || status === FETCH_STATUS.LOADING; + const hasFetchFailure = status === FETCH_STATUS.FAILURE; + + return ( + <> + +

+ {i18n.translate('xpack.apm.settings.anomalyDetection.titleText', { + defaultMessage: 'Anomaly detection', + })} +

+
+ + + {i18n.translate('xpack.apm.settings.anomalyDetection.descriptionText', { + defaultMessage: + 'The Machine Learning anomaly detection integration enables application health status indicators in the Service map by identifying transaction duration anomalies.', + })} + + + {viewAddEnvironments ? ( + environment)} + onCreateJobSuccess={() => { + refetch(); + setViewAddEnvironments(false); + }} + onCancel={() => { + setViewAddEnvironments(false); + }} + /> + ) : ( + { + setViewAddEnvironments(true); + }} + /> + )} + + ); +}; diff --git a/x-pack/plugins/apm/public/components/app/Settings/anomaly_detection/jobs_list.tsx b/x-pack/plugins/apm/public/components/app/Settings/anomaly_detection/jobs_list.tsx new file mode 100644 index 00000000000000..30b4805011f03d --- /dev/null +++ b/x-pack/plugins/apm/public/components/app/Settings/anomaly_detection/jobs_list.tsx @@ -0,0 +1,162 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import React from 'react'; +import { + EuiPanel, + EuiTitle, + EuiText, + EuiSpacer, + EuiButton, + EuiFlexGroup, + EuiFlexItem, +} from '@elastic/eui'; +import { i18n } from '@kbn/i18n'; +import { FormattedMessage } from '@kbn/i18n/react'; +import { ITableColumn, ManagedTable } from '../../../shared/ManagedTable'; +import { LoadingStatePrompt } from '../../../shared/LoadingStatePrompt'; +import { AnomalyDetectionJobByEnv } from '../../../../../typings/anomaly_detection'; +import { MLJobLink } from '../../../shared/Links/MachineLearningLinks/MLJobLink'; +import { MLLink } from '../../../shared/Links/MachineLearningLinks/MLLink'; +import { ENVIRONMENT_NOT_DEFINED } from '../../../../../common/environment_filter_values'; + +const columns: Array> = [ + { + field: 'environment', + name: i18n.translate( + 'xpack.apm.settings.anomalyDetection.jobList.environmentColumnLabel', + { defaultMessage: 'Environment' } + ), + render: (environment: string) => { + if (environment === ENVIRONMENT_NOT_DEFINED) { + return i18n.translate('xpack.apm.filter.environment.notDefinedLabel', { + defaultMessage: 'Not defined', + }); + } + return environment; + }, + }, + { + field: 'job_id', + align: 'right', + name: i18n.translate( + 'xpack.apm.settings.anomalyDetection.jobList.actionColumnLabel', + { defaultMessage: 'Action' } + ), + render: (jobId: string) => ( + + {i18n.translate( + 'xpack.apm.settings.anomalyDetection.jobList.mlJobLinkText', + { + defaultMessage: 'View job in ML', + } + )} + + ), + }, +]; + +interface Props { + isLoading: boolean; + hasFetchFailure: boolean; + onAddEnvironments: () => void; + anomalyDetectionJobsByEnv: AnomalyDetectionJobByEnv[]; +} +export const JobsList = ({ + isLoading, + hasFetchFailure, + onAddEnvironments, + anomalyDetectionJobsByEnv, +}: Props) => { + return ( + + + + +

+ {i18n.translate( + 'xpack.apm.settings.anomalyDetection.jobList.environments', + { + defaultMessage: 'Environments', + } + )} +

+
+
+ + + {i18n.translate( + 'xpack.apm.settings.anomalyDetection.jobList.addEnvironments', + { + defaultMessage: 'Add environments', + } + )} + + +
+ + + + {i18n.translate( + 'xpack.apm.settings.anomalyDetection.jobList.mlDescriptionText.mlJobsLinkText', + { + defaultMessage: 'Machine Learning', + } + )} + + ), + }} + /> + + + + ) : hasFetchFailure ? ( + + ) : ( + + ) + } + columns={columns} + items={isLoading || hasFetchFailure ? [] : anomalyDetectionJobsByEnv} + /> + +
+ ); +}; + +function EmptyStatePrompt() { + return ( + <> + {i18n.translate( + 'xpack.apm.settings.anomalyDetection.jobList.emptyListText', + { + defaultMessage: 'No anomaly detection jobs.', + } + )} + + ); +} + +function FailureStatePrompt() { + return ( + <> + {i18n.translate( + 'xpack.apm.settings.anomalyDetection.jobList.failedFetchText', + { + defaultMessage: 'Unabled to fetch anomaly detection jobs.', + } + )} + + ); +} diff --git a/x-pack/plugins/apm/public/components/app/Settings/index.tsx b/x-pack/plugins/apm/public/components/app/Settings/index.tsx index 578a7db1958d42..6d8571bf577674 100644 --- a/x-pack/plugins/apm/public/components/app/Settings/index.tsx +++ b/x-pack/plugins/apm/public/components/app/Settings/index.tsx @@ -49,12 +49,15 @@ export const Settings: React.FC = (props) => { ), }, { - name: i18n.translate('xpack.apm.settings.indices', { - defaultMessage: 'Indices', - }), - id: '2', - href: getAPMHref('/settings/apm-indices', search), - isSelected: pathname === '/settings/apm-indices', + name: i18n.translate( + 'xpack.apm.settings.anomalyDetection', + { + defaultMessage: 'Anomaly detection', + } + ), + id: '4', + href: getAPMHref('/settings/anomaly-detection', search), + isSelected: pathname === '/settings/anomaly-detection', }, { name: i18n.translate('xpack.apm.settings.customizeApp', { @@ -64,6 +67,14 @@ export const Settings: React.FC = (props) => { href: getAPMHref('/settings/customize-ui', search), isSelected: pathname === '/settings/customize-ui', }, + { + name: i18n.translate('xpack.apm.settings.indices', { + defaultMessage: 'Indices', + }), + id: '2', + href: getAPMHref('/settings/apm-indices', search), + isSelected: pathname === '/settings/apm-indices', + }, ], }, ]} diff --git a/x-pack/plugins/apm/public/components/shared/ManagedTable/index.tsx b/x-pack/plugins/apm/public/components/shared/ManagedTable/index.tsx index 3dbb1b2faac020..50d46844f0adb7 100644 --- a/x-pack/plugins/apm/public/components/shared/ManagedTable/index.tsx +++ b/x-pack/plugins/apm/public/components/shared/ManagedTable/index.tsx @@ -33,6 +33,7 @@ interface Props { hidePerPageOptions?: boolean; noItemsMessage?: React.ReactNode; sortItems?: boolean; + pagination?: boolean; } function UnoptimizedManagedTable(props: Props) { @@ -46,6 +47,7 @@ function UnoptimizedManagedTable(props: Props) { hidePerPageOptions = true, noItemsMessage, sortItems = true, + pagination = true, } = props; const { @@ -93,23 +95,26 @@ function UnoptimizedManagedTable(props: Props) { [] ); - const pagination = useMemo(() => { + const paginationProps = useMemo(() => { + if (!pagination) { + return; + } return { hidePerPageOptions, totalItemCount: items.length, pageIndex: page, pageSize, }; - }, [hidePerPageOptions, items, page, pageSize]); + }, [hidePerPageOptions, items, page, pageSize, pagination]); return ( >} // EuiBasicTableColumn is stricter than ITableColumn - pagination={pagination} sorting={sort} onChange={onTableChange} + {...(paginationProps ? { pagination: paginationProps } : {})} /> ); } diff --git a/x-pack/plugins/apm/server/lib/anomaly_detection/create_anomaly_detection_jobs.ts b/x-pack/plugins/apm/server/lib/anomaly_detection/create_anomaly_detection_jobs.ts new file mode 100644 index 00000000000000..406097805775d5 --- /dev/null +++ b/x-pack/plugins/apm/server/lib/anomaly_detection/create_anomaly_detection_jobs.ts @@ -0,0 +1,123 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { Logger } from 'kibana/server'; +import uuid from 'uuid/v4'; +import { PromiseReturnType } from '../../../../observability/typings/common'; +import { Setup } from '../helpers/setup_request'; +import { + SERVICE_ENVIRONMENT, + TRANSACTION_DURATION, + PROCESSOR_EVENT, +} from '../../../common/elasticsearch_fieldnames'; +import { ENVIRONMENT_NOT_DEFINED } from '../../../common/environment_filter_values'; + +const ML_MODULE_ID_APM_TRANSACTION = 'apm_transaction'; +export const ML_GROUP_NAME_APM = 'apm'; + +export type CreateAnomalyDetectionJobsAPIResponse = PromiseReturnType< + typeof createAnomalyDetectionJobs +>; +export async function createAnomalyDetectionJobs( + setup: Setup, + environments: string[], + logger: Logger +) { + const { ml, indices } = setup; + if (!ml) { + logger.warn('Anomaly detection plugin is not available.'); + return []; + } + const mlCapabilities = await ml.mlSystem.mlCapabilities(); + if (!mlCapabilities.mlFeatureEnabledInSpace) { + logger.warn('Anomaly detection feature is not enabled for the space.'); + return []; + } + if (!mlCapabilities.isPlatinumOrTrialLicense) { + logger.warn( + 'Unable to create anomaly detection jobs due to insufficient license.' + ); + return []; + } + logger.info( + `Creating ML anomaly detection jobs for environments: [${environments}].` + ); + + const indexPatternName = indices['apm_oss.transactionIndices']; + const responses = await Promise.all( + environments.map((environment) => + createAnomalyDetectionJob({ ml, environment, indexPatternName }) + ) + ); + const jobResponses = responses.flatMap((response) => response.jobs); + const failedJobs = jobResponses.filter(({ success }) => !success); + + if (failedJobs.length > 0) { + const failedJobIds = failedJobs.map(({ id }) => id).join(', '); + logger.error( + `Failed to create anomaly detection ML jobs for: [${failedJobIds}]:` + ); + failedJobs.forEach(({ error }) => logger.error(JSON.stringify(error))); + throw new Error( + `Failed to create anomaly detection ML jobs for: [${failedJobIds}].` + ); + } + + return jobResponses; +} + +async function createAnomalyDetectionJob({ + ml, + environment, + indexPatternName = 'apm-*-transaction-*', +}: { + ml: Required['ml']; + environment: string; + indexPatternName?: string | undefined; +}) { + const convertedEnvironmentName = convertToMLIdentifier(environment); + const randomToken = uuid().substr(-4); + + return ml.modules.setup({ + moduleId: ML_MODULE_ID_APM_TRANSACTION, + prefix: `${ML_GROUP_NAME_APM}-${convertedEnvironmentName}-${randomToken}-`, + groups: [ML_GROUP_NAME_APM, convertedEnvironmentName], + indexPatternName, + query: { + bool: { + filter: [ + { term: { [PROCESSOR_EVENT]: 'transaction' } }, + { exists: { field: TRANSACTION_DURATION } }, + environment === ENVIRONMENT_NOT_DEFINED + ? ENVIRONMENT_NOT_DEFINED_FILTER + : { term: { [SERVICE_ENVIRONMENT]: environment } }, + ], + }, + }, + startDatafeed: true, + jobOverrides: [ + { + custom_settings: { + job_tags: { environment }, + }, + }, + ], + }); +} + +const ENVIRONMENT_NOT_DEFINED_FILTER = { + bool: { + must_not: { + exists: { + field: SERVICE_ENVIRONMENT, + }, + }, + }, +}; + +export function convertToMLIdentifier(value: string) { + return value.replace(/\s+/g, '_').toLowerCase(); +} diff --git a/x-pack/plugins/apm/server/lib/anomaly_detection/get_anomaly_detection_jobs.ts b/x-pack/plugins/apm/server/lib/anomaly_detection/get_anomaly_detection_jobs.ts new file mode 100644 index 00000000000000..252c87e9263db3 --- /dev/null +++ b/x-pack/plugins/apm/server/lib/anomaly_detection/get_anomaly_detection_jobs.ts @@ -0,0 +1,60 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { Logger } from 'kibana/server'; +import { PromiseReturnType } from '../../../../observability/typings/common'; +import { Setup } from '../helpers/setup_request'; +import { AnomalyDetectionJobByEnv } from '../../../typings/anomaly_detection'; +import { ML_GROUP_NAME_APM } from './create_anomaly_detection_jobs'; + +export type AnomalyDetectionJobsAPIResponse = PromiseReturnType< + typeof getAnomalyDetectionJobs +>; +export async function getAnomalyDetectionJobs( + setup: Setup, + logger: Logger +): Promise { + const { ml } = setup; + if (!ml) { + return []; + } + try { + const mlCapabilities = await ml.mlSystem.mlCapabilities(); + if ( + !( + mlCapabilities.mlFeatureEnabledInSpace && + mlCapabilities.isPlatinumOrTrialLicense + ) + ) { + logger.warn( + 'Anomaly detection integration is not availble for this user.' + ); + return []; + } + } catch (error) { + logger.warn('Unable to get ML capabilities.'); + logger.error(error); + return []; + } + try { + const { jobs } = await ml.anomalyDetectors.jobs(ML_GROUP_NAME_APM); + return jobs + .map((job) => { + const environment = job.custom_settings?.job_tags?.environment ?? ''; + return { + job_id: job.job_id, + environment, + }; + }) + .filter((job) => job.environment); + } catch (error) { + if (error.statusCode !== 404) { + logger.warn('Unable to get APM ML jobs.'); + logger.error(error); + } + return []; + } +} diff --git a/x-pack/plugins/apm/server/lib/environments/__snapshots__/get_all_environments.test.ts.snap b/x-pack/plugins/apm/server/lib/environments/__snapshots__/get_all_environments.test.ts.snap new file mode 100644 index 00000000000000..b943102b39de82 --- /dev/null +++ b/x-pack/plugins/apm/server/lib/environments/__snapshots__/get_all_environments.test.ts.snap @@ -0,0 +1,85 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`getAllEnvironments fetches all environments 1`] = ` +Object { + "body": Object { + "aggs": Object { + "environments": Object { + "terms": Object { + "field": "service.environment", + "missing": undefined, + "size": 100, + }, + }, + }, + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "terms": Object { + "processor.event": Array [ + "transaction", + "error", + "metric", + ], + }, + }, + Object { + "term": Object { + "service.name": "test", + }, + }, + ], + }, + }, + "size": 0, + }, + "index": Array [ + "myIndex", + "myIndex", + "myIndex", + ], +} +`; + +exports[`getAllEnvironments fetches all environments with includeMissing 1`] = ` +Object { + "body": Object { + "aggs": Object { + "environments": Object { + "terms": Object { + "field": "service.environment", + "missing": "ENVIRONMENT_NOT_DEFINED", + "size": 100, + }, + }, + }, + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "terms": Object { + "processor.event": Array [ + "transaction", + "error", + "metric", + ], + }, + }, + Object { + "term": Object { + "service.name": "test", + }, + }, + ], + }, + }, + "size": 0, + }, + "index": Array [ + "myIndex", + "myIndex", + "myIndex", + ], +} +`; diff --git a/x-pack/plugins/apm/server/lib/environments/get_all_environments.test.ts b/x-pack/plugins/apm/server/lib/environments/get_all_environments.test.ts new file mode 100644 index 00000000000000..25fc1776947446 --- /dev/null +++ b/x-pack/plugins/apm/server/lib/environments/get_all_environments.test.ts @@ -0,0 +1,42 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { getAllEnvironments } from './get_all_environments'; +import { + SearchParamsMock, + inspectSearchParams, +} from '../../../public/utils/testHelpers'; + +describe('getAllEnvironments', () => { + let mock: SearchParamsMock; + + afterEach(() => { + mock.teardown(); + }); + + it('fetches all environments', async () => { + mock = await inspectSearchParams((setup) => + getAllEnvironments({ + serviceName: 'test', + setup, + }) + ); + + expect(mock.params).toMatchSnapshot(); + }); + + it('fetches all environments with includeMissing', async () => { + mock = await inspectSearchParams((setup) => + getAllEnvironments({ + serviceName: 'test', + setup, + includeMissing: true, + }) + ); + + expect(mock.params).toMatchSnapshot(); + }); +}); diff --git a/x-pack/plugins/apm/server/lib/settings/agent_configuration/get_environments/get_all_environments.ts b/x-pack/plugins/apm/server/lib/environments/get_all_environments.ts similarity index 78% rename from x-pack/plugins/apm/server/lib/settings/agent_configuration/get_environments/get_all_environments.ts rename to x-pack/plugins/apm/server/lib/environments/get_all_environments.ts index 88a528f12b41c9..9b17033a1f2a5e 100644 --- a/x-pack/plugins/apm/server/lib/settings/agent_configuration/get_environments/get_all_environments.ts +++ b/x-pack/plugins/apm/server/lib/environments/get_all_environments.ts @@ -4,20 +4,22 @@ * you may not use this file except in compliance with the Elastic License. */ -import { Setup } from '../../../helpers/setup_request'; +import { Setup } from '../helpers/setup_request'; import { PROCESSOR_EVENT, SERVICE_NAME, SERVICE_ENVIRONMENT, -} from '../../../../../common/elasticsearch_fieldnames'; -import { ALL_OPTION_VALUE } from '../../../../../common/agent_configuration/all_option'; +} from '../../../common/elasticsearch_fieldnames'; +import { ENVIRONMENT_NOT_DEFINED } from '../../../common/environment_filter_values'; export async function getAllEnvironments({ serviceName, setup, + includeMissing = false, }: { - serviceName: string | undefined; + serviceName?: string; setup: Setup; + includeMissing?: boolean; }) { const { client, indices } = setup; @@ -49,6 +51,7 @@ export async function getAllEnvironments({ terms: { field: SERVICE_ENVIRONMENT, size: 100, + missing: includeMissing ? ENVIRONMENT_NOT_DEFINED : undefined, }, }, }, @@ -60,5 +63,5 @@ export async function getAllEnvironments({ resp.aggregations?.environments.buckets.map( (bucket) => bucket.key as string ) || []; - return [ALL_OPTION_VALUE, ...environments]; + return environments; } diff --git a/x-pack/plugins/apm/server/lib/helpers/setup_request.ts b/x-pack/plugins/apm/server/lib/helpers/setup_request.ts index 14c9378d991928..af073076a812a7 100644 --- a/x-pack/plugins/apm/server/lib/helpers/setup_request.ts +++ b/x-pack/plugins/apm/server/lib/helpers/setup_request.ts @@ -116,6 +116,11 @@ function getMlSetup(context: APMRequestHandlerContext, request: KibanaRequest) { return { mlSystem: ml.mlSystemProvider(mlClient, request), anomalyDetectors: ml.anomalyDetectorsProvider(mlClient, request), + modules: ml.modulesProvider( + mlClient, + request, + context.core.savedObjects.client + ), mlClient, }; } diff --git a/x-pack/plugins/apm/server/lib/settings/agent_configuration/__snapshots__/queries.test.ts.snap b/x-pack/plugins/apm/server/lib/settings/agent_configuration/__snapshots__/queries.test.ts.snap index db34b4d5d20b5b..24a1840bc0ab87 100644 --- a/x-pack/plugins/apm/server/lib/settings/agent_configuration/__snapshots__/queries.test.ts.snap +++ b/x-pack/plugins/apm/server/lib/settings/agent_configuration/__snapshots__/queries.test.ts.snap @@ -84,47 +84,6 @@ Object { } `; -exports[`agent configuration queries getAllEnvironments fetches all environments 1`] = ` -Object { - "body": Object { - "aggs": Object { - "environments": Object { - "terms": Object { - "field": "service.environment", - "size": 100, - }, - }, - }, - "query": Object { - "bool": Object { - "filter": Array [ - Object { - "terms": Object { - "processor.event": Array [ - "transaction", - "error", - "metric", - ], - }, - }, - Object { - "term": Object { - "service.name": "foo", - }, - }, - ], - }, - }, - "size": 0, - }, - "index": Array [ - "myIndex", - "myIndex", - "myIndex", - ], -} -`; - exports[`agent configuration queries getExistingEnvironmentsForService fetches unavailable environments 1`] = ` Object { "body": Object { diff --git a/x-pack/plugins/apm/server/lib/settings/agent_configuration/get_environments/index.ts b/x-pack/plugins/apm/server/lib/settings/agent_configuration/get_environments/index.ts index d10e06d1df632e..630249052be0b9 100644 --- a/x-pack/plugins/apm/server/lib/settings/agent_configuration/get_environments/index.ts +++ b/x-pack/plugins/apm/server/lib/settings/agent_configuration/get_environments/index.ts @@ -4,10 +4,11 @@ * you may not use this file except in compliance with the Elastic License. */ -import { getAllEnvironments } from './get_all_environments'; +import { getAllEnvironments } from '../../../environments/get_all_environments'; import { Setup } from '../../../helpers/setup_request'; import { PromiseReturnType } from '../../../../../../observability/typings/common'; import { getExistingEnvironmentsForService } from './get_existing_environments_for_service'; +import { ALL_OPTION_VALUE } from '../../../../../common/agent_configuration/all_option'; export type AgentConfigurationEnvironmentsAPIResponse = PromiseReturnType< typeof getEnvironments @@ -25,7 +26,7 @@ export async function getEnvironments({ getExistingEnvironmentsForService({ serviceName, setup }), ]); - return allEnvironments.map((environment) => { + return [ALL_OPTION_VALUE, ...allEnvironments].map((environment) => { return { name: environment, alreadyConfigured: existingEnvironments.includes(environment), diff --git a/x-pack/plugins/apm/server/lib/settings/agent_configuration/queries.test.ts b/x-pack/plugins/apm/server/lib/settings/agent_configuration/queries.test.ts index 515376f8bb18be..5fe9d19ffc8605 100644 --- a/x-pack/plugins/apm/server/lib/settings/agent_configuration/queries.test.ts +++ b/x-pack/plugins/apm/server/lib/settings/agent_configuration/queries.test.ts @@ -4,7 +4,6 @@ * you may not use this file except in compliance with the Elastic License. */ -import { getAllEnvironments } from './get_environments/get_all_environments'; import { getExistingEnvironmentsForService } from './get_environments/get_existing_environments_for_service'; import { getServiceNames } from './get_service_names'; import { listConfigurations } from './list_configurations'; @@ -22,19 +21,6 @@ describe('agent configuration queries', () => { mock.teardown(); }); - describe('getAllEnvironments', () => { - it('fetches all environments', async () => { - mock = await inspectSearchParams((setup) => - getAllEnvironments({ - serviceName: 'foo', - setup, - }) - ); - - expect(mock.params).toMatchSnapshot(); - }); - }); - describe('getExistingEnvironmentsForService', () => { it('fetches unavailable environments', async () => { mock = await inspectSearchParams((setup) => diff --git a/x-pack/plugins/apm/server/routes/create_apm_api.ts b/x-pack/plugins/apm/server/routes/create_apm_api.ts index ed1c045616a27c..c314debcd80493 100644 --- a/x-pack/plugins/apm/server/routes/create_apm_api.ts +++ b/x-pack/plugins/apm/server/routes/create_apm_api.ts @@ -81,6 +81,11 @@ import { observabilityDashboardHasDataRoute, observabilityDashboardDataRoute, } from './observability_dashboard'; +import { + anomalyDetectionJobsRoute, + createAnomalyDetectionJobsRoute, + anomalyDetectionEnvironmentsRoute, +} from './settings/anomaly_detection'; const createApmApi = () => { const api = createApi() @@ -170,7 +175,12 @@ const createApmApi = () => { // Observability dashboard .add(observabilityDashboardHasDataRoute) - .add(observabilityDashboardDataRoute); + .add(observabilityDashboardDataRoute) + + // Anomaly detection + .add(anomalyDetectionJobsRoute) + .add(createAnomalyDetectionJobsRoute) + .add(anomalyDetectionEnvironmentsRoute); return api; }; diff --git a/x-pack/plugins/apm/server/routes/settings/anomaly_detection.ts b/x-pack/plugins/apm/server/routes/settings/anomaly_detection.ts new file mode 100644 index 00000000000000..67eca0da946d0a --- /dev/null +++ b/x-pack/plugins/apm/server/routes/settings/anomaly_detection.ts @@ -0,0 +1,55 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import * as t from 'io-ts'; +import { createRoute } from '../create_route'; +import { getAnomalyDetectionJobs } from '../../lib/anomaly_detection/get_anomaly_detection_jobs'; +import { createAnomalyDetectionJobs } from '../../lib/anomaly_detection/create_anomaly_detection_jobs'; +import { setupRequest } from '../../lib/helpers/setup_request'; +import { getAllEnvironments } from '../../lib/environments/get_all_environments'; + +// get ML anomaly detection jobs for each environment +export const anomalyDetectionJobsRoute = createRoute(() => ({ + method: 'GET', + path: '/api/apm/settings/anomaly-detection', + handler: async ({ context, request }) => { + const setup = await setupRequest(context, request); + return await getAnomalyDetectionJobs(setup, context.logger); + }, +})); + +// create new ML anomaly detection jobs for each given environment +export const createAnomalyDetectionJobsRoute = createRoute(() => ({ + method: 'POST', + path: '/api/apm/settings/anomaly-detection/jobs', + options: { + tags: ['access:apm', 'access:apm_write'], + }, + params: { + body: t.type({ + environments: t.array(t.string), + }), + }, + handler: async ({ context, request }) => { + const { environments } = context.params.body; + const setup = await setupRequest(context, request); + return await createAnomalyDetectionJobs( + setup, + environments, + context.logger + ); + }, +})); + +// get all available environments to create anomaly detection jobs for +export const anomalyDetectionEnvironmentsRoute = createRoute(() => ({ + method: 'GET', + path: '/api/apm/settings/anomaly-detection/environments', + handler: async ({ context, request }) => { + const setup = await setupRequest(context, request); + return await getAllEnvironments({ setup, includeMissing: true }); + }, +})); diff --git a/x-pack/plugins/apm/typings/anomaly_detection.ts b/x-pack/plugins/apm/typings/anomaly_detection.ts new file mode 100644 index 00000000000000..30dc92c36dea42 --- /dev/null +++ b/x-pack/plugins/apm/typings/anomaly_detection.ts @@ -0,0 +1,10 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +export interface AnomalyDetectionJobByEnv { + environment: string; + job_id: string; +} diff --git a/x-pack/plugins/canvas/server/routes/es_fields/es_fields.test.ts b/x-pack/plugins/canvas/server/routes/es_fields/es_fields.test.ts index c1918feb7f4ec3..c2cff83f85f0df 100644 --- a/x-pack/plugins/canvas/server/routes/es_fields/es_fields.test.ts +++ b/x-pack/plugins/canvas/server/routes/es_fields/es_fields.test.ts @@ -15,7 +15,9 @@ import { const mockRouteContext = ({ core: { - elasticsearch: { legacy: { client: elasticsearchServiceMock.createScopedClusterClient() } }, + elasticsearch: { + legacy: { client: elasticsearchServiceMock.createLegacyScopedClusterClient() }, + }, }, } as unknown) as RequestHandlerContext; diff --git a/x-pack/plugins/event_log/server/es/cluster_client_adapter.test.ts b/x-pack/plugins/event_log/server/es/cluster_client_adapter.test.ts index feec1ee9ba0088..ee6f0a301e9f80 100644 --- a/x-pack/plugins/event_log/server/es/cluster_client_adapter.test.ts +++ b/x-pack/plugins/event_log/server/es/cluster_client_adapter.test.ts @@ -18,7 +18,7 @@ let clusterClientAdapter: IClusterClientAdapter; beforeEach(() => { logger = loggingSystemMock.createLogger(); - clusterClient = elasticsearchServiceMock.createClusterClient(); + clusterClient = elasticsearchServiceMock.createLegacyClusterClient(); clusterClientAdapter = new ClusterClientAdapter({ logger, clusterClientPromise: Promise.resolve(clusterClient), diff --git a/x-pack/plugins/event_log/server/es/context.test.ts b/x-pack/plugins/event_log/server/es/context.test.ts index 3fd7e12ed8a0cd..a78e47446fef87 100644 --- a/x-pack/plugins/event_log/server/es/context.test.ts +++ b/x-pack/plugins/event_log/server/es/context.test.ts @@ -17,7 +17,7 @@ let clusterClient: EsClusterClient; beforeEach(() => { logger = loggingSystemMock.createLogger(); - clusterClient = elasticsearchServiceMock.createClusterClient(); + clusterClient = elasticsearchServiceMock.createLegacyClusterClient(); }); describe('createEsContext', () => { diff --git a/x-pack/plugins/global_search/server/services/context.mock.ts b/x-pack/plugins/global_search/server/services/context.mock.ts index 50c6da109f8dde..7c72686529c157 100644 --- a/x-pack/plugins/global_search/server/services/context.mock.ts +++ b/x-pack/plugins/global_search/server/services/context.mock.ts @@ -20,7 +20,7 @@ const createContextMock = () => { }, elasticsearch: { legacy: { - client: elasticsearchServiceMock.createScopedClusterClient(), + client: elasticsearchServiceMock.createLegacyScopedClusterClient(), }, }, uiSettings: { diff --git a/x-pack/plugins/licensing/server/plugin.test.ts b/x-pack/plugins/licensing/server/plugin.test.ts index bf549c18da303f..6e8327e151543e 100644 --- a/x-pack/plugins/licensing/server/plugin.test.ts +++ b/x-pack/plugins/licensing/server/plugin.test.ts @@ -31,11 +31,14 @@ const flushPromises = (ms = 50) => new Promise((res) => setTimeout(res, ms)); function createCoreSetupWith(esClient: ILegacyClusterClient) { const coreSetup = coreMock.createSetup(); - + const coreStart = coreMock.createStart(); coreSetup.getStartServices.mockResolvedValue([ { - ...coreMock.createStart(), - elasticsearch: { legacy: { client: esClient, createClient: jest.fn() } }, + ...coreStart, + elasticsearch: { + ...coreStart.elasticsearch, + legacy: { client: esClient, createClient: jest.fn() }, + }, }, {}, {}, @@ -61,7 +64,7 @@ describe('licensing plugin', () => { }); it('returns license', async () => { - const esClient = elasticsearchServiceMock.createClusterClient(); + const esClient = elasticsearchServiceMock.createLegacyClusterClient(); esClient.callAsInternalUser.mockResolvedValue({ license: buildRawLicense(), features: {}, @@ -77,7 +80,7 @@ describe('licensing plugin', () => { it('observable receives updated licenses', async () => { const types: LicenseType[] = ['basic', 'gold', 'platinum']; - const esClient = elasticsearchServiceMock.createClusterClient(); + const esClient = elasticsearchServiceMock.createLegacyClusterClient(); esClient.callAsInternalUser.mockImplementation(() => Promise.resolve({ license: buildRawLicense({ type: types.shift() }), @@ -96,7 +99,7 @@ describe('licensing plugin', () => { }); it('returns a license with error when request fails', async () => { - const esClient = elasticsearchServiceMock.createClusterClient(); + const esClient = elasticsearchServiceMock.createLegacyClusterClient(); esClient.callAsInternalUser.mockRejectedValue(new Error('test')); const coreSetup = createCoreSetupWith(esClient); @@ -109,7 +112,7 @@ describe('licensing plugin', () => { }); it('generate error message when x-pack plugin was not installed', async () => { - const esClient = elasticsearchServiceMock.createClusterClient(); + const esClient = elasticsearchServiceMock.createLegacyClusterClient(); const error: ElasticsearchError = new Error('reason'); error.status = 400; esClient.callAsInternalUser.mockRejectedValue(error); @@ -127,7 +130,7 @@ describe('licensing plugin', () => { const error1 = new Error('reason-1'); const error2 = new Error('reason-2'); - const esClient = elasticsearchServiceMock.createClusterClient(); + const esClient = elasticsearchServiceMock.createLegacyClusterClient(); esClient.callAsInternalUser .mockRejectedValueOnce(error1) @@ -145,7 +148,7 @@ describe('licensing plugin', () => { }); it('fetch license immediately without subscriptions', async () => { - const esClient = elasticsearchServiceMock.createClusterClient(); + const esClient = elasticsearchServiceMock.createLegacyClusterClient(); esClient.callAsInternalUser.mockResolvedValue({ license: buildRawLicense(), features: {}, @@ -161,7 +164,7 @@ describe('licensing plugin', () => { }); it('logs license details without subscriptions', async () => { - const esClient = elasticsearchServiceMock.createClusterClient(); + const esClient = elasticsearchServiceMock.createLegacyClusterClient(); esClient.callAsInternalUser.mockResolvedValue({ license: buildRawLicense(), features: {}, @@ -187,7 +190,7 @@ describe('licensing plugin', () => { it('generates signature based on fetched license content', async () => { const types: LicenseType[] = ['basic', 'gold', 'basic']; - const esClient = elasticsearchServiceMock.createClusterClient(); + const esClient = elasticsearchServiceMock.createLegacyClusterClient(); esClient.callAsInternalUser.mockImplementation(() => Promise.resolve({ license: buildRawLicense({ type: types.shift() }), @@ -218,7 +221,7 @@ describe('licensing plugin', () => { api_polling_frequency: moment.duration(50000), }) ); - const esClient = elasticsearchServiceMock.createClusterClient(); + const esClient = elasticsearchServiceMock.createLegacyClusterClient(); esClient.callAsInternalUser.mockResolvedValue({ license: buildRawLicense(), features: {}, @@ -253,7 +256,7 @@ describe('licensing plugin', () => { }) ); - const esClient = elasticsearchServiceMock.createClusterClient(); + const esClient = elasticsearchServiceMock.createLegacyClusterClient(); esClient.callAsInternalUser.mockResolvedValue({ license: buildRawLicense(), features: {}, @@ -262,7 +265,7 @@ describe('licensing plugin', () => { await plugin.setup(coreSetup); const { createLicensePoller, license$ } = await plugin.start(); - const customClient = elasticsearchServiceMock.createClusterClient(); + const customClient = elasticsearchServiceMock.createLegacyClusterClient(); customClient.callAsInternalUser.mockResolvedValue({ license: buildRawLicense({ type: 'gold' }), features: {}, @@ -297,7 +300,7 @@ describe('licensing plugin', () => { await plugin.setup(coreSetup); const { createLicensePoller } = await plugin.start(); - const customClient = elasticsearchServiceMock.createClusterClient(); + const customClient = elasticsearchServiceMock.createLegacyClusterClient(); customClient.callAsInternalUser.mockResolvedValue({ license: buildRawLicense({ type: 'gold' }), features: {}, diff --git a/x-pack/plugins/ml/common/types/anomaly_detection_jobs/job.ts b/x-pack/plugins/ml/common/types/anomaly_detection_jobs/job.ts index 3dbdb8bf3c0024..e2c4f1bae1a108 100644 --- a/x-pack/plugins/ml/common/types/anomaly_detection_jobs/job.ts +++ b/x-pack/plugins/ml/common/types/anomaly_detection_jobs/job.ts @@ -13,6 +13,9 @@ export type BucketSpan = string; export interface CustomSettings { custom_urls?: UrlConfig[]; created_by?: CREATED_BY_LABEL; + job_tags?: { + [tag: string]: string; + }; } export interface Job { diff --git a/x-pack/plugins/ml/common/types/anomaly_detection_jobs/job_stats.ts b/x-pack/plugins/ml/common/types/anomaly_detection_jobs/job_stats.ts index 2d64e70bb1f782..861eb46730f66a 100644 --- a/x-pack/plugins/ml/common/types/anomaly_detection_jobs/job_stats.ts +++ b/x-pack/plugins/ml/common/types/anomaly_detection_jobs/job_stats.ts @@ -45,6 +45,7 @@ export interface ModelSizeStats { model_bytes: number; model_bytes_exceeded: number; model_bytes_memory_limit: number; + peak_model_bytes?: number; total_by_field_count: number; total_over_field_count: number; total_partition_field_count: number; diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_details/format_values.js b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_details/format_values.js index 883ddfca70cd76..3fe4f0e5477a20 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_details/format_values.js +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/job_details/format_values.js @@ -38,6 +38,7 @@ export function formatValues([key, value]) { case 'model_bytes': case 'model_bytes_exceeded': case 'model_bytes_memory_limit': + case 'peak_model_bytes': value = formatData(value); break; diff --git a/x-pack/plugins/oss_telemetry/server/test_utils/index.ts b/x-pack/plugins/oss_telemetry/server/test_utils/index.ts index 7ac98196808394..3eee1978d4f1c0 100644 --- a/x-pack/plugins/oss_telemetry/server/test_utils/index.ts +++ b/x-pack/plugins/oss_telemetry/server/test_utils/index.ts @@ -49,7 +49,7 @@ const defaultMockTaskDocs = [getMockTaskInstance()]; export const getMockEs = async ( mockCallWithInternal: LegacyAPICaller = getMockCallWithInternal() ) => { - const client = elasticsearchServiceMock.createClusterClient(); + const client = elasticsearchServiceMock.createLegacyClusterClient(); (client.callAsInternalUser as any) = mockCallWithInternal; return client; }; diff --git a/x-pack/plugins/remote_clusters/server/routes/api/add_route.test.ts b/x-pack/plugins/remote_clusters/server/routes/api/add_route.test.ts index d28e95834ca0b3..406d5661c09154 100644 --- a/x-pack/plugins/remote_clusters/server/routes/api/add_route.test.ts +++ b/x-pack/plugins/remote_clusters/server/routes/api/add_route.test.ts @@ -28,7 +28,7 @@ describe('ADD remote clusters', () => { { licenseCheckResult = { valid: true }, apiResponses = [], asserts, payload }: TestOptions ) => { test(description, async () => { - const elasticsearchMock = elasticsearchServiceMock.createClusterClient(); + const elasticsearchMock = elasticsearchServiceMock.createLegacyClusterClient(); const mockRouteDependencies = { router: httpServiceMock.createRouter(), @@ -40,10 +40,10 @@ describe('ADD remote clusters', () => { }, }; - const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); elasticsearchServiceMock - .createClusterClient() + .createLegacyClusterClient() .asScoped.mockReturnValue(mockScopedClusterClient); for (const apiResponse of apiResponses) { diff --git a/x-pack/plugins/remote_clusters/server/routes/api/delete_route.test.ts b/x-pack/plugins/remote_clusters/server/routes/api/delete_route.test.ts index d1e3cf89e94d9b..bd2ad10c4013da 100644 --- a/x-pack/plugins/remote_clusters/server/routes/api/delete_route.test.ts +++ b/x-pack/plugins/remote_clusters/server/routes/api/delete_route.test.ts @@ -30,7 +30,7 @@ describe('DELETE remote clusters', () => { { licenseCheckResult = { valid: true }, apiResponses = [], asserts, params }: TestOptions ) => { test(description, async () => { - const elasticsearchMock = elasticsearchServiceMock.createClusterClient(); + const elasticsearchMock = elasticsearchServiceMock.createLegacyClusterClient(); const mockRouteDependencies = { router: httpServiceMock.createRouter(), @@ -42,10 +42,10 @@ describe('DELETE remote clusters', () => { }, }; - const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); elasticsearchServiceMock - .createClusterClient() + .createLegacyClusterClient() .asScoped.mockReturnValue(mockScopedClusterClient); for (const apiResponse of apiResponses) { diff --git a/x-pack/plugins/remote_clusters/server/routes/api/get_route.test.ts b/x-pack/plugins/remote_clusters/server/routes/api/get_route.test.ts index 24e469c9ec9b2b..910f9e69ea80c8 100644 --- a/x-pack/plugins/remote_clusters/server/routes/api/get_route.test.ts +++ b/x-pack/plugins/remote_clusters/server/routes/api/get_route.test.ts @@ -29,7 +29,7 @@ describe('GET remote clusters', () => { { licenseCheckResult = { valid: true }, apiResponses = [], asserts }: TestOptions ) => { test(description, async () => { - const elasticsearchMock = elasticsearchServiceMock.createClusterClient(); + const elasticsearchMock = elasticsearchServiceMock.createLegacyClusterClient(); const mockRouteDependencies = { router: httpServiceMock.createRouter(), @@ -41,10 +41,10 @@ describe('GET remote clusters', () => { }, }; - const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); elasticsearchServiceMock - .createClusterClient() + .createLegacyClusterClient() .asScoped.mockReturnValue(mockScopedClusterClient); for (const apiResponse of apiResponses) { diff --git a/x-pack/plugins/remote_clusters/server/routes/api/update_route.test.ts b/x-pack/plugins/remote_clusters/server/routes/api/update_route.test.ts index 9669c98e1349ef..c20ba0a1ec7a9a 100644 --- a/x-pack/plugins/remote_clusters/server/routes/api/update_route.test.ts +++ b/x-pack/plugins/remote_clusters/server/routes/api/update_route.test.ts @@ -37,7 +37,7 @@ describe('UPDATE remote clusters', () => { }: TestOptions ) => { test(description, async () => { - const elasticsearchMock = elasticsearchServiceMock.createClusterClient(); + const elasticsearchMock = elasticsearchServiceMock.createLegacyClusterClient(); const mockRouteDependencies = { router: httpServiceMock.createRouter(), @@ -49,10 +49,10 @@ describe('UPDATE remote clusters', () => { }, }; - const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); elasticsearchServiceMock - .createClusterClient() + .createLegacyClusterClient() .asScoped.mockReturnValue(mockScopedClusterClient); for (const apiResponse of apiResponses) { diff --git a/x-pack/plugins/security/server/authentication/api_keys.test.ts b/x-pack/plugins/security/server/authentication/api_keys.test.ts index 0cdd452d459d1f..631a6f9ab213c3 100644 --- a/x-pack/plugins/security/server/authentication/api_keys.test.ts +++ b/x-pack/plugins/security/server/authentication/api_keys.test.ts @@ -24,8 +24,8 @@ describe('API Keys', () => { let mockLicense: jest.Mocked; beforeEach(() => { - mockClusterClient = elasticsearchServiceMock.createClusterClient(); - mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + mockClusterClient = elasticsearchServiceMock.createLegacyClusterClient(); + mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockClusterClient.asScoped.mockReturnValue( (mockScopedClusterClient as unknown) as jest.Mocked ); diff --git a/x-pack/plugins/security/server/authentication/authenticator.test.ts b/x-pack/plugins/security/server/authentication/authenticator.test.ts index 3b77ea32481731..300447096af997 100644 --- a/x-pack/plugins/security/server/authentication/authenticator.test.ts +++ b/x-pack/plugins/security/server/authentication/authenticator.test.ts @@ -45,7 +45,7 @@ function getMockOptions({ return { auditLogger: securityAuditLoggerMock.create(), getCurrentUser: jest.fn(), - clusterClient: elasticsearchServiceMock.createClusterClient(), + clusterClient: elasticsearchServiceMock.createLegacyClusterClient(), basePath: httpServiceMock.createSetupContract().basePath, license: licenseMock.create(), loggers: loggingSystemMock.create(), diff --git a/x-pack/plugins/security/server/authentication/index.test.ts b/x-pack/plugins/security/server/authentication/index.test.ts index 4157f0598b3d06..56d44e6628a872 100644 --- a/x-pack/plugins/security/server/authentication/index.test.ts +++ b/x-pack/plugins/security/server/authentication/index.test.ts @@ -69,7 +69,7 @@ describe('setupAuthentication()', () => { loggingSystemMock.create().get(), { isTLSEnabled: false } ), - clusterClient: elasticsearchServiceMock.createClusterClient(), + clusterClient: elasticsearchServiceMock.createLegacyClusterClient(), license: licenseMock.create(), loggers: loggingSystemMock.create(), getFeatureUsageService: jest @@ -77,7 +77,7 @@ describe('setupAuthentication()', () => { .mockReturnValue(securityFeatureUsageServiceMock.createStartContract()), }; - mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockSetupAuthenticationParams.clusterClient.asScoped.mockReturnValue( (mockScopedClusterClient as unknown) as jest.Mocked ); diff --git a/x-pack/plugins/security/server/authentication/providers/base.mock.ts b/x-pack/plugins/security/server/authentication/providers/base.mock.ts index 7c71348bb8ca0f..1b574e6e44c100 100644 --- a/x-pack/plugins/security/server/authentication/providers/base.mock.ts +++ b/x-pack/plugins/security/server/authentication/providers/base.mock.ts @@ -16,7 +16,7 @@ export type MockAuthenticationProviderOptions = ReturnType< export function mockAuthenticationProviderOptions(options?: { name: string }) { return { - client: elasticsearchServiceMock.createClusterClient(), + client: elasticsearchServiceMock.createLegacyClusterClient(), logger: loggingSystemMock.create().get(), basePath: httpServiceMock.createBasePath(), tokens: { refresh: jest.fn(), invalidate: jest.fn() }, diff --git a/x-pack/plugins/security/server/authentication/providers/basic.test.ts b/x-pack/plugins/security/server/authentication/providers/basic.test.ts index 95de8ca9d00e71..22d10d1cec347a 100644 --- a/x-pack/plugins/security/server/authentication/providers/basic.test.ts +++ b/x-pack/plugins/security/server/authentication/providers/basic.test.ts @@ -43,7 +43,7 @@ describe('BasicAuthenticationProvider', () => { const credentials = { username: 'user', password: 'password' }; const authorization = generateAuthorizationHeader(credentials.username, credentials.password); - const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockResolvedValue(user); mockOptions.client.asScoped.mockReturnValue(mockScopedClusterClient); @@ -65,7 +65,7 @@ describe('BasicAuthenticationProvider', () => { const authorization = generateAuthorizationHeader(credentials.username, credentials.password); const authenticationError = new Error('Some error'); - const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockRejectedValue(authenticationError); mockOptions.client.asScoped.mockReturnValue(mockScopedClusterClient); @@ -147,7 +147,7 @@ describe('BasicAuthenticationProvider', () => { const user = mockAuthenticatedUser(); const authorization = generateAuthorizationHeader('user', 'password'); - const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockResolvedValue(user); mockOptions.client.asScoped.mockReturnValue(mockScopedClusterClient); @@ -163,7 +163,7 @@ describe('BasicAuthenticationProvider', () => { const authorization = generateAuthorizationHeader('user', 'password'); const authenticationError = new Error('Forbidden'); - const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockRejectedValue(authenticationError); mockOptions.client.asScoped.mockReturnValue(mockScopedClusterClient); diff --git a/x-pack/plugins/security/server/authentication/providers/http.test.ts b/x-pack/plugins/security/server/authentication/providers/http.test.ts index e6949269e3fc75..c221ecd3f1e20f 100644 --- a/x-pack/plugins/security/server/authentication/providers/http.test.ts +++ b/x-pack/plugins/security/server/authentication/providers/http.test.ts @@ -126,7 +126,7 @@ describe('HTTPAuthenticationProvider', () => { ]) { const request = httpServerMock.createKibanaRequest({ headers: { authorization: header } }); - const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockResolvedValue(user); mockOptions.client.asScoped.mockReturnValue(mockScopedClusterClient); mockOptions.client.asScoped.mockClear(); @@ -156,7 +156,7 @@ describe('HTTPAuthenticationProvider', () => { ]) { const request = httpServerMock.createKibanaRequest({ headers: { authorization: header } }); - const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockRejectedValue(failureReason); mockOptions.client.asScoped.mockReturnValue(mockScopedClusterClient); mockOptions.client.asScoped.mockClear(); diff --git a/x-pack/plugins/security/server/authentication/providers/kerberos.test.ts b/x-pack/plugins/security/server/authentication/providers/kerberos.test.ts index c00374efd59b47..f04506eb01593a 100644 --- a/x-pack/plugins/security/server/authentication/providers/kerberos.test.ts +++ b/x-pack/plugins/security/server/authentication/providers/kerberos.test.ts @@ -47,7 +47,7 @@ describe('KerberosAuthenticationProvider', () => { it('does not handle requests that can be authenticated without `Negotiate` header.', async () => { const request = httpServerMock.createKibanaRequest({ headers: {} }); - const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockResolvedValue({}); mockOptions.client.asScoped.mockReturnValue(mockScopedClusterClient); @@ -61,7 +61,7 @@ describe('KerberosAuthenticationProvider', () => { it('does not handle requests if backend does not support Kerberos.', async () => { const request = httpServerMock.createKibanaRequest({ headers: {} }); - const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockRejectedValue( LegacyElasticsearchErrorHelpers.decorateNotAuthorizedError(new Error()) ); @@ -82,7 +82,7 @@ describe('KerberosAuthenticationProvider', () => { body: { error: { header: { 'WWW-Authenticate': 'Negotiate' } } }, }) ); - const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockRejectedValue(failureReason); mockOptions.client.asScoped.mockReturnValue(mockScopedClusterClient); @@ -101,7 +101,7 @@ describe('KerberosAuthenticationProvider', () => { const request = httpServerMock.createKibanaRequest({ headers: {} }); const failureReason = new errors.ServiceUnavailable(); - const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockRejectedValue(failureReason); mockOptions.client.asScoped.mockReturnValue(mockScopedClusterClient); @@ -118,7 +118,7 @@ describe('KerberosAuthenticationProvider', () => { headers: { authorization: 'negotiate spnego' }, }); - const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockResolvedValue(user); mockOptions.client.asScoped.mockReturnValue(mockScopedClusterClient); mockOptions.client.callAsInternalUser.mockResolvedValue({ @@ -153,7 +153,7 @@ describe('KerberosAuthenticationProvider', () => { headers: { authorization: 'negotiate spnego' }, }); - const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockResolvedValue(user); mockOptions.client.asScoped.mockReturnValue(mockScopedClusterClient); mockOptions.client.callAsInternalUser.mockResolvedValue({ @@ -257,7 +257,7 @@ describe('KerberosAuthenticationProvider', () => { }); const failureReason = LegacyElasticsearchErrorHelpers.decorateNotAuthorizedError(new Error()); - const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockRejectedValue(failureReason); mockOptions.client.asScoped.mockReturnValue(mockScopedClusterClient); mockOptions.client.callAsInternalUser.mockResolvedValue({ @@ -323,7 +323,7 @@ describe('KerberosAuthenticationProvider', () => { const tokenPair = { accessToken: 'token', refreshToken: 'refresh-token' }; const failureReason = LegacyElasticsearchErrorHelpers.decorateNotAuthorizedError(new Error()); - const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockRejectedValue(failureReason); mockOptions.client.asScoped.mockReturnValue(mockScopedClusterClient); mockOptions.tokens.refresh.mockResolvedValue(null); @@ -355,7 +355,7 @@ describe('KerberosAuthenticationProvider', () => { }; const authorization = `Bearer ${tokenPair.accessToken}`; - const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockResolvedValue(user); mockOptions.client.asScoped.mockReturnValue(mockScopedClusterClient); @@ -378,7 +378,7 @@ describe('KerberosAuthenticationProvider', () => { mockOptions.client.asScoped.mockImplementation((scopeableRequest) => { if (scopeableRequest?.headers.authorization === `Bearer ${tokenPair.accessToken}`) { - const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockRejectedValue( LegacyElasticsearchErrorHelpers.decorateNotAuthorizedError(new Error()) ); @@ -386,7 +386,7 @@ describe('KerberosAuthenticationProvider', () => { } if (scopeableRequest?.headers.authorization === 'Bearer newfoo') { - const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockResolvedValue(user); return mockScopedClusterClient; } @@ -423,7 +423,7 @@ describe('KerberosAuthenticationProvider', () => { }; const failureReason = new errors.InternalServerError('Token is not valid!'); - const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockRejectedValue(failureReason); mockOptions.client.asScoped.mockReturnValue(mockScopedClusterClient); @@ -450,7 +450,7 @@ describe('KerberosAuthenticationProvider', () => { body: { error: { header: { 'WWW-Authenticate': 'Negotiate' } } }, }) ); - const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockRejectedValue(failureReason); mockOptions.client.asScoped.mockReturnValue(mockScopedClusterClient); @@ -475,7 +475,7 @@ describe('KerberosAuthenticationProvider', () => { body: { error: { header: { 'WWW-Authenticate': 'Negotiate' } } }, }) ); - const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockRejectedValue(failureReason); mockOptions.client.asScoped.mockReturnValue(mockScopedClusterClient); diff --git a/x-pack/plugins/security/server/authentication/providers/oidc.test.ts b/x-pack/plugins/security/server/authentication/providers/oidc.test.ts index d787e76628d6db..aea5994e3ba3ef 100644 --- a/x-pack/plugins/security/server/authentication/providers/oidc.test.ts +++ b/x-pack/plugins/security/server/authentication/providers/oidc.test.ts @@ -389,7 +389,7 @@ describe('OIDCAuthenticationProvider', () => { }; const authorization = `Bearer ${tokenPair.accessToken}`; - const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockResolvedValue(user); mockOptions.client.asScoped.mockReturnValue(mockScopedClusterClient); @@ -446,7 +446,7 @@ describe('OIDCAuthenticationProvider', () => { const authorization = `Bearer ${tokenPair.accessToken}`; const failureReason = new Error('Token is not valid!'); - const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockRejectedValue(failureReason); mockOptions.client.asScoped.mockReturnValue(mockScopedClusterClient); @@ -466,7 +466,7 @@ describe('OIDCAuthenticationProvider', () => { mockOptions.client.asScoped.mockImplementation((scopeableRequest) => { if (scopeableRequest?.headers.authorization === `Bearer ${tokenPair.accessToken}`) { - const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockRejectedValue( LegacyElasticsearchErrorHelpers.decorateNotAuthorizedError(new Error()) ); @@ -474,7 +474,7 @@ describe('OIDCAuthenticationProvider', () => { } if (scopeableRequest?.headers.authorization === 'Bearer new-access-token') { - const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockResolvedValue(user); return mockScopedClusterClient; } @@ -514,7 +514,7 @@ describe('OIDCAuthenticationProvider', () => { const tokenPair = { accessToken: 'expired-token', refreshToken: 'invalid-refresh-token' }; const authorization = `Bearer ${tokenPair.accessToken}`; - const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockRejectedValue( LegacyElasticsearchErrorHelpers.decorateNotAuthorizedError(new Error()) ); @@ -554,7 +554,7 @@ describe('OIDCAuthenticationProvider', () => { '&redirect_uri=https%3A%2F%2Ftest-hostname:1234%2Ftest-base-path%2Fapi%2Fsecurity%2Fv1%2F/oidc', }); - const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockRejectedValue( LegacyElasticsearchErrorHelpers.decorateNotAuthorizedError(new Error()) ); @@ -602,7 +602,7 @@ describe('OIDCAuthenticationProvider', () => { const tokenPair = { accessToken: 'expired-token', refreshToken: 'expired-refresh-token' }; const authorization = `Bearer ${tokenPair.accessToken}`; - const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockRejectedValue( LegacyElasticsearchErrorHelpers.decorateNotAuthorizedError(new Error()) ); @@ -631,7 +631,7 @@ describe('OIDCAuthenticationProvider', () => { const tokenPair = { accessToken: 'expired-token', refreshToken: 'expired-refresh-token' }; const authorization = `Bearer ${tokenPair.accessToken}`; - const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockRejectedValue( LegacyElasticsearchErrorHelpers.decorateNotAuthorizedError(new Error()) ); diff --git a/x-pack/plugins/security/server/authentication/providers/pki.test.ts b/x-pack/plugins/security/server/authentication/providers/pki.test.ts index fd014e1a7cb814..fec03c5d04b0d8 100644 --- a/x-pack/plugins/security/server/authentication/providers/pki.test.ts +++ b/x-pack/plugins/security/server/authentication/providers/pki.test.ts @@ -120,7 +120,7 @@ describe('PKIAuthenticationProvider', () => { }), }); - const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockResolvedValue(user); mockOptions.client.asScoped.mockReturnValue(mockScopedClusterClient); mockOptions.client.callAsInternalUser.mockResolvedValue({ access_token: 'access-token' }); @@ -162,7 +162,7 @@ describe('PKIAuthenticationProvider', () => { }), }); - const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockResolvedValue(user); mockOptions.client.asScoped.mockReturnValue(mockScopedClusterClient); mockOptions.client.callAsInternalUser.mockResolvedValue({ access_token: 'access-token' }); @@ -220,7 +220,7 @@ describe('PKIAuthenticationProvider', () => { }); const failureReason = LegacyElasticsearchErrorHelpers.decorateNotAuthorizedError(new Error()); - const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockRejectedValue(failureReason); mockOptions.client.asScoped.mockReturnValue(mockScopedClusterClient); mockOptions.client.callAsInternalUser.mockResolvedValue({ access_token: 'access-token' }); @@ -349,7 +349,7 @@ describe('PKIAuthenticationProvider', () => { }); const state = { accessToken: 'existing-token', peerCertificateFingerprint256: '3A:9A:C5:DD' }; - const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockResolvedValue(user); mockOptions.client.asScoped.mockReturnValue(mockScopedClusterClient); mockOptions.client.callAsInternalUser.mockResolvedValue({ access_token: 'access-token' }); @@ -392,7 +392,7 @@ describe('PKIAuthenticationProvider', () => { }); const state = { accessToken: 'existing-token', peerCertificateFingerprint256: '2A:7A:C2:DD' }; - const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser // In response to call with an expired token. .mockRejectedValueOnce( @@ -436,7 +436,7 @@ describe('PKIAuthenticationProvider', () => { }); const state = { accessToken: 'existing-token', peerCertificateFingerprint256: '2A:7A:C2:DD' }; - const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockRejectedValueOnce( LegacyElasticsearchErrorHelpers.decorateNotAuthorizedError(new Error()) ); @@ -454,7 +454,7 @@ describe('PKIAuthenticationProvider', () => { const request = httpServerMock.createKibanaRequest({ socket: getMockSocket() }); const state = { accessToken: 'existing-token', peerCertificateFingerprint256: '2A:7A:C2:DD' }; - const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockRejectedValue( LegacyElasticsearchErrorHelpers.decorateNotAuthorizedError(new Error()) ); @@ -480,7 +480,7 @@ describe('PKIAuthenticationProvider', () => { }), }); - const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockResolvedValue(user); mockOptions.client.asScoped.mockReturnValue(mockScopedClusterClient); @@ -509,7 +509,7 @@ describe('PKIAuthenticationProvider', () => { }); const failureReason = new errors.ServiceUnavailable(); - const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockRejectedValue(failureReason); mockOptions.client.asScoped.mockReturnValue(mockScopedClusterClient); diff --git a/x-pack/plugins/security/server/authentication/providers/saml.test.ts b/x-pack/plugins/security/server/authentication/providers/saml.test.ts index e9af806b36f042..851ecf8107ad20 100644 --- a/x-pack/plugins/security/server/authentication/providers/saml.test.ts +++ b/x-pack/plugins/security/server/authentication/providers/saml.test.ts @@ -319,7 +319,7 @@ describe('SAMLAuthenticationProvider', () => { beforeEach(() => { mockOptions.basePath.get.mockReturnValue(mockOptions.basePath.serverBasePath); - const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockImplementation(() => Promise.resolve(mockAuthenticatedUser()) ); @@ -448,7 +448,7 @@ describe('SAMLAuthenticationProvider', () => { const authorization = 'Bearer some-valid-token'; const user = mockAuthenticatedUser(); - const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockResolvedValue(user); mockOptions.client.asScoped.mockReturnValue(mockScopedClusterClient); @@ -489,7 +489,7 @@ describe('SAMLAuthenticationProvider', () => { const authorization = `Bearer ${state.accessToken}`; const user = mockAuthenticatedUser(); - const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockResolvedValue(user); mockOptions.client.asScoped.mockReturnValue(mockScopedClusterClient); @@ -543,7 +543,7 @@ describe('SAMLAuthenticationProvider', () => { }; const authorization = `Bearer ${state.accessToken}`; - const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockImplementation(() => response); mockOptions.client.asScoped.mockReturnValue(mockScopedClusterClient); @@ -598,7 +598,7 @@ describe('SAMLAuthenticationProvider', () => { }; const authorization = `Bearer ${state.accessToken}`; - const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockImplementation(() => response); mockOptions.client.asScoped.mockReturnValue(mockScopedClusterClient); @@ -663,7 +663,7 @@ describe('SAMLAuthenticationProvider', () => { }; const authorization = `Bearer ${state.accessToken}`; - const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockImplementation(() => response); mockOptions.client.asScoped.mockReturnValue(mockScopedClusterClient); @@ -1061,7 +1061,7 @@ describe('SAMLAuthenticationProvider', () => { }; const authorization = `Bearer ${state.accessToken}`; - const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockResolvedValue(user); mockOptions.client.asScoped.mockReturnValue(mockScopedClusterClient); @@ -1088,7 +1088,7 @@ describe('SAMLAuthenticationProvider', () => { const authorization = `Bearer ${state.accessToken}`; const failureReason = { statusCode: 500, message: 'Token is not valid!' }; - const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockRejectedValue(failureReason); mockOptions.client.asScoped.mockReturnValue(mockScopedClusterClient); @@ -1113,7 +1113,7 @@ describe('SAMLAuthenticationProvider', () => { mockOptions.client.asScoped.mockImplementation((scopeableRequest) => { if (scopeableRequest?.headers.authorization === `Bearer ${state.accessToken}`) { - const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockRejectedValue( LegacyElasticsearchErrorHelpers.decorateNotAuthorizedError(new Error()) ); @@ -1121,7 +1121,7 @@ describe('SAMLAuthenticationProvider', () => { } if (scopeableRequest?.headers.authorization === 'Bearer new-access-token') { - const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockResolvedValue(user); return mockScopedClusterClient; } @@ -1165,7 +1165,7 @@ describe('SAMLAuthenticationProvider', () => { }; const authorization = `Bearer ${state.accessToken}`; - const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockRejectedValue( LegacyElasticsearchErrorHelpers.decorateNotAuthorizedError(new Error()) ); @@ -1199,7 +1199,7 @@ describe('SAMLAuthenticationProvider', () => { }; const authorization = `Bearer ${state.accessToken}`; - const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockRejectedValue( LegacyElasticsearchErrorHelpers.decorateNotAuthorizedError(new Error()) ); @@ -1231,7 +1231,7 @@ describe('SAMLAuthenticationProvider', () => { }; const authorization = `Bearer ${state.accessToken}`; - const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockRejectedValue( LegacyElasticsearchErrorHelpers.decorateNotAuthorizedError(new Error()) ); @@ -1263,7 +1263,7 @@ describe('SAMLAuthenticationProvider', () => { }; const authorization = `Bearer ${state.accessToken}`; - const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockRejectedValue( LegacyElasticsearchErrorHelpers.decorateNotAuthorizedError(new Error()) ); @@ -1304,7 +1304,7 @@ describe('SAMLAuthenticationProvider', () => { redirect: 'https://idp-host/path/login?SAMLRequest=some%20request%20', }); - const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockRejectedValue( LegacyElasticsearchErrorHelpers.decorateNotAuthorizedError(new Error()) ); diff --git a/x-pack/plugins/security/server/authentication/providers/token.test.ts b/x-pack/plugins/security/server/authentication/providers/token.test.ts index ba0f23a3393ae6..f83331d84e43ce 100644 --- a/x-pack/plugins/security/server/authentication/providers/token.test.ts +++ b/x-pack/plugins/security/server/authentication/providers/token.test.ts @@ -49,7 +49,7 @@ describe('TokenAuthenticationProvider', () => { const tokenPair = { accessToken: 'foo', refreshToken: 'bar' }; const authorization = `Bearer ${tokenPair.accessToken}`; - const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockResolvedValue(user); mockOptions.client.asScoped.mockReturnValue(mockScopedClusterClient); @@ -106,7 +106,7 @@ describe('TokenAuthenticationProvider', () => { }); const authenticationError = new Error('Some error'); - const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockRejectedValue(authenticationError); mockOptions.client.asScoped.mockReturnValue(mockScopedClusterClient); @@ -190,7 +190,7 @@ describe('TokenAuthenticationProvider', () => { const user = mockAuthenticatedUser(); const authorization = `Bearer ${tokenPair.accessToken}`; - const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockResolvedValue(user); mockOptions.client.asScoped.mockReturnValue(mockScopedClusterClient); @@ -213,7 +213,7 @@ describe('TokenAuthenticationProvider', () => { mockOptions.client.asScoped.mockImplementation((scopeableRequest) => { if (scopeableRequest?.headers.authorization === `Bearer ${tokenPair.accessToken}`) { - const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockRejectedValue( LegacyElasticsearchErrorHelpers.decorateNotAuthorizedError(new Error()) ); @@ -221,7 +221,7 @@ describe('TokenAuthenticationProvider', () => { } if (scopeableRequest?.headers.authorization === 'Bearer newfoo') { - const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockResolvedValue(user); return mockScopedClusterClient; } @@ -256,7 +256,7 @@ describe('TokenAuthenticationProvider', () => { const authorization = `Bearer ${tokenPair.accessToken}`; const authenticationError = new errors.InternalServerError('something went wrong'); - const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockRejectedValue(authenticationError); mockOptions.client.asScoped.mockReturnValue(mockScopedClusterClient); @@ -274,7 +274,7 @@ describe('TokenAuthenticationProvider', () => { const tokenPair = { accessToken: 'foo', refreshToken: 'bar' }; const authorization = `Bearer ${tokenPair.accessToken}`; - const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockRejectedValue( LegacyElasticsearchErrorHelpers.decorateNotAuthorizedError(new Error()) ); @@ -300,7 +300,7 @@ describe('TokenAuthenticationProvider', () => { const tokenPair = { accessToken: 'foo', refreshToken: 'bar' }; const authorization = `Bearer ${tokenPair.accessToken}`; - const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockRejectedValue( LegacyElasticsearchErrorHelpers.decorateNotAuthorizedError(new Error()) ); @@ -331,7 +331,7 @@ describe('TokenAuthenticationProvider', () => { const tokenPair = { accessToken: 'foo', refreshToken: 'bar' }; const authorization = `Bearer ${tokenPair.accessToken}`; - const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockRejectedValue( LegacyElasticsearchErrorHelpers.decorateNotAuthorizedError(new Error()) ); @@ -362,7 +362,7 @@ describe('TokenAuthenticationProvider', () => { const tokenPair = { accessToken: 'foo', refreshToken: 'bar' }; const authorization = `Bearer ${tokenPair.accessToken}`; - const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockRejectedValue( LegacyElasticsearchErrorHelpers.decorateNotAuthorizedError(new Error()) ); @@ -389,7 +389,7 @@ describe('TokenAuthenticationProvider', () => { const authenticationError = new errors.AuthenticationException('Some error'); mockOptions.client.asScoped.mockImplementation((scopeableRequest) => { if (scopeableRequest?.headers.authorization === `Bearer ${tokenPair.accessToken}`) { - const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockRejectedValue( LegacyElasticsearchErrorHelpers.decorateNotAuthorizedError(new Error()) ); @@ -397,7 +397,7 @@ describe('TokenAuthenticationProvider', () => { } if (scopeableRequest?.headers.authorization === 'Bearer newfoo') { - const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockRejectedValue(authenticationError); return mockScopedClusterClient; } diff --git a/x-pack/plugins/security/server/authentication/tokens.test.ts b/x-pack/plugins/security/server/authentication/tokens.test.ts index 8ad04672fdfade..e8cf37330aff26 100644 --- a/x-pack/plugins/security/server/authentication/tokens.test.ts +++ b/x-pack/plugins/security/server/authentication/tokens.test.ts @@ -18,7 +18,7 @@ describe('Tokens', () => { let tokens: Tokens; let mockClusterClient: jest.Mocked; beforeEach(() => { - mockClusterClient = elasticsearchServiceMock.createClusterClient(); + mockClusterClient = elasticsearchServiceMock.createLegacyClusterClient(); const tokensOptions = { client: mockClusterClient, diff --git a/x-pack/plugins/security/server/authorization/authorization_service.test.ts b/x-pack/plugins/security/server/authorization/authorization_service.test.ts index 4d0ab1c964741d..f67e0863086bb2 100644 --- a/x-pack/plugins/security/server/authorization/authorization_service.test.ts +++ b/x-pack/plugins/security/server/authorization/authorization_service.test.ts @@ -56,7 +56,7 @@ afterEach(() => { }); it(`#setup returns exposed services`, () => { - const mockClusterClient = elasticsearchServiceMock.createClusterClient(); + const mockClusterClient = elasticsearchServiceMock.createLegacyClusterClient(); const mockGetSpacesService = jest .fn() .mockReturnValue({ getSpaceId: jest.fn(), namespaceToSpaceId: jest.fn() }); @@ -119,7 +119,7 @@ describe('#start', () => { let licenseSubject: BehaviorSubject; let mockLicense: jest.Mocked; beforeEach(() => { - const mockClusterClient = elasticsearchServiceMock.createClusterClient(); + const mockClusterClient = elasticsearchServiceMock.createLegacyClusterClient(); licenseSubject = new BehaviorSubject(({} as unknown) as SecurityLicenseFeatures); mockLicense = licenseMock.create(); @@ -221,7 +221,7 @@ describe('#start', () => { }); it('#stop unsubscribes from license and ES updates.', () => { - const mockClusterClient = elasticsearchServiceMock.createClusterClient(); + const mockClusterClient = elasticsearchServiceMock.createLegacyClusterClient(); const licenseSubject = new BehaviorSubject(({} as unknown) as SecurityLicenseFeatures); const mockLicense = licenseMock.create(); diff --git a/x-pack/plugins/security/server/authorization/check_privileges.test.ts b/x-pack/plugins/security/server/authorization/check_privileges.test.ts index 65a3d1bf1650b8..b380f45a12d814 100644 --- a/x-pack/plugins/security/server/authorization/check_privileges.test.ts +++ b/x-pack/plugins/security/server/authorization/check_privileges.test.ts @@ -21,10 +21,10 @@ const mockActions = { const savedObjectTypes = ['foo-type', 'bar-type']; const createMockClusterClient = (response: any) => { - const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockScopedClusterClient.callAsCurrentUser.mockResolvedValue(response); - const mockClusterClient = elasticsearchServiceMock.createClusterClient(); + const mockClusterClient = elasticsearchServiceMock.createLegacyClusterClient(); mockClusterClient.asScoped.mockReturnValue(mockScopedClusterClient); return { mockClusterClient, mockScopedClusterClient }; @@ -737,7 +737,7 @@ describe('#atSpaces', () => { [`saved_object:${savedObjectTypes[0]}/get`]: false, [`saved_object:${savedObjectTypes[1]}/get`]: true, }, - // @ts-ignore this is wrong on purpose + // @ts-expect-error this is wrong on purpose 'space:space_1': { [mockActions.login]: true, [mockActions.version]: true, @@ -765,7 +765,7 @@ describe('#atSpaces', () => { [mockActions.login]: true, [mockActions.version]: true, }, - // @ts-ignore this is wrong on purpose + // @ts-expect-error this is wrong on purpose 'space:space_1': { [mockActions.login]: true, [mockActions.version]: true, diff --git a/x-pack/plugins/security/server/authorization/register_privileges_with_cluster.test.ts b/x-pack/plugins/security/server/authorization/register_privileges_with_cluster.test.ts index 0ce7eae932feae..c102af76805b0b 100644 --- a/x-pack/plugins/security/server/authorization/register_privileges_with_cluster.test.ts +++ b/x-pack/plugins/security/server/authorization/register_privileges_with_cluster.test.ts @@ -100,7 +100,7 @@ const registerPrivilegesWithClusterTest = ( }; test(description, async () => { - const mockClusterClient = elasticsearchServiceMock.createClusterClient(); + const mockClusterClient = elasticsearchServiceMock.createLegacyClusterClient(); mockClusterClient.callAsInternalUser.mockImplementation(async (api) => { switch (api) { case 'shield.getPrivilege': { diff --git a/x-pack/plugins/security/server/plugin.test.ts b/x-pack/plugins/security/server/plugin.test.ts index 5d626068a91c6c..54d7df84f61628 100644 --- a/x-pack/plugins/security/server/plugin.test.ts +++ b/x-pack/plugins/security/server/plugin.test.ts @@ -43,7 +43,7 @@ describe('Security Plugin', () => { protocol: 'https', }); - mockClusterClient = elasticsearchServiceMock.createCustomClusterClient(); + mockClusterClient = elasticsearchServiceMock.createLegacyCustomClusterClient(); mockCoreSetup.elasticsearch.legacy.createClient.mockReturnValue(mockClusterClient); mockDependencies = ({ diff --git a/x-pack/plugins/security/server/routes/api_keys/get.test.ts b/x-pack/plugins/security/server/routes/api_keys/get.test.ts index f77469552d980a..40065e757e9996 100644 --- a/x-pack/plugins/security/server/routes/api_keys/get.test.ts +++ b/x-pack/plugins/security/server/routes/api_keys/get.test.ts @@ -27,7 +27,7 @@ describe('Get API keys', () => { test(description, async () => { const mockRouteDefinitionParams = routeDefinitionParamsMock.create(); - const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockRouteDefinitionParams.clusterClient.asScoped.mockReturnValue(mockScopedClusterClient); if (apiResponse) { mockScopedClusterClient.callAsCurrentUser.mockImplementation(apiResponse); diff --git a/x-pack/plugins/security/server/routes/api_keys/invalidate.test.ts b/x-pack/plugins/security/server/routes/api_keys/invalidate.test.ts index 2889cf78aff83f..33c52688ce8e3d 100644 --- a/x-pack/plugins/security/server/routes/api_keys/invalidate.test.ts +++ b/x-pack/plugins/security/server/routes/api_keys/invalidate.test.ts @@ -27,7 +27,7 @@ describe('Invalidate API keys', () => { ) => { test(description, async () => { const mockRouteDefinitionParams = routeDefinitionParamsMock.create(); - const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockRouteDefinitionParams.clusterClient.asScoped.mockReturnValue(mockScopedClusterClient); for (const apiResponse of apiResponses) { mockScopedClusterClient.callAsCurrentUser.mockImplementationOnce(apiResponse); diff --git a/x-pack/plugins/security/server/routes/api_keys/privileges.test.ts b/x-pack/plugins/security/server/routes/api_keys/privileges.test.ts index afb67dc3bbfca1..a506cc6306c535 100644 --- a/x-pack/plugins/security/server/routes/api_keys/privileges.test.ts +++ b/x-pack/plugins/security/server/routes/api_keys/privileges.test.ts @@ -48,7 +48,7 @@ describe('Check API keys privileges', () => { apiKeys.areAPIKeysEnabled() ); - const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockRouteDefinitionParams.clusterClient.asScoped.mockReturnValue(mockScopedClusterClient); for (const apiResponse of callAsCurrentUserResponses) { mockScopedClusterClient.callAsCurrentUser.mockImplementationOnce(apiResponse); diff --git a/x-pack/plugins/security/server/routes/authorization/roles/delete.test.ts b/x-pack/plugins/security/server/routes/authorization/roles/delete.test.ts index ada6a1c8d2dc3d..399f79f44744d2 100644 --- a/x-pack/plugins/security/server/routes/authorization/roles/delete.test.ts +++ b/x-pack/plugins/security/server/routes/authorization/roles/delete.test.ts @@ -30,7 +30,7 @@ describe('DELETE role', () => { test(description, async () => { const mockRouteDefinitionParams = routeDefinitionParamsMock.create(); - const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockRouteDefinitionParams.clusterClient.asScoped.mockReturnValue(mockScopedClusterClient); if (apiResponse) { mockScopedClusterClient.callAsCurrentUser.mockImplementation(apiResponse); diff --git a/x-pack/plugins/security/server/routes/authorization/roles/get.test.ts b/x-pack/plugins/security/server/routes/authorization/roles/get.test.ts index 49123fe9c74d71..d9062bcfa2efe1 100644 --- a/x-pack/plugins/security/server/routes/authorization/roles/get.test.ts +++ b/x-pack/plugins/security/server/routes/authorization/roles/get.test.ts @@ -33,7 +33,7 @@ describe('GET role', () => { const mockRouteDefinitionParams = routeDefinitionParamsMock.create(); mockRouteDefinitionParams.authz.applicationName = application; - const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockRouteDefinitionParams.clusterClient.asScoped.mockReturnValue(mockScopedClusterClient); if (apiResponse) { mockScopedClusterClient.callAsCurrentUser.mockImplementation(apiResponse); diff --git a/x-pack/plugins/security/server/routes/authorization/roles/get_all.test.ts b/x-pack/plugins/security/server/routes/authorization/roles/get_all.test.ts index 5dbe8682c54269..66e8086d49c666 100644 --- a/x-pack/plugins/security/server/routes/authorization/roles/get_all.test.ts +++ b/x-pack/plugins/security/server/routes/authorization/roles/get_all.test.ts @@ -33,7 +33,7 @@ describe('GET all roles', () => { const mockRouteDefinitionParams = routeDefinitionParamsMock.create(); mockRouteDefinitionParams.authz.applicationName = application; - const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockRouteDefinitionParams.clusterClient.asScoped.mockReturnValue(mockScopedClusterClient); if (apiResponse) { mockScopedClusterClient.callAsCurrentUser.mockImplementation(apiResponse); diff --git a/x-pack/plugins/security/server/routes/authorization/roles/put.test.ts b/x-pack/plugins/security/server/routes/authorization/roles/put.test.ts index bec60fa149bcf9..8f115f11329d3f 100644 --- a/x-pack/plugins/security/server/routes/authorization/roles/put.test.ts +++ b/x-pack/plugins/security/server/routes/authorization/roles/put.test.ts @@ -72,7 +72,7 @@ const putRoleTest = ( mockRouteDefinitionParams.authz.applicationName = application; mockRouteDefinitionParams.authz.privileges.get.mockReturnValue(privilegeMap); - const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockRouteDefinitionParams.clusterClient.asScoped.mockReturnValue(mockScopedClusterClient); for (const apiResponse of apiResponses) { mockScopedClusterClient.callAsCurrentUser.mockImplementationOnce(apiResponse); diff --git a/x-pack/plugins/security/server/routes/index.mock.ts b/x-pack/plugins/security/server/routes/index.mock.ts index c7ff2a1e68b027..24de2af5e9703c 100644 --- a/x-pack/plugins/security/server/routes/index.mock.ts +++ b/x-pack/plugins/security/server/routes/index.mock.ts @@ -21,7 +21,7 @@ export const routeDefinitionParamsMock = { basePath: httpServiceMock.createBasePath(), csp: httpServiceMock.createSetupContract().csp, logger: loggingSystemMock.create().get(), - clusterClient: elasticsearchServiceMock.createClusterClient(), + clusterClient: elasticsearchServiceMock.createLegacyClusterClient(), config: createConfig(ConfigSchema.validate(config), loggingSystemMock.create().get(), { isTLSEnabled: false, }), diff --git a/x-pack/plugins/security/server/routes/role_mapping/delete.test.ts b/x-pack/plugins/security/server/routes/role_mapping/delete.test.ts index 34961dbe27675e..aec0310129f6ee 100644 --- a/x-pack/plugins/security/server/routes/role_mapping/delete.test.ts +++ b/x-pack/plugins/security/server/routes/role_mapping/delete.test.ts @@ -13,7 +13,7 @@ describe('DELETE role mappings', () => { it('allows a role mapping to be deleted', async () => { const mockRouteDefinitionParams = routeDefinitionParamsMock.create(); - const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockRouteDefinitionParams.clusterClient.asScoped.mockReturnValue(mockScopedClusterClient); mockScopedClusterClient.callAsCurrentUser.mockResolvedValue({ acknowledged: true }); diff --git a/x-pack/plugins/security/server/routes/role_mapping/feature_check.test.ts b/x-pack/plugins/security/server/routes/role_mapping/feature_check.test.ts index 8070b3371fcb38..ee1d550bbe24d5 100644 --- a/x-pack/plugins/security/server/routes/role_mapping/feature_check.test.ts +++ b/x-pack/plugins/security/server/routes/role_mapping/feature_check.test.ts @@ -76,7 +76,7 @@ describe('GET role mappings feature check', () => { test(description, async () => { const mockRouteDefinitionParams = routeDefinitionParamsMock.create(); - const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockRouteDefinitionParams.clusterClient.asScoped.mockReturnValue(mockScopedClusterClient); mockRouteDefinitionParams.clusterClient.callAsInternalUser.mockImplementation( internalUserClusterClientImpl diff --git a/x-pack/plugins/security/server/routes/role_mapping/get.test.ts b/x-pack/plugins/security/server/routes/role_mapping/get.test.ts index e0df59ebe7a00d..9af7268a57f9ce 100644 --- a/x-pack/plugins/security/server/routes/role_mapping/get.test.ts +++ b/x-pack/plugins/security/server/routes/role_mapping/get.test.ts @@ -53,7 +53,7 @@ describe('GET role mappings', () => { it('returns all role mappings', async () => { const mockRouteDefinitionParams = routeDefinitionParamsMock.create(); - const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockRouteDefinitionParams.clusterClient.asScoped.mockReturnValue(mockScopedClusterClient); mockScopedClusterClient.callAsCurrentUser.mockResolvedValue(mockRoleMappingResponse); @@ -128,7 +128,7 @@ describe('GET role mappings', () => { it('returns role mapping by name', async () => { const mockRouteDefinitionParams = routeDefinitionParamsMock.create(); - const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockRouteDefinitionParams.clusterClient.asScoped.mockReturnValue(mockScopedClusterClient); mockScopedClusterClient.callAsCurrentUser.mockResolvedValue({ mapping1: { @@ -216,7 +216,7 @@ describe('GET role mappings', () => { it('returns a 404 when the role mapping is not found', async () => { const mockRouteDefinitionParams = routeDefinitionParamsMock.create(); - const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockRouteDefinitionParams.clusterClient.asScoped.mockReturnValue(mockScopedClusterClient); mockScopedClusterClient.callAsCurrentUser.mockRejectedValue( Boom.notFound('role mapping not found!') diff --git a/x-pack/plugins/security/server/routes/role_mapping/post.test.ts b/x-pack/plugins/security/server/routes/role_mapping/post.test.ts index ed3d1bbd0fca2b..8f61d2a122f0c1 100644 --- a/x-pack/plugins/security/server/routes/role_mapping/post.test.ts +++ b/x-pack/plugins/security/server/routes/role_mapping/post.test.ts @@ -13,7 +13,7 @@ describe('POST role mappings', () => { it('allows a role mapping to be created', async () => { const mockRouteDefinitionParams = routeDefinitionParamsMock.create(); - const mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + const mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockRouteDefinitionParams.clusterClient.asScoped.mockReturnValue(mockScopedClusterClient); mockScopedClusterClient.callAsCurrentUser.mockResolvedValue({ created: true }); diff --git a/x-pack/plugins/security/server/routes/users/change_password.test.ts b/x-pack/plugins/security/server/routes/users/change_password.test.ts index 721c020c7431b5..21c7fc13404371 100644 --- a/x-pack/plugins/security/server/routes/users/change_password.test.ts +++ b/x-pack/plugins/security/server/routes/users/change_password.test.ts @@ -56,7 +56,7 @@ describe('Change password', () => { provider: { type: 'basic', name: 'basic' }, }); - mockScopedClusterClient = elasticsearchServiceMock.createScopedClusterClient(); + mockScopedClusterClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockClusterClient = routeParamsMock.clusterClient; mockClusterClient.asScoped.mockReturnValue(mockScopedClusterClient); diff --git a/x-pack/plugins/security_solution/server/endpoint/routes/artifacts/download_exception_list.test.ts b/x-pack/plugins/security_solution/server/endpoint/routes/artifacts/download_exception_list.test.ts index 540976134d8ae1..863a1d50377565 100644 --- a/x-pack/plugins/security_solution/server/endpoint/routes/artifacts/download_exception_list.test.ts +++ b/x-pack/plugins/security_solution/server/endpoint/routes/artifacts/download_exception_list.test.ts @@ -85,8 +85,8 @@ describe('test alerts route', () => { let ingestSavedObjectClient: jest.Mocked; beforeEach(() => { - mockClusterClient = elasticsearchServiceMock.createClusterClient(); - mockScopedClient = elasticsearchServiceMock.createScopedClusterClient(); + mockClusterClient = elasticsearchServiceMock.createLegacyClusterClient(); + mockScopedClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockSavedObjectClient = savedObjectsClientMock.create(); mockResponse = httpServerMock.createResponseFactory(); mockClusterClient.asScoped.mockReturnValue(mockScopedClient); diff --git a/x-pack/plugins/security_solution/server/endpoint/routes/metadata/metadata.test.ts b/x-pack/plugins/security_solution/server/endpoint/routes/metadata/metadata.test.ts index 668911b8d1f296..42cce382ec20ca 100644 --- a/x-pack/plugins/security_solution/server/endpoint/routes/metadata/metadata.test.ts +++ b/x-pack/plugins/security_solution/server/endpoint/routes/metadata/metadata.test.ts @@ -59,10 +59,10 @@ describe('test endpoint route', () => { }; beforeEach(() => { - mockClusterClient = elasticsearchServiceMock.createClusterClient() as jest.Mocked< + mockClusterClient = elasticsearchServiceMock.createLegacyClusterClient() as jest.Mocked< ILegacyClusterClient >; - mockScopedClient = elasticsearchServiceMock.createScopedClusterClient(); + mockScopedClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockSavedObjectClient = savedObjectsClientMock.create(); mockClusterClient.asScoped.mockReturnValue(mockScopedClient); routerMock = httpServiceMock.createRouter(); diff --git a/x-pack/plugins/security_solution/server/endpoint/routes/policy/handlers.test.ts b/x-pack/plugins/security_solution/server/endpoint/routes/policy/handlers.test.ts index 0578f795f4a4e5..8d4524e06c49ff 100644 --- a/x-pack/plugins/security_solution/server/endpoint/routes/policy/handlers.test.ts +++ b/x-pack/plugins/security_solution/server/endpoint/routes/policy/handlers.test.ts @@ -32,7 +32,7 @@ describe('test policy response handler', () => { let mockResponse: jest.Mocked; beforeEach(() => { - mockScopedClient = elasticsearchServiceMock.createScopedClusterClient(); + mockScopedClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); mockSavedObjectClient = savedObjectsClientMock.create(); mockResponse = httpServerMock.createResponseFactory(); endpointAppContextService = new EndpointAppContextService(); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/__mocks__/request_context.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/__mocks__/request_context.ts index 7289eb6dea1610..c45dd5bd8a2817 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/__mocks__/request_context.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/__mocks__/request_context.ts @@ -16,7 +16,7 @@ import { siemMock } from '../../../../mocks'; const createMockClients = () => ({ alertsClient: alertsClientMock.create(), - clusterClient: elasticsearchServiceMock.createScopedClusterClient(), + clusterClient: elasticsearchServiceMock.createLegacyScopedClusterClient(), licensing: { license: licensingMock.createLicenseMock() }, savedObjectsClient: savedObjectsClientMock.create(), appClient: siemMock.createClient(), diff --git a/x-pack/plugins/security_solution/server/lib/machine_learning/mocks.ts b/x-pack/plugins/security_solution/server/lib/machine_learning/mocks.ts index f044022d6db69e..e9b692e4731aab 100644 --- a/x-pack/plugins/security_solution/server/lib/machine_learning/mocks.ts +++ b/x-pack/plugins/security_solution/server/lib/machine_learning/mocks.ts @@ -7,7 +7,7 @@ import { MlPluginSetup } from '../../../../ml/server'; import { elasticsearchServiceMock } from '../../../../../../src/core/server/mocks'; -const createMockClient = () => elasticsearchServiceMock.createClusterClient(); +const createMockClient = () => elasticsearchServiceMock.createLegacyClusterClient(); const createMockMlSystemProvider = () => jest.fn(() => ({ mlCapabilities: jest.fn(), diff --git a/x-pack/plugins/upgrade_assistant/server/lib/es_deprecation_logging_apis.test.ts b/x-pack/plugins/upgrade_assistant/server/lib/es_deprecation_logging_apis.test.ts index 4ce21f1b311e81..b0dec299b2b12c 100644 --- a/x-pack/plugins/upgrade_assistant/server/lib/es_deprecation_logging_apis.test.ts +++ b/x-pack/plugins/upgrade_assistant/server/lib/es_deprecation_logging_apis.test.ts @@ -12,7 +12,7 @@ import { describe('getDeprecationLoggingStatus', () => { it('calls cluster.getSettings', async () => { - const dataClient = elasticsearchServiceMock.createScopedClusterClient(); + const dataClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); await getDeprecationLoggingStatus(dataClient); expect(dataClient.callAsCurrentUser).toHaveBeenCalledWith('cluster.getSettings', { includeDefaults: true, @@ -23,7 +23,7 @@ describe('getDeprecationLoggingStatus', () => { describe('setDeprecationLogging', () => { describe('isEnabled = true', () => { it('calls cluster.putSettings with logger.deprecation = WARN', async () => { - const dataClient = elasticsearchServiceMock.createScopedClusterClient(); + const dataClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); await setDeprecationLogging(dataClient, true); expect(dataClient.callAsCurrentUser).toHaveBeenCalledWith('cluster.putSettings', { body: { transient: { 'logger.deprecation': 'WARN' } }, @@ -33,7 +33,7 @@ describe('setDeprecationLogging', () => { describe('isEnabled = false', () => { it('calls cluster.putSettings with logger.deprecation = ERROR', async () => { - const dataClient = elasticsearchServiceMock.createScopedClusterClient(); + const dataClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); await setDeprecationLogging(dataClient, false); expect(dataClient.callAsCurrentUser).toHaveBeenCalledWith('cluster.putSettings', { body: { transient: { 'logger.deprecation': 'ERROR' } }, diff --git a/x-pack/plugins/upgrade_assistant/server/lib/es_migration_apis.test.ts b/x-pack/plugins/upgrade_assistant/server/lib/es_migration_apis.test.ts index 89571a4a18231a..2a4fa5cd48ded2 100644 --- a/x-pack/plugins/upgrade_assistant/server/lib/es_migration_apis.test.ts +++ b/x-pack/plugins/upgrade_assistant/server/lib/es_migration_apis.test.ts @@ -14,7 +14,7 @@ import fakeDeprecations from './__fixtures__/fake_deprecations.json'; describe('getUpgradeAssistantStatus', () => { let deprecationsResponse: DeprecationAPIResponse; - const dataClient = elasticsearchServiceMock.createScopedClusterClient(); + const dataClient = elasticsearchServiceMock.createLegacyScopedClusterClient(); (dataClient.callAsCurrentUser as jest.Mock).mockImplementation(async (api, { path, index }) => { if (path === '/_migration/deprecations') { return deprecationsResponse; diff --git a/x-pack/plugins/upgrade_assistant/server/lib/telemetry/usage_collector.test.ts b/x-pack/plugins/upgrade_assistant/server/lib/telemetry/usage_collector.test.ts index 7188241e10f9a2..e14056439ca6b2 100644 --- a/x-pack/plugins/upgrade_assistant/server/lib/telemetry/usage_collector.test.ts +++ b/x-pack/plugins/upgrade_assistant/server/lib/telemetry/usage_collector.test.ts @@ -21,7 +21,7 @@ describe('Upgrade Assistant Usage Collector', () => { let clusterClient: ILegacyClusterClient; beforeEach(() => { - clusterClient = elasticsearchServiceMock.createClusterClient(); + clusterClient = elasticsearchServiceMock.createLegacyClusterClient(); (clusterClient.callAsInternalUser as jest.Mock).mockResolvedValue({ persistent: {}, transient: { diff --git a/x-pack/plugins/upgrade_assistant/server/routes/__mocks__/routes.mock.ts b/x-pack/plugins/upgrade_assistant/server/routes/__mocks__/routes.mock.ts index 861ef2d3968dc4..2df770c3ce45c0 100644 --- a/x-pack/plugins/upgrade_assistant/server/routes/__mocks__/routes.mock.ts +++ b/x-pack/plugins/upgrade_assistant/server/routes/__mocks__/routes.mock.ts @@ -13,7 +13,7 @@ export const routeHandlerContextMock = ({ core: { elasticsearch: { legacy: { - client: elasticsearchServiceMock.createScopedClusterClient(), + client: elasticsearchServiceMock.createLegacyScopedClusterClient(), }, }, savedObjects: { client: savedObjectsClientMock.create() }, diff --git a/x-pack/plugins/uptime/server/lib/requests/__tests__/get_monitor_status.test.ts b/x-pack/plugins/uptime/server/lib/requests/__tests__/get_monitor_status.test.ts index 17bbb051b1ab11..2a1417b49dca41 100644 --- a/x-pack/plugins/uptime/server/lib/requests/__tests__/get_monitor_status.test.ts +++ b/x-pack/plugins/uptime/server/lib/requests/__tests__/get_monitor_status.test.ts @@ -51,7 +51,7 @@ type MockCallES = (method: any, params: any) => Promise; const setupMock = ( criteria: MultiPageCriteria[] ): [MockCallES, jest.Mocked>] => { - const esMock = elasticsearchServiceMock.createScopedClusterClient(); + const esMock = elasticsearchServiceMock.createLegacyScopedClusterClient(); criteria.forEach(({ after_key, bucketCriteria }) => { const mockResponse = {